From 866249452ec823f74f75e63e5bd264516848bb30 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Wed, 31 Jul 2024 15:00:17 -0700 Subject: [PATCH 01/44] Add runtime (remove later) --- TestModels/Positional/Makefile | 5 + TestModels/Positional/removeDotFromExtern.sh | 27 + .../ImplementationFromDafny-go.dtr | 14 + .../ImplementationFromDafny.go | 25 + .../SimplePositionalImpl.go | 199 ++++ .../SimpleResource.go | 34 + .../SimpleResource/SimpleResource.go | 105 ++ .../ImplementationFromDafny-go/api_client.go | 66 ++ .../go/ImplementationFromDafny-go/go.mod | 11 + .../simplepositional/SimpleResource.go | 34 + .../simplepositional/api_client.go | 66 ++ .../simplepositional/to_dafny.go | 144 +++ .../simplepositional/to_native.go | 160 +++ .../simplepositionalinternaldafny.go | 175 +++ .../simplepositionalinternaldafnytypes.go | 993 ++++++++++++++++++ .../shim.go | 43 + .../simplepositionaltypes/errors.go | 18 + .../simplepositionaltypes/types.go | 93 ++ .../unmodelled_errors.go | 26 + .../go/ImplementationFromDafny-go/to_dafny.go | 144 +++ .../ImplementationFromDafny-go/to_native.go | 160 +++ .../SimplePositionalImpl.go | 199 ++++ .../SimplePositionalImplTest.go | 154 +++ .../go/TestsFromDafny-go/SimpleResource.go | 34 + .../SimpleResource/SimpleResource.go | 105 ++ .../TestsFromDafny-go/TestsFromDafny-go.dtr | 22 + .../go/TestsFromDafny-go/TestsFromDafny.go | 118 +++ .../WrappedSimplePositionalTest.go | 85 ++ .../go/TestsFromDafny-go/api_client.go | 66 ++ .../runtimes/go/TestsFromDafny-go/go.mod | 11 + .../simplepositional/SimpleResource.go | 34 + .../simplepositional/api_client.go | 66 ++ .../simplepositional/to_dafny.go | 144 +++ .../simplepositional/to_native.go | 160 +++ .../simplepositionalinternaldafny.go | 175 +++ .../simplepositionalinternaldafnytypes.go | 993 ++++++++++++++++++ .../shim.go | 43 + .../simplepositionalinternaldafnywrapped.go | 70 ++ .../simplepositionaltypes/errors.go | 18 + .../simplepositionaltypes/types.go | 93 ++ .../unmodelled_errors.go | 26 + .../runtimes/go/TestsFromDafny-go/to_dafny.go | 144 +++ .../go/TestsFromDafny-go/to_native.go | 160 +++ TestModels/Positional/src/Index.dfy | 31 + .../src/WrappedSimplePositionalImpl.dfy | 10 + 45 files changed, 5503 insertions(+) create mode 100644 TestModels/Positional/removeDotFromExtern.sh create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny-go.dtr create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource/SimpleResource.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/api_client.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/go.mod create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/SimpleResource.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/api_client.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_dafny.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_native.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnywrapped/shim.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/errors.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/types.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/unmodelled_errors.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_dafny.go create mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_native.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImplTest/SimplePositionalImplTest.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource/SimpleResource.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny-go.dtr create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/WrappedSimplePositionalTest/WrappedSimplePositionalTest.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/api_client.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/go.mod create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/SimpleResource.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/api_client.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_dafny.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_native.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/shim.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/simplepositionalinternaldafnywrapped.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/errors.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/types.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/unmodelled_errors.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/to_dafny.go create mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/to_native.go create mode 100644 TestModels/Positional/src/Index.dfy create mode 100644 TestModels/Positional/src/WrappedSimplePositionalImpl.dfy diff --git a/TestModels/Positional/Makefile b/TestModels/Positional/Makefile index 388b205594..b38d348dad 100644 --- a/TestModels/Positional/Makefile +++ b/TestModels/Positional/Makefile @@ -16,6 +16,11 @@ SERVICE_DEPS_SimplePositional := SMITHY_DEPS=dafny-dependencies/Model/traits.smithy +GO_MODULE_NAME="github.com/Smithy-dafny/TestModels/Positional" + +PROJECT_DTR := \ + dafny-dependencies/StandardLibrary/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny-go.dtr + # This project has no dependencies # DEPENDENT-MODELS:= diff --git a/TestModels/Positional/removeDotFromExtern.sh b/TestModels/Positional/removeDotFromExtern.sh new file mode 100644 index 0000000000..410b6a0fe9 --- /dev/null +++ b/TestModels/Positional/removeDotFromExtern.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# TODO: remove this file if codegen is not generating extern with "." in go + +removeDotFromExtern() { + local directory="$1" + # Recursively search for all files in the current directory and subdirectories + for file in $(find "$directory" -type f); do + # Check if the file contains the pattern "{:extern "XYZ" }" + if grep -q '{:extern ".*"' "$file"; then + # Extract the "XYZ" part from the pattern + xyz=$(grep -o '{:extern "\([^"]*\)"' "$file" | sed 's/{:extern "\([^"]*\)"/\1/') + # Check if the "XYZ" part contains a dot + if [[ "$xyz" == *"."* ]]; then + # Remove the dot from "XYZ" + new_xyz=$(echo "$xyz" | sed 's/\.//g') + # Update the file with the new pattern + sed "s/{:extern \"$xyz\"/{:extern \"$new_xyz\"/g" $file > $file.tmp + cat $file.tmp > $file + rm $file.tmp + fi + fi + done +} + +removeDotFromExtern "Model" +removeDotFromExtern "src" + diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny-go.dtr b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny-go.dtr new file mode 100644 index 0000000000..2f8abe1715 --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny-go.dtr @@ -0,0 +1,14 @@ +file_format_version = "1.0" +dafny_version = "4.6.0.0" +[options_by_module.SimplePositionalTypes] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" +[options_by_module.AbstractSimplePositionalOperations] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" +[options_by_module.AbstractSimplePositionalService] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" +[options_by_module.SimpleResource] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" +[options_by_module.SimplePositionalImpl] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" +[options_by_module.SimplePositional] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny.go new file mode 100644 index 0000000000..66bc0796bd --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny.go @@ -0,0 +1,25 @@ +// Dafny program the_program compiled into Go +package the_program + +import ( + os "os" + + SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" + SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" + _System "github.com/dafny-lang/DafnyRuntimeGo/System_" + _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" + StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" + StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" + StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" + Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +var _ = os.Args +var _ _dafny.Dummy__ +var _ _System.Dummy__ +var _ Wrappers.Dummy__ +var _ StandardLibrary_UInt.Dummy__ +var _ StandardLibrary.Dummy__ +var _ StandardLibraryInterop.Dummy__ +var _ SimpleResource.Dummy__ +var _ SimplePositionalImpl.Dummy__ diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go new file mode 100644 index 0000000000..4d5ac41233 --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go @@ -0,0 +1,199 @@ +// Package SimplePositionalImpl +// Dafny module SimplePositionalImpl compiled into Go + +package SimplePositionalImpl + +import ( + os "os" + + SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" + simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + _System "github.com/dafny-lang/DafnyRuntimeGo/System_" + _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" + StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" + StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" + StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" + Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +var _ = os.Args +var _ _dafny.Dummy__ +var _ _System.Dummy__ +var _ Wrappers.Dummy__ +var _ StandardLibrary_UInt.Dummy__ +var _ StandardLibrary.Dummy__ +var _ StandardLibraryInterop.Dummy__ +var _ SimpleResource.Dummy__ + +type Dummy__ struct{} + +// Definition of class Default__ +type Default__ struct { + dummy byte +} + +func New_Default___() *Default__ { + _this := Default__{} + + return &_this +} + +type CompanionStruct_Default___ struct { +} + +var Companion_Default___ = CompanionStruct_Default___{} + +func (_this *Default__) Equals(other *Default__) bool { + return _this == other +} + +func (_this *Default__) EqualsGeneric(x interface{}) bool { + other, ok := x.(*Default__) + return ok && _this.Equals(other) +} + +func (*Default__) String() string { + return "SimplePositionalImpl.Default__" +} +func (_this *Default__) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = &Default__{} + +func (_static *CompanionStruct_Default___) GetResource(config Config, input simplepositionalinternaldafnytypes.GetResourceInput) Wrappers.Result { + var output Wrappers.Result = Wrappers.Result{} + _ = output + var _1_resource *SimpleResource.SimpleResource + _ = _1_resource + var _nw0 *SimpleResource.SimpleResource = SimpleResource.New_SimpleResource_() + _ = _nw0 + _nw0.Ctor__((input).Dtor_name()) + _1_resource = _nw0 + var _2_result simplepositionalinternaldafnytypes.GetResourceOutput + _ = _2_result + _2_result = simplepositionalinternaldafnytypes.Companion_GetResourceOutput_.Create_GetResourceOutput_(_1_resource) + output = Wrappers.Companion_Result_.Create_Success_(_2_result) + return output + return output +} +func (_static *CompanionStruct_Default___) GetResourcePositional(config Config, input _dafny.Sequence) Wrappers.Result { + var output Wrappers.Result = Wrappers.Result{} + _ = output + var _3_resource *SimpleResource.SimpleResource + _ = _3_resource + var _nw1 *SimpleResource.SimpleResource = SimpleResource.New_SimpleResource_() + _ = _nw1 + _nw1.Ctor__(input) + _3_resource = _nw1 + output = Wrappers.Companion_Result_.Create_Success_(_3_resource) + return output + return output +} + +// End of class Default__ + +// Definition of datatype Config +type Config struct { + Data_Config_ +} + +func (_this Config) Get_() Data_Config_ { + return _this.Data_Config_ +} + +type Data_Config_ interface { + isConfig() +} + +type CompanionStruct_Config_ struct { +} + +var Companion_Config_ = CompanionStruct_Config_{} + +type Config_Config struct { +} + +func (Config_Config) isConfig() {} + +func (CompanionStruct_Config_) Create_Config_() Config { + return Config{Config_Config{}} +} + +func (_this Config) Is_Config() bool { + _, ok := _this.Get_().(Config_Config) + return ok +} + +func (CompanionStruct_Config_) Default() Config { + return Companion_Config_.Create_Config_() +} + +func (_ CompanionStruct_Config_) AllSingletonConstructors() _dafny.Iterator { + i := -1 + return func() (interface{}, bool) { + i++ + switch i { + case 0: + return Companion_Config_.Create_Config_(), true + default: + return Config{}, false + } + } +} + +func (_this Config) String() string { + switch _this.Get_().(type) { + case nil: + return "null" + case Config_Config: + { + return "SimplePositionalImpl.Config.Config" + } + default: + { + return "" + } + } +} + +func (_this Config) Equals(other Config) bool { + switch _this.Get_().(type) { + case Config_Config: + { + _, ok := other.Get_().(Config_Config) + return ok + } + default: + { + return false // unexpected + } + } +} + +func (_this Config) EqualsGeneric(other interface{}) bool { + typed, ok := other.(Config) + return ok && _this.Equals(typed) +} + +func Type_Config_() _dafny.TypeDescriptor { + return type_Config_{} +} + +type type_Config_ struct { +} + +func (_this type_Config_) Default() interface{} { + return Companion_Config_.Default() +} + +func (_this type_Config_) String() string { + return "SimplePositionalImpl.Config" +} +func (_this Config) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = Config{} + +// End of datatype Config diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource.go new file mode 100644 index 0000000000..53f16e63ab --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource.go @@ -0,0 +1,34 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" +) + +type SimpleResource struct { + Impl simplepositionalinternaldafnytypes.ISimpleResource +} + +func (this *SimpleResource) GetName(params simplepositionaltypes.GetNameInput) (*simplepositionaltypes.GetNameOutput, error) { + var dafny_request simplepositionalinternaldafnytypes.GetNameInput = GetNameInput_ToDafny(params) + var dafny_response = this.Impl.GetName(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) + if err.Is_SimplePositionalException() { + return nil, SimplePositionalException_FromDafny(err) + } + + if err.Is_CollectionOfErrors() { + return nil, CollectionOfErrors_Output_FromDafny(err) + } + if err.Is_Opaque() { + return nil, OpaqueError_Output_FromDafny(err) + } + } + var native_response = GetNameOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetNameOutput)) + return &native_response, nil + +} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource/SimpleResource.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource/SimpleResource.go new file mode 100644 index 0000000000..2c171ede04 --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource/SimpleResource.go @@ -0,0 +1,105 @@ +// Package SimpleResource +// Dafny module SimpleResource compiled into Go + +package SimpleResource + +import ( + os "os" + + simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + _System "github.com/dafny-lang/DafnyRuntimeGo/System_" + _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" + StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" + StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" + StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" + Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +var _ = os.Args +var _ _dafny.Dummy__ +var _ _System.Dummy__ +var _ Wrappers.Dummy__ +var _ StandardLibrary_UInt.Dummy__ +var _ StandardLibrary.Dummy__ +var _ StandardLibraryInterop.Dummy__ + +type Dummy__ struct{} + +// Definition of class SimpleResource +type SimpleResource struct { + _name _dafny.Sequence +} + +func New_SimpleResource_() *SimpleResource { + _this := SimpleResource{} + + _this._name = _dafny.EmptySeq.SetString() + return &_this +} + +type CompanionStruct_SimpleResource_ struct { +} + +var Companion_SimpleResource_ = CompanionStruct_SimpleResource_{} + +func (_this *SimpleResource) Equals(other *SimpleResource) bool { + return _this == other +} + +func (_this *SimpleResource) EqualsGeneric(x interface{}) bool { + other, ok := x.(*SimpleResource) + return ok && _this.Equals(other) +} + +func (*SimpleResource) String() string { + return "SimpleResource.SimpleResource" +} + +func Type_SimpleResource_() _dafny.TypeDescriptor { + return type_SimpleResource_{} +} + +type type_SimpleResource_ struct { +} + +func (_this type_SimpleResource_) Default() interface{} { + return (*SimpleResource)(nil) +} + +func (_this type_SimpleResource_) String() string { + return "SimpleResource.SimpleResource" +} +func (_this *SimpleResource) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){simplepositionalinternaldafnytypes.Companion_ISimpleResource_.TraitID_} +} + +var _ simplepositionalinternaldafnytypes.ISimpleResource = &SimpleResource{} +var _ _dafny.TraitOffspring = &SimpleResource{} + +func (_this *SimpleResource) GetName(input simplepositionalinternaldafnytypes.GetNameInput) Wrappers.Result { + var _out1 Wrappers.Result + _ = _out1 + _out1 = simplepositionalinternaldafnytypes.Companion_ISimpleResource_.GetName(_this, input) + return _out1 +} +func (_this *SimpleResource) Ctor__(name _dafny.Sequence) { + { + (_this)._name = name + } +} +func (_this *SimpleResource) GetName_k(input simplepositionalinternaldafnytypes.GetNameInput) Wrappers.Result { + { + var output Wrappers.Result = Wrappers.Companion_Result_.Default(simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Default()) + _ = output + output = Wrappers.Companion_Result_.Create_Success_(simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Create_GetNameOutput_((_this).Name())) + return output + return output + } +} +func (_this *SimpleResource) Name() _dafny.Sequence { + { + return _this._name + } +} + +// End of class SimpleResource diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/api_client.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/api_client.go new file mode 100644 index 0000000000..8419c833fc --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/api_client.go @@ -0,0 +1,66 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "context" + + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafny" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" +) + +type Client struct { + DafnyClient *simplepositionalinternaldafny.SimplePositionalClient +} + +func NewClient(clientConfig simplepositionaltypes.SimplePositionalConfig) (*Client, error) { + var dafnyConfig = SimplePositionalConfig_ToDafny(clientConfig) + var dafny_response = simplepositionalinternaldafny.Companion_Default___.SimplePositional(dafnyConfig) + if dafny_response.Is_Failure() { + panic("Client construction failed. This should never happen") + } + var dafnyClient = dafny_response.Extract().(*simplepositionalinternaldafny.SimplePositionalClient) + client := &Client{dafnyClient} + return client, nil +} + +func (client *Client) GetResource(ctx context.Context, params simplepositionaltypes.GetResourceInput) (*simplepositionaltypes.GetResourceOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := &simplepositionaltypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + var dafny_request simplepositionalinternaldafnytypes.GetResourceInput = GetResourceInput_ToDafny(params) + var dafny_response = client.DafnyClient.GetResource(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetResourceOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourceOutput)) + return &native_response, nil + +} + +func (client *Client) GetResourcePositional(ctx context.Context, params simplepositionaltypes.GetResourcePositionalInput) (*simplepositionaltypes.GetResourcePositionalOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := &simplepositionaltypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + var dafny_request simplepositionalinternaldafnytypes.GetResourcePositionalInput = GetResourcePositionalInput_ToDafny(params) + var dafny_response = client.DafnyClient.GetResourcePositional(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetResourcePositionalOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourcePositionalOutput)) + return &native_response, nil + +} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/go.mod b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/go.mod new file mode 100644 index 0000000000..e852819557 --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/go.mod @@ -0,0 +1,11 @@ +module github.com/Smithy-dafny/TestModels/Positional + +go 1.22.2 + +require github.com/dafny-lang/DafnyStandardLibGo v0.0.0 + +require github.com/dafny-lang/DafnyRuntimeGo v0.0.0 + +replace github.com/dafny-lang/DafnyRuntimeGo => ../../../../../DafnyRuntimeGo/ + +replace github.com/dafny-lang/DafnyStandardLibGo => ../../../../dafny-dependencies/StandardLibrary/runtimes/go/ImplementationFromDafny-go/ diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/SimpleResource.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/SimpleResource.go new file mode 100644 index 0000000000..53f16e63ab --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/SimpleResource.go @@ -0,0 +1,34 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" +) + +type SimpleResource struct { + Impl simplepositionalinternaldafnytypes.ISimpleResource +} + +func (this *SimpleResource) GetName(params simplepositionaltypes.GetNameInput) (*simplepositionaltypes.GetNameOutput, error) { + var dafny_request simplepositionalinternaldafnytypes.GetNameInput = GetNameInput_ToDafny(params) + var dafny_response = this.Impl.GetName(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) + if err.Is_SimplePositionalException() { + return nil, SimplePositionalException_FromDafny(err) + } + + if err.Is_CollectionOfErrors() { + return nil, CollectionOfErrors_Output_FromDafny(err) + } + if err.Is_Opaque() { + return nil, OpaqueError_Output_FromDafny(err) + } + } + var native_response = GetNameOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetNameOutput)) + return &native_response, nil + +} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/api_client.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/api_client.go new file mode 100644 index 0000000000..8419c833fc --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/api_client.go @@ -0,0 +1,66 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "context" + + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafny" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" +) + +type Client struct { + DafnyClient *simplepositionalinternaldafny.SimplePositionalClient +} + +func NewClient(clientConfig simplepositionaltypes.SimplePositionalConfig) (*Client, error) { + var dafnyConfig = SimplePositionalConfig_ToDafny(clientConfig) + var dafny_response = simplepositionalinternaldafny.Companion_Default___.SimplePositional(dafnyConfig) + if dafny_response.Is_Failure() { + panic("Client construction failed. This should never happen") + } + var dafnyClient = dafny_response.Extract().(*simplepositionalinternaldafny.SimplePositionalClient) + client := &Client{dafnyClient} + return client, nil +} + +func (client *Client) GetResource(ctx context.Context, params simplepositionaltypes.GetResourceInput) (*simplepositionaltypes.GetResourceOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := &simplepositionaltypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + var dafny_request simplepositionalinternaldafnytypes.GetResourceInput = GetResourceInput_ToDafny(params) + var dafny_response = client.DafnyClient.GetResource(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetResourceOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourceOutput)) + return &native_response, nil + +} + +func (client *Client) GetResourcePositional(ctx context.Context, params simplepositionaltypes.GetResourcePositionalInput) (*simplepositionaltypes.GetResourcePositionalOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := &simplepositionaltypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + var dafny_request simplepositionalinternaldafnytypes.GetResourcePositionalInput = GetResourcePositionalInput_ToDafny(params) + var dafny_response = client.DafnyClient.GetResourcePositional(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetResourcePositionalOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourcePositionalOutput)) + return &native_response, nil + +} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_dafny.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_dafny.go new file mode 100644 index 0000000000..39442e0038 --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_dafny.go @@ -0,0 +1,144 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" + "github.com/dafny-lang/DafnyRuntimeGo/dafny" +) + +func GetResourceInput_ToDafny(nativeInput simplepositionaltypes.GetResourceInput) simplepositionalinternaldafnytypes.GetResourceInput { + + return func() simplepositionalinternaldafnytypes.GetResourceInput { + + return simplepositionalinternaldafnytypes.Companion_GetResourceInput_.Create_GetResourceInput_(func() dafny.Sequence { + if nativeInput.Name == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) + }()) + }() + +} + +func GetResourceOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourceOutput) simplepositionalinternaldafnytypes.GetResourceOutput { + + return func() simplepositionalinternaldafnytypes.GetResourceOutput { + + return simplepositionalinternaldafnytypes.Companion_GetResourceOutput_.Create_GetResourceOutput_(SimpleResource_ToDafny(nativeOutput.Output)) + }() + +} + +func GetResourcePositionalInput_ToDafny(nativeInput simplepositionaltypes.GetResourcePositionalInput) simplepositionalinternaldafnytypes.GetResourcePositionalInput { + + return func() simplepositionalinternaldafnytypes.GetResourcePositionalInput { + + return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalInput_.Create_GetResourcePositionalInput_(func() dafny.Sequence { + if nativeInput.Name == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) + }()) + }() + +} + +func GetResourcePositionalOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourcePositionalOutput) simplepositionalinternaldafnytypes.GetResourcePositionalOutput { + + return func() simplepositionalinternaldafnytypes.GetResourcePositionalOutput { + + return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalOutput_.Create_GetResourcePositionalOutput_(SimpleResource_ToDafny(nativeOutput.Output)) + }() + +} + +func GetNameInput_ToDafny(nativeInput simplepositionaltypes.GetNameInput) simplepositionalinternaldafnytypes.GetNameInput { + + return func() simplepositionalinternaldafnytypes.GetNameInput { + + return simplepositionalinternaldafnytypes.Companion_GetNameInput_.Create_GetNameInput_() + }() + +} + +func GetNameOutput_ToDafny(nativeOutput simplepositionaltypes.GetNameOutput) simplepositionalinternaldafnytypes.GetNameOutput { + + return func() simplepositionalinternaldafnytypes.GetNameOutput { + + return simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Create_GetNameOutput_(func() dafny.Sequence { + if nativeOutput.Name == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeOutput.Name)...) + }()) + }() + +} + +func SimpleResource_ToDafny(nativeResource simplepositionaltypes.ISimpleResource) simplepositionalinternaldafnytypes.ISimpleResource { + return nativeResource.(*SimpleResource).Impl + +} + +func SimplePositionalException_ToDafny(nativeInput simplepositionaltypes.SimplePositionalException) simplepositionalinternaldafnytypes.Error { + return func() simplepositionalinternaldafnytypes.Error { + + return simplepositionalinternaldafnytypes.Companion_Error_.Create_SimplePositionalException_(func() dafny.Sequence { + if nativeInput.Message == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeInput.Message)...) + }()) + }() + +} + +func CollectionOfErrors_Input_ToDafny(nativeInput simplepositionaltypes.CollectionOfErrors) simplepositionalinternaldafnytypes.Error { + var e []interface{} + for _, i2 := range nativeInput.ListOfErrors { + e = append(e, Error_ToDafny(i2)) + } + return simplepositionalinternaldafnytypes.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) +} +func OpaqueError_Input_ToDafny(nativeInput simplepositionaltypes.OpaqueError) simplepositionalinternaldafnytypes.Error { + return simplepositionalinternaldafnytypes.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) +} + +func Error_ToDafny(err error) simplepositionalinternaldafnytypes.Error { + switch err.(type) { + // Service Errors + case simplepositionaltypes.SimplePositionalException: + return SimplePositionalException_ToDafny(err.(simplepositionaltypes.SimplePositionalException)) + + //DependentErrors + + //Unmodelled Errors + case simplepositionaltypes.CollectionOfErrors: + return CollectionOfErrors_Input_ToDafny(err.(simplepositionaltypes.CollectionOfErrors)) + + default: + // TODO: Is changing from the commented code to this new one reasonable? + // return OpaqueError_Input_ToDafny(err.(*simpleconstraintstypes.OpaqueError)) + + // TODO: why is err a pointer? + error, ok := err.(*simplepositionaltypes.OpaqueError) + + if !ok { + panic("Error is not an OpaqueError") + } + if error == nil { + panic("Error is nil") + } + return OpaqueError_Input_ToDafny(*error) + } +} + +func SimplePositionalConfig_ToDafny(nativeInput simplepositionaltypes.SimplePositionalConfig) simplepositionalinternaldafnytypes.SimplePositionalConfig { + return func() simplepositionalinternaldafnytypes.SimplePositionalConfig { + + return simplepositionalinternaldafnytypes.Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() + }() + +} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_native.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_native.go new file mode 100644 index 0000000000..23328bb04f --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_native.go @@ -0,0 +1,160 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" + "github.com/dafny-lang/DafnyRuntimeGo/dafny" +) + +func GetResourceInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourceInput) simplepositionaltypes.GetResourceInput { + + return simplepositionaltypes.GetResourceInput{Name: func() *string { + var s string + if dafnyInput.Dtor_name() == nil { + return nil + } + for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func GetResourceOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourceOutput) simplepositionaltypes.GetResourceOutput { + + return simplepositionaltypes.GetResourceOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} + +} + +func GetResourcePositionalInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourcePositionalInput) simplepositionaltypes.GetResourcePositionalInput { + + return simplepositionaltypes.GetResourcePositionalInput{Name: func() *string { + var s string + if dafnyInput.Dtor_name() == nil { + return nil + } + for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func GetResourcePositionalOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourcePositionalOutput) simplepositionaltypes.GetResourcePositionalOutput { + + return simplepositionaltypes.GetResourcePositionalOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} + +} + +func GetNameInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetNameInput) simplepositionaltypes.GetNameInput { + + return simplepositionaltypes.GetNameInput{} + +} + +func GetNameOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetNameOutput) simplepositionaltypes.GetNameOutput { + + return simplepositionaltypes.GetNameOutput{Name: func() *string { + var s string + if dafnyOutput.Dtor_name() == nil { + return nil + } + for i := dafny.Iterate(dafnyOutput.Dtor_name()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func SimpleResource_FromDafny(dafnyResource simplepositionalinternaldafnytypes.ISimpleResource) simplepositionaltypes.ISimpleResource { + + return &SimpleResource{dafnyResource} +} + +func SimplePositionalException_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.SimplePositionalException { + return simplepositionaltypes.SimplePositionalException{Message: func() *string { + var s string + if dafnyOutput.Dtor_message() == nil { + return nil + } + for i := dafny.Iterate(dafnyOutput.Dtor_message()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func CollectionOfErrors_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.CollectionOfErrors { + listOfErrors := dafnyOutput.Dtor_list() + message := dafnyOutput.Dtor_message() + t := simplepositionaltypes.CollectionOfErrors{} + for i := dafny.Iterate(listOfErrors); ; { + val, ok := i() + if !ok { + break + } + err := val.(simplepositionalinternaldafnytypes.Error) + t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) + + } + t.Message = func() string { + var s string + for i := dafny.Iterate(message); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() + return t +} +func OpaqueError_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.OpaqueError { + return simplepositionaltypes.OpaqueError{ + ErrObject: dafnyOutput.Dtor_obj(), + } +} + +func Error_FromDafny(err simplepositionalinternaldafnytypes.Error) error { + // Service Errors + if err.Is_SimplePositionalException() { + return SimplePositionalException_FromDafny(err) + } + + //DependentErrors + + //Unmodelled Errors + if err.Is_CollectionOfErrors() { + return CollectionOfErrors_Output_FromDafny(err) + } + + return OpaqueError_Output_FromDafny(err) +} + +func SimplePositionalConfig_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.SimplePositionalConfig) simplepositionaltypes.SimplePositionalConfig { + return simplepositionaltypes.SimplePositionalConfig{} + +} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go new file mode 100644 index 0000000000..8679c91ebf --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go @@ -0,0 +1,175 @@ +// Package simplepositionalinternaldafny +// Dafny module simplepositionalinternaldafny compiled into Go + +package simplepositionalinternaldafny + +import ( + os "os" + + SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" + SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" + simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + _System "github.com/dafny-lang/DafnyRuntimeGo/System_" + _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" + StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" + StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" + StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" + Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +var _ = os.Args +var _ _dafny.Dummy__ +var _ _System.Dummy__ +var _ Wrappers.Dummy__ +var _ StandardLibrary_UInt.Dummy__ +var _ StandardLibrary.Dummy__ +var _ StandardLibraryInterop.Dummy__ +var _ SimpleResource.Dummy__ +var _ SimplePositionalImpl.Dummy__ + +type Dummy__ struct{} + +// Definition of class Default__ +type Default__ struct { + dummy byte +} + +func New_Default___() *Default__ { + _this := Default__{} + + return &_this +} + +type CompanionStruct_Default___ struct { +} + +var Companion_Default___ = CompanionStruct_Default___{} + +func (_this *Default__) Equals(other *Default__) bool { + return _this == other +} + +func (_this *Default__) EqualsGeneric(x interface{}) bool { + other, ok := x.(*Default__) + return ok && _this.Equals(other) +} + +func (*Default__) String() string { + return "simplepositionalinternaldafny.Default__" +} +func (_this *Default__) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = &Default__{} + +func (_static *CompanionStruct_Default___) DefaultSimplePositionalConfig() simplepositionalinternaldafnytypes.SimplePositionalConfig { + return simplepositionalinternaldafnytypes.Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() +} +func (_static *CompanionStruct_Default___) SimplePositional(config simplepositionalinternaldafnytypes.SimplePositionalConfig) Wrappers.Result { + var res Wrappers.Result = Wrappers.Result{} + _ = res + var _4_client *SimplePositionalClient + _ = _4_client + var _nw2 *SimplePositionalClient = New_SimplePositionalClient_() + _ = _nw2 + _nw2.Ctor__(SimplePositionalImpl.Companion_Config_.Create_Config_()) + _4_client = _nw2 + res = Wrappers.Companion_Result_.Create_Success_(_4_client) + return res + return res +} +func (_static *CompanionStruct_Default___) CreateSuccessOfClient(client simplepositionalinternaldafnytypes.ISimplePositionalClient) Wrappers.Result { + return Wrappers.Companion_Result_.Create_Success_(client) +} +func (_static *CompanionStruct_Default___) CreateFailureOfError(error_ simplepositionalinternaldafnytypes.Error) Wrappers.Result { + return Wrappers.Companion_Result_.Create_Failure_(error_) +} + +// End of class Default__ + +// Definition of class SimplePositionalClient +type SimplePositionalClient struct { + _config SimplePositionalImpl.Config +} + +func New_SimplePositionalClient_() *SimplePositionalClient { + _this := SimplePositionalClient{} + + _this._config = SimplePositionalImpl.Companion_Config_.Default() + return &_this +} + +type CompanionStruct_SimplePositionalClient_ struct { +} + +var Companion_SimplePositionalClient_ = CompanionStruct_SimplePositionalClient_{} + +func (_this *SimplePositionalClient) Equals(other *SimplePositionalClient) bool { + return _this == other +} + +func (_this *SimplePositionalClient) EqualsGeneric(x interface{}) bool { + other, ok := x.(*SimplePositionalClient) + return ok && _this.Equals(other) +} + +func (*SimplePositionalClient) String() string { + return "simplepositionalinternaldafny.SimplePositionalClient" +} + +func Type_SimplePositionalClient_() _dafny.TypeDescriptor { + return type_SimplePositionalClient_{} +} + +type type_SimplePositionalClient_ struct { +} + +func (_this type_SimplePositionalClient_) Default() interface{} { + return (*SimplePositionalClient)(nil) +} + +func (_this type_SimplePositionalClient_) String() string { + return "simplepositionalinternaldafny.SimplePositionalClient" +} +func (_this *SimplePositionalClient) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){simplepositionalinternaldafnytypes.Companion_ISimplePositionalClient_.TraitID_} +} + +var _ simplepositionalinternaldafnytypes.ISimplePositionalClient = &SimplePositionalClient{} +var _ _dafny.TraitOffspring = &SimplePositionalClient{} + +func (_this *SimplePositionalClient) Ctor__(config SimplePositionalImpl.Config) { + { + (_this)._config = config + } +} +func (_this *SimplePositionalClient) GetResource(input simplepositionalinternaldafnytypes.GetResourceInput) Wrappers.Result { + { + var output Wrappers.Result = Wrappers.Result{} + _ = output + var _out2 Wrappers.Result + _ = _out2 + _out2 = SimplePositionalImpl.Companion_Default___.GetResource((_this).Config(), input) + output = _out2 + return output + } +} +func (_this *SimplePositionalClient) GetResourcePositional(input _dafny.Sequence) Wrappers.Result { + { + var output Wrappers.Result = Wrappers.Result{} + _ = output + var _out3 Wrappers.Result + _ = _out3 + _out3 = SimplePositionalImpl.Companion_Default___.GetResourcePositional((_this).Config(), input) + output = _out3 + return output + } +} +func (_this *SimplePositionalClient) Config() SimplePositionalImpl.Config { + { + return _this._config + } +} + +// End of class SimplePositionalClient diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go new file mode 100644 index 0000000000..45ca0af901 --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go @@ -0,0 +1,993 @@ +// Package simplepositionalinternaldafnytypes +// Dafny module simplepositionalinternaldafnytypes compiled into Go + +package simplepositionalinternaldafnytypes + +import ( + os "os" + + _System "github.com/dafny-lang/DafnyRuntimeGo/System_" + _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" + StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" + StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" + StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" + Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +var _ = os.Args +var _ _dafny.Dummy__ +var _ _System.Dummy__ +var _ Wrappers.Dummy__ +var _ StandardLibrary_UInt.Dummy__ +var _ StandardLibrary.Dummy__ +var _ StandardLibraryInterop.Dummy__ + +type Dummy__ struct{} + +// Definition of datatype DafnyCallEvent +type DafnyCallEvent struct { + Data_DafnyCallEvent_ +} + +func (_this DafnyCallEvent) Get_() Data_DafnyCallEvent_ { + return _this.Data_DafnyCallEvent_ +} + +type Data_DafnyCallEvent_ interface { + isDafnyCallEvent() +} + +type CompanionStruct_DafnyCallEvent_ struct { +} + +var Companion_DafnyCallEvent_ = CompanionStruct_DafnyCallEvent_{} + +type DafnyCallEvent_DafnyCallEvent struct { + Input interface{} + Output interface{} +} + +func (DafnyCallEvent_DafnyCallEvent) isDafnyCallEvent() {} + +func (CompanionStruct_DafnyCallEvent_) Create_DafnyCallEvent_(Input interface{}, Output interface{}) DafnyCallEvent { + return DafnyCallEvent{DafnyCallEvent_DafnyCallEvent{Input, Output}} +} + +func (_this DafnyCallEvent) Is_DafnyCallEvent() bool { + _, ok := _this.Get_().(DafnyCallEvent_DafnyCallEvent) + return ok +} + +func (CompanionStruct_DafnyCallEvent_) Default(_default_I interface{}, _default_O interface{}) DafnyCallEvent { + return Companion_DafnyCallEvent_.Create_DafnyCallEvent_(_default_I, _default_O) +} + +func (_this DafnyCallEvent) Dtor_input() interface{} { + return _this.Get_().(DafnyCallEvent_DafnyCallEvent).Input +} + +func (_this DafnyCallEvent) Dtor_output() interface{} { + return _this.Get_().(DafnyCallEvent_DafnyCallEvent).Output +} + +func (_this DafnyCallEvent) String() string { + switch data := _this.Get_().(type) { + case nil: + return "null" + case DafnyCallEvent_DafnyCallEvent: + { + return "SimplePositionalTypes.DafnyCallEvent.DafnyCallEvent" + "(" + _dafny.String(data.Input) + ", " + _dafny.String(data.Output) + ")" + } + default: + { + return "" + } + } +} + +func (_this DafnyCallEvent) Equals(other DafnyCallEvent) bool { + switch data1 := _this.Get_().(type) { + case DafnyCallEvent_DafnyCallEvent: + { + data2, ok := other.Get_().(DafnyCallEvent_DafnyCallEvent) + return ok && _dafny.AreEqual(data1.Input, data2.Input) && _dafny.AreEqual(data1.Output, data2.Output) + } + default: + { + return false // unexpected + } + } +} + +func (_this DafnyCallEvent) EqualsGeneric(other interface{}) bool { + typed, ok := other.(DafnyCallEvent) + return ok && _this.Equals(typed) +} + +func Type_DafnyCallEvent_(Type_I_ _dafny.TypeDescriptor, Type_O_ _dafny.TypeDescriptor) _dafny.TypeDescriptor { + return type_DafnyCallEvent_{Type_I_, Type_O_} +} + +type type_DafnyCallEvent_ struct { + Type_I_ _dafny.TypeDescriptor + Type_O_ _dafny.TypeDescriptor +} + +func (_this type_DafnyCallEvent_) Default() interface{} { + Type_I_ := _this.Type_I_ + _ = Type_I_ + Type_O_ := _this.Type_O_ + _ = Type_O_ + return Companion_DafnyCallEvent_.Default(Type_I_.Default(), Type_O_.Default()) +} + +func (_this type_DafnyCallEvent_) String() string { + return "simplepositionalinternaldafnytypes.DafnyCallEvent" +} +func (_this DafnyCallEvent) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = DafnyCallEvent{} + +// End of datatype DafnyCallEvent + +// Definition of datatype GetNameInput +type GetNameInput struct { + Data_GetNameInput_ +} + +func (_this GetNameInput) Get_() Data_GetNameInput_ { + return _this.Data_GetNameInput_ +} + +type Data_GetNameInput_ interface { + isGetNameInput() +} + +type CompanionStruct_GetNameInput_ struct { +} + +var Companion_GetNameInput_ = CompanionStruct_GetNameInput_{} + +type GetNameInput_GetNameInput struct { +} + +func (GetNameInput_GetNameInput) isGetNameInput() {} + +func (CompanionStruct_GetNameInput_) Create_GetNameInput_() GetNameInput { + return GetNameInput{GetNameInput_GetNameInput{}} +} + +func (_this GetNameInput) Is_GetNameInput() bool { + _, ok := _this.Get_().(GetNameInput_GetNameInput) + return ok +} + +func (CompanionStruct_GetNameInput_) Default() GetNameInput { + return Companion_GetNameInput_.Create_GetNameInput_() +} + +func (_ CompanionStruct_GetNameInput_) AllSingletonConstructors() _dafny.Iterator { + i := -1 + return func() (interface{}, bool) { + i++ + switch i { + case 0: + return Companion_GetNameInput_.Create_GetNameInput_(), true + default: + return GetNameInput{}, false + } + } +} + +func (_this GetNameInput) String() string { + switch _this.Get_().(type) { + case nil: + return "null" + case GetNameInput_GetNameInput: + { + return "SimplePositionalTypes.GetNameInput.GetNameInput" + } + default: + { + return "" + } + } +} + +func (_this GetNameInput) Equals(other GetNameInput) bool { + switch _this.Get_().(type) { + case GetNameInput_GetNameInput: + { + _, ok := other.Get_().(GetNameInput_GetNameInput) + return ok + } + default: + { + return false // unexpected + } + } +} + +func (_this GetNameInput) EqualsGeneric(other interface{}) bool { + typed, ok := other.(GetNameInput) + return ok && _this.Equals(typed) +} + +func Type_GetNameInput_() _dafny.TypeDescriptor { + return type_GetNameInput_{} +} + +type type_GetNameInput_ struct { +} + +func (_this type_GetNameInput_) Default() interface{} { + return Companion_GetNameInput_.Default() +} + +func (_this type_GetNameInput_) String() string { + return "simplepositionalinternaldafnytypes.GetNameInput" +} +func (_this GetNameInput) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = GetNameInput{} + +// End of datatype GetNameInput + +// Definition of datatype GetNameOutput +type GetNameOutput struct { + Data_GetNameOutput_ +} + +func (_this GetNameOutput) Get_() Data_GetNameOutput_ { + return _this.Data_GetNameOutput_ +} + +type Data_GetNameOutput_ interface { + isGetNameOutput() +} + +type CompanionStruct_GetNameOutput_ struct { +} + +var Companion_GetNameOutput_ = CompanionStruct_GetNameOutput_{} + +type GetNameOutput_GetNameOutput struct { + Name _dafny.Sequence +} + +func (GetNameOutput_GetNameOutput) isGetNameOutput() {} + +func (CompanionStruct_GetNameOutput_) Create_GetNameOutput_(Name _dafny.Sequence) GetNameOutput { + return GetNameOutput{GetNameOutput_GetNameOutput{Name}} +} + +func (_this GetNameOutput) Is_GetNameOutput() bool { + _, ok := _this.Get_().(GetNameOutput_GetNameOutput) + return ok +} + +func (CompanionStruct_GetNameOutput_) Default() GetNameOutput { + return Companion_GetNameOutput_.Create_GetNameOutput_(_dafny.EmptySeq.SetString()) +} + +func (_this GetNameOutput) Dtor_name() _dafny.Sequence { + return _this.Get_().(GetNameOutput_GetNameOutput).Name +} + +func (_this GetNameOutput) String() string { + switch data := _this.Get_().(type) { + case nil: + return "null" + case GetNameOutput_GetNameOutput: + { + return "SimplePositionalTypes.GetNameOutput.GetNameOutput" + "(" + _dafny.String(data.Name) + ")" + } + default: + { + return "" + } + } +} + +func (_this GetNameOutput) Equals(other GetNameOutput) bool { + switch data1 := _this.Get_().(type) { + case GetNameOutput_GetNameOutput: + { + data2, ok := other.Get_().(GetNameOutput_GetNameOutput) + return ok && data1.Name.Equals(data2.Name) + } + default: + { + return false // unexpected + } + } +} + +func (_this GetNameOutput) EqualsGeneric(other interface{}) bool { + typed, ok := other.(GetNameOutput) + return ok && _this.Equals(typed) +} + +func Type_GetNameOutput_() _dafny.TypeDescriptor { + return type_GetNameOutput_{} +} + +type type_GetNameOutput_ struct { +} + +func (_this type_GetNameOutput_) Default() interface{} { + return Companion_GetNameOutput_.Default() +} + +func (_this type_GetNameOutput_) String() string { + return "simplepositionalinternaldafnytypes.GetNameOutput" +} +func (_this GetNameOutput) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = GetNameOutput{} + +// End of datatype GetNameOutput + +// Definition of datatype GetResourceInput +type GetResourceInput struct { + Data_GetResourceInput_ +} + +func (_this GetResourceInput) Get_() Data_GetResourceInput_ { + return _this.Data_GetResourceInput_ +} + +type Data_GetResourceInput_ interface { + isGetResourceInput() +} + +type CompanionStruct_GetResourceInput_ struct { +} + +var Companion_GetResourceInput_ = CompanionStruct_GetResourceInput_{} + +type GetResourceInput_GetResourceInput struct { + Name _dafny.Sequence +} + +func (GetResourceInput_GetResourceInput) isGetResourceInput() {} + +func (CompanionStruct_GetResourceInput_) Create_GetResourceInput_(Name _dafny.Sequence) GetResourceInput { + return GetResourceInput{GetResourceInput_GetResourceInput{Name}} +} + +func (_this GetResourceInput) Is_GetResourceInput() bool { + _, ok := _this.Get_().(GetResourceInput_GetResourceInput) + return ok +} + +func (CompanionStruct_GetResourceInput_) Default() GetResourceInput { + return Companion_GetResourceInput_.Create_GetResourceInput_(_dafny.EmptySeq.SetString()) +} + +func (_this GetResourceInput) Dtor_name() _dafny.Sequence { + return _this.Get_().(GetResourceInput_GetResourceInput).Name +} + +func (_this GetResourceInput) String() string { + switch data := _this.Get_().(type) { + case nil: + return "null" + case GetResourceInput_GetResourceInput: + { + return "SimplePositionalTypes.GetResourceInput.GetResourceInput" + "(" + _dafny.String(data.Name) + ")" + } + default: + { + return "" + } + } +} + +func (_this GetResourceInput) Equals(other GetResourceInput) bool { + switch data1 := _this.Get_().(type) { + case GetResourceInput_GetResourceInput: + { + data2, ok := other.Get_().(GetResourceInput_GetResourceInput) + return ok && data1.Name.Equals(data2.Name) + } + default: + { + return false // unexpected + } + } +} + +func (_this GetResourceInput) EqualsGeneric(other interface{}) bool { + typed, ok := other.(GetResourceInput) + return ok && _this.Equals(typed) +} + +func Type_GetResourceInput_() _dafny.TypeDescriptor { + return type_GetResourceInput_{} +} + +type type_GetResourceInput_ struct { +} + +func (_this type_GetResourceInput_) Default() interface{} { + return Companion_GetResourceInput_.Default() +} + +func (_this type_GetResourceInput_) String() string { + return "simplepositionalinternaldafnytypes.GetResourceInput" +} +func (_this GetResourceInput) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = GetResourceInput{} + +// End of datatype GetResourceInput + +// Definition of datatype GetResourceOutput +type GetResourceOutput struct { + Data_GetResourceOutput_ +} + +func (_this GetResourceOutput) Get_() Data_GetResourceOutput_ { + return _this.Data_GetResourceOutput_ +} + +type Data_GetResourceOutput_ interface { + isGetResourceOutput() +} + +type CompanionStruct_GetResourceOutput_ struct { +} + +var Companion_GetResourceOutput_ = CompanionStruct_GetResourceOutput_{} + +type GetResourceOutput_GetResourceOutput struct { + Output ISimpleResource +} + +func (GetResourceOutput_GetResourceOutput) isGetResourceOutput() {} + +func (CompanionStruct_GetResourceOutput_) Create_GetResourceOutput_(Output ISimpleResource) GetResourceOutput { + return GetResourceOutput{GetResourceOutput_GetResourceOutput{Output}} +} + +func (_this GetResourceOutput) Is_GetResourceOutput() bool { + _, ok := _this.Get_().(GetResourceOutput_GetResourceOutput) + return ok +} + +func (CompanionStruct_GetResourceOutput_) Default() GetResourceOutput { + return Companion_GetResourceOutput_.Create_GetResourceOutput_((ISimpleResource)(nil)) +} + +func (_this GetResourceOutput) Dtor_output() ISimpleResource { + return _this.Get_().(GetResourceOutput_GetResourceOutput).Output +} + +func (_this GetResourceOutput) String() string { + switch data := _this.Get_().(type) { + case nil: + return "null" + case GetResourceOutput_GetResourceOutput: + { + return "SimplePositionalTypes.GetResourceOutput.GetResourceOutput" + "(" + _dafny.String(data.Output) + ")" + } + default: + { + return "" + } + } +} + +func (_this GetResourceOutput) Equals(other GetResourceOutput) bool { + switch data1 := _this.Get_().(type) { + case GetResourceOutput_GetResourceOutput: + { + data2, ok := other.Get_().(GetResourceOutput_GetResourceOutput) + return ok && _dafny.AreEqual(data1.Output, data2.Output) + } + default: + { + return false // unexpected + } + } +} + +func (_this GetResourceOutput) EqualsGeneric(other interface{}) bool { + typed, ok := other.(GetResourceOutput) + return ok && _this.Equals(typed) +} + +func Type_GetResourceOutput_() _dafny.TypeDescriptor { + return type_GetResourceOutput_{} +} + +type type_GetResourceOutput_ struct { +} + +func (_this type_GetResourceOutput_) Default() interface{} { + return Companion_GetResourceOutput_.Default() +} + +func (_this type_GetResourceOutput_) String() string { + return "simplepositionalinternaldafnytypes.GetResourceOutput" +} +func (_this GetResourceOutput) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = GetResourceOutput{} + +// End of datatype GetResourceOutput + +// Definition of class ISimplePositionalClientCallHistory +type ISimplePositionalClientCallHistory struct { + dummy byte +} + +func New_ISimplePositionalClientCallHistory_() *ISimplePositionalClientCallHistory { + _this := ISimplePositionalClientCallHistory{} + + return &_this +} + +type CompanionStruct_ISimplePositionalClientCallHistory_ struct { +} + +var Companion_ISimplePositionalClientCallHistory_ = CompanionStruct_ISimplePositionalClientCallHistory_{} + +func (_this *ISimplePositionalClientCallHistory) Equals(other *ISimplePositionalClientCallHistory) bool { + return _this == other +} + +func (_this *ISimplePositionalClientCallHistory) EqualsGeneric(x interface{}) bool { + other, ok := x.(*ISimplePositionalClientCallHistory) + return ok && _this.Equals(other) +} + +func (*ISimplePositionalClientCallHistory) String() string { + return "simplepositionalinternaldafnytypes.ISimplePositionalClientCallHistory" +} + +func Type_ISimplePositionalClientCallHistory_() _dafny.TypeDescriptor { + return type_ISimplePositionalClientCallHistory_{} +} + +type type_ISimplePositionalClientCallHistory_ struct { +} + +func (_this type_ISimplePositionalClientCallHistory_) Default() interface{} { + return (*ISimplePositionalClientCallHistory)(nil) +} + +func (_this type_ISimplePositionalClientCallHistory_) String() string { + return "simplepositionalinternaldafnytypes.ISimplePositionalClientCallHistory" +} +func (_this *ISimplePositionalClientCallHistory) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = &ISimplePositionalClientCallHistory{} + +// End of class ISimplePositionalClientCallHistory + +// Definition of trait ISimplePositionalClient +type ISimplePositionalClient interface { + String() string + GetResource(input GetResourceInput) Wrappers.Result + GetResourcePositional(input _dafny.Sequence) Wrappers.Result +} +type CompanionStruct_ISimplePositionalClient_ struct { + TraitID_ *_dafny.TraitID +} + +var Companion_ISimplePositionalClient_ = CompanionStruct_ISimplePositionalClient_{ + TraitID_: &_dafny.TraitID{}, +} + +func (CompanionStruct_ISimplePositionalClient_) CastTo_(x interface{}) ISimplePositionalClient { + var t ISimplePositionalClient + t, _ = x.(ISimplePositionalClient) + return t +} + +// End of trait ISimplePositionalClient + +// Definition of datatype SimplePositionalConfig +type SimplePositionalConfig struct { + Data_SimplePositionalConfig_ +} + +func (_this SimplePositionalConfig) Get_() Data_SimplePositionalConfig_ { + return _this.Data_SimplePositionalConfig_ +} + +type Data_SimplePositionalConfig_ interface { + isSimplePositionalConfig() +} + +type CompanionStruct_SimplePositionalConfig_ struct { +} + +var Companion_SimplePositionalConfig_ = CompanionStruct_SimplePositionalConfig_{} + +type SimplePositionalConfig_SimplePositionalConfig struct { +} + +func (SimplePositionalConfig_SimplePositionalConfig) isSimplePositionalConfig() {} + +func (CompanionStruct_SimplePositionalConfig_) Create_SimplePositionalConfig_() SimplePositionalConfig { + return SimplePositionalConfig{SimplePositionalConfig_SimplePositionalConfig{}} +} + +func (_this SimplePositionalConfig) Is_SimplePositionalConfig() bool { + _, ok := _this.Get_().(SimplePositionalConfig_SimplePositionalConfig) + return ok +} + +func (CompanionStruct_SimplePositionalConfig_) Default() SimplePositionalConfig { + return Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() +} + +func (_ CompanionStruct_SimplePositionalConfig_) AllSingletonConstructors() _dafny.Iterator { + i := -1 + return func() (interface{}, bool) { + i++ + switch i { + case 0: + return Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_(), true + default: + return SimplePositionalConfig{}, false + } + } +} + +func (_this SimplePositionalConfig) String() string { + switch _this.Get_().(type) { + case nil: + return "null" + case SimplePositionalConfig_SimplePositionalConfig: + { + return "SimplePositionalTypes.SimplePositionalConfig.SimplePositionalConfig" + } + default: + { + return "" + } + } +} + +func (_this SimplePositionalConfig) Equals(other SimplePositionalConfig) bool { + switch _this.Get_().(type) { + case SimplePositionalConfig_SimplePositionalConfig: + { + _, ok := other.Get_().(SimplePositionalConfig_SimplePositionalConfig) + return ok + } + default: + { + return false // unexpected + } + } +} + +func (_this SimplePositionalConfig) EqualsGeneric(other interface{}) bool { + typed, ok := other.(SimplePositionalConfig) + return ok && _this.Equals(typed) +} + +func Type_SimplePositionalConfig_() _dafny.TypeDescriptor { + return type_SimplePositionalConfig_{} +} + +type type_SimplePositionalConfig_ struct { +} + +func (_this type_SimplePositionalConfig_) Default() interface{} { + return Companion_SimplePositionalConfig_.Default() +} + +func (_this type_SimplePositionalConfig_) String() string { + return "simplepositionalinternaldafnytypes.SimplePositionalConfig" +} +func (_this SimplePositionalConfig) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = SimplePositionalConfig{} + +// End of datatype SimplePositionalConfig + +// Definition of class ISimpleResourceCallHistory +type ISimpleResourceCallHistory struct { + dummy byte +} + +func New_ISimpleResourceCallHistory_() *ISimpleResourceCallHistory { + _this := ISimpleResourceCallHistory{} + + return &_this +} + +type CompanionStruct_ISimpleResourceCallHistory_ struct { +} + +var Companion_ISimpleResourceCallHistory_ = CompanionStruct_ISimpleResourceCallHistory_{} + +func (_this *ISimpleResourceCallHistory) Equals(other *ISimpleResourceCallHistory) bool { + return _this == other +} + +func (_this *ISimpleResourceCallHistory) EqualsGeneric(x interface{}) bool { + other, ok := x.(*ISimpleResourceCallHistory) + return ok && _this.Equals(other) +} + +func (*ISimpleResourceCallHistory) String() string { + return "simplepositionalinternaldafnytypes.ISimpleResourceCallHistory" +} + +func Type_ISimpleResourceCallHistory_() _dafny.TypeDescriptor { + return type_ISimpleResourceCallHistory_{} +} + +type type_ISimpleResourceCallHistory_ struct { +} + +func (_this type_ISimpleResourceCallHistory_) Default() interface{} { + return (*ISimpleResourceCallHistory)(nil) +} + +func (_this type_ISimpleResourceCallHistory_) String() string { + return "simplepositionalinternaldafnytypes.ISimpleResourceCallHistory" +} +func (_this *ISimpleResourceCallHistory) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = &ISimpleResourceCallHistory{} + +// End of class ISimpleResourceCallHistory + +// Definition of trait ISimpleResource +type ISimpleResource interface { + String() string + GetName(input GetNameInput) Wrappers.Result + GetName_k(input GetNameInput) Wrappers.Result +} + +func (_static *CompanionStruct_ISimpleResource_) GetName(_this ISimpleResource, input GetNameInput) Wrappers.Result { + { + var output Wrappers.Result = Wrappers.Companion_Result_.Default(Companion_GetNameOutput_.Default()) + _ = output + var _out0 Wrappers.Result + _ = _out0 + _out0 = (_this).GetName_k(input) + output = _out0 + return output + } +} + +type CompanionStruct_ISimpleResource_ struct { + TraitID_ *_dafny.TraitID +} + +var Companion_ISimpleResource_ = CompanionStruct_ISimpleResource_{ + TraitID_: &_dafny.TraitID{}, +} + +func (CompanionStruct_ISimpleResource_) CastTo_(x interface{}) ISimpleResource { + var t ISimpleResource + t, _ = x.(ISimpleResource) + return t +} + +// End of trait ISimpleResource + +// Definition of datatype Error +type Error struct { + Data_Error_ +} + +func (_this Error) Get_() Data_Error_ { + return _this.Data_Error_ +} + +type Data_Error_ interface { + isError() +} + +type CompanionStruct_Error_ struct { +} + +var Companion_Error_ = CompanionStruct_Error_{} + +type Error_SimplePositionalException struct { + Message _dafny.Sequence +} + +func (Error_SimplePositionalException) isError() {} + +func (CompanionStruct_Error_) Create_SimplePositionalException_(Message _dafny.Sequence) Error { + return Error{Error_SimplePositionalException{Message}} +} + +func (_this Error) Is_SimplePositionalException() bool { + _, ok := _this.Get_().(Error_SimplePositionalException) + return ok +} + +type Error_CollectionOfErrors struct { + List _dafny.Sequence + Message _dafny.Sequence +} + +func (Error_CollectionOfErrors) isError() {} + +func (CompanionStruct_Error_) Create_CollectionOfErrors_(List _dafny.Sequence, Message _dafny.Sequence) Error { + return Error{Error_CollectionOfErrors{List, Message}} +} + +func (_this Error) Is_CollectionOfErrors() bool { + _, ok := _this.Get_().(Error_CollectionOfErrors) + return ok +} + +type Error_Opaque struct { + Obj interface{} +} + +func (Error_Opaque) isError() {} + +func (CompanionStruct_Error_) Create_Opaque_(Obj interface{}) Error { + return Error{Error_Opaque{Obj}} +} + +func (_this Error) Is_Opaque() bool { + _, ok := _this.Get_().(Error_Opaque) + return ok +} + +func (CompanionStruct_Error_) Default() Error { + return Companion_Error_.Create_SimplePositionalException_(_dafny.EmptySeq.SetString()) +} + +func (_this Error) Dtor_message() _dafny.Sequence { + switch data := _this.Get_().(type) { + case Error_SimplePositionalException: + return data.Message + default: + return data.(Error_CollectionOfErrors).Message + } +} + +func (_this Error) Dtor_list() _dafny.Sequence { + return _this.Get_().(Error_CollectionOfErrors).List +} + +func (_this Error) Dtor_obj() interface{} { + return _this.Get_().(Error_Opaque).Obj +} + +func (_this Error) String() string { + switch data := _this.Get_().(type) { + case nil: + return "null" + case Error_SimplePositionalException: + { + return "SimplePositionalTypes.Error.SimplePositionalException" + "(" + _dafny.String(data.Message) + ")" + } + case Error_CollectionOfErrors: + { + return "SimplePositionalTypes.Error.CollectionOfErrors" + "(" + _dafny.String(data.List) + ", " + _dafny.String(data.Message) + ")" + } + case Error_Opaque: + { + return "SimplePositionalTypes.Error.Opaque" + "(" + _dafny.String(data.Obj) + ")" + } + default: + { + return "" + } + } +} + +func (_this Error) Equals(other Error) bool { + switch data1 := _this.Get_().(type) { + case Error_SimplePositionalException: + { + data2, ok := other.Get_().(Error_SimplePositionalException) + return ok && data1.Message.Equals(data2.Message) + } + case Error_CollectionOfErrors: + { + data2, ok := other.Get_().(Error_CollectionOfErrors) + return ok && data1.List.Equals(data2.List) && data1.Message.Equals(data2.Message) + } + case Error_Opaque: + { + data2, ok := other.Get_().(Error_Opaque) + return ok && _dafny.AreEqual(data1.Obj, data2.Obj) + } + default: + { + return false // unexpected + } + } +} + +func (_this Error) EqualsGeneric(other interface{}) bool { + typed, ok := other.(Error) + return ok && _this.Equals(typed) +} + +func Type_Error_() _dafny.TypeDescriptor { + return type_Error_{} +} + +type type_Error_ struct { +} + +func (_this type_Error_) Default() interface{} { + return Companion_Error_.Default() +} + +func (_this type_Error_) String() string { + return "simplepositionalinternaldafnytypes.Error" +} +func (_this Error) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = Error{} + +// End of datatype Error + +// Definition of class OpaqueError +type OpaqueError struct { +} + +func New_OpaqueError_() *OpaqueError { + _this := OpaqueError{} + + return &_this +} + +type CompanionStruct_OpaqueError_ struct { +} + +var Companion_OpaqueError_ = CompanionStruct_OpaqueError_{} + +func (*OpaqueError) String() string { + return "simplepositionalinternaldafnytypes.OpaqueError" +} + +// End of class OpaqueError + +func Type_OpaqueError_() _dafny.TypeDescriptor { + return type_OpaqueError_{} +} + +type type_OpaqueError_ struct { +} + +func (_this type_OpaqueError_) Default() interface{} { + return Companion_Error_.Default() +} + +func (_this type_OpaqueError_) String() string { + return "simplepositionalinternaldafnytypes.OpaqueError" +} +func (_this *CompanionStruct_OpaqueError_) Is_(__source Error) bool { + var _0_e Error = (__source) + _ = _0_e + return (_0_e).Is_Opaque() +} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnywrapped/shim.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnywrapped/shim.go new file mode 100644 index 0000000000..d173c74f17 --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnywrapped/shim.go @@ -0,0 +1,43 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositionalinternaldafnywrapped + +import ( + "context" + + "github.com/Smithy-dafny/TestModels/Positional/simplepositional" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +type Shim struct { + simplepositionalinternaldafnytypes.ISimplePositionalClient + client *simplepositional.Client +} + +func WrappedSimplePositional(inputConfig simplepositionalinternaldafnytypes.SimplePositionalConfig) Wrappers.Result { + var nativeConfig = simplepositional.SimplePositionalConfig_FromDafny(inputConfig) + var nativeClient, nativeError = simplepositional.NewClient(nativeConfig) + if nativeError != nil { + return Wrappers.Companion_Result_.Create_Failure_(simplepositionalinternaldafnytypes.Companion_Error_.Create_Opaque_(nativeError)) + } + return Wrappers.Companion_Result_.Create_Success_(&Shim{client: nativeClient}) +} + +func (shim *Shim) GetResource(input simplepositionalinternaldafnytypes.GetResourceInput) Wrappers.Result { + var native_request = simplepositional.GetResourceInput_FromDafny(input) + var native_response, native_error = shim.client.GetResource(context.Background(), native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(simplepositional.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(simplepositional.GetResourceOutput_ToDafny(*native_response)) +} + +func (shim *Shim) GetResourcePositional(input simplepositionalinternaldafnytypes.GetResourcePositionalInput) Wrappers.Result { + var native_request = simplepositional.GetResourcePositionalInput_FromDafny(input) + var native_response, native_error = shim.client.GetResourcePositional(context.Background(), native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(simplepositional.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(simplepositional.GetResourcePositionalOutput_ToDafny(*native_response)) +} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/errors.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/errors.go new file mode 100644 index 0000000000..a4f1fdaf51 --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/errors.go @@ -0,0 +1,18 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositionaltypes + +import ( + "fmt" +) + +type SimplePositionalException struct { + SimplePositionalBaseException + Message *string + + ErrorCodeOverride *string +} + +func (e SimplePositionalException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/types.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/types.go new file mode 100644 index 0000000000..84ddf62564 --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/types.go @@ -0,0 +1,93 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositionaltypes + +import ( + "fmt" +) + +type GetResourceInput struct { + Name *string +} + +func (input GetResourceInput) Validate() error { + if input.Name == nil { + return fmt.Errorf("Name is required but has a nil value.") + } + + return nil +} + +type SimpleResourceReference struct { +} + +func (input SimpleResourceReference) Validate() error { + return nil +} + +type GetResourceOutput struct { + Output ISimpleResource +} + +func (input GetResourceOutput) Validate() error { + + return nil +} + +type GetResourcePositionalInput struct { + Name *string +} + +func (input GetResourcePositionalInput) Validate() error { + if input.Name == nil { + return fmt.Errorf("Name is required but has a nil value.") + } + + return nil +} + +type GetResourcePositionalOutput struct { + Output ISimpleResource +} + +func (input GetResourcePositionalOutput) Validate() error { + + return nil +} + +type SimplePositionalConfig struct { +} + +func (input SimplePositionalConfig) Validate() error { + return nil +} + +type SimplePositionalBaseException interface { + // This is a dummy method to allow type assertion since Go empty interfaces + // aren't useful for type assertion checks. No concrete class is expected to implement + // this method. This is also not exported. + interfaceBindingMethod() +} + +type ISimpleResource interface { + GetName(GetNameInput) (*GetNameOutput, error) +} + +type GetNameInput struct { +} + +func (input GetNameInput) Validate() error { + return nil +} + +type GetNameOutput struct { + Name *string +} + +func (input GetNameOutput) Validate() error { + if input.Name == nil { + return fmt.Errorf("Name is required but has a nil value.") + } + + return nil +} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/unmodelled_errors.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/unmodelled_errors.go new file mode 100644 index 0000000000..33aff14a2c --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/unmodelled_errors.go @@ -0,0 +1,26 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositionaltypes + +import ( + "fmt" +) + +type CollectionOfErrors struct { + SimplePositionalBaseException + ListOfErrors []error + Message string +} + +func (e CollectionOfErrors) Error() string { + return fmt.Sprintf("message: %s\n err %v", e.Message, e.ListOfErrors) +} + +type OpaqueError struct { + SimplePositionalBaseException + ErrObject interface{} +} + +func (e OpaqueError) Error() string { + return fmt.Sprintf("message: %v", e.ErrObject) +} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_dafny.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_dafny.go new file mode 100644 index 0000000000..39442e0038 --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_dafny.go @@ -0,0 +1,144 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" + "github.com/dafny-lang/DafnyRuntimeGo/dafny" +) + +func GetResourceInput_ToDafny(nativeInput simplepositionaltypes.GetResourceInput) simplepositionalinternaldafnytypes.GetResourceInput { + + return func() simplepositionalinternaldafnytypes.GetResourceInput { + + return simplepositionalinternaldafnytypes.Companion_GetResourceInput_.Create_GetResourceInput_(func() dafny.Sequence { + if nativeInput.Name == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) + }()) + }() + +} + +func GetResourceOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourceOutput) simplepositionalinternaldafnytypes.GetResourceOutput { + + return func() simplepositionalinternaldafnytypes.GetResourceOutput { + + return simplepositionalinternaldafnytypes.Companion_GetResourceOutput_.Create_GetResourceOutput_(SimpleResource_ToDafny(nativeOutput.Output)) + }() + +} + +func GetResourcePositionalInput_ToDafny(nativeInput simplepositionaltypes.GetResourcePositionalInput) simplepositionalinternaldafnytypes.GetResourcePositionalInput { + + return func() simplepositionalinternaldafnytypes.GetResourcePositionalInput { + + return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalInput_.Create_GetResourcePositionalInput_(func() dafny.Sequence { + if nativeInput.Name == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) + }()) + }() + +} + +func GetResourcePositionalOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourcePositionalOutput) simplepositionalinternaldafnytypes.GetResourcePositionalOutput { + + return func() simplepositionalinternaldafnytypes.GetResourcePositionalOutput { + + return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalOutput_.Create_GetResourcePositionalOutput_(SimpleResource_ToDafny(nativeOutput.Output)) + }() + +} + +func GetNameInput_ToDafny(nativeInput simplepositionaltypes.GetNameInput) simplepositionalinternaldafnytypes.GetNameInput { + + return func() simplepositionalinternaldafnytypes.GetNameInput { + + return simplepositionalinternaldafnytypes.Companion_GetNameInput_.Create_GetNameInput_() + }() + +} + +func GetNameOutput_ToDafny(nativeOutput simplepositionaltypes.GetNameOutput) simplepositionalinternaldafnytypes.GetNameOutput { + + return func() simplepositionalinternaldafnytypes.GetNameOutput { + + return simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Create_GetNameOutput_(func() dafny.Sequence { + if nativeOutput.Name == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeOutput.Name)...) + }()) + }() + +} + +func SimpleResource_ToDafny(nativeResource simplepositionaltypes.ISimpleResource) simplepositionalinternaldafnytypes.ISimpleResource { + return nativeResource.(*SimpleResource).Impl + +} + +func SimplePositionalException_ToDafny(nativeInput simplepositionaltypes.SimplePositionalException) simplepositionalinternaldafnytypes.Error { + return func() simplepositionalinternaldafnytypes.Error { + + return simplepositionalinternaldafnytypes.Companion_Error_.Create_SimplePositionalException_(func() dafny.Sequence { + if nativeInput.Message == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeInput.Message)...) + }()) + }() + +} + +func CollectionOfErrors_Input_ToDafny(nativeInput simplepositionaltypes.CollectionOfErrors) simplepositionalinternaldafnytypes.Error { + var e []interface{} + for _, i2 := range nativeInput.ListOfErrors { + e = append(e, Error_ToDafny(i2)) + } + return simplepositionalinternaldafnytypes.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) +} +func OpaqueError_Input_ToDafny(nativeInput simplepositionaltypes.OpaqueError) simplepositionalinternaldafnytypes.Error { + return simplepositionalinternaldafnytypes.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) +} + +func Error_ToDafny(err error) simplepositionalinternaldafnytypes.Error { + switch err.(type) { + // Service Errors + case simplepositionaltypes.SimplePositionalException: + return SimplePositionalException_ToDafny(err.(simplepositionaltypes.SimplePositionalException)) + + //DependentErrors + + //Unmodelled Errors + case simplepositionaltypes.CollectionOfErrors: + return CollectionOfErrors_Input_ToDafny(err.(simplepositionaltypes.CollectionOfErrors)) + + default: + // TODO: Is changing from the commented code to this new one reasonable? + // return OpaqueError_Input_ToDafny(err.(*simpleconstraintstypes.OpaqueError)) + + // TODO: why is err a pointer? + error, ok := err.(*simplepositionaltypes.OpaqueError) + + if !ok { + panic("Error is not an OpaqueError") + } + if error == nil { + panic("Error is nil") + } + return OpaqueError_Input_ToDafny(*error) + } +} + +func SimplePositionalConfig_ToDafny(nativeInput simplepositionaltypes.SimplePositionalConfig) simplepositionalinternaldafnytypes.SimplePositionalConfig { + return func() simplepositionalinternaldafnytypes.SimplePositionalConfig { + + return simplepositionalinternaldafnytypes.Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() + }() + +} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_native.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_native.go new file mode 100644 index 0000000000..23328bb04f --- /dev/null +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_native.go @@ -0,0 +1,160 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" + "github.com/dafny-lang/DafnyRuntimeGo/dafny" +) + +func GetResourceInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourceInput) simplepositionaltypes.GetResourceInput { + + return simplepositionaltypes.GetResourceInput{Name: func() *string { + var s string + if dafnyInput.Dtor_name() == nil { + return nil + } + for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func GetResourceOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourceOutput) simplepositionaltypes.GetResourceOutput { + + return simplepositionaltypes.GetResourceOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} + +} + +func GetResourcePositionalInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourcePositionalInput) simplepositionaltypes.GetResourcePositionalInput { + + return simplepositionaltypes.GetResourcePositionalInput{Name: func() *string { + var s string + if dafnyInput.Dtor_name() == nil { + return nil + } + for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func GetResourcePositionalOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourcePositionalOutput) simplepositionaltypes.GetResourcePositionalOutput { + + return simplepositionaltypes.GetResourcePositionalOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} + +} + +func GetNameInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetNameInput) simplepositionaltypes.GetNameInput { + + return simplepositionaltypes.GetNameInput{} + +} + +func GetNameOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetNameOutput) simplepositionaltypes.GetNameOutput { + + return simplepositionaltypes.GetNameOutput{Name: func() *string { + var s string + if dafnyOutput.Dtor_name() == nil { + return nil + } + for i := dafny.Iterate(dafnyOutput.Dtor_name()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func SimpleResource_FromDafny(dafnyResource simplepositionalinternaldafnytypes.ISimpleResource) simplepositionaltypes.ISimpleResource { + + return &SimpleResource{dafnyResource} +} + +func SimplePositionalException_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.SimplePositionalException { + return simplepositionaltypes.SimplePositionalException{Message: func() *string { + var s string + if dafnyOutput.Dtor_message() == nil { + return nil + } + for i := dafny.Iterate(dafnyOutput.Dtor_message()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func CollectionOfErrors_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.CollectionOfErrors { + listOfErrors := dafnyOutput.Dtor_list() + message := dafnyOutput.Dtor_message() + t := simplepositionaltypes.CollectionOfErrors{} + for i := dafny.Iterate(listOfErrors); ; { + val, ok := i() + if !ok { + break + } + err := val.(simplepositionalinternaldafnytypes.Error) + t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) + + } + t.Message = func() string { + var s string + for i := dafny.Iterate(message); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() + return t +} +func OpaqueError_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.OpaqueError { + return simplepositionaltypes.OpaqueError{ + ErrObject: dafnyOutput.Dtor_obj(), + } +} + +func Error_FromDafny(err simplepositionalinternaldafnytypes.Error) error { + // Service Errors + if err.Is_SimplePositionalException() { + return SimplePositionalException_FromDafny(err) + } + + //DependentErrors + + //Unmodelled Errors + if err.Is_CollectionOfErrors() { + return CollectionOfErrors_Output_FromDafny(err) + } + + return OpaqueError_Output_FromDafny(err) +} + +func SimplePositionalConfig_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.SimplePositionalConfig) simplepositionaltypes.SimplePositionalConfig { + return simplepositionaltypes.SimplePositionalConfig{} + +} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go new file mode 100644 index 0000000000..4d5ac41233 --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go @@ -0,0 +1,199 @@ +// Package SimplePositionalImpl +// Dafny module SimplePositionalImpl compiled into Go + +package SimplePositionalImpl + +import ( + os "os" + + SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" + simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + _System "github.com/dafny-lang/DafnyRuntimeGo/System_" + _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" + StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" + StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" + StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" + Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +var _ = os.Args +var _ _dafny.Dummy__ +var _ _System.Dummy__ +var _ Wrappers.Dummy__ +var _ StandardLibrary_UInt.Dummy__ +var _ StandardLibrary.Dummy__ +var _ StandardLibraryInterop.Dummy__ +var _ SimpleResource.Dummy__ + +type Dummy__ struct{} + +// Definition of class Default__ +type Default__ struct { + dummy byte +} + +func New_Default___() *Default__ { + _this := Default__{} + + return &_this +} + +type CompanionStruct_Default___ struct { +} + +var Companion_Default___ = CompanionStruct_Default___{} + +func (_this *Default__) Equals(other *Default__) bool { + return _this == other +} + +func (_this *Default__) EqualsGeneric(x interface{}) bool { + other, ok := x.(*Default__) + return ok && _this.Equals(other) +} + +func (*Default__) String() string { + return "SimplePositionalImpl.Default__" +} +func (_this *Default__) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = &Default__{} + +func (_static *CompanionStruct_Default___) GetResource(config Config, input simplepositionalinternaldafnytypes.GetResourceInput) Wrappers.Result { + var output Wrappers.Result = Wrappers.Result{} + _ = output + var _1_resource *SimpleResource.SimpleResource + _ = _1_resource + var _nw0 *SimpleResource.SimpleResource = SimpleResource.New_SimpleResource_() + _ = _nw0 + _nw0.Ctor__((input).Dtor_name()) + _1_resource = _nw0 + var _2_result simplepositionalinternaldafnytypes.GetResourceOutput + _ = _2_result + _2_result = simplepositionalinternaldafnytypes.Companion_GetResourceOutput_.Create_GetResourceOutput_(_1_resource) + output = Wrappers.Companion_Result_.Create_Success_(_2_result) + return output + return output +} +func (_static *CompanionStruct_Default___) GetResourcePositional(config Config, input _dafny.Sequence) Wrappers.Result { + var output Wrappers.Result = Wrappers.Result{} + _ = output + var _3_resource *SimpleResource.SimpleResource + _ = _3_resource + var _nw1 *SimpleResource.SimpleResource = SimpleResource.New_SimpleResource_() + _ = _nw1 + _nw1.Ctor__(input) + _3_resource = _nw1 + output = Wrappers.Companion_Result_.Create_Success_(_3_resource) + return output + return output +} + +// End of class Default__ + +// Definition of datatype Config +type Config struct { + Data_Config_ +} + +func (_this Config) Get_() Data_Config_ { + return _this.Data_Config_ +} + +type Data_Config_ interface { + isConfig() +} + +type CompanionStruct_Config_ struct { +} + +var Companion_Config_ = CompanionStruct_Config_{} + +type Config_Config struct { +} + +func (Config_Config) isConfig() {} + +func (CompanionStruct_Config_) Create_Config_() Config { + return Config{Config_Config{}} +} + +func (_this Config) Is_Config() bool { + _, ok := _this.Get_().(Config_Config) + return ok +} + +func (CompanionStruct_Config_) Default() Config { + return Companion_Config_.Create_Config_() +} + +func (_ CompanionStruct_Config_) AllSingletonConstructors() _dafny.Iterator { + i := -1 + return func() (interface{}, bool) { + i++ + switch i { + case 0: + return Companion_Config_.Create_Config_(), true + default: + return Config{}, false + } + } +} + +func (_this Config) String() string { + switch _this.Get_().(type) { + case nil: + return "null" + case Config_Config: + { + return "SimplePositionalImpl.Config.Config" + } + default: + { + return "" + } + } +} + +func (_this Config) Equals(other Config) bool { + switch _this.Get_().(type) { + case Config_Config: + { + _, ok := other.Get_().(Config_Config) + return ok + } + default: + { + return false // unexpected + } + } +} + +func (_this Config) EqualsGeneric(other interface{}) bool { + typed, ok := other.(Config) + return ok && _this.Equals(typed) +} + +func Type_Config_() _dafny.TypeDescriptor { + return type_Config_{} +} + +type type_Config_ struct { +} + +func (_this type_Config_) Default() interface{} { + return Companion_Config_.Default() +} + +func (_this type_Config_) String() string { + return "SimplePositionalImpl.Config" +} +func (_this Config) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = Config{} + +// End of datatype Config diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImplTest/SimplePositionalImplTest.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImplTest/SimplePositionalImplTest.go new file mode 100644 index 0000000000..0f7bac0302 --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImplTest/SimplePositionalImplTest.go @@ -0,0 +1,154 @@ +// Package SimplePositionalImplTest +// Dafny module SimplePositionalImplTest compiled into Go + +package SimplePositionalImplTest + +import ( + os "os" + + SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" + SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" + simplepositionalinternaldafny "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafny" + simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + _System "github.com/dafny-lang/DafnyRuntimeGo/System_" + _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" + StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" + StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" + StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" + Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +var _ = os.Args +var _ _dafny.Dummy__ +var _ _System.Dummy__ +var _ Wrappers.Dummy__ +var _ StandardLibrary_UInt.Dummy__ +var _ StandardLibrary.Dummy__ +var _ StandardLibraryInterop.Dummy__ +var _ SimpleResource.Dummy__ +var _ SimplePositionalImpl.Dummy__ + +type Dummy__ struct{} + +// Definition of class Default__ +type Default__ struct { + dummy byte +} + +func New_Default___() *Default__ { + _this := Default__{} + + return &_this +} + +type CompanionStruct_Default___ struct { +} + +var Companion_Default___ = CompanionStruct_Default___{} + +func (_this *Default__) Equals(other *Default__) bool { + return _this == other +} + +func (_this *Default__) EqualsGeneric(x interface{}) bool { + other, ok := x.(*Default__) + return ok && _this.Equals(other) +} + +func (*Default__) String() string { + return "SimplePositionalImplTest.Default__" +} +func (_this *Default__) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = &Default__{} + +func (_static *CompanionStruct_Default___) TestClient(client simplepositionalinternaldafnytypes.ISimplePositionalClient) { + Companion_Default___.TestGetResource(client) + Companion_Default___.TestGetResourcePositional(client) +} +func (_static *CompanionStruct_Default___) TestGetResource(client simplepositionalinternaldafnytypes.ISimplePositionalClient) { + var _5_input simplepositionalinternaldafnytypes.GetResourceInput + _ = _5_input + _5_input = simplepositionalinternaldafnytypes.Companion_GetResourceInput_.Create_GetResourceInput_(_dafny.SeqOfString("Test")) + var _6_output simplepositionalinternaldafnytypes.GetResourceOutput + _ = _6_output + var _7_valueOrError0 Wrappers.Result = Wrappers.Result{} + _ = _7_valueOrError0 + var _out4 Wrappers.Result + _ = _out4 + _out4 = (client).GetResource(_5_input) + _7_valueOrError0 = _out4 + if !(!((_7_valueOrError0).IsFailure())) { + panic("test/SimplePositionalImplTest.dfy(27,22): " + (_7_valueOrError0).String()) + } + _6_output = (_7_valueOrError0).Extract().(simplepositionalinternaldafnytypes.GetResourceOutput) + var _8_resource simplepositionalinternaldafnytypes.ISimpleResource + _ = _8_resource + _8_resource = (_6_output).Dtor_output() + var _9_getNameOutput simplepositionalinternaldafnytypes.GetNameOutput + _ = _9_getNameOutput + var _10_valueOrError1 Wrappers.Result = Wrappers.Companion_Result_.Default(simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Default()) + _ = _10_valueOrError1 + var _out5 Wrappers.Result + _ = _out5 + _out5 = (_8_resource).GetName(simplepositionalinternaldafnytypes.Companion_GetNameInput_.Create_GetNameInput_()) + _10_valueOrError1 = _out5 + if !(!((_10_valueOrError1).IsFailure())) { + panic("test/SimplePositionalImplTest.dfy(29,29): " + (_10_valueOrError1).String()) + } + _9_getNameOutput = (_10_valueOrError1).Extract().(simplepositionalinternaldafnytypes.GetNameOutput) + if !(_dafny.Companion_Sequence_.Equal((_9_getNameOutput).Dtor_name(), _dafny.SeqOfString("Test"))) { + panic("test/SimplePositionalImplTest.dfy(30,8): " + (_dafny.SeqOfString("expectation violation")).String()) + } +} +func (_static *CompanionStruct_Default___) TestGetResourcePositional(client simplepositionalinternaldafnytypes.ISimplePositionalClient) { + var _11_input _dafny.Sequence + _ = _11_input + _11_input = _dafny.SeqOfString("TestPositional") + var _12_resource simplepositionalinternaldafnytypes.ISimpleResource + _ = _12_resource + var _13_valueOrError0 Wrappers.Result = Wrappers.Result{} + _ = _13_valueOrError0 + var _out6 Wrappers.Result + _ = _out6 + _out6 = (client).GetResourcePositional(_11_input) + _13_valueOrError0 = _out6 + if !(!((_13_valueOrError0).IsFailure())) { + panic("test/SimplePositionalImplTest.dfy(39,47): " + (_13_valueOrError0).String()) + } + _12_resource = simplepositionalinternaldafnytypes.Companion_ISimpleResource_.CastTo_((_13_valueOrError0).Extract()) + var _14_getNameOutput simplepositionalinternaldafnytypes.GetNameOutput + _ = _14_getNameOutput + var _15_valueOrError1 Wrappers.Result = Wrappers.Companion_Result_.Default(simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Default()) + _ = _15_valueOrError1 + var _out7 Wrappers.Result + _ = _out7 + _out7 = (_12_resource).GetName(simplepositionalinternaldafnytypes.Companion_GetNameInput_.Create_GetNameInput_()) + _15_valueOrError1 = _out7 + if !(!((_15_valueOrError1).IsFailure())) { + panic("test/SimplePositionalImplTest.dfy(40,29): " + (_15_valueOrError1).String()) + } + _14_getNameOutput = (_15_valueOrError1).Extract().(simplepositionalinternaldafnytypes.GetNameOutput) + if !(_dafny.Companion_Sequence_.Equal((_14_getNameOutput).Dtor_name(), _dafny.SeqOfString("TestPositional"))) { + panic("test/SimplePositionalImplTest.dfy(41,8): " + (_dafny.SeqOfString("expectation violation")).String()) + } +} +func (_static *CompanionStruct_Default___) TestDefaultConfig() { + var _16_client *simplepositionalinternaldafny.SimplePositionalClient + _ = _16_client + var _17_valueOrError0 Wrappers.Result = Wrappers.Result{} + _ = _17_valueOrError0 + var _out8 Wrappers.Result + _ = _out8 + _out8 = simplepositionalinternaldafny.Companion_Default___.SimplePositional(simplepositionalinternaldafny.Companion_Default___.DefaultSimplePositionalConfig()) + _17_valueOrError0 = _out8 + if !(!((_17_valueOrError0).IsFailure())) { + panic("test/SimplePositionalImplTest.dfy(45,22): " + (_17_valueOrError0).String()) + } + _16_client = (_17_valueOrError0).Extract().(*simplepositionalinternaldafny.SimplePositionalClient) + Companion_Default___.TestClient(_16_client) +} + +// End of class Default__ diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource.go new file mode 100644 index 0000000000..53f16e63ab --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource.go @@ -0,0 +1,34 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" +) + +type SimpleResource struct { + Impl simplepositionalinternaldafnytypes.ISimpleResource +} + +func (this *SimpleResource) GetName(params simplepositionaltypes.GetNameInput) (*simplepositionaltypes.GetNameOutput, error) { + var dafny_request simplepositionalinternaldafnytypes.GetNameInput = GetNameInput_ToDafny(params) + var dafny_response = this.Impl.GetName(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) + if err.Is_SimplePositionalException() { + return nil, SimplePositionalException_FromDafny(err) + } + + if err.Is_CollectionOfErrors() { + return nil, CollectionOfErrors_Output_FromDafny(err) + } + if err.Is_Opaque() { + return nil, OpaqueError_Output_FromDafny(err) + } + } + var native_response = GetNameOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetNameOutput)) + return &native_response, nil + +} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource/SimpleResource.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource/SimpleResource.go new file mode 100644 index 0000000000..2c171ede04 --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource/SimpleResource.go @@ -0,0 +1,105 @@ +// Package SimpleResource +// Dafny module SimpleResource compiled into Go + +package SimpleResource + +import ( + os "os" + + simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + _System "github.com/dafny-lang/DafnyRuntimeGo/System_" + _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" + StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" + StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" + StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" + Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +var _ = os.Args +var _ _dafny.Dummy__ +var _ _System.Dummy__ +var _ Wrappers.Dummy__ +var _ StandardLibrary_UInt.Dummy__ +var _ StandardLibrary.Dummy__ +var _ StandardLibraryInterop.Dummy__ + +type Dummy__ struct{} + +// Definition of class SimpleResource +type SimpleResource struct { + _name _dafny.Sequence +} + +func New_SimpleResource_() *SimpleResource { + _this := SimpleResource{} + + _this._name = _dafny.EmptySeq.SetString() + return &_this +} + +type CompanionStruct_SimpleResource_ struct { +} + +var Companion_SimpleResource_ = CompanionStruct_SimpleResource_{} + +func (_this *SimpleResource) Equals(other *SimpleResource) bool { + return _this == other +} + +func (_this *SimpleResource) EqualsGeneric(x interface{}) bool { + other, ok := x.(*SimpleResource) + return ok && _this.Equals(other) +} + +func (*SimpleResource) String() string { + return "SimpleResource.SimpleResource" +} + +func Type_SimpleResource_() _dafny.TypeDescriptor { + return type_SimpleResource_{} +} + +type type_SimpleResource_ struct { +} + +func (_this type_SimpleResource_) Default() interface{} { + return (*SimpleResource)(nil) +} + +func (_this type_SimpleResource_) String() string { + return "SimpleResource.SimpleResource" +} +func (_this *SimpleResource) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){simplepositionalinternaldafnytypes.Companion_ISimpleResource_.TraitID_} +} + +var _ simplepositionalinternaldafnytypes.ISimpleResource = &SimpleResource{} +var _ _dafny.TraitOffspring = &SimpleResource{} + +func (_this *SimpleResource) GetName(input simplepositionalinternaldafnytypes.GetNameInput) Wrappers.Result { + var _out1 Wrappers.Result + _ = _out1 + _out1 = simplepositionalinternaldafnytypes.Companion_ISimpleResource_.GetName(_this, input) + return _out1 +} +func (_this *SimpleResource) Ctor__(name _dafny.Sequence) { + { + (_this)._name = name + } +} +func (_this *SimpleResource) GetName_k(input simplepositionalinternaldafnytypes.GetNameInput) Wrappers.Result { + { + var output Wrappers.Result = Wrappers.Companion_Result_.Default(simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Default()) + _ = output + output = Wrappers.Companion_Result_.Create_Success_(simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Create_GetNameOutput_((_this).Name())) + return output + return output + } +} +func (_this *SimpleResource) Name() _dafny.Sequence { + { + return _this._name + } +} + +// End of class SimpleResource diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny-go.dtr b/TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny-go.dtr new file mode 100644 index 0000000000..546347e43c --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny-go.dtr @@ -0,0 +1,22 @@ +file_format_version = "1.0" +dafny_version = "4.6.0.0" +[options_by_module.SimplePositionalTypes] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" +[options_by_module.AbstractSimplePositionalOperations] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" +[options_by_module.SimpleResource] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" +[options_by_module.SimplePositionalImpl] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" +[options_by_module.AbstractSimplePositionalService] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" +[options_by_module.SimplePositional] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" +[options_by_module.WrappedAbstractSimplePositionalService] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" +[options_by_module.WrappedSimplePositionalService] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" +[options_by_module.SimplePositionalImplTest] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" +[options_by_module.WrappedSimplePositionalTest] +go-module-name = "github.com/Smithy-dafny/TestModels/Positional" diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny.go new file mode 100644 index 0000000000..fb1949b6ac --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny.go @@ -0,0 +1,118 @@ +// Dafny program the_program compiled into Go +package main + +import ( + os "os" + + SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" + SimplePositionalImplTest "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImplTest" + SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" + WrappedSimplePositionalTest "github.com/Smithy-dafny/TestModels/Positional/WrappedSimplePositionalTest" + _System "github.com/dafny-lang/DafnyRuntimeGo/System_" + _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" + StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" + StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" + StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" + Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +var _ = os.Args +var _ _dafny.Dummy__ +var _ _System.Dummy__ +var _ Wrappers.Dummy__ +var _ StandardLibrary_UInt.Dummy__ +var _ StandardLibrary.Dummy__ +var _ StandardLibraryInterop.Dummy__ +var _ SimpleResource.Dummy__ +var _ SimplePositionalImpl.Dummy__ +var _ SimplePositionalImplTest.Dummy__ +var _ WrappedSimplePositionalTest.Dummy__ + +// Definition of class Default__ +type Default__ struct { + dummy byte +} + +func New_Default___() *Default__ { + _this := Default__{} + + return &_this +} + +type CompanionStruct_Default___ struct { +} + +var Companion_Default___ = CompanionStruct_Default___{} + +func (_this *Default__) Equals(other *Default__) bool { + return _this == other +} + +func (_this *Default__) EqualsGeneric(x interface{}) bool { + other, ok := x.(*Default__) + return ok && _this.Equals(other) +} + +func (*Default__) String() string { + return "_module.Default__" +} +func (_this *Default__) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = &Default__{} + +func (_static *CompanionStruct_Default___) Test____Main____(__noArgsParameter _dafny.Sequence) { + var _20_success bool + _ = _20_success + _20_success = true + _dafny.Print((_dafny.SeqOfString("SimplePositionalImplTest.TestDefaultConfig: ")).SetString()) + func() { + defer func() { + if r := recover(); r != nil { + var _21_haltMessage = _dafny.SeqOfString(r.(string)) + { + _dafny.Print((_dafny.SeqOfString("FAILED\n ")).SetString()) + _dafny.Print((_21_haltMessage).SetString()) + _dafny.Print((_dafny.SeqOfString("\n")).SetString()) + _20_success = false + } + } + }() + { + SimplePositionalImplTest.Companion_Default___.TestDefaultConfig() + { + _dafny.Print((_dafny.SeqOfString("PASSED\n")).SetString()) + } + } + }() + _dafny.Print((_dafny.SeqOfString("WrappedSimplePositionalTest.TestWrappedClient: ")).SetString()) + func() { + defer func() { + if r := recover(); r != nil { + var _22_haltMessage = _dafny.SeqOfString(r.(string)) + { + _dafny.Print((_dafny.SeqOfString("FAILED\n ")).SetString()) + _dafny.Print((_22_haltMessage).SetString()) + _dafny.Print((_dafny.SeqOfString("\n")).SetString()) + _20_success = false + } + } + }() + { + WrappedSimplePositionalTest.Companion_Default___.TestWrappedClient() + { + _dafny.Print((_dafny.SeqOfString("PASSED\n")).SetString()) + } + } + }() + if !(_20_success) { + panic("(1,0): " + (_dafny.SeqOfString("Test failures occurred: see above.\n")).String()) + } +} + +// End of class Default__ +func main() { + defer _dafny.CatchHalt() + Companion_Default___.Test____Main____(_dafny.FromMainArguments(os.Args)) +} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/WrappedSimplePositionalTest/WrappedSimplePositionalTest.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/WrappedSimplePositionalTest/WrappedSimplePositionalTest.go new file mode 100644 index 0000000000..3213830225 --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/WrappedSimplePositionalTest/WrappedSimplePositionalTest.go @@ -0,0 +1,85 @@ +// Package WrappedSimplePositionalTest +// Dafny module WrappedSimplePositionalTest compiled into Go + +package WrappedSimplePositionalTest + +import ( + os "os" + + SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" + SimplePositionalImplTest "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImplTest" + SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" + simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + simplepositionalinternaldafnywrapped "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnywrapped" + _System "github.com/dafny-lang/DafnyRuntimeGo/System_" + _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" + StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" + StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" + StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" + Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +var _ = os.Args +var _ _dafny.Dummy__ +var _ _System.Dummy__ +var _ Wrappers.Dummy__ +var _ StandardLibrary_UInt.Dummy__ +var _ StandardLibrary.Dummy__ +var _ StandardLibraryInterop.Dummy__ +var _ SimpleResource.Dummy__ +var _ SimplePositionalImpl.Dummy__ +var _ SimplePositionalImplTest.Dummy__ + +type Dummy__ struct{} + +// Definition of class Default__ +type Default__ struct { + dummy byte +} + +func New_Default___() *Default__ { + _this := Default__{} + + return &_this +} + +type CompanionStruct_Default___ struct { +} + +var Companion_Default___ = CompanionStruct_Default___{} + +func (_this *Default__) Equals(other *Default__) bool { + return _this == other +} + +func (_this *Default__) EqualsGeneric(x interface{}) bool { + other, ok := x.(*Default__) + return ok && _this.Equals(other) +} + +func (*Default__) String() string { + return "WrappedSimplePositionalTest.Default__" +} +func (_this *Default__) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = &Default__{} + +func (_static *CompanionStruct_Default___) TestWrappedClient() { + var _18_client simplepositionalinternaldafnytypes.ISimplePositionalClient + _ = _18_client + var _19_valueOrError0 Wrappers.Result = Wrappers.Result{} + _ = _19_valueOrError0 + var _out9 Wrappers.Result + _ = _out9 + _out9 = simplepositionalinternaldafnywrapped.WrappedSimplePositional(simplepositionalinternaldafnywrapped.Companion_Default___.WrappedDefaultSimplePositionalConfig()) + _19_valueOrError0 = _out9 + if !(!((_19_valueOrError0).IsFailure())) { + panic("test/WrappedSimplePositionalTest.dfy(12,22): " + (_19_valueOrError0).String()) + } + _18_client = simplepositionalinternaldafnytypes.Companion_ISimplePositionalClient_.CastTo_((_19_valueOrError0).Extract()) + SimplePositionalImplTest.Companion_Default___.TestClient(_18_client) +} + +// End of class Default__ diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/api_client.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/api_client.go new file mode 100644 index 0000000000..8419c833fc --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/api_client.go @@ -0,0 +1,66 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "context" + + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafny" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" +) + +type Client struct { + DafnyClient *simplepositionalinternaldafny.SimplePositionalClient +} + +func NewClient(clientConfig simplepositionaltypes.SimplePositionalConfig) (*Client, error) { + var dafnyConfig = SimplePositionalConfig_ToDafny(clientConfig) + var dafny_response = simplepositionalinternaldafny.Companion_Default___.SimplePositional(dafnyConfig) + if dafny_response.Is_Failure() { + panic("Client construction failed. This should never happen") + } + var dafnyClient = dafny_response.Extract().(*simplepositionalinternaldafny.SimplePositionalClient) + client := &Client{dafnyClient} + return client, nil +} + +func (client *Client) GetResource(ctx context.Context, params simplepositionaltypes.GetResourceInput) (*simplepositionaltypes.GetResourceOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := &simplepositionaltypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + var dafny_request simplepositionalinternaldafnytypes.GetResourceInput = GetResourceInput_ToDafny(params) + var dafny_response = client.DafnyClient.GetResource(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetResourceOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourceOutput)) + return &native_response, nil + +} + +func (client *Client) GetResourcePositional(ctx context.Context, params simplepositionaltypes.GetResourcePositionalInput) (*simplepositionaltypes.GetResourcePositionalOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := &simplepositionaltypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + var dafny_request simplepositionalinternaldafnytypes.GetResourcePositionalInput = GetResourcePositionalInput_ToDafny(params) + var dafny_response = client.DafnyClient.GetResourcePositional(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetResourcePositionalOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourcePositionalOutput)) + return &native_response, nil + +} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/go.mod b/TestModels/Positional/runtimes/go/TestsFromDafny-go/go.mod new file mode 100644 index 0000000000..e852819557 --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/go.mod @@ -0,0 +1,11 @@ +module github.com/Smithy-dafny/TestModels/Positional + +go 1.22.2 + +require github.com/dafny-lang/DafnyStandardLibGo v0.0.0 + +require github.com/dafny-lang/DafnyRuntimeGo v0.0.0 + +replace github.com/dafny-lang/DafnyRuntimeGo => ../../../../../DafnyRuntimeGo/ + +replace github.com/dafny-lang/DafnyStandardLibGo => ../../../../dafny-dependencies/StandardLibrary/runtimes/go/ImplementationFromDafny-go/ diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/SimpleResource.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/SimpleResource.go new file mode 100644 index 0000000000..53f16e63ab --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/SimpleResource.go @@ -0,0 +1,34 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" +) + +type SimpleResource struct { + Impl simplepositionalinternaldafnytypes.ISimpleResource +} + +func (this *SimpleResource) GetName(params simplepositionaltypes.GetNameInput) (*simplepositionaltypes.GetNameOutput, error) { + var dafny_request simplepositionalinternaldafnytypes.GetNameInput = GetNameInput_ToDafny(params) + var dafny_response = this.Impl.GetName(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) + if err.Is_SimplePositionalException() { + return nil, SimplePositionalException_FromDafny(err) + } + + if err.Is_CollectionOfErrors() { + return nil, CollectionOfErrors_Output_FromDafny(err) + } + if err.Is_Opaque() { + return nil, OpaqueError_Output_FromDafny(err) + } + } + var native_response = GetNameOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetNameOutput)) + return &native_response, nil + +} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/api_client.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/api_client.go new file mode 100644 index 0000000000..8419c833fc --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/api_client.go @@ -0,0 +1,66 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "context" + + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafny" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" +) + +type Client struct { + DafnyClient *simplepositionalinternaldafny.SimplePositionalClient +} + +func NewClient(clientConfig simplepositionaltypes.SimplePositionalConfig) (*Client, error) { + var dafnyConfig = SimplePositionalConfig_ToDafny(clientConfig) + var dafny_response = simplepositionalinternaldafny.Companion_Default___.SimplePositional(dafnyConfig) + if dafny_response.Is_Failure() { + panic("Client construction failed. This should never happen") + } + var dafnyClient = dafny_response.Extract().(*simplepositionalinternaldafny.SimplePositionalClient) + client := &Client{dafnyClient} + return client, nil +} + +func (client *Client) GetResource(ctx context.Context, params simplepositionaltypes.GetResourceInput) (*simplepositionaltypes.GetResourceOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := &simplepositionaltypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + var dafny_request simplepositionalinternaldafnytypes.GetResourceInput = GetResourceInput_ToDafny(params) + var dafny_response = client.DafnyClient.GetResource(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetResourceOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourceOutput)) + return &native_response, nil + +} + +func (client *Client) GetResourcePositional(ctx context.Context, params simplepositionaltypes.GetResourcePositionalInput) (*simplepositionaltypes.GetResourcePositionalOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := &simplepositionaltypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + var dafny_request simplepositionalinternaldafnytypes.GetResourcePositionalInput = GetResourcePositionalInput_ToDafny(params) + var dafny_response = client.DafnyClient.GetResourcePositional(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetResourcePositionalOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourcePositionalOutput)) + return &native_response, nil + +} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_dafny.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_dafny.go new file mode 100644 index 0000000000..39442e0038 --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_dafny.go @@ -0,0 +1,144 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" + "github.com/dafny-lang/DafnyRuntimeGo/dafny" +) + +func GetResourceInput_ToDafny(nativeInput simplepositionaltypes.GetResourceInput) simplepositionalinternaldafnytypes.GetResourceInput { + + return func() simplepositionalinternaldafnytypes.GetResourceInput { + + return simplepositionalinternaldafnytypes.Companion_GetResourceInput_.Create_GetResourceInput_(func() dafny.Sequence { + if nativeInput.Name == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) + }()) + }() + +} + +func GetResourceOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourceOutput) simplepositionalinternaldafnytypes.GetResourceOutput { + + return func() simplepositionalinternaldafnytypes.GetResourceOutput { + + return simplepositionalinternaldafnytypes.Companion_GetResourceOutput_.Create_GetResourceOutput_(SimpleResource_ToDafny(nativeOutput.Output)) + }() + +} + +func GetResourcePositionalInput_ToDafny(nativeInput simplepositionaltypes.GetResourcePositionalInput) simplepositionalinternaldafnytypes.GetResourcePositionalInput { + + return func() simplepositionalinternaldafnytypes.GetResourcePositionalInput { + + return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalInput_.Create_GetResourcePositionalInput_(func() dafny.Sequence { + if nativeInput.Name == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) + }()) + }() + +} + +func GetResourcePositionalOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourcePositionalOutput) simplepositionalinternaldafnytypes.GetResourcePositionalOutput { + + return func() simplepositionalinternaldafnytypes.GetResourcePositionalOutput { + + return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalOutput_.Create_GetResourcePositionalOutput_(SimpleResource_ToDafny(nativeOutput.Output)) + }() + +} + +func GetNameInput_ToDafny(nativeInput simplepositionaltypes.GetNameInput) simplepositionalinternaldafnytypes.GetNameInput { + + return func() simplepositionalinternaldafnytypes.GetNameInput { + + return simplepositionalinternaldafnytypes.Companion_GetNameInput_.Create_GetNameInput_() + }() + +} + +func GetNameOutput_ToDafny(nativeOutput simplepositionaltypes.GetNameOutput) simplepositionalinternaldafnytypes.GetNameOutput { + + return func() simplepositionalinternaldafnytypes.GetNameOutput { + + return simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Create_GetNameOutput_(func() dafny.Sequence { + if nativeOutput.Name == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeOutput.Name)...) + }()) + }() + +} + +func SimpleResource_ToDafny(nativeResource simplepositionaltypes.ISimpleResource) simplepositionalinternaldafnytypes.ISimpleResource { + return nativeResource.(*SimpleResource).Impl + +} + +func SimplePositionalException_ToDafny(nativeInput simplepositionaltypes.SimplePositionalException) simplepositionalinternaldafnytypes.Error { + return func() simplepositionalinternaldafnytypes.Error { + + return simplepositionalinternaldafnytypes.Companion_Error_.Create_SimplePositionalException_(func() dafny.Sequence { + if nativeInput.Message == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeInput.Message)...) + }()) + }() + +} + +func CollectionOfErrors_Input_ToDafny(nativeInput simplepositionaltypes.CollectionOfErrors) simplepositionalinternaldafnytypes.Error { + var e []interface{} + for _, i2 := range nativeInput.ListOfErrors { + e = append(e, Error_ToDafny(i2)) + } + return simplepositionalinternaldafnytypes.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) +} +func OpaqueError_Input_ToDafny(nativeInput simplepositionaltypes.OpaqueError) simplepositionalinternaldafnytypes.Error { + return simplepositionalinternaldafnytypes.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) +} + +func Error_ToDafny(err error) simplepositionalinternaldafnytypes.Error { + switch err.(type) { + // Service Errors + case simplepositionaltypes.SimplePositionalException: + return SimplePositionalException_ToDafny(err.(simplepositionaltypes.SimplePositionalException)) + + //DependentErrors + + //Unmodelled Errors + case simplepositionaltypes.CollectionOfErrors: + return CollectionOfErrors_Input_ToDafny(err.(simplepositionaltypes.CollectionOfErrors)) + + default: + // TODO: Is changing from the commented code to this new one reasonable? + // return OpaqueError_Input_ToDafny(err.(*simpleconstraintstypes.OpaqueError)) + + // TODO: why is err a pointer? + error, ok := err.(*simplepositionaltypes.OpaqueError) + + if !ok { + panic("Error is not an OpaqueError") + } + if error == nil { + panic("Error is nil") + } + return OpaqueError_Input_ToDafny(*error) + } +} + +func SimplePositionalConfig_ToDafny(nativeInput simplepositionaltypes.SimplePositionalConfig) simplepositionalinternaldafnytypes.SimplePositionalConfig { + return func() simplepositionalinternaldafnytypes.SimplePositionalConfig { + + return simplepositionalinternaldafnytypes.Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() + }() + +} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_native.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_native.go new file mode 100644 index 0000000000..23328bb04f --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_native.go @@ -0,0 +1,160 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" + "github.com/dafny-lang/DafnyRuntimeGo/dafny" +) + +func GetResourceInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourceInput) simplepositionaltypes.GetResourceInput { + + return simplepositionaltypes.GetResourceInput{Name: func() *string { + var s string + if dafnyInput.Dtor_name() == nil { + return nil + } + for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func GetResourceOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourceOutput) simplepositionaltypes.GetResourceOutput { + + return simplepositionaltypes.GetResourceOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} + +} + +func GetResourcePositionalInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourcePositionalInput) simplepositionaltypes.GetResourcePositionalInput { + + return simplepositionaltypes.GetResourcePositionalInput{Name: func() *string { + var s string + if dafnyInput.Dtor_name() == nil { + return nil + } + for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func GetResourcePositionalOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourcePositionalOutput) simplepositionaltypes.GetResourcePositionalOutput { + + return simplepositionaltypes.GetResourcePositionalOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} + +} + +func GetNameInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetNameInput) simplepositionaltypes.GetNameInput { + + return simplepositionaltypes.GetNameInput{} + +} + +func GetNameOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetNameOutput) simplepositionaltypes.GetNameOutput { + + return simplepositionaltypes.GetNameOutput{Name: func() *string { + var s string + if dafnyOutput.Dtor_name() == nil { + return nil + } + for i := dafny.Iterate(dafnyOutput.Dtor_name()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func SimpleResource_FromDafny(dafnyResource simplepositionalinternaldafnytypes.ISimpleResource) simplepositionaltypes.ISimpleResource { + + return &SimpleResource{dafnyResource} +} + +func SimplePositionalException_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.SimplePositionalException { + return simplepositionaltypes.SimplePositionalException{Message: func() *string { + var s string + if dafnyOutput.Dtor_message() == nil { + return nil + } + for i := dafny.Iterate(dafnyOutput.Dtor_message()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func CollectionOfErrors_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.CollectionOfErrors { + listOfErrors := dafnyOutput.Dtor_list() + message := dafnyOutput.Dtor_message() + t := simplepositionaltypes.CollectionOfErrors{} + for i := dafny.Iterate(listOfErrors); ; { + val, ok := i() + if !ok { + break + } + err := val.(simplepositionalinternaldafnytypes.Error) + t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) + + } + t.Message = func() string { + var s string + for i := dafny.Iterate(message); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() + return t +} +func OpaqueError_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.OpaqueError { + return simplepositionaltypes.OpaqueError{ + ErrObject: dafnyOutput.Dtor_obj(), + } +} + +func Error_FromDafny(err simplepositionalinternaldafnytypes.Error) error { + // Service Errors + if err.Is_SimplePositionalException() { + return SimplePositionalException_FromDafny(err) + } + + //DependentErrors + + //Unmodelled Errors + if err.Is_CollectionOfErrors() { + return CollectionOfErrors_Output_FromDafny(err) + } + + return OpaqueError_Output_FromDafny(err) +} + +func SimplePositionalConfig_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.SimplePositionalConfig) simplepositionaltypes.SimplePositionalConfig { + return simplepositionaltypes.SimplePositionalConfig{} + +} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go new file mode 100644 index 0000000000..8679c91ebf --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go @@ -0,0 +1,175 @@ +// Package simplepositionalinternaldafny +// Dafny module simplepositionalinternaldafny compiled into Go + +package simplepositionalinternaldafny + +import ( + os "os" + + SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" + SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" + simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + _System "github.com/dafny-lang/DafnyRuntimeGo/System_" + _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" + StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" + StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" + StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" + Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +var _ = os.Args +var _ _dafny.Dummy__ +var _ _System.Dummy__ +var _ Wrappers.Dummy__ +var _ StandardLibrary_UInt.Dummy__ +var _ StandardLibrary.Dummy__ +var _ StandardLibraryInterop.Dummy__ +var _ SimpleResource.Dummy__ +var _ SimplePositionalImpl.Dummy__ + +type Dummy__ struct{} + +// Definition of class Default__ +type Default__ struct { + dummy byte +} + +func New_Default___() *Default__ { + _this := Default__{} + + return &_this +} + +type CompanionStruct_Default___ struct { +} + +var Companion_Default___ = CompanionStruct_Default___{} + +func (_this *Default__) Equals(other *Default__) bool { + return _this == other +} + +func (_this *Default__) EqualsGeneric(x interface{}) bool { + other, ok := x.(*Default__) + return ok && _this.Equals(other) +} + +func (*Default__) String() string { + return "simplepositionalinternaldafny.Default__" +} +func (_this *Default__) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = &Default__{} + +func (_static *CompanionStruct_Default___) DefaultSimplePositionalConfig() simplepositionalinternaldafnytypes.SimplePositionalConfig { + return simplepositionalinternaldafnytypes.Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() +} +func (_static *CompanionStruct_Default___) SimplePositional(config simplepositionalinternaldafnytypes.SimplePositionalConfig) Wrappers.Result { + var res Wrappers.Result = Wrappers.Result{} + _ = res + var _4_client *SimplePositionalClient + _ = _4_client + var _nw2 *SimplePositionalClient = New_SimplePositionalClient_() + _ = _nw2 + _nw2.Ctor__(SimplePositionalImpl.Companion_Config_.Create_Config_()) + _4_client = _nw2 + res = Wrappers.Companion_Result_.Create_Success_(_4_client) + return res + return res +} +func (_static *CompanionStruct_Default___) CreateSuccessOfClient(client simplepositionalinternaldafnytypes.ISimplePositionalClient) Wrappers.Result { + return Wrappers.Companion_Result_.Create_Success_(client) +} +func (_static *CompanionStruct_Default___) CreateFailureOfError(error_ simplepositionalinternaldafnytypes.Error) Wrappers.Result { + return Wrappers.Companion_Result_.Create_Failure_(error_) +} + +// End of class Default__ + +// Definition of class SimplePositionalClient +type SimplePositionalClient struct { + _config SimplePositionalImpl.Config +} + +func New_SimplePositionalClient_() *SimplePositionalClient { + _this := SimplePositionalClient{} + + _this._config = SimplePositionalImpl.Companion_Config_.Default() + return &_this +} + +type CompanionStruct_SimplePositionalClient_ struct { +} + +var Companion_SimplePositionalClient_ = CompanionStruct_SimplePositionalClient_{} + +func (_this *SimplePositionalClient) Equals(other *SimplePositionalClient) bool { + return _this == other +} + +func (_this *SimplePositionalClient) EqualsGeneric(x interface{}) bool { + other, ok := x.(*SimplePositionalClient) + return ok && _this.Equals(other) +} + +func (*SimplePositionalClient) String() string { + return "simplepositionalinternaldafny.SimplePositionalClient" +} + +func Type_SimplePositionalClient_() _dafny.TypeDescriptor { + return type_SimplePositionalClient_{} +} + +type type_SimplePositionalClient_ struct { +} + +func (_this type_SimplePositionalClient_) Default() interface{} { + return (*SimplePositionalClient)(nil) +} + +func (_this type_SimplePositionalClient_) String() string { + return "simplepositionalinternaldafny.SimplePositionalClient" +} +func (_this *SimplePositionalClient) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){simplepositionalinternaldafnytypes.Companion_ISimplePositionalClient_.TraitID_} +} + +var _ simplepositionalinternaldafnytypes.ISimplePositionalClient = &SimplePositionalClient{} +var _ _dafny.TraitOffspring = &SimplePositionalClient{} + +func (_this *SimplePositionalClient) Ctor__(config SimplePositionalImpl.Config) { + { + (_this)._config = config + } +} +func (_this *SimplePositionalClient) GetResource(input simplepositionalinternaldafnytypes.GetResourceInput) Wrappers.Result { + { + var output Wrappers.Result = Wrappers.Result{} + _ = output + var _out2 Wrappers.Result + _ = _out2 + _out2 = SimplePositionalImpl.Companion_Default___.GetResource((_this).Config(), input) + output = _out2 + return output + } +} +func (_this *SimplePositionalClient) GetResourcePositional(input _dafny.Sequence) Wrappers.Result { + { + var output Wrappers.Result = Wrappers.Result{} + _ = output + var _out3 Wrappers.Result + _ = _out3 + _out3 = SimplePositionalImpl.Companion_Default___.GetResourcePositional((_this).Config(), input) + output = _out3 + return output + } +} +func (_this *SimplePositionalClient) Config() SimplePositionalImpl.Config { + { + return _this._config + } +} + +// End of class SimplePositionalClient diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go new file mode 100644 index 0000000000..45ca0af901 --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go @@ -0,0 +1,993 @@ +// Package simplepositionalinternaldafnytypes +// Dafny module simplepositionalinternaldafnytypes compiled into Go + +package simplepositionalinternaldafnytypes + +import ( + os "os" + + _System "github.com/dafny-lang/DafnyRuntimeGo/System_" + _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" + StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" + StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" + StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" + Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +var _ = os.Args +var _ _dafny.Dummy__ +var _ _System.Dummy__ +var _ Wrappers.Dummy__ +var _ StandardLibrary_UInt.Dummy__ +var _ StandardLibrary.Dummy__ +var _ StandardLibraryInterop.Dummy__ + +type Dummy__ struct{} + +// Definition of datatype DafnyCallEvent +type DafnyCallEvent struct { + Data_DafnyCallEvent_ +} + +func (_this DafnyCallEvent) Get_() Data_DafnyCallEvent_ { + return _this.Data_DafnyCallEvent_ +} + +type Data_DafnyCallEvent_ interface { + isDafnyCallEvent() +} + +type CompanionStruct_DafnyCallEvent_ struct { +} + +var Companion_DafnyCallEvent_ = CompanionStruct_DafnyCallEvent_{} + +type DafnyCallEvent_DafnyCallEvent struct { + Input interface{} + Output interface{} +} + +func (DafnyCallEvent_DafnyCallEvent) isDafnyCallEvent() {} + +func (CompanionStruct_DafnyCallEvent_) Create_DafnyCallEvent_(Input interface{}, Output interface{}) DafnyCallEvent { + return DafnyCallEvent{DafnyCallEvent_DafnyCallEvent{Input, Output}} +} + +func (_this DafnyCallEvent) Is_DafnyCallEvent() bool { + _, ok := _this.Get_().(DafnyCallEvent_DafnyCallEvent) + return ok +} + +func (CompanionStruct_DafnyCallEvent_) Default(_default_I interface{}, _default_O interface{}) DafnyCallEvent { + return Companion_DafnyCallEvent_.Create_DafnyCallEvent_(_default_I, _default_O) +} + +func (_this DafnyCallEvent) Dtor_input() interface{} { + return _this.Get_().(DafnyCallEvent_DafnyCallEvent).Input +} + +func (_this DafnyCallEvent) Dtor_output() interface{} { + return _this.Get_().(DafnyCallEvent_DafnyCallEvent).Output +} + +func (_this DafnyCallEvent) String() string { + switch data := _this.Get_().(type) { + case nil: + return "null" + case DafnyCallEvent_DafnyCallEvent: + { + return "SimplePositionalTypes.DafnyCallEvent.DafnyCallEvent" + "(" + _dafny.String(data.Input) + ", " + _dafny.String(data.Output) + ")" + } + default: + { + return "" + } + } +} + +func (_this DafnyCallEvent) Equals(other DafnyCallEvent) bool { + switch data1 := _this.Get_().(type) { + case DafnyCallEvent_DafnyCallEvent: + { + data2, ok := other.Get_().(DafnyCallEvent_DafnyCallEvent) + return ok && _dafny.AreEqual(data1.Input, data2.Input) && _dafny.AreEqual(data1.Output, data2.Output) + } + default: + { + return false // unexpected + } + } +} + +func (_this DafnyCallEvent) EqualsGeneric(other interface{}) bool { + typed, ok := other.(DafnyCallEvent) + return ok && _this.Equals(typed) +} + +func Type_DafnyCallEvent_(Type_I_ _dafny.TypeDescriptor, Type_O_ _dafny.TypeDescriptor) _dafny.TypeDescriptor { + return type_DafnyCallEvent_{Type_I_, Type_O_} +} + +type type_DafnyCallEvent_ struct { + Type_I_ _dafny.TypeDescriptor + Type_O_ _dafny.TypeDescriptor +} + +func (_this type_DafnyCallEvent_) Default() interface{} { + Type_I_ := _this.Type_I_ + _ = Type_I_ + Type_O_ := _this.Type_O_ + _ = Type_O_ + return Companion_DafnyCallEvent_.Default(Type_I_.Default(), Type_O_.Default()) +} + +func (_this type_DafnyCallEvent_) String() string { + return "simplepositionalinternaldafnytypes.DafnyCallEvent" +} +func (_this DafnyCallEvent) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = DafnyCallEvent{} + +// End of datatype DafnyCallEvent + +// Definition of datatype GetNameInput +type GetNameInput struct { + Data_GetNameInput_ +} + +func (_this GetNameInput) Get_() Data_GetNameInput_ { + return _this.Data_GetNameInput_ +} + +type Data_GetNameInput_ interface { + isGetNameInput() +} + +type CompanionStruct_GetNameInput_ struct { +} + +var Companion_GetNameInput_ = CompanionStruct_GetNameInput_{} + +type GetNameInput_GetNameInput struct { +} + +func (GetNameInput_GetNameInput) isGetNameInput() {} + +func (CompanionStruct_GetNameInput_) Create_GetNameInput_() GetNameInput { + return GetNameInput{GetNameInput_GetNameInput{}} +} + +func (_this GetNameInput) Is_GetNameInput() bool { + _, ok := _this.Get_().(GetNameInput_GetNameInput) + return ok +} + +func (CompanionStruct_GetNameInput_) Default() GetNameInput { + return Companion_GetNameInput_.Create_GetNameInput_() +} + +func (_ CompanionStruct_GetNameInput_) AllSingletonConstructors() _dafny.Iterator { + i := -1 + return func() (interface{}, bool) { + i++ + switch i { + case 0: + return Companion_GetNameInput_.Create_GetNameInput_(), true + default: + return GetNameInput{}, false + } + } +} + +func (_this GetNameInput) String() string { + switch _this.Get_().(type) { + case nil: + return "null" + case GetNameInput_GetNameInput: + { + return "SimplePositionalTypes.GetNameInput.GetNameInput" + } + default: + { + return "" + } + } +} + +func (_this GetNameInput) Equals(other GetNameInput) bool { + switch _this.Get_().(type) { + case GetNameInput_GetNameInput: + { + _, ok := other.Get_().(GetNameInput_GetNameInput) + return ok + } + default: + { + return false // unexpected + } + } +} + +func (_this GetNameInput) EqualsGeneric(other interface{}) bool { + typed, ok := other.(GetNameInput) + return ok && _this.Equals(typed) +} + +func Type_GetNameInput_() _dafny.TypeDescriptor { + return type_GetNameInput_{} +} + +type type_GetNameInput_ struct { +} + +func (_this type_GetNameInput_) Default() interface{} { + return Companion_GetNameInput_.Default() +} + +func (_this type_GetNameInput_) String() string { + return "simplepositionalinternaldafnytypes.GetNameInput" +} +func (_this GetNameInput) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = GetNameInput{} + +// End of datatype GetNameInput + +// Definition of datatype GetNameOutput +type GetNameOutput struct { + Data_GetNameOutput_ +} + +func (_this GetNameOutput) Get_() Data_GetNameOutput_ { + return _this.Data_GetNameOutput_ +} + +type Data_GetNameOutput_ interface { + isGetNameOutput() +} + +type CompanionStruct_GetNameOutput_ struct { +} + +var Companion_GetNameOutput_ = CompanionStruct_GetNameOutput_{} + +type GetNameOutput_GetNameOutput struct { + Name _dafny.Sequence +} + +func (GetNameOutput_GetNameOutput) isGetNameOutput() {} + +func (CompanionStruct_GetNameOutput_) Create_GetNameOutput_(Name _dafny.Sequence) GetNameOutput { + return GetNameOutput{GetNameOutput_GetNameOutput{Name}} +} + +func (_this GetNameOutput) Is_GetNameOutput() bool { + _, ok := _this.Get_().(GetNameOutput_GetNameOutput) + return ok +} + +func (CompanionStruct_GetNameOutput_) Default() GetNameOutput { + return Companion_GetNameOutput_.Create_GetNameOutput_(_dafny.EmptySeq.SetString()) +} + +func (_this GetNameOutput) Dtor_name() _dafny.Sequence { + return _this.Get_().(GetNameOutput_GetNameOutput).Name +} + +func (_this GetNameOutput) String() string { + switch data := _this.Get_().(type) { + case nil: + return "null" + case GetNameOutput_GetNameOutput: + { + return "SimplePositionalTypes.GetNameOutput.GetNameOutput" + "(" + _dafny.String(data.Name) + ")" + } + default: + { + return "" + } + } +} + +func (_this GetNameOutput) Equals(other GetNameOutput) bool { + switch data1 := _this.Get_().(type) { + case GetNameOutput_GetNameOutput: + { + data2, ok := other.Get_().(GetNameOutput_GetNameOutput) + return ok && data1.Name.Equals(data2.Name) + } + default: + { + return false // unexpected + } + } +} + +func (_this GetNameOutput) EqualsGeneric(other interface{}) bool { + typed, ok := other.(GetNameOutput) + return ok && _this.Equals(typed) +} + +func Type_GetNameOutput_() _dafny.TypeDescriptor { + return type_GetNameOutput_{} +} + +type type_GetNameOutput_ struct { +} + +func (_this type_GetNameOutput_) Default() interface{} { + return Companion_GetNameOutput_.Default() +} + +func (_this type_GetNameOutput_) String() string { + return "simplepositionalinternaldafnytypes.GetNameOutput" +} +func (_this GetNameOutput) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = GetNameOutput{} + +// End of datatype GetNameOutput + +// Definition of datatype GetResourceInput +type GetResourceInput struct { + Data_GetResourceInput_ +} + +func (_this GetResourceInput) Get_() Data_GetResourceInput_ { + return _this.Data_GetResourceInput_ +} + +type Data_GetResourceInput_ interface { + isGetResourceInput() +} + +type CompanionStruct_GetResourceInput_ struct { +} + +var Companion_GetResourceInput_ = CompanionStruct_GetResourceInput_{} + +type GetResourceInput_GetResourceInput struct { + Name _dafny.Sequence +} + +func (GetResourceInput_GetResourceInput) isGetResourceInput() {} + +func (CompanionStruct_GetResourceInput_) Create_GetResourceInput_(Name _dafny.Sequence) GetResourceInput { + return GetResourceInput{GetResourceInput_GetResourceInput{Name}} +} + +func (_this GetResourceInput) Is_GetResourceInput() bool { + _, ok := _this.Get_().(GetResourceInput_GetResourceInput) + return ok +} + +func (CompanionStruct_GetResourceInput_) Default() GetResourceInput { + return Companion_GetResourceInput_.Create_GetResourceInput_(_dafny.EmptySeq.SetString()) +} + +func (_this GetResourceInput) Dtor_name() _dafny.Sequence { + return _this.Get_().(GetResourceInput_GetResourceInput).Name +} + +func (_this GetResourceInput) String() string { + switch data := _this.Get_().(type) { + case nil: + return "null" + case GetResourceInput_GetResourceInput: + { + return "SimplePositionalTypes.GetResourceInput.GetResourceInput" + "(" + _dafny.String(data.Name) + ")" + } + default: + { + return "" + } + } +} + +func (_this GetResourceInput) Equals(other GetResourceInput) bool { + switch data1 := _this.Get_().(type) { + case GetResourceInput_GetResourceInput: + { + data2, ok := other.Get_().(GetResourceInput_GetResourceInput) + return ok && data1.Name.Equals(data2.Name) + } + default: + { + return false // unexpected + } + } +} + +func (_this GetResourceInput) EqualsGeneric(other interface{}) bool { + typed, ok := other.(GetResourceInput) + return ok && _this.Equals(typed) +} + +func Type_GetResourceInput_() _dafny.TypeDescriptor { + return type_GetResourceInput_{} +} + +type type_GetResourceInput_ struct { +} + +func (_this type_GetResourceInput_) Default() interface{} { + return Companion_GetResourceInput_.Default() +} + +func (_this type_GetResourceInput_) String() string { + return "simplepositionalinternaldafnytypes.GetResourceInput" +} +func (_this GetResourceInput) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = GetResourceInput{} + +// End of datatype GetResourceInput + +// Definition of datatype GetResourceOutput +type GetResourceOutput struct { + Data_GetResourceOutput_ +} + +func (_this GetResourceOutput) Get_() Data_GetResourceOutput_ { + return _this.Data_GetResourceOutput_ +} + +type Data_GetResourceOutput_ interface { + isGetResourceOutput() +} + +type CompanionStruct_GetResourceOutput_ struct { +} + +var Companion_GetResourceOutput_ = CompanionStruct_GetResourceOutput_{} + +type GetResourceOutput_GetResourceOutput struct { + Output ISimpleResource +} + +func (GetResourceOutput_GetResourceOutput) isGetResourceOutput() {} + +func (CompanionStruct_GetResourceOutput_) Create_GetResourceOutput_(Output ISimpleResource) GetResourceOutput { + return GetResourceOutput{GetResourceOutput_GetResourceOutput{Output}} +} + +func (_this GetResourceOutput) Is_GetResourceOutput() bool { + _, ok := _this.Get_().(GetResourceOutput_GetResourceOutput) + return ok +} + +func (CompanionStruct_GetResourceOutput_) Default() GetResourceOutput { + return Companion_GetResourceOutput_.Create_GetResourceOutput_((ISimpleResource)(nil)) +} + +func (_this GetResourceOutput) Dtor_output() ISimpleResource { + return _this.Get_().(GetResourceOutput_GetResourceOutput).Output +} + +func (_this GetResourceOutput) String() string { + switch data := _this.Get_().(type) { + case nil: + return "null" + case GetResourceOutput_GetResourceOutput: + { + return "SimplePositionalTypes.GetResourceOutput.GetResourceOutput" + "(" + _dafny.String(data.Output) + ")" + } + default: + { + return "" + } + } +} + +func (_this GetResourceOutput) Equals(other GetResourceOutput) bool { + switch data1 := _this.Get_().(type) { + case GetResourceOutput_GetResourceOutput: + { + data2, ok := other.Get_().(GetResourceOutput_GetResourceOutput) + return ok && _dafny.AreEqual(data1.Output, data2.Output) + } + default: + { + return false // unexpected + } + } +} + +func (_this GetResourceOutput) EqualsGeneric(other interface{}) bool { + typed, ok := other.(GetResourceOutput) + return ok && _this.Equals(typed) +} + +func Type_GetResourceOutput_() _dafny.TypeDescriptor { + return type_GetResourceOutput_{} +} + +type type_GetResourceOutput_ struct { +} + +func (_this type_GetResourceOutput_) Default() interface{} { + return Companion_GetResourceOutput_.Default() +} + +func (_this type_GetResourceOutput_) String() string { + return "simplepositionalinternaldafnytypes.GetResourceOutput" +} +func (_this GetResourceOutput) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = GetResourceOutput{} + +// End of datatype GetResourceOutput + +// Definition of class ISimplePositionalClientCallHistory +type ISimplePositionalClientCallHistory struct { + dummy byte +} + +func New_ISimplePositionalClientCallHistory_() *ISimplePositionalClientCallHistory { + _this := ISimplePositionalClientCallHistory{} + + return &_this +} + +type CompanionStruct_ISimplePositionalClientCallHistory_ struct { +} + +var Companion_ISimplePositionalClientCallHistory_ = CompanionStruct_ISimplePositionalClientCallHistory_{} + +func (_this *ISimplePositionalClientCallHistory) Equals(other *ISimplePositionalClientCallHistory) bool { + return _this == other +} + +func (_this *ISimplePositionalClientCallHistory) EqualsGeneric(x interface{}) bool { + other, ok := x.(*ISimplePositionalClientCallHistory) + return ok && _this.Equals(other) +} + +func (*ISimplePositionalClientCallHistory) String() string { + return "simplepositionalinternaldafnytypes.ISimplePositionalClientCallHistory" +} + +func Type_ISimplePositionalClientCallHistory_() _dafny.TypeDescriptor { + return type_ISimplePositionalClientCallHistory_{} +} + +type type_ISimplePositionalClientCallHistory_ struct { +} + +func (_this type_ISimplePositionalClientCallHistory_) Default() interface{} { + return (*ISimplePositionalClientCallHistory)(nil) +} + +func (_this type_ISimplePositionalClientCallHistory_) String() string { + return "simplepositionalinternaldafnytypes.ISimplePositionalClientCallHistory" +} +func (_this *ISimplePositionalClientCallHistory) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = &ISimplePositionalClientCallHistory{} + +// End of class ISimplePositionalClientCallHistory + +// Definition of trait ISimplePositionalClient +type ISimplePositionalClient interface { + String() string + GetResource(input GetResourceInput) Wrappers.Result + GetResourcePositional(input _dafny.Sequence) Wrappers.Result +} +type CompanionStruct_ISimplePositionalClient_ struct { + TraitID_ *_dafny.TraitID +} + +var Companion_ISimplePositionalClient_ = CompanionStruct_ISimplePositionalClient_{ + TraitID_: &_dafny.TraitID{}, +} + +func (CompanionStruct_ISimplePositionalClient_) CastTo_(x interface{}) ISimplePositionalClient { + var t ISimplePositionalClient + t, _ = x.(ISimplePositionalClient) + return t +} + +// End of trait ISimplePositionalClient + +// Definition of datatype SimplePositionalConfig +type SimplePositionalConfig struct { + Data_SimplePositionalConfig_ +} + +func (_this SimplePositionalConfig) Get_() Data_SimplePositionalConfig_ { + return _this.Data_SimplePositionalConfig_ +} + +type Data_SimplePositionalConfig_ interface { + isSimplePositionalConfig() +} + +type CompanionStruct_SimplePositionalConfig_ struct { +} + +var Companion_SimplePositionalConfig_ = CompanionStruct_SimplePositionalConfig_{} + +type SimplePositionalConfig_SimplePositionalConfig struct { +} + +func (SimplePositionalConfig_SimplePositionalConfig) isSimplePositionalConfig() {} + +func (CompanionStruct_SimplePositionalConfig_) Create_SimplePositionalConfig_() SimplePositionalConfig { + return SimplePositionalConfig{SimplePositionalConfig_SimplePositionalConfig{}} +} + +func (_this SimplePositionalConfig) Is_SimplePositionalConfig() bool { + _, ok := _this.Get_().(SimplePositionalConfig_SimplePositionalConfig) + return ok +} + +func (CompanionStruct_SimplePositionalConfig_) Default() SimplePositionalConfig { + return Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() +} + +func (_ CompanionStruct_SimplePositionalConfig_) AllSingletonConstructors() _dafny.Iterator { + i := -1 + return func() (interface{}, bool) { + i++ + switch i { + case 0: + return Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_(), true + default: + return SimplePositionalConfig{}, false + } + } +} + +func (_this SimplePositionalConfig) String() string { + switch _this.Get_().(type) { + case nil: + return "null" + case SimplePositionalConfig_SimplePositionalConfig: + { + return "SimplePositionalTypes.SimplePositionalConfig.SimplePositionalConfig" + } + default: + { + return "" + } + } +} + +func (_this SimplePositionalConfig) Equals(other SimplePositionalConfig) bool { + switch _this.Get_().(type) { + case SimplePositionalConfig_SimplePositionalConfig: + { + _, ok := other.Get_().(SimplePositionalConfig_SimplePositionalConfig) + return ok + } + default: + { + return false // unexpected + } + } +} + +func (_this SimplePositionalConfig) EqualsGeneric(other interface{}) bool { + typed, ok := other.(SimplePositionalConfig) + return ok && _this.Equals(typed) +} + +func Type_SimplePositionalConfig_() _dafny.TypeDescriptor { + return type_SimplePositionalConfig_{} +} + +type type_SimplePositionalConfig_ struct { +} + +func (_this type_SimplePositionalConfig_) Default() interface{} { + return Companion_SimplePositionalConfig_.Default() +} + +func (_this type_SimplePositionalConfig_) String() string { + return "simplepositionalinternaldafnytypes.SimplePositionalConfig" +} +func (_this SimplePositionalConfig) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = SimplePositionalConfig{} + +// End of datatype SimplePositionalConfig + +// Definition of class ISimpleResourceCallHistory +type ISimpleResourceCallHistory struct { + dummy byte +} + +func New_ISimpleResourceCallHistory_() *ISimpleResourceCallHistory { + _this := ISimpleResourceCallHistory{} + + return &_this +} + +type CompanionStruct_ISimpleResourceCallHistory_ struct { +} + +var Companion_ISimpleResourceCallHistory_ = CompanionStruct_ISimpleResourceCallHistory_{} + +func (_this *ISimpleResourceCallHistory) Equals(other *ISimpleResourceCallHistory) bool { + return _this == other +} + +func (_this *ISimpleResourceCallHistory) EqualsGeneric(x interface{}) bool { + other, ok := x.(*ISimpleResourceCallHistory) + return ok && _this.Equals(other) +} + +func (*ISimpleResourceCallHistory) String() string { + return "simplepositionalinternaldafnytypes.ISimpleResourceCallHistory" +} + +func Type_ISimpleResourceCallHistory_() _dafny.TypeDescriptor { + return type_ISimpleResourceCallHistory_{} +} + +type type_ISimpleResourceCallHistory_ struct { +} + +func (_this type_ISimpleResourceCallHistory_) Default() interface{} { + return (*ISimpleResourceCallHistory)(nil) +} + +func (_this type_ISimpleResourceCallHistory_) String() string { + return "simplepositionalinternaldafnytypes.ISimpleResourceCallHistory" +} +func (_this *ISimpleResourceCallHistory) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = &ISimpleResourceCallHistory{} + +// End of class ISimpleResourceCallHistory + +// Definition of trait ISimpleResource +type ISimpleResource interface { + String() string + GetName(input GetNameInput) Wrappers.Result + GetName_k(input GetNameInput) Wrappers.Result +} + +func (_static *CompanionStruct_ISimpleResource_) GetName(_this ISimpleResource, input GetNameInput) Wrappers.Result { + { + var output Wrappers.Result = Wrappers.Companion_Result_.Default(Companion_GetNameOutput_.Default()) + _ = output + var _out0 Wrappers.Result + _ = _out0 + _out0 = (_this).GetName_k(input) + output = _out0 + return output + } +} + +type CompanionStruct_ISimpleResource_ struct { + TraitID_ *_dafny.TraitID +} + +var Companion_ISimpleResource_ = CompanionStruct_ISimpleResource_{ + TraitID_: &_dafny.TraitID{}, +} + +func (CompanionStruct_ISimpleResource_) CastTo_(x interface{}) ISimpleResource { + var t ISimpleResource + t, _ = x.(ISimpleResource) + return t +} + +// End of trait ISimpleResource + +// Definition of datatype Error +type Error struct { + Data_Error_ +} + +func (_this Error) Get_() Data_Error_ { + return _this.Data_Error_ +} + +type Data_Error_ interface { + isError() +} + +type CompanionStruct_Error_ struct { +} + +var Companion_Error_ = CompanionStruct_Error_{} + +type Error_SimplePositionalException struct { + Message _dafny.Sequence +} + +func (Error_SimplePositionalException) isError() {} + +func (CompanionStruct_Error_) Create_SimplePositionalException_(Message _dafny.Sequence) Error { + return Error{Error_SimplePositionalException{Message}} +} + +func (_this Error) Is_SimplePositionalException() bool { + _, ok := _this.Get_().(Error_SimplePositionalException) + return ok +} + +type Error_CollectionOfErrors struct { + List _dafny.Sequence + Message _dafny.Sequence +} + +func (Error_CollectionOfErrors) isError() {} + +func (CompanionStruct_Error_) Create_CollectionOfErrors_(List _dafny.Sequence, Message _dafny.Sequence) Error { + return Error{Error_CollectionOfErrors{List, Message}} +} + +func (_this Error) Is_CollectionOfErrors() bool { + _, ok := _this.Get_().(Error_CollectionOfErrors) + return ok +} + +type Error_Opaque struct { + Obj interface{} +} + +func (Error_Opaque) isError() {} + +func (CompanionStruct_Error_) Create_Opaque_(Obj interface{}) Error { + return Error{Error_Opaque{Obj}} +} + +func (_this Error) Is_Opaque() bool { + _, ok := _this.Get_().(Error_Opaque) + return ok +} + +func (CompanionStruct_Error_) Default() Error { + return Companion_Error_.Create_SimplePositionalException_(_dafny.EmptySeq.SetString()) +} + +func (_this Error) Dtor_message() _dafny.Sequence { + switch data := _this.Get_().(type) { + case Error_SimplePositionalException: + return data.Message + default: + return data.(Error_CollectionOfErrors).Message + } +} + +func (_this Error) Dtor_list() _dafny.Sequence { + return _this.Get_().(Error_CollectionOfErrors).List +} + +func (_this Error) Dtor_obj() interface{} { + return _this.Get_().(Error_Opaque).Obj +} + +func (_this Error) String() string { + switch data := _this.Get_().(type) { + case nil: + return "null" + case Error_SimplePositionalException: + { + return "SimplePositionalTypes.Error.SimplePositionalException" + "(" + _dafny.String(data.Message) + ")" + } + case Error_CollectionOfErrors: + { + return "SimplePositionalTypes.Error.CollectionOfErrors" + "(" + _dafny.String(data.List) + ", " + _dafny.String(data.Message) + ")" + } + case Error_Opaque: + { + return "SimplePositionalTypes.Error.Opaque" + "(" + _dafny.String(data.Obj) + ")" + } + default: + { + return "" + } + } +} + +func (_this Error) Equals(other Error) bool { + switch data1 := _this.Get_().(type) { + case Error_SimplePositionalException: + { + data2, ok := other.Get_().(Error_SimplePositionalException) + return ok && data1.Message.Equals(data2.Message) + } + case Error_CollectionOfErrors: + { + data2, ok := other.Get_().(Error_CollectionOfErrors) + return ok && data1.List.Equals(data2.List) && data1.Message.Equals(data2.Message) + } + case Error_Opaque: + { + data2, ok := other.Get_().(Error_Opaque) + return ok && _dafny.AreEqual(data1.Obj, data2.Obj) + } + default: + { + return false // unexpected + } + } +} + +func (_this Error) EqualsGeneric(other interface{}) bool { + typed, ok := other.(Error) + return ok && _this.Equals(typed) +} + +func Type_Error_() _dafny.TypeDescriptor { + return type_Error_{} +} + +type type_Error_ struct { +} + +func (_this type_Error_) Default() interface{} { + return Companion_Error_.Default() +} + +func (_this type_Error_) String() string { + return "simplepositionalinternaldafnytypes.Error" +} +func (_this Error) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = Error{} + +// End of datatype Error + +// Definition of class OpaqueError +type OpaqueError struct { +} + +func New_OpaqueError_() *OpaqueError { + _this := OpaqueError{} + + return &_this +} + +type CompanionStruct_OpaqueError_ struct { +} + +var Companion_OpaqueError_ = CompanionStruct_OpaqueError_{} + +func (*OpaqueError) String() string { + return "simplepositionalinternaldafnytypes.OpaqueError" +} + +// End of class OpaqueError + +func Type_OpaqueError_() _dafny.TypeDescriptor { + return type_OpaqueError_{} +} + +type type_OpaqueError_ struct { +} + +func (_this type_OpaqueError_) Default() interface{} { + return Companion_Error_.Default() +} + +func (_this type_OpaqueError_) String() string { + return "simplepositionalinternaldafnytypes.OpaqueError" +} +func (_this *CompanionStruct_OpaqueError_) Is_(__source Error) bool { + var _0_e Error = (__source) + _ = _0_e + return (_0_e).Is_Opaque() +} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/shim.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/shim.go new file mode 100644 index 0000000000..d173c74f17 --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/shim.go @@ -0,0 +1,43 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositionalinternaldafnywrapped + +import ( + "context" + + "github.com/Smithy-dafny/TestModels/Positional/simplepositional" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +type Shim struct { + simplepositionalinternaldafnytypes.ISimplePositionalClient + client *simplepositional.Client +} + +func WrappedSimplePositional(inputConfig simplepositionalinternaldafnytypes.SimplePositionalConfig) Wrappers.Result { + var nativeConfig = simplepositional.SimplePositionalConfig_FromDafny(inputConfig) + var nativeClient, nativeError = simplepositional.NewClient(nativeConfig) + if nativeError != nil { + return Wrappers.Companion_Result_.Create_Failure_(simplepositionalinternaldafnytypes.Companion_Error_.Create_Opaque_(nativeError)) + } + return Wrappers.Companion_Result_.Create_Success_(&Shim{client: nativeClient}) +} + +func (shim *Shim) GetResource(input simplepositionalinternaldafnytypes.GetResourceInput) Wrappers.Result { + var native_request = simplepositional.GetResourceInput_FromDafny(input) + var native_response, native_error = shim.client.GetResource(context.Background(), native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(simplepositional.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(simplepositional.GetResourceOutput_ToDafny(*native_response)) +} + +func (shim *Shim) GetResourcePositional(input simplepositionalinternaldafnytypes.GetResourcePositionalInput) Wrappers.Result { + var native_request = simplepositional.GetResourcePositionalInput_FromDafny(input) + var native_response, native_error = shim.client.GetResourcePositional(context.Background(), native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(simplepositional.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(simplepositional.GetResourcePositionalOutput_ToDafny(*native_response)) +} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/simplepositionalinternaldafnywrapped.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/simplepositionalinternaldafnywrapped.go new file mode 100644 index 0000000000..0aaee5aa66 --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/simplepositionalinternaldafnywrapped.go @@ -0,0 +1,70 @@ +// Package simplepositionalinternaldafnywrapped +// Dafny module simplepositionalinternaldafnywrapped compiled into Go + +package simplepositionalinternaldafnywrapped + +import ( + os "os" + + SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" + SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" + simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + _System "github.com/dafny-lang/DafnyRuntimeGo/System_" + _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" + StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" + StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" + StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" + Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" +) + +var _ = os.Args +var _ _dafny.Dummy__ +var _ _System.Dummy__ +var _ Wrappers.Dummy__ +var _ StandardLibrary_UInt.Dummy__ +var _ StandardLibrary.Dummy__ +var _ StandardLibraryInterop.Dummy__ +var _ SimpleResource.Dummy__ +var _ SimplePositionalImpl.Dummy__ + +type Dummy__ struct{} + +// Definition of class Default__ +type Default__ struct { + dummy byte +} + +func New_Default___() *Default__ { + _this := Default__{} + + return &_this +} + +type CompanionStruct_Default___ struct { +} + +var Companion_Default___ = CompanionStruct_Default___{} + +func (_this *Default__) Equals(other *Default__) bool { + return _this == other +} + +func (_this *Default__) EqualsGeneric(x interface{}) bool { + other, ok := x.(*Default__) + return ok && _this.Equals(other) +} + +func (*Default__) String() string { + return "simplepositionalinternaldafnywrapped.Default__" +} +func (_this *Default__) ParentTraits_() []*_dafny.TraitID { + return [](*_dafny.TraitID){} +} + +var _ _dafny.TraitOffspring = &Default__{} + +func (_static *CompanionStruct_Default___) WrappedDefaultSimplePositionalConfig() simplepositionalinternaldafnytypes.SimplePositionalConfig { + return simplepositionalinternaldafnytypes.Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() +} + +// End of class Default__ diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/errors.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/errors.go new file mode 100644 index 0000000000..a4f1fdaf51 --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/errors.go @@ -0,0 +1,18 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositionaltypes + +import ( + "fmt" +) + +type SimplePositionalException struct { + SimplePositionalBaseException + Message *string + + ErrorCodeOverride *string +} + +func (e SimplePositionalException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/types.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/types.go new file mode 100644 index 0000000000..84ddf62564 --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/types.go @@ -0,0 +1,93 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositionaltypes + +import ( + "fmt" +) + +type GetResourceInput struct { + Name *string +} + +func (input GetResourceInput) Validate() error { + if input.Name == nil { + return fmt.Errorf("Name is required but has a nil value.") + } + + return nil +} + +type SimpleResourceReference struct { +} + +func (input SimpleResourceReference) Validate() error { + return nil +} + +type GetResourceOutput struct { + Output ISimpleResource +} + +func (input GetResourceOutput) Validate() error { + + return nil +} + +type GetResourcePositionalInput struct { + Name *string +} + +func (input GetResourcePositionalInput) Validate() error { + if input.Name == nil { + return fmt.Errorf("Name is required but has a nil value.") + } + + return nil +} + +type GetResourcePositionalOutput struct { + Output ISimpleResource +} + +func (input GetResourcePositionalOutput) Validate() error { + + return nil +} + +type SimplePositionalConfig struct { +} + +func (input SimplePositionalConfig) Validate() error { + return nil +} + +type SimplePositionalBaseException interface { + // This is a dummy method to allow type assertion since Go empty interfaces + // aren't useful for type assertion checks. No concrete class is expected to implement + // this method. This is also not exported. + interfaceBindingMethod() +} + +type ISimpleResource interface { + GetName(GetNameInput) (*GetNameOutput, error) +} + +type GetNameInput struct { +} + +func (input GetNameInput) Validate() error { + return nil +} + +type GetNameOutput struct { + Name *string +} + +func (input GetNameOutput) Validate() error { + if input.Name == nil { + return fmt.Errorf("Name is required but has a nil value.") + } + + return nil +} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/unmodelled_errors.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/unmodelled_errors.go new file mode 100644 index 0000000000..33aff14a2c --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/unmodelled_errors.go @@ -0,0 +1,26 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositionaltypes + +import ( + "fmt" +) + +type CollectionOfErrors struct { + SimplePositionalBaseException + ListOfErrors []error + Message string +} + +func (e CollectionOfErrors) Error() string { + return fmt.Sprintf("message: %s\n err %v", e.Message, e.ListOfErrors) +} + +type OpaqueError struct { + SimplePositionalBaseException + ErrObject interface{} +} + +func (e OpaqueError) Error() string { + return fmt.Sprintf("message: %v", e.ErrObject) +} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/to_dafny.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/to_dafny.go new file mode 100644 index 0000000000..39442e0038 --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/to_dafny.go @@ -0,0 +1,144 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" + "github.com/dafny-lang/DafnyRuntimeGo/dafny" +) + +func GetResourceInput_ToDafny(nativeInput simplepositionaltypes.GetResourceInput) simplepositionalinternaldafnytypes.GetResourceInput { + + return func() simplepositionalinternaldafnytypes.GetResourceInput { + + return simplepositionalinternaldafnytypes.Companion_GetResourceInput_.Create_GetResourceInput_(func() dafny.Sequence { + if nativeInput.Name == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) + }()) + }() + +} + +func GetResourceOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourceOutput) simplepositionalinternaldafnytypes.GetResourceOutput { + + return func() simplepositionalinternaldafnytypes.GetResourceOutput { + + return simplepositionalinternaldafnytypes.Companion_GetResourceOutput_.Create_GetResourceOutput_(SimpleResource_ToDafny(nativeOutput.Output)) + }() + +} + +func GetResourcePositionalInput_ToDafny(nativeInput simplepositionaltypes.GetResourcePositionalInput) simplepositionalinternaldafnytypes.GetResourcePositionalInput { + + return func() simplepositionalinternaldafnytypes.GetResourcePositionalInput { + + return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalInput_.Create_GetResourcePositionalInput_(func() dafny.Sequence { + if nativeInput.Name == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) + }()) + }() + +} + +func GetResourcePositionalOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourcePositionalOutput) simplepositionalinternaldafnytypes.GetResourcePositionalOutput { + + return func() simplepositionalinternaldafnytypes.GetResourcePositionalOutput { + + return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalOutput_.Create_GetResourcePositionalOutput_(SimpleResource_ToDafny(nativeOutput.Output)) + }() + +} + +func GetNameInput_ToDafny(nativeInput simplepositionaltypes.GetNameInput) simplepositionalinternaldafnytypes.GetNameInput { + + return func() simplepositionalinternaldafnytypes.GetNameInput { + + return simplepositionalinternaldafnytypes.Companion_GetNameInput_.Create_GetNameInput_() + }() + +} + +func GetNameOutput_ToDafny(nativeOutput simplepositionaltypes.GetNameOutput) simplepositionalinternaldafnytypes.GetNameOutput { + + return func() simplepositionalinternaldafnytypes.GetNameOutput { + + return simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Create_GetNameOutput_(func() dafny.Sequence { + if nativeOutput.Name == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeOutput.Name)...) + }()) + }() + +} + +func SimpleResource_ToDafny(nativeResource simplepositionaltypes.ISimpleResource) simplepositionalinternaldafnytypes.ISimpleResource { + return nativeResource.(*SimpleResource).Impl + +} + +func SimplePositionalException_ToDafny(nativeInput simplepositionaltypes.SimplePositionalException) simplepositionalinternaldafnytypes.Error { + return func() simplepositionalinternaldafnytypes.Error { + + return simplepositionalinternaldafnytypes.Companion_Error_.Create_SimplePositionalException_(func() dafny.Sequence { + if nativeInput.Message == nil { + return nil + } + return dafny.SeqOfChars([]dafny.Char(*nativeInput.Message)...) + }()) + }() + +} + +func CollectionOfErrors_Input_ToDafny(nativeInput simplepositionaltypes.CollectionOfErrors) simplepositionalinternaldafnytypes.Error { + var e []interface{} + for _, i2 := range nativeInput.ListOfErrors { + e = append(e, Error_ToDafny(i2)) + } + return simplepositionalinternaldafnytypes.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) +} +func OpaqueError_Input_ToDafny(nativeInput simplepositionaltypes.OpaqueError) simplepositionalinternaldafnytypes.Error { + return simplepositionalinternaldafnytypes.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) +} + +func Error_ToDafny(err error) simplepositionalinternaldafnytypes.Error { + switch err.(type) { + // Service Errors + case simplepositionaltypes.SimplePositionalException: + return SimplePositionalException_ToDafny(err.(simplepositionaltypes.SimplePositionalException)) + + //DependentErrors + + //Unmodelled Errors + case simplepositionaltypes.CollectionOfErrors: + return CollectionOfErrors_Input_ToDafny(err.(simplepositionaltypes.CollectionOfErrors)) + + default: + // TODO: Is changing from the commented code to this new one reasonable? + // return OpaqueError_Input_ToDafny(err.(*simpleconstraintstypes.OpaqueError)) + + // TODO: why is err a pointer? + error, ok := err.(*simplepositionaltypes.OpaqueError) + + if !ok { + panic("Error is not an OpaqueError") + } + if error == nil { + panic("Error is nil") + } + return OpaqueError_Input_ToDafny(*error) + } +} + +func SimplePositionalConfig_ToDafny(nativeInput simplepositionaltypes.SimplePositionalConfig) simplepositionalinternaldafnytypes.SimplePositionalConfig { + return func() simplepositionalinternaldafnytypes.SimplePositionalConfig { + + return simplepositionalinternaldafnytypes.Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() + }() + +} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/to_native.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/to_native.go new file mode 100644 index 0000000000..23328bb04f --- /dev/null +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/to_native.go @@ -0,0 +1,160 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package simplepositional + +import ( + "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" + "github.com/dafny-lang/DafnyRuntimeGo/dafny" +) + +func GetResourceInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourceInput) simplepositionaltypes.GetResourceInput { + + return simplepositionaltypes.GetResourceInput{Name: func() *string { + var s string + if dafnyInput.Dtor_name() == nil { + return nil + } + for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func GetResourceOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourceOutput) simplepositionaltypes.GetResourceOutput { + + return simplepositionaltypes.GetResourceOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} + +} + +func GetResourcePositionalInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourcePositionalInput) simplepositionaltypes.GetResourcePositionalInput { + + return simplepositionaltypes.GetResourcePositionalInput{Name: func() *string { + var s string + if dafnyInput.Dtor_name() == nil { + return nil + } + for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func GetResourcePositionalOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourcePositionalOutput) simplepositionaltypes.GetResourcePositionalOutput { + + return simplepositionaltypes.GetResourcePositionalOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} + +} + +func GetNameInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetNameInput) simplepositionaltypes.GetNameInput { + + return simplepositionaltypes.GetNameInput{} + +} + +func GetNameOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetNameOutput) simplepositionaltypes.GetNameOutput { + + return simplepositionaltypes.GetNameOutput{Name: func() *string { + var s string + if dafnyOutput.Dtor_name() == nil { + return nil + } + for i := dafny.Iterate(dafnyOutput.Dtor_name()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func SimpleResource_FromDafny(dafnyResource simplepositionalinternaldafnytypes.ISimpleResource) simplepositionaltypes.ISimpleResource { + + return &SimpleResource{dafnyResource} +} + +func SimplePositionalException_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.SimplePositionalException { + return simplepositionaltypes.SimplePositionalException{Message: func() *string { + var s string + if dafnyOutput.Dtor_message() == nil { + return nil + } + for i := dafny.Iterate(dafnyOutput.Dtor_message()); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }()} + +} + +func CollectionOfErrors_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.CollectionOfErrors { + listOfErrors := dafnyOutput.Dtor_list() + message := dafnyOutput.Dtor_message() + t := simplepositionaltypes.CollectionOfErrors{} + for i := dafny.Iterate(listOfErrors); ; { + val, ok := i() + if !ok { + break + } + err := val.(simplepositionalinternaldafnytypes.Error) + t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) + + } + t.Message = func() string { + var s string + for i := dafny.Iterate(message); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() + return t +} +func OpaqueError_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.OpaqueError { + return simplepositionaltypes.OpaqueError{ + ErrObject: dafnyOutput.Dtor_obj(), + } +} + +func Error_FromDafny(err simplepositionalinternaldafnytypes.Error) error { + // Service Errors + if err.Is_SimplePositionalException() { + return SimplePositionalException_FromDafny(err) + } + + //DependentErrors + + //Unmodelled Errors + if err.Is_CollectionOfErrors() { + return CollectionOfErrors_Output_FromDafny(err) + } + + return OpaqueError_Output_FromDafny(err) +} + +func SimplePositionalConfig_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.SimplePositionalConfig) simplepositionaltypes.SimplePositionalConfig { + return simplepositionaltypes.SimplePositionalConfig{} + +} diff --git a/TestModels/Positional/src/Index.dfy b/TestModels/Positional/src/Index.dfy new file mode 100644 index 0000000000..4b7e7c3561 --- /dev/null +++ b/TestModels/Positional/src/Index.dfy @@ -0,0 +1,31 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "SimplePositionalImpl.dfy" + +module {:extern "simplepositionalinternaldafny" } SimplePositional refines AbstractSimplePositionalService { + import Operations = SimplePositionalImpl + + function method DefaultSimplePositionalConfig(): SimplePositionalConfig { + SimplePositionalConfig + } + + method SimplePositional(config: SimplePositionalConfig) + returns (res: Result) + { + var client := new SimplePositionalClient(Operations.Config); + return Success(client); + } + + class SimplePositionalClient... { + predicate ValidState() { + && Operations.ValidInternalConfig?(config) + && Modifies == Operations.ModifiesInternalConfig(config) + {History} + } + + constructor(config: Operations.InternalConfig) { + this.config := config; + History := new ISimplePositionalClientCallHistory(); + Modifies := Operations.ModifiesInternalConfig(config) + {History}; + } + } +} diff --git a/TestModels/Positional/src/WrappedSimplePositionalImpl.dfy b/TestModels/Positional/src/WrappedSimplePositionalImpl.dfy new file mode 100644 index 0000000000..c8264f4475 --- /dev/null +++ b/TestModels/Positional/src/WrappedSimplePositionalImpl.dfy @@ -0,0 +1,10 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/SimplePositionalTypesWrapped.dfy" + +module {:options "--function-syntax:4"} {:extern "simplepositionalinternaldafnywrapped"} WrappedSimplePositionalService refines WrappedAbstractSimplePositionalService { + import WrappedService = SimplePositional + function WrappedDefaultSimplePositionalConfig(): SimplePositionalConfig { + SimplePositionalConfig + } +} From 2e05f7360da5360af8e19596d2d824f4e7d3b436 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Wed, 31 Jul 2024 15:03:44 -0700 Subject: [PATCH 02/44] Comment all test model for faster workflow run --- .github/workflows/test_models_go_tests.yml | 69 +++++++++++----------- 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/.github/workflows/test_models_go_tests.yml b/.github/workflows/test_models_go_tests.yml index 4df45eff81..b8622bc78f 100644 --- a/.github/workflows/test_models_go_tests.yml +++ b/.github/workflows/test_models_go_tests.yml @@ -8,39 +8,42 @@ jobs: fail-fast: false matrix: library: [ - # TestModels/dafny-dependencies/StandardLibrary, # This stores current Polymorph dependencies that all TestModels depend on - TestModels/Aggregate, - # TestModels/AggregateReferences, - TestModels/CodegenPatches, - TestModels/Constraints, - TestModels/Constructor, - # TestModels/Dependencies, - TestModels/Errors, - TestModels/Extendable, - TestModels/Extern, - # TestModels/LanguageSpecificLogic, - # TestModels/LocalService, - # TestModels/MultipleModels, - TestModels/Refinement, - TestModels/Resource, - # TestModels/SimpleTypes/BigDecimal, - # TestModels/SimpleTypes/BigInteger, - TestModels/SimpleTypes/SimpleBlob, - TestModels/SimpleTypes/SimpleBoolean, - # TestModels/SimpleTypes/SimpleByte, - TestModels/SimpleTypes/SimpleDouble, - TestModels/SimpleTypes/SimpleEnum, - # TestModels/SimpleTypes/SimpleEnumV2, - # TestModels/SimpleTypes/SimpleFloat, - TestModels/SimpleTypes/SimpleInteger, - TestModels/SimpleTypes/SimpleLong, - # TestModels/SimpleTypes/SimpleShort, - TestModels/SimpleTypes/SimpleString, - # TestModels/SimpleTypes/SimpleTimestamp, - # TestModels/Union, - # TestModels/aws-sdks/ddb, - # TestModels/aws-sdks/kms - ] + TestModels/Positional + # TODO: Uncomment below before making PR + # # TestModels/dafny-dependencies/StandardLibrary, # This stores current Polymorph dependencies that all TestModels depend on + # TestModels/Aggregate, + # # TestModels/AggregateReferences, + # TestModels/CodegenPatches, + # TestModels/Constraints, + # TestModels/Constructor, + # # TestModels/Dependencies, + # TestModels/Errors, + # TestModels/Extendable, + # TestModels/Extern, + # # TestModels/LanguageSpecificLogic, + # # TestModels/LocalService, + # # TestModels/MultipleModels, + # TestModels/Positional, + # TestModels/Refinement, + # TestModels/Resource, + # # TestModels/SimpleTypes/BigDecimal, + # # TestModels/SimpleTypes/BigInteger, + # TestModels/SimpleTypes/SimpleBlob, + # TestModels/SimpleTypes/SimpleBoolean, + # # TestModels/SimpleTypes/SimpleByte, + # TestModels/SimpleTypes/SimpleDouble, + # TestModels/SimpleTypes/SimpleEnum, + # # TestModels/SimpleTypes/SimpleEnumV2, + # # TestModels/SimpleTypes/SimpleFloat, + # TestModels/SimpleTypes/SimpleInteger, + # TestModels/SimpleTypes/SimpleLong, + # # TestModels/SimpleTypes/SimpleShort, + # TestModels/SimpleTypes/SimpleString, + # # TestModels/SimpleTypes/SimpleTimestamp, + # # TestModels/Union, + # # TestModels/aws-sdks/ddb, + # # TestModels/aws-sdks/kms + # ] runs-on: "macos-12" steps: - uses: actions/checkout@v2 From ea8fd4ac1d62b569845a67202342e2b827779fef Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Wed, 31 Jul 2024 20:06:41 -0700 Subject: [PATCH 03/44] Add runtime --- .../SimplePositionalImpl.go | 14 ++++ .../SimpleResource/SimpleResource.go | 9 ++- .../simplepositionalinternaldafny.go | 15 ++++ .../SimplePositionalImpl.go | 14 ++++ .../SimplePositionalImplTest.go | 16 ++++ .../SimpleResource/SimpleResource.go | 4 +- .../simplepositional/api_client.go | 17 ++-- .../simplepositional/to_dafny.go | 18 +---- .../simplepositional/to_native.go | 12 +-- .../simplepositionalinternaldafny.go | 13 +++ .../shim.go | 22 ++++- .../Positional/runtimes/java/build.gradle.kts | 80 +++++++++++++++++++ .../Dafny/simple/positional/__default.java | 5 ++ .../internaldafny/wrapped/__default.java | 32 ++++++++ 14 files changed, 234 insertions(+), 37 deletions(-) create mode 100644 TestModels/Positional/runtimes/java/build.gradle.kts create mode 100644 TestModels/Positional/runtimes/java/src/main/java/Dafny/simple/positional/__default.java create mode 100644 TestModels/Positional/runtimes/java/src/test/java/simple/positional/internaldafny/wrapped/__default.java diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go index 4d5ac41233..dee6c1def6 100644 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go @@ -4,6 +4,7 @@ package SimplePositionalImpl import ( + "fmt" os "os" SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" @@ -77,7 +78,20 @@ func (_static *CompanionStruct_Default___) GetResource(config Config, input simp return output return output } + +// recover function to handle panic +func handlePanic() { + + // detect if panic occurs or not + a := recover() + + if a != nil { + fmt.Println("RECOVER Simple Positional Impl", a) + } + +} func (_static *CompanionStruct_Default___) GetResourcePositional(config Config, input _dafny.Sequence) Wrappers.Result { + defer handlePanic() var output Wrappers.Result = Wrappers.Result{} _ = output var _3_resource *SimpleResource.SimpleResource diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource/SimpleResource.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource/SimpleResource.go index 2c171ede04..89b1ff0a17 100644 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource/SimpleResource.go +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource/SimpleResource.go @@ -4,6 +4,7 @@ package SimpleResource import ( + "fmt" os "os" simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" @@ -51,8 +52,9 @@ func (_this *SimpleResource) EqualsGeneric(x interface{}) bool { return ok && _this.Equals(other) } -func (*SimpleResource) String() string { - return "SimpleResource.SimpleResource" +func (_this *SimpleResource) String() string { + fmt.Println(_this._name) + return "_this._name" } func Type_SimpleResource_() _dafny.TypeDescriptor { @@ -67,7 +69,8 @@ func (_this type_SimpleResource_) Default() interface{} { } func (_this type_SimpleResource_) String() string { - return "SimpleResource.SimpleResource" + + return "SimpleResource.SimpleResource yo" } func (_this *SimpleResource) ParentTraits_() []*_dafny.TraitID { return [](*_dafny.TraitID){simplepositionalinternaldafnytypes.Companion_ISimpleResource_.TraitID_} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go index 8679c91ebf..3b803d2483 100644 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go +++ b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go @@ -4,6 +4,7 @@ package simplepositionalinternaldafny import ( + "fmt" os "os" SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" @@ -155,8 +156,22 @@ func (_this *SimplePositionalClient) GetResource(input simplepositionalinternald return output } } + +// recover function to handle panic +func handlePanic() { + + // detect if panic occurs or not + a := recover() + + if a != nil { + fmt.Println("RECOVER in simplepositionalinternaldafny", a) + } + +} + func (_this *SimplePositionalClient) GetResourcePositional(input _dafny.Sequence) Wrappers.Result { { + defer handlePanic() var output Wrappers.Result = Wrappers.Result{} _ = output var _out3 Wrappers.Result diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go index 4d5ac41233..44525fdabd 100644 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go @@ -4,6 +4,7 @@ package SimplePositionalImpl import ( + "fmt" os "os" SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" @@ -77,7 +78,20 @@ func (_static *CompanionStruct_Default___) GetResource(config Config, input simp return output return output } + +// recover function to handle panic +func handlePanic() { + + // detect if panic occurs or not + a := recover() + + if a != nil { + fmt.Println("RECOVER Impl", a) + } + +} func (_static *CompanionStruct_Default___) GetResourcePositional(config Config, input _dafny.Sequence) Wrappers.Result { + defer handlePanic() var output Wrappers.Result = Wrappers.Result{} _ = output var _3_resource *SimpleResource.SimpleResource diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImplTest/SimplePositionalImplTest.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImplTest/SimplePositionalImplTest.go index 0f7bac0302..5df5cd63a8 100644 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImplTest/SimplePositionalImplTest.go +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImplTest/SimplePositionalImplTest.go @@ -4,6 +4,7 @@ package SimplePositionalImplTest import ( + "fmt" os "os" SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" @@ -103,7 +104,20 @@ func (_static *CompanionStruct_Default___) TestGetResource(client simpleposition panic("test/SimplePositionalImplTest.dfy(30,8): " + (_dafny.SeqOfString("expectation violation")).String()) } } + +// recover function to handle panic +func handlePanic() { + + // detect if panic occurs or not + a := recover() + + if a != nil { + fmt.Println("RECOVER impl test", a) + } + +} func (_static *CompanionStruct_Default___) TestGetResourcePositional(client simplepositionalinternaldafnytypes.ISimplePositionalClient) { + defer handlePanic() var _11_input _dafny.Sequence _ = _11_input _11_input = _dafny.SeqOfString("TestPositional") @@ -125,12 +139,14 @@ func (_static *CompanionStruct_Default___) TestGetResourcePositional(client simp _ = _15_valueOrError1 var _out7 Wrappers.Result _ = _out7 + _out7 = (_12_resource).GetName(simplepositionalinternaldafnytypes.Companion_GetNameInput_.Create_GetNameInput_()) _15_valueOrError1 = _out7 if !(!((_15_valueOrError1).IsFailure())) { panic("test/SimplePositionalImplTest.dfy(40,29): " + (_15_valueOrError1).String()) } _14_getNameOutput = (_15_valueOrError1).Extract().(simplepositionalinternaldafnytypes.GetNameOutput) + if !(_dafny.Companion_Sequence_.Equal((_14_getNameOutput).Dtor_name(), _dafny.SeqOfString("TestPositional"))) { panic("test/SimplePositionalImplTest.dfy(41,8): " + (_dafny.SeqOfString("expectation violation")).String()) } diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource/SimpleResource.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource/SimpleResource.go index 2c171ede04..023c79b61e 100644 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource/SimpleResource.go +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource/SimpleResource.go @@ -4,6 +4,7 @@ package SimpleResource import ( + "fmt" os "os" simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" @@ -51,7 +52,8 @@ func (_this *SimpleResource) EqualsGeneric(x interface{}) bool { return ok && _this.Equals(other) } -func (*SimpleResource) String() string { +func (_this *SimpleResource) String() string { + fmt.Println(_this._name) return "SimpleResource.SimpleResource" } diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/api_client.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/api_client.go index 8419c833fc..5c09273c0e 100644 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/api_client.go +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/api_client.go @@ -4,10 +4,15 @@ package simplepositional import ( "context" + "fmt" + "reflect" + + SimpleResources "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafny" "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" + "github.com/dafny-lang/DafnyRuntimeGo/dafny" ) type Client struct { @@ -45,7 +50,8 @@ func (client *Client) GetResource(ctx context.Context, params simplepositionalty } -func (client *Client) GetResourcePositional(ctx context.Context, params simplepositionaltypes.GetResourcePositionalInput) (*simplepositionaltypes.GetResourcePositionalOutput, error) { +func (client *Client) GetResourcePositional(ctx context.Context, params simplepositionaltypes.GetResourcePositionalInput) (*SimpleResources.SimpleResource, error) { + err := params.Validate() if err != nil { opaqueErr := &simplepositionaltypes.OpaqueError{ @@ -53,14 +59,15 @@ func (client *Client) GetResourcePositional(ctx context.Context, params simplepo } return nil, opaqueErr } - var dafny_request simplepositionalinternaldafnytypes.GetResourcePositionalInput = GetResourcePositionalInput_ToDafny(params) + var dafny_request dafny.Sequence = GetResourcePositionalInput_ToDafny(params) var dafny_response = client.DafnyClient.GetResourcePositional(dafny_request) - + if dafny_response.Is_Failure() { err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) return nil, Error_FromDafny(err) } - var native_response = GetResourcePositionalOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourcePositionalOutput)) - return &native_response, nil + fmt.Println(reflect.TypeOf(dafny_response.Extract())) + var native_response = dafny_response.Extract().(*SimpleResources.SimpleResource) + return native_response, nil } diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_dafny.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_dafny.go index 39442e0038..223329b664 100644 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_dafny.go +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_dafny.go @@ -31,26 +31,12 @@ func GetResourceOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourceOut } -func GetResourcePositionalInput_ToDafny(nativeInput simplepositionaltypes.GetResourcePositionalInput) simplepositionalinternaldafnytypes.GetResourcePositionalInput { - - return func() simplepositionalinternaldafnytypes.GetResourcePositionalInput { - - return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalInput_.Create_GetResourcePositionalInput_(func() dafny.Sequence { +func GetResourcePositionalInput_ToDafny(nativeInput simplepositionaltypes.GetResourcePositionalInput) dafny.Sequence { if nativeInput.Name == nil { return nil } return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) - }()) - }() - -} - -func GetResourcePositionalOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourcePositionalOutput) simplepositionalinternaldafnytypes.GetResourcePositionalOutput { - - return func() simplepositionalinternaldafnytypes.GetResourcePositionalOutput { - - return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalOutput_.Create_GetResourcePositionalOutput_(SimpleResource_ToDafny(nativeOutput.Output)) - }() + } diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_native.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_native.go index 23328bb04f..06921c5122 100644 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_native.go +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_native.go @@ -33,14 +33,14 @@ func GetResourceOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes. } -func GetResourcePositionalInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourcePositionalInput) simplepositionaltypes.GetResourcePositionalInput { +func GetResourcePositionalInput_FromDafny(dafnyInput dafny.Sequence) simplepositionaltypes.GetResourcePositionalInput { return simplepositionaltypes.GetResourcePositionalInput{Name: func() *string { var s string - if dafnyInput.Dtor_name() == nil { + if dafnyInput == nil { return nil } - for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { + for i := dafny.Iterate(dafnyInput); ; { val, ok := i() if !ok { return &[]string{s}[0] @@ -52,12 +52,6 @@ func GetResourcePositionalInput_FromDafny(dafnyInput simplepositionalinternaldaf } -func GetResourcePositionalOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourcePositionalOutput) simplepositionaltypes.GetResourcePositionalOutput { - - return simplepositionaltypes.GetResourcePositionalOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} - -} - func GetNameInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetNameInput) simplepositionaltypes.GetNameInput { return simplepositionaltypes.GetNameInput{} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go index 8679c91ebf..86c81ba831 100644 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go @@ -4,6 +4,7 @@ package simplepositionalinternaldafny import ( + "fmt" os "os" SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" @@ -155,6 +156,18 @@ func (_this *SimplePositionalClient) GetResource(input simplepositionalinternald return output } } + +// recover function to handle panic +func handlePanic() { + + // detect if panic occurs or not + a := recover() + + if a != nil { + fmt.Println("RECOVERED IN INTERNAL DAFNY", a) + } + +} func (_this *SimplePositionalClient) GetResourcePositional(input _dafny.Sequence) Wrappers.Result { { var output Wrappers.Result = Wrappers.Result{} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/shim.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/shim.go index d173c74f17..04c3907139 100644 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/shim.go +++ b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/shim.go @@ -4,9 +4,10 @@ package simplepositionalinternaldafnywrapped import ( "context" - + "fmt" "github.com/Smithy-dafny/TestModels/Positional/simplepositional" "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" + "github.com/dafny-lang/DafnyRuntimeGo/dafny" "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" ) @@ -33,11 +34,26 @@ func (shim *Shim) GetResource(input simplepositionalinternaldafnytypes.GetResour return Wrappers.Companion_Result_.Create_Success_(simplepositional.GetResourceOutput_ToDafny(*native_response)) } -func (shim *Shim) GetResourcePositional(input simplepositionalinternaldafnytypes.GetResourcePositionalInput) Wrappers.Result { +// recover function to handle panic +func handlePanic() { + + // detect if panic occurs or not + a := recover() + + if a != nil { + fmt.Println("RECOVER IN SHIM", a) + } + + } + +func (shim *Shim) GetResourcePositional(input dafny.Sequence) Wrappers.Result { + defer handlePanic() + var native_request = simplepositional.GetResourcePositionalInput_FromDafny(input) var native_response, native_error = shim.client.GetResourcePositional(context.Background(), native_request) + fmt.Println(native_response) if native_error != nil { return Wrappers.Companion_Result_.Create_Failure_(simplepositional.Error_ToDafny(native_error)) } - return Wrappers.Companion_Result_.Create_Success_(simplepositional.GetResourcePositionalOutput_ToDafny(*native_response)) + return Wrappers.Companion_Result_.Create_Success_(native_response) } diff --git a/TestModels/Positional/runtimes/java/build.gradle.kts b/TestModels/Positional/runtimes/java/build.gradle.kts new file mode 100644 index 0000000000..bd264c0d00 --- /dev/null +++ b/TestModels/Positional/runtimes/java/build.gradle.kts @@ -0,0 +1,80 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +import java.io.File +import java.io.FileInputStream +import java.util.Properties +import java.net.URI +import javax.annotation.Nullable + +tasks.wrapper { + gradleVersion = "7.6" +} + +plugins { + `java-library` + `maven-publish` +} + +var props = Properties().apply { + load(FileInputStream(File(rootProject.rootDir, "../../project.properties"))) +} +var dafnyVersion = props.getProperty("dafnyVersion") + +group = "simple.positional" +version = "1.0-SNAPSHOT" +description = "SimplePositional" + +java { + toolchain.languageVersion.set(JavaLanguageVersion.of(8)) + sourceSets["main"].java { + srcDir("src/main/java") + srcDir("src/main/dafny-generated") + srcDir("src/main/smithy-generated") + } + sourceSets["test"].java { + srcDir("src/test/java") + srcDir("src/test/dafny-generated") + srcDir("src/test/smithy-generated") + } +} + +repositories { + mavenCentral() + mavenLocal() +} + +dependencies { + implementation("org.dafny:DafnyRuntime:${dafnyVersion}") + implementation("software.amazon.smithy.dafny:conversion:0.1") + implementation("software.amazon.cryptography:StandardLibrary:1.0-SNAPSHOT") + testImplementation("org.testng:testng:7.5") +} + +publishing { + publications.create("mavenLocal") { + groupId = group as String? + artifactId = description + from(components["java"]) + } + publications.create("maven") { + groupId = group as String? + artifactId = description + from(components["java"]) + } + repositories { mavenLocal() } +} + +tasks.withType() { + options.encoding = "UTF-8" +} + +tasks { + register("runTests", JavaExec::class.java) { + mainClass.set("TestsFromDafny") + classpath = sourceSets["test"].runtimeClasspath + } +} + +tasks.named("test") { + useTestNG() +} diff --git a/TestModels/Positional/runtimes/java/src/main/java/Dafny/simple/positional/__default.java b/TestModels/Positional/runtimes/java/src/main/java/Dafny/simple/positional/__default.java new file mode 100644 index 0000000000..817d9a442c --- /dev/null +++ b/TestModels/Positional/runtimes/java/src/main/java/Dafny/simple/positional/__default.java @@ -0,0 +1,5 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package simple.positional.internaldafny; + +public class __default extends _ExternBase___default {} diff --git a/TestModels/Positional/runtimes/java/src/test/java/simple/positional/internaldafny/wrapped/__default.java b/TestModels/Positional/runtimes/java/src/test/java/simple/positional/internaldafny/wrapped/__default.java new file mode 100644 index 0000000000..6b94d7dd9a --- /dev/null +++ b/TestModels/Positional/runtimes/java/src/test/java/simple/positional/internaldafny/wrapped/__default.java @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package simple.positional.internaldafny.wrapped; + +import Wrappers_Compile.Result; +import simple.positional.SimplePositional; +import simple.positional.ToNative; +import simple.positional.internaldafny.types.Error; +import simple.positional.internaldafny.types.ISimplePositionalClient; +import simple.positional.internaldafny.types.SimplePositionalConfig; +import simple.positional.wrapped.TestSimplePositional; + +public class __default extends _ExternBase___default { + + public static Result WrappedSimplePositional( + SimplePositionalConfig config + ) { + simple.positional.model.SimplePositionalConfig wrappedConfig = + ToNative.SimplePositionalConfig(config); + simple.positional.SimplePositional impl = SimplePositional + .builder() + .SimplePositionalConfig(wrappedConfig) + .build(); + TestSimplePositional wrappedClient = TestSimplePositional + .builder() + .impl(impl) + .build(); + return simple.positional.internaldafny.__default.CreateSuccessOfClient( + wrappedClient + ); + } +} From eb466e3b2a42ad8ce4d8b4ebe064aba428b76695 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 5 Aug 2024 09:27:48 -0700 Subject: [PATCH 04/44] Changes for the positional trait --- .../SmithyToDafnyShapeVisitor.java | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java index c9a9108552..a6854fd426 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java @@ -6,6 +6,7 @@ import software.amazon.polymorph.smithygo.localservice.nameresolver.DafnyNameResolver; import software.amazon.polymorph.smithygo.localservice.nameresolver.SmithyNameResolver; import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; +import software.amazon.polymorph.traits.PositionalTrait; import software.amazon.polymorph.traits.ReferenceTrait; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.model.shapes.BlobShape; @@ -164,15 +165,24 @@ public String structureShape(final StructureShape shape) { if (isPointerType) { nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); } - var goCodeBlock = """ + String goCodeBlock = ""; + String fieldSeparator = ","; + if (!shape.hasTrait(PositionalTrait.class)){ + builder.append("%1$s(".formatted(companionStruct)); + goCodeBlock = """ func () %s { %s return %s }()"""; - - - builder.append("%1$s(".formatted(companionStruct)); - String fieldSeparator = ","; + } + else { + // Positional trait can only have one variable. + fieldSeparator = ""; + // Don't unwrap position trait shape + goCodeBlock = """ + %s + """; + } for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { final var memberName = memberShapeEntry.getKey(); final var memberShape = memberShapeEntry.getValue(); @@ -184,8 +194,9 @@ public String structureShape(final StructureShape shape) { )), fieldSeparator )); } - - + if (shape.hasTrait(PositionalTrait.class)){ + return goCodeBlock.formatted(builder.toString()); + } return goCodeBlock.formatted(returnType, nilCheck, someWrapIfRequired.formatted(builder.append(")").toString())); } From fc3244add69b4b61193496579a7e9cc4e5ef1773 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 5 Aug 2024 11:50:08 -0700 Subject: [PATCH 05/44] Changes for positional trait --- .../shapevisitor/DafnyToSmithyShapeVisitor.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java index 9c19558880..aae58740c0 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java @@ -6,6 +6,7 @@ import software.amazon.polymorph.smithygo.localservice.nameresolver.DafnyNameResolver; import software.amazon.polymorph.smithygo.localservice.nameresolver.SmithyNameResolver; import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; +import software.amazon.polymorph.traits.PositionalTrait; import software.amazon.polymorph.traits.ReferenceTrait; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.model.shapes.BlobShape; @@ -140,9 +141,17 @@ public String structureShape(final StructureShape shape) { final var memberName = memberShapeEntry.getKey(); final var memberShape = memberShapeEntry.getValue(); final var targetShape = context.model().expectShape(memberShape.getTarget()); + final String DtorConversion; + System.out.println(shape.hasTrait(PositionalTrait.class)); + if (!shape.hasTrait(PositionalTrait.class)) { + DtorConversion = ".Dtor_%s()".formatted(memberName); + } else { + // Shapes with PositionalTrait already gets input unwrapped so no conversion needed. + DtorConversion = ""; + } //TODO: Is it ever possible for structure to be nil? final var derivedDataSource = "%1$s%2$s%3$s%4$s".formatted(dataSource, - ".Dtor_%s()".formatted(memberName), + DtorConversion, memberShape.isOptional() ? ".UnwrapOr(nil)" : "", memberShape.isOptional() && targetShape.isStructureShape() && !targetShape.hasTrait(ReferenceTrait.class) ? ".(%s)".formatted(DafnyNameResolver.getDafnyType(targetShape, context.symbolProvider().toSymbol(memberShape))) : ""); builder.append("%1$s: %2$s%3$s,".formatted( From 3a7264fe01a5c675558547009256f961b19832be Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 5 Aug 2024 11:55:54 -0700 Subject: [PATCH 06/44] Remove redundant code --- .../localservice/shapevisitor/DafnyToSmithyShapeVisitor.java | 1 - 1 file changed, 1 deletion(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java index aae58740c0..dd7487d1ce 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java @@ -142,7 +142,6 @@ public String structureShape(final StructureShape shape) { final var memberShape = memberShapeEntry.getValue(); final var targetShape = context.model().expectShape(memberShape.getTarget()); final String DtorConversion; - System.out.println(shape.hasTrait(PositionalTrait.class)); if (!shape.hasTrait(PositionalTrait.class)) { DtorConversion = ".Dtor_%s()".formatted(memberName); } else { From df3e00cfae2f6e892192470501f90757c5fa38ce Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Wed, 7 Aug 2024 14:15:02 -0700 Subject: [PATCH 07/44] Add everything --- .../smithygo/codegen/StructureGenerator.java | 10 +++- .../DafnyLocalServiceGenerator.java | 57 ++++++++++++++++--- ...fnyLocalServiceTypeConversionProtocol.java | 25 ++++++-- .../nameresolver/SmithyNameResolver.java | 14 +++++ 4 files changed, 91 insertions(+), 15 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java index 6d578df262..bcb56a9c9f 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java @@ -112,6 +112,7 @@ public void renderStructure(Runnable runnable, boolean isInputStructure) { if (targetShape.hasTrait(ReferenceTrait.class)) { memberSymbol = memberSymbol.getProperty("Referred", Symbol.class).get(); + var refShape = targetShape.expectTrait(ReferenceTrait.class); if (refShape.isService()) { namespace = SmithyNameResolver.shapeNamespace(model.expectShape(refShape.getReferentId())); @@ -124,9 +125,14 @@ public void renderStructure(Runnable runnable, boolean isInputStructure) { writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(targetShape.toShapeId().getNamespace()), namespace); } } - + + System.out.println(memberSymbol); writer.write("$L $P", memberName, memberSymbol); - + System.out.println(""" + \n\n\n + >>>> + %s + """.formatted(writer)); }); writer.closeBlock("}").write(""); renderValidator(symbol, sortedMembers, isInputStructure); diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java index daa012dba4..290a3235de 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java @@ -3,6 +3,7 @@ package software.amazon.polymorph.smithygo.localservice; +import software.amazon.awssdk.core.traits.RequiredTrait; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoDelegator; import software.amazon.polymorph.smithygo.codegen.GoWriter; @@ -13,6 +14,7 @@ import software.amazon.polymorph.smithygo.localservice.nameresolver.SmithyNameResolver; import software.amazon.polymorph.traits.ExtendableTrait; import software.amazon.polymorph.traits.LocalServiceTrait; +import software.amazon.polymorph.traits.PositionalTrait; import software.amazon.polymorph.traits.ReferenceTrait; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.Model; @@ -119,7 +121,7 @@ func NewClient(clientConfig $L) (*$T, error) { } final var inputType = inputShape.hasTrait(UnitTypeTrait.class) ? "" : ", params %s.%s".formatted(SmithyNameResolver.smithyTypesNamespace(inputShape), inputShape.toShapeId().getName()); - final var outputType = outputShape.hasTrait(UnitTypeTrait.class) ? "" + var maybeOutputType = outputShape.hasTrait(UnitTypeTrait.class) ? "" : "*%s.%s,".formatted(SmithyNameResolver.smithyTypesNamespace(outputShape), outputShape.toShapeId().getName()); String validationCheck = ""; if(!inputType.equals("")) { @@ -130,7 +132,7 @@ func NewClient(clientConfig $L) (*$T, error) { ErrObject: err, } """.formatted(SmithyNameResolver.smithyTypesNamespace(inputShape)); - if(outputType.equals("")) { + if(maybeOutputType.equals("")) { validationCheck += "return opaqueErr }"; } else{ @@ -141,26 +143,63 @@ func NewClient(clientConfig $L) (*$T, error) { if (inputShape.hasTrait(UnitTypeTrait.class)) { baseClientCall = "var dafny_response = client.DafnyClient.%s()".formatted(operationShape.getId().getName()); } else { + String dafnyType; + if (inputShape.hasTrait(PositionalTrait.class)) { + // TODO: Change this + // System.out.println(SmithyNameResolver.shapeNamespace(outputShape.getAllMembers().values().stream().findFirst().get())); + // System.out.println(SmithyNameResolver.getSmithyType(b, symbolProvider.toSymbol(b))); + // System.out.println(symbolProvider.toSymbol(model.expectShape(ReferentId))); + dafnyType = "dafny.Sequence"; + } + else { + dafnyType = DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(inputShape)); + } baseClientCall = """ var dafny_request %s = %s(params) var dafny_response = client.DafnyClient.%s(dafny_request) - """.formatted(DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(inputShape)), + """.formatted(dafnyType, SmithyNameResolver.getToDafnyMethodName(service, inputShape, ""), operationShape.getId().getName()); } String returnResponse, returnError; + final String outputType; if (outputShape.hasTrait(UnitTypeTrait.class)) { returnResponse = "return nil"; returnError = "return"; + outputType = maybeOutputType; } else { - returnResponse = """ - var native_response = %s(dafny_response.Extract().(%s)) - return &native_response, nil - """.formatted(SmithyNameResolver.getFromDafnyMethodName(service, outputShape, ""), - DafnyNameResolver.getDafnyType(outputShape, symbolProvider.toSymbol(outputShape))); + if (inputShape.hasTrait(PositionalTrait.class)) { + var insideOutputShape = outputShape.getAllMembers().values().stream().findFirst().get().getTarget(); + Shape shapeInsideOutputShape = model.expectShape(insideOutputShape); + if (shapeInsideOutputShape.hasTrait(ReferenceTrait.class)) { + var ReferentId = shapeInsideOutputShape.getTrait(ReferenceTrait.class).get().getReferentId(); + Shape referenceShape = model.expectShape(ReferentId); + outputType = "*%s.%s,".formatted(SmithyNameResolver.smithyTypesNamespace(referenceShape), referenceShape.toShapeId().getName()); + returnResponse = """ + var native_response = dafny_response.Extract().(%s) + return &native_response, nil + """.formatted(SmithyNameResolver.getSmithyType(referenceShape, symbolProvider.toSymbol(referenceShape))); + } else { + outputType = "*%s.%s,".formatted(SmithyNameResolver.smithyTypesNamespace(shapeInsideOutputShape), shapeInsideOutputShape.toShapeId().getName()); + returnResponse = """ + var native_response = dafny_response.Extract().(%s) + return &native_response, nil + """.formatted(SmithyNameResolver.getSmithyType(shapeInsideOutputShape, symbolProvider.toSymbol(shapeInsideOutputShape))); + } + // dafny_response is unwrapped PositionalTrait + + } + else { + outputType = maybeOutputType; + returnResponse = """ + var native_response = %s(dafny_response.Extract().(%s)) + return &native_response, nil + """.formatted(SmithyNameResolver.getFromDafnyMethodName(service, outputShape, ""), + DafnyNameResolver.getDafnyType(outputShape, symbolProvider.toSymbol(outputShape))); + } returnError = "return nil,"; } - + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); writer.write(""" func (client *$T) $L(ctx context.Context $L) ($L error) { $L diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java index 45b130b4e4..20ddd94f1f 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java @@ -10,6 +10,7 @@ import software.amazon.polymorph.smithygo.localservice.shapevisitor.SmithyToDafnyShapeVisitor; import software.amazon.polymorph.traits.ExtendableTrait; import software.amazon.polymorph.traits.LocalServiceTrait; +import software.amazon.polymorph.traits.PositionalTrait; import software.amazon.polymorph.traits.ReferenceTrait; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ResourceShape; @@ -52,20 +53,28 @@ public void generateSerializers(GenerationContext context) { if (!input.hasTrait(UnitTypeTrait.class) && input.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { final var inputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, input, ""); final var inputSymbol = symbolProvider.toSymbol(input); + final String returnType; + if (input.hasTrait(PositionalTrait.class)) { + // TODO: Change this + returnType = "dafny.Sequence"; + } + else { + returnType = DafnyNameResolver.getDafnyType(input, inputSymbol); + } writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(input.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(input)); writer.write(""" func $L(nativeInput $L)($L) { ${C|} }""", inputToDafnyMethodName, SmithyNameResolver.getSmithyType(input, inputSymbol), - DafnyNameResolver.getDafnyType(input, inputSymbol), + returnType, writer.consumer(w -> generateRequestSerializer(context, operation, context.writerDelegator()))); }); } } final var output = model.expectShape(operation.getOutputShape()); - if (!alreadyVisited.contains(output.toShapeId())) { + if (!alreadyVisited.contains(output.toShapeId()) && !output.hasTrait(PositionalTrait.class)) { alreadyVisited.add(output.toShapeId()); if (!output.hasTrait(UnitTypeTrait.class) && output.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { final var outputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, output, ""); @@ -172,13 +181,21 @@ public void generateDeserializers(GenerationContext context) { if (!input.hasTrait(UnitTypeTrait.class) && input.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { final var inputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, input, ""); final var inputSymbol = context.symbolProvider().toSymbol(input); + final String inputType; + if (input.hasTrait(PositionalTrait.class)) { + // TODO: Change this + inputType = "dafny.Sequence"; + } + else { + inputType = DafnyNameResolver.getDafnyType(input, inputSymbol); + } delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(input.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(input)); writer.write(""" func $L(dafnyInput $L)($L) { ${C|} - }""", inputFromDafnyMethodName, DafnyNameResolver.getDafnyType(input, inputSymbol), + }""", inputFromDafnyMethodName, inputType, SmithyNameResolver.getSmithyType(input, inputSymbol), writer.consumer(w -> generateRequestDeserializer(context, operation, context.writerDelegator()))); }); @@ -186,7 +203,7 @@ public void generateDeserializers(GenerationContext context) { } final var output = context.model().expectShape(operation.getOutputShape()); - if (!alreadyVisited.contains(output.toShapeId())) { + if (!alreadyVisited.contains(output.toShapeId()) && !output.hasTrait(PositionalTrait.class)) { alreadyVisited.add(output.toShapeId()); if (!output.hasTrait(UnitTypeTrait.class) && output.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { final var outputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, output, ""); diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java index e17bb15827..1cafd47f4d 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java @@ -1,8 +1,10 @@ package software.amazon.polymorph.smithygo.localservice.nameresolver; import software.amazon.smithy.codegen.core.Symbol; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; +import software.amazon.polymorph.traits.ReferenceTrait; import java.util.Map; @@ -31,6 +33,10 @@ public static String shapeNamespace(final Shape shape) { } public static String smithyTypesNamespace(final Shape shape) { + // if (shape.isResourceShape()) { + // // TypesNamespace for resources are in ShapeName + // return shape.getId().getName(); + // } return shape.toShapeId().getNamespace().replace(DOT, BLANK).toLowerCase().concat("types"); } @@ -49,6 +55,10 @@ public static String getSmithyType(final Shape shape, final Symbol symbol) { if(symbol.getNamespace().contains("smithy.")) { return symbol.getName(); } + else if (shape.isResourceShape()) { + // Symbol for resources are found in ShapeName.ShapeName + return SmithyNameResolver.smithyTypesNamespace(shape).concat(DOT).concat(shape.getId().getName()); + } return SmithyNameResolver.smithyTypesNamespace(shape).concat(DOT).concat(symbol.getName()); } @@ -90,4 +100,8 @@ public static String getFromDafnyMethodName(final Shape shape, final String disa final var methodName = shape.getId().getName().concat("_FromDafny"); return SmithyNameResolver.shapeNamespace(shape).concat(DOT).concat(methodName); } + + public static String getNativeTypeForShape (final Shape shape) { + return "Dummy"; + } } From 2df4fd082cfcc47559f4c73e67305817859105e1 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Wed, 7 Aug 2024 14:58:15 -0700 Subject: [PATCH 08/44] Revert the unwanted changes --- TestModels/SimpleTypes/SimpleEnum/src/Index.dfy | 2 +- TestModels/SimpleTypes/SimpleEnum/src/WrappedSimpleEnumImpl.dfy | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/TestModels/SimpleTypes/SimpleEnum/src/Index.dfy b/TestModels/SimpleTypes/SimpleEnum/src/Index.dfy index 387dfb540f..ae668b750c 100644 --- a/TestModels/SimpleTypes/SimpleEnum/src/Index.dfy +++ b/TestModels/SimpleTypes/SimpleEnum/src/Index.dfy @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 include "SimpleEnumImpl.dfy" -module {:extern "simpletypessmithyenuminternaldafny" } SimpleEnum refines AbstractSimpleTypesSmithyEnumService { +module {:extern "simple.types.smithyenum.internaldafny" } SimpleEnum refines AbstractSimpleTypesSmithyEnumService { import Operations = SimpleEnumImpl function method DefaultSimpleEnumConfig(): SimpleEnumConfig { diff --git a/TestModels/SimpleTypes/SimpleEnum/src/WrappedSimpleEnumImpl.dfy b/TestModels/SimpleTypes/SimpleEnum/src/WrappedSimpleEnumImpl.dfy index eeb6482d43..bb8c6ea175 100644 --- a/TestModels/SimpleTypes/SimpleEnum/src/WrappedSimpleEnumImpl.dfy +++ b/TestModels/SimpleTypes/SimpleEnum/src/WrappedSimpleEnumImpl.dfy @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 include "../Model/SimpleTypesSmithyEnumTypesWrapped.dfy" -module {:extern "simpletypessmithyenuminternaldafnywrapped"} WrappedSimpleTypesEnumService refines WrappedAbstractSimpleTypesSmithyEnumService { +module {:extern "simple.types.smithyenum.internaldafny.wrapped"} WrappedSimpleTypesEnumService refines WrappedAbstractSimpleTypesSmithyEnumService { import WrappedService = SimpleEnum function method WrappedDefaultSimpleEnumConfig(): SimpleEnumConfig { SimpleEnumConfig From 662bb74562dda00b2c6ffba9655d531db4e58480 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Wed, 7 Aug 2024 16:34:17 -0700 Subject: [PATCH 09/44] Changes for shim --- .../localservice/DafnyLocalServiceGenerator.java | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java index 290a3235de..0ee56113fc 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java @@ -267,7 +267,8 @@ void generateShim() { final var operationShape = model.expectShape(operation, OperationShape.class); final var inputShape = model.expectShape(operationShape.getInputShape()); final var outputShape = model.expectShape(operationShape.getOutputShape()); - final var inputType = inputShape.hasTrait(UnitTypeTrait.class) ? "" + // this is maybe because positional trait can change this + final var maybeInputType = inputShape.hasTrait(UnitTypeTrait.class) ? "" : "input %s".formatted(DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(inputShape))); final var typeConversion = inputShape.hasTrait(UnitTypeTrait.class) ? "" @@ -277,13 +278,24 @@ void generateShim() { inputShape.hasTrait(UnitTypeTrait.class) ? "" : ", native_request"); String clientResponse, returnResponse; + final String inputType; if (outputShape.hasTrait(UnitTypeTrait.class)) { clientResponse = "var native_error"; returnResponse = "dafny.TupleOf()"; writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + inputType = maybeInputType; } else { + if (inputShape.hasTrait(PositionalTrait.class)) { + // TODO: get dafny.Sequence from name resolver + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + inputType = "input %s".formatted("dafny.Sequence"); + returnResponse = "(native_response)"; + } + else { + inputType = maybeInputType; + returnResponse = "%s(*native_response)".formatted(SmithyNameResolver.getToDafnyMethodName(outputShape, "")); + } clientResponse = "var native_response, native_error"; - returnResponse = "%s(*native_response)".formatted(SmithyNameResolver.getToDafnyMethodName(outputShape, "")); } writer.write(""" From 9d3ea35186a8f37bc9095a4d9acf3b98f4466418 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Fri, 9 Aug 2024 12:15:29 -0700 Subject: [PATCH 10/44] Update API client return type for interface --- .../DafnyLocalServiceGenerator.java | 23 +++-------------- ...fnyLocalServiceTypeConversionProtocol.java | 25 +++++++++++-------- .../nameresolver/DafnyNameResolver.java | 22 ++++++++++++++++ 3 files changed, 41 insertions(+), 29 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java index 0ee56113fc..eb7e439923 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java @@ -169,25 +169,10 @@ func NewClient(clientConfig $L) (*$T, error) { outputType = maybeOutputType; } else { if (inputShape.hasTrait(PositionalTrait.class)) { - var insideOutputShape = outputShape.getAllMembers().values().stream().findFirst().get().getTarget(); - Shape shapeInsideOutputShape = model.expectShape(insideOutputShape); - if (shapeInsideOutputShape.hasTrait(ReferenceTrait.class)) { - var ReferentId = shapeInsideOutputShape.getTrait(ReferenceTrait.class).get().getReferentId(); - Shape referenceShape = model.expectShape(ReferentId); - outputType = "*%s.%s,".formatted(SmithyNameResolver.smithyTypesNamespace(referenceShape), referenceShape.toShapeId().getName()); - returnResponse = """ - var native_response = dafny_response.Extract().(%s) - return &native_response, nil - """.formatted(SmithyNameResolver.getSmithyType(referenceShape, symbolProvider.toSymbol(referenceShape))); - } else { - outputType = "*%s.%s,".formatted(SmithyNameResolver.smithyTypesNamespace(shapeInsideOutputShape), shapeInsideOutputShape.toShapeId().getName()); - returnResponse = """ - var native_response = dafny_response.Extract().(%s) - return &native_response, nil - """.formatted(SmithyNameResolver.getSmithyType(shapeInsideOutputShape, symbolProvider.toSymbol(shapeInsideOutputShape))); - } - // dafny_response is unwrapped PositionalTrait - + returnResponse = """ + var native_response = dafny_response.Extract() + return native_response, nil + """; } else { outputType = maybeOutputType; diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java index 20ddd94f1f..d454e70693 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java @@ -17,8 +17,10 @@ import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.StructureShape; +import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.UnitTypeTrait; +import software.amazon.smithy.codegen.core.Symbol; import java.util.HashSet; import java.util.LinkedList; @@ -47,19 +49,20 @@ public void generateSerializers(GenerationContext context) { final var writerDelegator = context.writerDelegator(); serviceShape.getOperations().forEach(eachOperation -> { final var operation = model.expectShape(eachOperation, OperationShape.class); - final var input = model.expectShape(operation.getInputShape()); + final Shape input = model.expectShape(operation.getInputShape()); if (!alreadyVisited.contains(input.toShapeId())) { alreadyVisited.add(input.toShapeId()); if (!input.hasTrait(UnitTypeTrait.class) && input.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { final var inputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, input, ""); final var inputSymbol = symbolProvider.toSymbol(input); - final String returnType; + final String outputType; if (input.hasTrait(PositionalTrait.class)) { - // TODO: Change this - returnType = "dafny.Sequence"; - } - else { - returnType = DafnyNameResolver.getDafnyType(input, inputSymbol); + // Output type in To Dafny should be unwrapped + Shape inputForPositional = model.expectShape(input.getAllMembers().values().stream().findFirst().get().getTarget()); + Symbol symbolForPositional = symbolProvider.toSymbol(inputForPositional); + outputType = DafnyNameResolver.getDafnyType(inputForPositional, symbolForPositional); + } else { + outputType = DafnyNameResolver.getDafnyType(input, inputSymbol); } writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(input.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(input)); @@ -67,7 +70,7 @@ public void generateSerializers(GenerationContext context) { func $L(nativeInput $L)($L) { ${C|} }""", inputToDafnyMethodName, SmithyNameResolver.getSmithyType(input, inputSymbol), - returnType, + outputType, writer.consumer(w -> generateRequestSerializer(context, operation, context.writerDelegator()))); }); } @@ -183,8 +186,10 @@ public void generateDeserializers(GenerationContext context) { final var inputSymbol = context.symbolProvider().toSymbol(input); final String inputType; if (input.hasTrait(PositionalTrait.class)) { - // TODO: Change this - inputType = "dafny.Sequence"; + // Input type in To native should be unwrapped + Shape inputForPositional = context.model().expectShape(input.getAllMembers().values().stream().findFirst().get().getTarget()); + Symbol symbolForPositional = context.symbolProvider().toSymbol(input); + inputType = DafnyNameResolver.getDafnyType(inputForPositional, symbolForPositional); } else { inputType = DafnyNameResolver.getDafnyType(input, inputSymbol); diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java index 8a89a99a7b..2f930e954e 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java @@ -2,6 +2,7 @@ import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.model.shapes.Shape; +import software.amazon.smithy.model.traits.EnumTrait; import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.DOT; @@ -23,6 +24,27 @@ public static String dafnyNamespace(final Shape shape) { } public static String getDafnyType(final Shape shape, final Symbol symbol) { + + switch (shape.getType()) { + case STRING: + if (shape.hasTrait(EnumTrait.class)) { + return getDafnyTypeDefaultCase(shape, symbol); + } + else { + return "dafny.Sequence"; + } + // case MAP: + // return "map"; + // case STRUCTURE: + // case UNION: + // return symbol.getName(); + default: + return getDafnyTypeDefaultCase(shape, symbol); + } + + } + + private static String getDafnyTypeDefaultCase(final Shape shape, final Symbol symbol) { return DafnyNameResolver.dafnyTypesNamespace(shape) .concat(DOT) .concat(symbol.getName()); From 68f868fbb84741b6b9df7368450cc3a076450226 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Fri, 9 Aug 2024 12:19:57 -0700 Subject: [PATCH 11/44] maybe output to output --- .../smithygo/localservice/DafnyLocalServiceGenerator.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java index eb7e439923..c936b7a8aa 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java @@ -121,7 +121,7 @@ func NewClient(clientConfig $L) (*$T, error) { } final var inputType = inputShape.hasTrait(UnitTypeTrait.class) ? "" : ", params %s.%s".formatted(SmithyNameResolver.smithyTypesNamespace(inputShape), inputShape.toShapeId().getName()); - var maybeOutputType = outputShape.hasTrait(UnitTypeTrait.class) ? "" + var outputType = outputShape.hasTrait(UnitTypeTrait.class) ? "" : "*%s.%s,".formatted(SmithyNameResolver.smithyTypesNamespace(outputShape), outputShape.toShapeId().getName()); String validationCheck = ""; if(!inputType.equals("")) { @@ -132,7 +132,7 @@ func NewClient(clientConfig $L) (*$T, error) { ErrObject: err, } """.formatted(SmithyNameResolver.smithyTypesNamespace(inputShape)); - if(maybeOutputType.equals("")) { + if(outputType.equals("")) { validationCheck += "return opaqueErr }"; } else{ @@ -162,11 +162,9 @@ func NewClient(clientConfig $L) (*$T, error) { } String returnResponse, returnError; - final String outputType; if (outputShape.hasTrait(UnitTypeTrait.class)) { returnResponse = "return nil"; returnError = "return"; - outputType = maybeOutputType; } else { if (inputShape.hasTrait(PositionalTrait.class)) { returnResponse = """ @@ -175,7 +173,6 @@ func NewClient(clientConfig $L) (*$T, error) { """; } else { - outputType = maybeOutputType; returnResponse = """ var native_response = %s(dafny_response.Extract().(%s)) return &native_response, nil From f5b9b362a228819b21a1eaf310cbb60f3ee4699c Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Fri, 9 Aug 2024 12:57:13 -0700 Subject: [PATCH 12/44] get dafny type from DafnyNameResolver --- .../localservice/DafnyLocalServiceGenerator.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java index c936b7a8aa..131eddb8ce 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java @@ -16,6 +16,7 @@ import software.amazon.polymorph.traits.LocalServiceTrait; import software.amazon.polymorph.traits.PositionalTrait; import software.amazon.polymorph.traits.ReferenceTrait; +import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.TopDownIndex; @@ -145,11 +146,10 @@ func NewClient(clientConfig $L) (*$T, error) { } else { String dafnyType; if (inputShape.hasTrait(PositionalTrait.class)) { - // TODO: Change this - // System.out.println(SmithyNameResolver.shapeNamespace(outputShape.getAllMembers().values().stream().findFirst().get())); - // System.out.println(SmithyNameResolver.getSmithyType(b, symbolProvider.toSymbol(b))); - // System.out.println(symbolProvider.toSymbol(model.expectShape(ReferentId))); - dafnyType = "dafny.Sequence"; + Shape inputForPositional = model.expectShape(inputShape.getAllMembers().values().stream().findFirst().get().getTarget()); + Symbol symbolForPositional = symbolProvider.toSymbol(inputForPositional); + dafnyType = DafnyNameResolver.getDafnyType(inputForPositional, symbolForPositional); + outputType = "interface{},"; } else { dafnyType = DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(inputShape)); From fd66e38554fcf8858a11d0a1e8db5b509ad57f72 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Sat, 10 Aug 2024 15:38:10 -0700 Subject: [PATCH 13/44] remove print statement --- .../polymorph/smithygo/codegen/StructureGenerator.java | 7 ------- 1 file changed, 7 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java index bcb56a9c9f..b4958e00cb 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java @@ -125,14 +125,7 @@ public void renderStructure(Runnable runnable, boolean isInputStructure) { writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(targetShape.toShapeId().getNamespace()), namespace); } } - - System.out.println(memberSymbol); writer.write("$L $P", memberName, memberSymbol); - System.out.println(""" - \n\n\n - >>>> - %s - """.formatted(writer)); }); writer.closeBlock("}").write(""); renderValidator(symbol, sortedMembers, isInputStructure); From fa80eb9303d4feab0cf373e82e365f6eaf8ed89a Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Sat, 10 Aug 2024 15:47:00 -0700 Subject: [PATCH 14/44] api client part where we return values --- .../smithygo/localservice/DafnyLocalServiceGenerator.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java index 131eddb8ce..b1dc1883c4 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java @@ -268,9 +268,11 @@ void generateShim() { inputType = maybeInputType; } else { if (inputShape.hasTrait(PositionalTrait.class)) { - // TODO: get dafny.Sequence from name resolver writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - inputType = "input %s".formatted("dafny.Sequence"); + Shape inputForPositional = model.expectShape(inputShape.getAllMembers().values().stream().findFirst().get().getTarget()); + Symbol symbolForPositional = symbolProvider.toSymbol(inputForPositional); + String dafnyType = DafnyNameResolver.getDafnyType(inputForPositional, symbolForPositional); + inputType = "input %s".formatted(dafnyType); returnResponse = "(native_response)"; } else { From 29f4a01968a89c489aedf6f2a9d1476168b0a94e Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Sat, 10 Aug 2024 15:48:25 -0700 Subject: [PATCH 15/44] Uncomment so that CI runs --- .github/workflows/test_models_go_tests.yml | 69 +++++++++++----------- 1 file changed, 34 insertions(+), 35 deletions(-) diff --git a/.github/workflows/test_models_go_tests.yml b/.github/workflows/test_models_go_tests.yml index b8622bc78f..dfcd8f0d1b 100644 --- a/.github/workflows/test_models_go_tests.yml +++ b/.github/workflows/test_models_go_tests.yml @@ -8,42 +8,41 @@ jobs: fail-fast: false matrix: library: [ - TestModels/Positional # TODO: Uncomment below before making PR - # # TestModels/dafny-dependencies/StandardLibrary, # This stores current Polymorph dependencies that all TestModels depend on - # TestModels/Aggregate, - # # TestModels/AggregateReferences, - # TestModels/CodegenPatches, - # TestModels/Constraints, - # TestModels/Constructor, - # # TestModels/Dependencies, - # TestModels/Errors, - # TestModels/Extendable, - # TestModels/Extern, - # # TestModels/LanguageSpecificLogic, - # # TestModels/LocalService, - # # TestModels/MultipleModels, - # TestModels/Positional, - # TestModels/Refinement, - # TestModels/Resource, - # # TestModels/SimpleTypes/BigDecimal, - # # TestModels/SimpleTypes/BigInteger, - # TestModels/SimpleTypes/SimpleBlob, - # TestModels/SimpleTypes/SimpleBoolean, - # # TestModels/SimpleTypes/SimpleByte, - # TestModels/SimpleTypes/SimpleDouble, - # TestModels/SimpleTypes/SimpleEnum, - # # TestModels/SimpleTypes/SimpleEnumV2, - # # TestModels/SimpleTypes/SimpleFloat, - # TestModels/SimpleTypes/SimpleInteger, - # TestModels/SimpleTypes/SimpleLong, - # # TestModels/SimpleTypes/SimpleShort, - # TestModels/SimpleTypes/SimpleString, - # # TestModels/SimpleTypes/SimpleTimestamp, - # # TestModels/Union, - # # TestModels/aws-sdks/ddb, - # # TestModels/aws-sdks/kms - # ] + # TestModels/dafny-dependencies/StandardLibrary, # This stores current Polymorph dependencies that all TestModels depend on + TestModels/Aggregate, + # TestModels/AggregateReferences, + TestModels/CodegenPatches, + TestModels/Constraints, + TestModels/Constructor, + # TestModels/Dependencies, + TestModels/Errors, + TestModels/Extendable, + TestModels/Extern, + # TestModels/LanguageSpecificLogic, + # TestModels/LocalService, + # TestModels/MultipleModels, + TestModels/Positional, + TestModels/Refinement, + TestModels/Resource, + # TestModels/SimpleTypes/BigDecimal, + # TestModels/SimpleTypes/BigInteger, + TestModels/SimpleTypes/SimpleBlob, + TestModels/SimpleTypes/SimpleBoolean, + # TestModels/SimpleTypes/SimpleByte, + TestModels/SimpleTypes/SimpleDouble, + TestModels/SimpleTypes/SimpleEnum, + # TestModels/SimpleTypes/SimpleEnumV2, + # TestModels/SimpleTypes/SimpleFloat, + TestModels/SimpleTypes/SimpleInteger, + TestModels/SimpleTypes/SimpleLong, + # TestModels/SimpleTypes/SimpleShort, + TestModels/SimpleTypes/SimpleString, + # TestModels/SimpleTypes/SimpleTimestamp, + # TestModels/Union, + # TestModels/aws-sdks/ddb, + # TestModels/aws-sdks/kms + ] runs-on: "macos-12" steps: - uses: actions/checkout@v2 From c6b27c1468294ebf0df640ad3ec64bfcbedac300 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Sat, 10 Aug 2024 16:39:44 -0700 Subject: [PATCH 16/44] Remove runtimes --- .../ImplementationFromDafny-go.dtr | 14 - .../ImplementationFromDafny.go | 25 - .../SimplePositionalImpl.go | 213 ---- .../SimpleResource.go | 34 - .../SimpleResource/SimpleResource.go | 108 -- .../ImplementationFromDafny-go/api_client.go | 66 -- .../go/ImplementationFromDafny-go/go.mod | 11 - .../simplepositional/SimpleResource.go | 34 - .../simplepositional/api_client.go | 66 -- .../simplepositional/to_dafny.go | 144 --- .../simplepositional/to_native.go | 160 --- .../simplepositionalinternaldafny.go | 190 ---- .../simplepositionalinternaldafnytypes.go | 993 ------------------ .../shim.go | 43 - .../simplepositionaltypes/errors.go | 18 - .../simplepositionaltypes/types.go | 93 -- .../unmodelled_errors.go | 26 - .../go/ImplementationFromDafny-go/to_dafny.go | 144 --- .../ImplementationFromDafny-go/to_native.go | 160 --- .../SimplePositionalImpl.go | 213 ---- .../SimplePositionalImplTest.go | 170 --- .../go/TestsFromDafny-go/SimpleResource.go | 34 - .../SimpleResource/SimpleResource.go | 107 -- .../TestsFromDafny-go/TestsFromDafny-go.dtr | 22 - .../go/TestsFromDafny-go/TestsFromDafny.go | 118 --- .../WrappedSimplePositionalTest.go | 85 -- .../go/TestsFromDafny-go/api_client.go | 66 -- .../runtimes/go/TestsFromDafny-go/go.mod | 11 - .../simplepositional/SimpleResource.go | 34 - .../simplepositional/api_client.go | 73 -- .../simplepositional/to_dafny.go | 130 --- .../simplepositional/to_native.go | 154 --- .../simplepositionalinternaldafny.go | 188 ---- .../simplepositionalinternaldafnytypes.go | 993 ------------------ .../shim.go | 59 -- .../simplepositionalinternaldafnywrapped.go | 70 -- .../simplepositionaltypes/errors.go | 18 - .../simplepositionaltypes/types.go | 93 -- .../unmodelled_errors.go | 26 - .../runtimes/go/TestsFromDafny-go/to_dafny.go | 144 --- .../go/TestsFromDafny-go/to_native.go | 160 --- .../Positional/runtimes/java/build.gradle.kts | 80 -- .../Dafny/simple/positional/__default.java | 5 - .../internaldafny/wrapped/__default.java | 32 - 44 files changed, 5627 deletions(-) delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny-go.dtr delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource/SimpleResource.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/api_client.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/go.mod delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/SimpleResource.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/api_client.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_dafny.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_native.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnywrapped/shim.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/errors.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/types.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/unmodelled_errors.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_dafny.go delete mode 100644 TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_native.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImplTest/SimplePositionalImplTest.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource/SimpleResource.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny-go.dtr delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/WrappedSimplePositionalTest/WrappedSimplePositionalTest.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/api_client.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/go.mod delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/SimpleResource.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/api_client.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_dafny.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_native.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/shim.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/simplepositionalinternaldafnywrapped.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/errors.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/types.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/unmodelled_errors.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/to_dafny.go delete mode 100644 TestModels/Positional/runtimes/go/TestsFromDafny-go/to_native.go delete mode 100644 TestModels/Positional/runtimes/java/build.gradle.kts delete mode 100644 TestModels/Positional/runtimes/java/src/main/java/Dafny/simple/positional/__default.java delete mode 100644 TestModels/Positional/runtimes/java/src/test/java/simple/positional/internaldafny/wrapped/__default.java diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny-go.dtr b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny-go.dtr deleted file mode 100644 index 2f8abe1715..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny-go.dtr +++ /dev/null @@ -1,14 +0,0 @@ -file_format_version = "1.0" -dafny_version = "4.6.0.0" -[options_by_module.SimplePositionalTypes] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" -[options_by_module.AbstractSimplePositionalOperations] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" -[options_by_module.AbstractSimplePositionalService] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" -[options_by_module.SimpleResource] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" -[options_by_module.SimplePositionalImpl] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" -[options_by_module.SimplePositional] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny.go deleted file mode 100644 index 66bc0796bd..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny.go +++ /dev/null @@ -1,25 +0,0 @@ -// Dafny program the_program compiled into Go -package the_program - -import ( - os "os" - - SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" - SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" - _System "github.com/dafny-lang/DafnyRuntimeGo/System_" - _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" - StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" - StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" - StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" - Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -var _ = os.Args -var _ _dafny.Dummy__ -var _ _System.Dummy__ -var _ Wrappers.Dummy__ -var _ StandardLibrary_UInt.Dummy__ -var _ StandardLibrary.Dummy__ -var _ StandardLibraryInterop.Dummy__ -var _ SimpleResource.Dummy__ -var _ SimplePositionalImpl.Dummy__ diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go deleted file mode 100644 index dee6c1def6..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go +++ /dev/null @@ -1,213 +0,0 @@ -// Package SimplePositionalImpl -// Dafny module SimplePositionalImpl compiled into Go - -package SimplePositionalImpl - -import ( - "fmt" - os "os" - - SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" - simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - _System "github.com/dafny-lang/DafnyRuntimeGo/System_" - _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" - StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" - StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" - StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" - Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -var _ = os.Args -var _ _dafny.Dummy__ -var _ _System.Dummy__ -var _ Wrappers.Dummy__ -var _ StandardLibrary_UInt.Dummy__ -var _ StandardLibrary.Dummy__ -var _ StandardLibraryInterop.Dummy__ -var _ SimpleResource.Dummy__ - -type Dummy__ struct{} - -// Definition of class Default__ -type Default__ struct { - dummy byte -} - -func New_Default___() *Default__ { - _this := Default__{} - - return &_this -} - -type CompanionStruct_Default___ struct { -} - -var Companion_Default___ = CompanionStruct_Default___{} - -func (_this *Default__) Equals(other *Default__) bool { - return _this == other -} - -func (_this *Default__) EqualsGeneric(x interface{}) bool { - other, ok := x.(*Default__) - return ok && _this.Equals(other) -} - -func (*Default__) String() string { - return "SimplePositionalImpl.Default__" -} -func (_this *Default__) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = &Default__{} - -func (_static *CompanionStruct_Default___) GetResource(config Config, input simplepositionalinternaldafnytypes.GetResourceInput) Wrappers.Result { - var output Wrappers.Result = Wrappers.Result{} - _ = output - var _1_resource *SimpleResource.SimpleResource - _ = _1_resource - var _nw0 *SimpleResource.SimpleResource = SimpleResource.New_SimpleResource_() - _ = _nw0 - _nw0.Ctor__((input).Dtor_name()) - _1_resource = _nw0 - var _2_result simplepositionalinternaldafnytypes.GetResourceOutput - _ = _2_result - _2_result = simplepositionalinternaldafnytypes.Companion_GetResourceOutput_.Create_GetResourceOutput_(_1_resource) - output = Wrappers.Companion_Result_.Create_Success_(_2_result) - return output - return output -} - -// recover function to handle panic -func handlePanic() { - - // detect if panic occurs or not - a := recover() - - if a != nil { - fmt.Println("RECOVER Simple Positional Impl", a) - } - -} -func (_static *CompanionStruct_Default___) GetResourcePositional(config Config, input _dafny.Sequence) Wrappers.Result { - defer handlePanic() - var output Wrappers.Result = Wrappers.Result{} - _ = output - var _3_resource *SimpleResource.SimpleResource - _ = _3_resource - var _nw1 *SimpleResource.SimpleResource = SimpleResource.New_SimpleResource_() - _ = _nw1 - _nw1.Ctor__(input) - _3_resource = _nw1 - output = Wrappers.Companion_Result_.Create_Success_(_3_resource) - return output - return output -} - -// End of class Default__ - -// Definition of datatype Config -type Config struct { - Data_Config_ -} - -func (_this Config) Get_() Data_Config_ { - return _this.Data_Config_ -} - -type Data_Config_ interface { - isConfig() -} - -type CompanionStruct_Config_ struct { -} - -var Companion_Config_ = CompanionStruct_Config_{} - -type Config_Config struct { -} - -func (Config_Config) isConfig() {} - -func (CompanionStruct_Config_) Create_Config_() Config { - return Config{Config_Config{}} -} - -func (_this Config) Is_Config() bool { - _, ok := _this.Get_().(Config_Config) - return ok -} - -func (CompanionStruct_Config_) Default() Config { - return Companion_Config_.Create_Config_() -} - -func (_ CompanionStruct_Config_) AllSingletonConstructors() _dafny.Iterator { - i := -1 - return func() (interface{}, bool) { - i++ - switch i { - case 0: - return Companion_Config_.Create_Config_(), true - default: - return Config{}, false - } - } -} - -func (_this Config) String() string { - switch _this.Get_().(type) { - case nil: - return "null" - case Config_Config: - { - return "SimplePositionalImpl.Config.Config" - } - default: - { - return "" - } - } -} - -func (_this Config) Equals(other Config) bool { - switch _this.Get_().(type) { - case Config_Config: - { - _, ok := other.Get_().(Config_Config) - return ok - } - default: - { - return false // unexpected - } - } -} - -func (_this Config) EqualsGeneric(other interface{}) bool { - typed, ok := other.(Config) - return ok && _this.Equals(typed) -} - -func Type_Config_() _dafny.TypeDescriptor { - return type_Config_{} -} - -type type_Config_ struct { -} - -func (_this type_Config_) Default() interface{} { - return Companion_Config_.Default() -} - -func (_this type_Config_) String() string { - return "SimplePositionalImpl.Config" -} -func (_this Config) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = Config{} - -// End of datatype Config diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource.go deleted file mode 100644 index 53f16e63ab..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource.go +++ /dev/null @@ -1,34 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" -) - -type SimpleResource struct { - Impl simplepositionalinternaldafnytypes.ISimpleResource -} - -func (this *SimpleResource) GetName(params simplepositionaltypes.GetNameInput) (*simplepositionaltypes.GetNameOutput, error) { - var dafny_request simplepositionalinternaldafnytypes.GetNameInput = GetNameInput_ToDafny(params) - var dafny_response = this.Impl.GetName(dafny_request) - - if dafny_response.Is_Failure() { - err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) - if err.Is_SimplePositionalException() { - return nil, SimplePositionalException_FromDafny(err) - } - - if err.Is_CollectionOfErrors() { - return nil, CollectionOfErrors_Output_FromDafny(err) - } - if err.Is_Opaque() { - return nil, OpaqueError_Output_FromDafny(err) - } - } - var native_response = GetNameOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetNameOutput)) - return &native_response, nil - -} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource/SimpleResource.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource/SimpleResource.go deleted file mode 100644 index 89b1ff0a17..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/SimpleResource/SimpleResource.go +++ /dev/null @@ -1,108 +0,0 @@ -// Package SimpleResource -// Dafny module SimpleResource compiled into Go - -package SimpleResource - -import ( - "fmt" - os "os" - - simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - _System "github.com/dafny-lang/DafnyRuntimeGo/System_" - _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" - StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" - StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" - StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" - Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -var _ = os.Args -var _ _dafny.Dummy__ -var _ _System.Dummy__ -var _ Wrappers.Dummy__ -var _ StandardLibrary_UInt.Dummy__ -var _ StandardLibrary.Dummy__ -var _ StandardLibraryInterop.Dummy__ - -type Dummy__ struct{} - -// Definition of class SimpleResource -type SimpleResource struct { - _name _dafny.Sequence -} - -func New_SimpleResource_() *SimpleResource { - _this := SimpleResource{} - - _this._name = _dafny.EmptySeq.SetString() - return &_this -} - -type CompanionStruct_SimpleResource_ struct { -} - -var Companion_SimpleResource_ = CompanionStruct_SimpleResource_{} - -func (_this *SimpleResource) Equals(other *SimpleResource) bool { - return _this == other -} - -func (_this *SimpleResource) EqualsGeneric(x interface{}) bool { - other, ok := x.(*SimpleResource) - return ok && _this.Equals(other) -} - -func (_this *SimpleResource) String() string { - fmt.Println(_this._name) - return "_this._name" -} - -func Type_SimpleResource_() _dafny.TypeDescriptor { - return type_SimpleResource_{} -} - -type type_SimpleResource_ struct { -} - -func (_this type_SimpleResource_) Default() interface{} { - return (*SimpleResource)(nil) -} - -func (_this type_SimpleResource_) String() string { - - return "SimpleResource.SimpleResource yo" -} -func (_this *SimpleResource) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){simplepositionalinternaldafnytypes.Companion_ISimpleResource_.TraitID_} -} - -var _ simplepositionalinternaldafnytypes.ISimpleResource = &SimpleResource{} -var _ _dafny.TraitOffspring = &SimpleResource{} - -func (_this *SimpleResource) GetName(input simplepositionalinternaldafnytypes.GetNameInput) Wrappers.Result { - var _out1 Wrappers.Result - _ = _out1 - _out1 = simplepositionalinternaldafnytypes.Companion_ISimpleResource_.GetName(_this, input) - return _out1 -} -func (_this *SimpleResource) Ctor__(name _dafny.Sequence) { - { - (_this)._name = name - } -} -func (_this *SimpleResource) GetName_k(input simplepositionalinternaldafnytypes.GetNameInput) Wrappers.Result { - { - var output Wrappers.Result = Wrappers.Companion_Result_.Default(simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Default()) - _ = output - output = Wrappers.Companion_Result_.Create_Success_(simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Create_GetNameOutput_((_this).Name())) - return output - return output - } -} -func (_this *SimpleResource) Name() _dafny.Sequence { - { - return _this._name - } -} - -// End of class SimpleResource diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/api_client.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/api_client.go deleted file mode 100644 index 8419c833fc..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/api_client.go +++ /dev/null @@ -1,66 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "context" - - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafny" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" -) - -type Client struct { - DafnyClient *simplepositionalinternaldafny.SimplePositionalClient -} - -func NewClient(clientConfig simplepositionaltypes.SimplePositionalConfig) (*Client, error) { - var dafnyConfig = SimplePositionalConfig_ToDafny(clientConfig) - var dafny_response = simplepositionalinternaldafny.Companion_Default___.SimplePositional(dafnyConfig) - if dafny_response.Is_Failure() { - panic("Client construction failed. This should never happen") - } - var dafnyClient = dafny_response.Extract().(*simplepositionalinternaldafny.SimplePositionalClient) - client := &Client{dafnyClient} - return client, nil -} - -func (client *Client) GetResource(ctx context.Context, params simplepositionaltypes.GetResourceInput) (*simplepositionaltypes.GetResourceOutput, error) { - err := params.Validate() - if err != nil { - opaqueErr := &simplepositionaltypes.OpaqueError{ - ErrObject: err, - } - return nil, opaqueErr - } - var dafny_request simplepositionalinternaldafnytypes.GetResourceInput = GetResourceInput_ToDafny(params) - var dafny_response = client.DafnyClient.GetResource(dafny_request) - - if dafny_response.Is_Failure() { - err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) - return nil, Error_FromDafny(err) - } - var native_response = GetResourceOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourceOutput)) - return &native_response, nil - -} - -func (client *Client) GetResourcePositional(ctx context.Context, params simplepositionaltypes.GetResourcePositionalInput) (*simplepositionaltypes.GetResourcePositionalOutput, error) { - err := params.Validate() - if err != nil { - opaqueErr := &simplepositionaltypes.OpaqueError{ - ErrObject: err, - } - return nil, opaqueErr - } - var dafny_request simplepositionalinternaldafnytypes.GetResourcePositionalInput = GetResourcePositionalInput_ToDafny(params) - var dafny_response = client.DafnyClient.GetResourcePositional(dafny_request) - - if dafny_response.Is_Failure() { - err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) - return nil, Error_FromDafny(err) - } - var native_response = GetResourcePositionalOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourcePositionalOutput)) - return &native_response, nil - -} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/go.mod b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/go.mod deleted file mode 100644 index e852819557..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/go.mod +++ /dev/null @@ -1,11 +0,0 @@ -module github.com/Smithy-dafny/TestModels/Positional - -go 1.22.2 - -require github.com/dafny-lang/DafnyStandardLibGo v0.0.0 - -require github.com/dafny-lang/DafnyRuntimeGo v0.0.0 - -replace github.com/dafny-lang/DafnyRuntimeGo => ../../../../../DafnyRuntimeGo/ - -replace github.com/dafny-lang/DafnyStandardLibGo => ../../../../dafny-dependencies/StandardLibrary/runtimes/go/ImplementationFromDafny-go/ diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/SimpleResource.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/SimpleResource.go deleted file mode 100644 index 53f16e63ab..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/SimpleResource.go +++ /dev/null @@ -1,34 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" -) - -type SimpleResource struct { - Impl simplepositionalinternaldafnytypes.ISimpleResource -} - -func (this *SimpleResource) GetName(params simplepositionaltypes.GetNameInput) (*simplepositionaltypes.GetNameOutput, error) { - var dafny_request simplepositionalinternaldafnytypes.GetNameInput = GetNameInput_ToDafny(params) - var dafny_response = this.Impl.GetName(dafny_request) - - if dafny_response.Is_Failure() { - err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) - if err.Is_SimplePositionalException() { - return nil, SimplePositionalException_FromDafny(err) - } - - if err.Is_CollectionOfErrors() { - return nil, CollectionOfErrors_Output_FromDafny(err) - } - if err.Is_Opaque() { - return nil, OpaqueError_Output_FromDafny(err) - } - } - var native_response = GetNameOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetNameOutput)) - return &native_response, nil - -} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/api_client.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/api_client.go deleted file mode 100644 index 8419c833fc..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/api_client.go +++ /dev/null @@ -1,66 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "context" - - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafny" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" -) - -type Client struct { - DafnyClient *simplepositionalinternaldafny.SimplePositionalClient -} - -func NewClient(clientConfig simplepositionaltypes.SimplePositionalConfig) (*Client, error) { - var dafnyConfig = SimplePositionalConfig_ToDafny(clientConfig) - var dafny_response = simplepositionalinternaldafny.Companion_Default___.SimplePositional(dafnyConfig) - if dafny_response.Is_Failure() { - panic("Client construction failed. This should never happen") - } - var dafnyClient = dafny_response.Extract().(*simplepositionalinternaldafny.SimplePositionalClient) - client := &Client{dafnyClient} - return client, nil -} - -func (client *Client) GetResource(ctx context.Context, params simplepositionaltypes.GetResourceInput) (*simplepositionaltypes.GetResourceOutput, error) { - err := params.Validate() - if err != nil { - opaqueErr := &simplepositionaltypes.OpaqueError{ - ErrObject: err, - } - return nil, opaqueErr - } - var dafny_request simplepositionalinternaldafnytypes.GetResourceInput = GetResourceInput_ToDafny(params) - var dafny_response = client.DafnyClient.GetResource(dafny_request) - - if dafny_response.Is_Failure() { - err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) - return nil, Error_FromDafny(err) - } - var native_response = GetResourceOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourceOutput)) - return &native_response, nil - -} - -func (client *Client) GetResourcePositional(ctx context.Context, params simplepositionaltypes.GetResourcePositionalInput) (*simplepositionaltypes.GetResourcePositionalOutput, error) { - err := params.Validate() - if err != nil { - opaqueErr := &simplepositionaltypes.OpaqueError{ - ErrObject: err, - } - return nil, opaqueErr - } - var dafny_request simplepositionalinternaldafnytypes.GetResourcePositionalInput = GetResourcePositionalInput_ToDafny(params) - var dafny_response = client.DafnyClient.GetResourcePositional(dafny_request) - - if dafny_response.Is_Failure() { - err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) - return nil, Error_FromDafny(err) - } - var native_response = GetResourcePositionalOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourcePositionalOutput)) - return &native_response, nil - -} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_dafny.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_dafny.go deleted file mode 100644 index 39442e0038..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_dafny.go +++ /dev/null @@ -1,144 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" - "github.com/dafny-lang/DafnyRuntimeGo/dafny" -) - -func GetResourceInput_ToDafny(nativeInput simplepositionaltypes.GetResourceInput) simplepositionalinternaldafnytypes.GetResourceInput { - - return func() simplepositionalinternaldafnytypes.GetResourceInput { - - return simplepositionalinternaldafnytypes.Companion_GetResourceInput_.Create_GetResourceInput_(func() dafny.Sequence { - if nativeInput.Name == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) - }()) - }() - -} - -func GetResourceOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourceOutput) simplepositionalinternaldafnytypes.GetResourceOutput { - - return func() simplepositionalinternaldafnytypes.GetResourceOutput { - - return simplepositionalinternaldafnytypes.Companion_GetResourceOutput_.Create_GetResourceOutput_(SimpleResource_ToDafny(nativeOutput.Output)) - }() - -} - -func GetResourcePositionalInput_ToDafny(nativeInput simplepositionaltypes.GetResourcePositionalInput) simplepositionalinternaldafnytypes.GetResourcePositionalInput { - - return func() simplepositionalinternaldafnytypes.GetResourcePositionalInput { - - return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalInput_.Create_GetResourcePositionalInput_(func() dafny.Sequence { - if nativeInput.Name == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) - }()) - }() - -} - -func GetResourcePositionalOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourcePositionalOutput) simplepositionalinternaldafnytypes.GetResourcePositionalOutput { - - return func() simplepositionalinternaldafnytypes.GetResourcePositionalOutput { - - return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalOutput_.Create_GetResourcePositionalOutput_(SimpleResource_ToDafny(nativeOutput.Output)) - }() - -} - -func GetNameInput_ToDafny(nativeInput simplepositionaltypes.GetNameInput) simplepositionalinternaldafnytypes.GetNameInput { - - return func() simplepositionalinternaldafnytypes.GetNameInput { - - return simplepositionalinternaldafnytypes.Companion_GetNameInput_.Create_GetNameInput_() - }() - -} - -func GetNameOutput_ToDafny(nativeOutput simplepositionaltypes.GetNameOutput) simplepositionalinternaldafnytypes.GetNameOutput { - - return func() simplepositionalinternaldafnytypes.GetNameOutput { - - return simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Create_GetNameOutput_(func() dafny.Sequence { - if nativeOutput.Name == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeOutput.Name)...) - }()) - }() - -} - -func SimpleResource_ToDafny(nativeResource simplepositionaltypes.ISimpleResource) simplepositionalinternaldafnytypes.ISimpleResource { - return nativeResource.(*SimpleResource).Impl - -} - -func SimplePositionalException_ToDafny(nativeInput simplepositionaltypes.SimplePositionalException) simplepositionalinternaldafnytypes.Error { - return func() simplepositionalinternaldafnytypes.Error { - - return simplepositionalinternaldafnytypes.Companion_Error_.Create_SimplePositionalException_(func() dafny.Sequence { - if nativeInput.Message == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeInput.Message)...) - }()) - }() - -} - -func CollectionOfErrors_Input_ToDafny(nativeInput simplepositionaltypes.CollectionOfErrors) simplepositionalinternaldafnytypes.Error { - var e []interface{} - for _, i2 := range nativeInput.ListOfErrors { - e = append(e, Error_ToDafny(i2)) - } - return simplepositionalinternaldafnytypes.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) -} -func OpaqueError_Input_ToDafny(nativeInput simplepositionaltypes.OpaqueError) simplepositionalinternaldafnytypes.Error { - return simplepositionalinternaldafnytypes.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) -} - -func Error_ToDafny(err error) simplepositionalinternaldafnytypes.Error { - switch err.(type) { - // Service Errors - case simplepositionaltypes.SimplePositionalException: - return SimplePositionalException_ToDafny(err.(simplepositionaltypes.SimplePositionalException)) - - //DependentErrors - - //Unmodelled Errors - case simplepositionaltypes.CollectionOfErrors: - return CollectionOfErrors_Input_ToDafny(err.(simplepositionaltypes.CollectionOfErrors)) - - default: - // TODO: Is changing from the commented code to this new one reasonable? - // return OpaqueError_Input_ToDafny(err.(*simpleconstraintstypes.OpaqueError)) - - // TODO: why is err a pointer? - error, ok := err.(*simplepositionaltypes.OpaqueError) - - if !ok { - panic("Error is not an OpaqueError") - } - if error == nil { - panic("Error is nil") - } - return OpaqueError_Input_ToDafny(*error) - } -} - -func SimplePositionalConfig_ToDafny(nativeInput simplepositionaltypes.SimplePositionalConfig) simplepositionalinternaldafnytypes.SimplePositionalConfig { - return func() simplepositionalinternaldafnytypes.SimplePositionalConfig { - - return simplepositionalinternaldafnytypes.Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() - }() - -} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_native.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_native.go deleted file mode 100644 index 23328bb04f..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositional/to_native.go +++ /dev/null @@ -1,160 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" - "github.com/dafny-lang/DafnyRuntimeGo/dafny" -) - -func GetResourceInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourceInput) simplepositionaltypes.GetResourceInput { - - return simplepositionaltypes.GetResourceInput{Name: func() *string { - var s string - if dafnyInput.Dtor_name() == nil { - return nil - } - for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func GetResourceOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourceOutput) simplepositionaltypes.GetResourceOutput { - - return simplepositionaltypes.GetResourceOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} - -} - -func GetResourcePositionalInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourcePositionalInput) simplepositionaltypes.GetResourcePositionalInput { - - return simplepositionaltypes.GetResourcePositionalInput{Name: func() *string { - var s string - if dafnyInput.Dtor_name() == nil { - return nil - } - for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func GetResourcePositionalOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourcePositionalOutput) simplepositionaltypes.GetResourcePositionalOutput { - - return simplepositionaltypes.GetResourcePositionalOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} - -} - -func GetNameInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetNameInput) simplepositionaltypes.GetNameInput { - - return simplepositionaltypes.GetNameInput{} - -} - -func GetNameOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetNameOutput) simplepositionaltypes.GetNameOutput { - - return simplepositionaltypes.GetNameOutput{Name: func() *string { - var s string - if dafnyOutput.Dtor_name() == nil { - return nil - } - for i := dafny.Iterate(dafnyOutput.Dtor_name()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func SimpleResource_FromDafny(dafnyResource simplepositionalinternaldafnytypes.ISimpleResource) simplepositionaltypes.ISimpleResource { - - return &SimpleResource{dafnyResource} -} - -func SimplePositionalException_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.SimplePositionalException { - return simplepositionaltypes.SimplePositionalException{Message: func() *string { - var s string - if dafnyOutput.Dtor_message() == nil { - return nil - } - for i := dafny.Iterate(dafnyOutput.Dtor_message()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func CollectionOfErrors_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.CollectionOfErrors { - listOfErrors := dafnyOutput.Dtor_list() - message := dafnyOutput.Dtor_message() - t := simplepositionaltypes.CollectionOfErrors{} - for i := dafny.Iterate(listOfErrors); ; { - val, ok := i() - if !ok { - break - } - err := val.(simplepositionalinternaldafnytypes.Error) - t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) - - } - t.Message = func() string { - var s string - for i := dafny.Iterate(message); ; { - val, ok := i() - if !ok { - return s - } else { - s = s + string(val.(dafny.Char)) - } - } - }() - return t -} -func OpaqueError_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.OpaqueError { - return simplepositionaltypes.OpaqueError{ - ErrObject: dafnyOutput.Dtor_obj(), - } -} - -func Error_FromDafny(err simplepositionalinternaldafnytypes.Error) error { - // Service Errors - if err.Is_SimplePositionalException() { - return SimplePositionalException_FromDafny(err) - } - - //DependentErrors - - //Unmodelled Errors - if err.Is_CollectionOfErrors() { - return CollectionOfErrors_Output_FromDafny(err) - } - - return OpaqueError_Output_FromDafny(err) -} - -func SimplePositionalConfig_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.SimplePositionalConfig) simplepositionaltypes.SimplePositionalConfig { - return simplepositionaltypes.SimplePositionalConfig{} - -} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go deleted file mode 100644 index 3b803d2483..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go +++ /dev/null @@ -1,190 +0,0 @@ -// Package simplepositionalinternaldafny -// Dafny module simplepositionalinternaldafny compiled into Go - -package simplepositionalinternaldafny - -import ( - "fmt" - os "os" - - SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" - SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" - simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - _System "github.com/dafny-lang/DafnyRuntimeGo/System_" - _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" - StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" - StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" - StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" - Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -var _ = os.Args -var _ _dafny.Dummy__ -var _ _System.Dummy__ -var _ Wrappers.Dummy__ -var _ StandardLibrary_UInt.Dummy__ -var _ StandardLibrary.Dummy__ -var _ StandardLibraryInterop.Dummy__ -var _ SimpleResource.Dummy__ -var _ SimplePositionalImpl.Dummy__ - -type Dummy__ struct{} - -// Definition of class Default__ -type Default__ struct { - dummy byte -} - -func New_Default___() *Default__ { - _this := Default__{} - - return &_this -} - -type CompanionStruct_Default___ struct { -} - -var Companion_Default___ = CompanionStruct_Default___{} - -func (_this *Default__) Equals(other *Default__) bool { - return _this == other -} - -func (_this *Default__) EqualsGeneric(x interface{}) bool { - other, ok := x.(*Default__) - return ok && _this.Equals(other) -} - -func (*Default__) String() string { - return "simplepositionalinternaldafny.Default__" -} -func (_this *Default__) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = &Default__{} - -func (_static *CompanionStruct_Default___) DefaultSimplePositionalConfig() simplepositionalinternaldafnytypes.SimplePositionalConfig { - return simplepositionalinternaldafnytypes.Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() -} -func (_static *CompanionStruct_Default___) SimplePositional(config simplepositionalinternaldafnytypes.SimplePositionalConfig) Wrappers.Result { - var res Wrappers.Result = Wrappers.Result{} - _ = res - var _4_client *SimplePositionalClient - _ = _4_client - var _nw2 *SimplePositionalClient = New_SimplePositionalClient_() - _ = _nw2 - _nw2.Ctor__(SimplePositionalImpl.Companion_Config_.Create_Config_()) - _4_client = _nw2 - res = Wrappers.Companion_Result_.Create_Success_(_4_client) - return res - return res -} -func (_static *CompanionStruct_Default___) CreateSuccessOfClient(client simplepositionalinternaldafnytypes.ISimplePositionalClient) Wrappers.Result { - return Wrappers.Companion_Result_.Create_Success_(client) -} -func (_static *CompanionStruct_Default___) CreateFailureOfError(error_ simplepositionalinternaldafnytypes.Error) Wrappers.Result { - return Wrappers.Companion_Result_.Create_Failure_(error_) -} - -// End of class Default__ - -// Definition of class SimplePositionalClient -type SimplePositionalClient struct { - _config SimplePositionalImpl.Config -} - -func New_SimplePositionalClient_() *SimplePositionalClient { - _this := SimplePositionalClient{} - - _this._config = SimplePositionalImpl.Companion_Config_.Default() - return &_this -} - -type CompanionStruct_SimplePositionalClient_ struct { -} - -var Companion_SimplePositionalClient_ = CompanionStruct_SimplePositionalClient_{} - -func (_this *SimplePositionalClient) Equals(other *SimplePositionalClient) bool { - return _this == other -} - -func (_this *SimplePositionalClient) EqualsGeneric(x interface{}) bool { - other, ok := x.(*SimplePositionalClient) - return ok && _this.Equals(other) -} - -func (*SimplePositionalClient) String() string { - return "simplepositionalinternaldafny.SimplePositionalClient" -} - -func Type_SimplePositionalClient_() _dafny.TypeDescriptor { - return type_SimplePositionalClient_{} -} - -type type_SimplePositionalClient_ struct { -} - -func (_this type_SimplePositionalClient_) Default() interface{} { - return (*SimplePositionalClient)(nil) -} - -func (_this type_SimplePositionalClient_) String() string { - return "simplepositionalinternaldafny.SimplePositionalClient" -} -func (_this *SimplePositionalClient) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){simplepositionalinternaldafnytypes.Companion_ISimplePositionalClient_.TraitID_} -} - -var _ simplepositionalinternaldafnytypes.ISimplePositionalClient = &SimplePositionalClient{} -var _ _dafny.TraitOffspring = &SimplePositionalClient{} - -func (_this *SimplePositionalClient) Ctor__(config SimplePositionalImpl.Config) { - { - (_this)._config = config - } -} -func (_this *SimplePositionalClient) GetResource(input simplepositionalinternaldafnytypes.GetResourceInput) Wrappers.Result { - { - var output Wrappers.Result = Wrappers.Result{} - _ = output - var _out2 Wrappers.Result - _ = _out2 - _out2 = SimplePositionalImpl.Companion_Default___.GetResource((_this).Config(), input) - output = _out2 - return output - } -} - -// recover function to handle panic -func handlePanic() { - - // detect if panic occurs or not - a := recover() - - if a != nil { - fmt.Println("RECOVER in simplepositionalinternaldafny", a) - } - -} - -func (_this *SimplePositionalClient) GetResourcePositional(input _dafny.Sequence) Wrappers.Result { - { - defer handlePanic() - var output Wrappers.Result = Wrappers.Result{} - _ = output - var _out3 Wrappers.Result - _ = _out3 - _out3 = SimplePositionalImpl.Companion_Default___.GetResourcePositional((_this).Config(), input) - output = _out3 - return output - } -} -func (_this *SimplePositionalClient) Config() SimplePositionalImpl.Config { - { - return _this._config - } -} - -// End of class SimplePositionalClient diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go deleted file mode 100644 index 45ca0af901..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go +++ /dev/null @@ -1,993 +0,0 @@ -// Package simplepositionalinternaldafnytypes -// Dafny module simplepositionalinternaldafnytypes compiled into Go - -package simplepositionalinternaldafnytypes - -import ( - os "os" - - _System "github.com/dafny-lang/DafnyRuntimeGo/System_" - _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" - StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" - StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" - StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" - Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -var _ = os.Args -var _ _dafny.Dummy__ -var _ _System.Dummy__ -var _ Wrappers.Dummy__ -var _ StandardLibrary_UInt.Dummy__ -var _ StandardLibrary.Dummy__ -var _ StandardLibraryInterop.Dummy__ - -type Dummy__ struct{} - -// Definition of datatype DafnyCallEvent -type DafnyCallEvent struct { - Data_DafnyCallEvent_ -} - -func (_this DafnyCallEvent) Get_() Data_DafnyCallEvent_ { - return _this.Data_DafnyCallEvent_ -} - -type Data_DafnyCallEvent_ interface { - isDafnyCallEvent() -} - -type CompanionStruct_DafnyCallEvent_ struct { -} - -var Companion_DafnyCallEvent_ = CompanionStruct_DafnyCallEvent_{} - -type DafnyCallEvent_DafnyCallEvent struct { - Input interface{} - Output interface{} -} - -func (DafnyCallEvent_DafnyCallEvent) isDafnyCallEvent() {} - -func (CompanionStruct_DafnyCallEvent_) Create_DafnyCallEvent_(Input interface{}, Output interface{}) DafnyCallEvent { - return DafnyCallEvent{DafnyCallEvent_DafnyCallEvent{Input, Output}} -} - -func (_this DafnyCallEvent) Is_DafnyCallEvent() bool { - _, ok := _this.Get_().(DafnyCallEvent_DafnyCallEvent) - return ok -} - -func (CompanionStruct_DafnyCallEvent_) Default(_default_I interface{}, _default_O interface{}) DafnyCallEvent { - return Companion_DafnyCallEvent_.Create_DafnyCallEvent_(_default_I, _default_O) -} - -func (_this DafnyCallEvent) Dtor_input() interface{} { - return _this.Get_().(DafnyCallEvent_DafnyCallEvent).Input -} - -func (_this DafnyCallEvent) Dtor_output() interface{} { - return _this.Get_().(DafnyCallEvent_DafnyCallEvent).Output -} - -func (_this DafnyCallEvent) String() string { - switch data := _this.Get_().(type) { - case nil: - return "null" - case DafnyCallEvent_DafnyCallEvent: - { - return "SimplePositionalTypes.DafnyCallEvent.DafnyCallEvent" + "(" + _dafny.String(data.Input) + ", " + _dafny.String(data.Output) + ")" - } - default: - { - return "" - } - } -} - -func (_this DafnyCallEvent) Equals(other DafnyCallEvent) bool { - switch data1 := _this.Get_().(type) { - case DafnyCallEvent_DafnyCallEvent: - { - data2, ok := other.Get_().(DafnyCallEvent_DafnyCallEvent) - return ok && _dafny.AreEqual(data1.Input, data2.Input) && _dafny.AreEqual(data1.Output, data2.Output) - } - default: - { - return false // unexpected - } - } -} - -func (_this DafnyCallEvent) EqualsGeneric(other interface{}) bool { - typed, ok := other.(DafnyCallEvent) - return ok && _this.Equals(typed) -} - -func Type_DafnyCallEvent_(Type_I_ _dafny.TypeDescriptor, Type_O_ _dafny.TypeDescriptor) _dafny.TypeDescriptor { - return type_DafnyCallEvent_{Type_I_, Type_O_} -} - -type type_DafnyCallEvent_ struct { - Type_I_ _dafny.TypeDescriptor - Type_O_ _dafny.TypeDescriptor -} - -func (_this type_DafnyCallEvent_) Default() interface{} { - Type_I_ := _this.Type_I_ - _ = Type_I_ - Type_O_ := _this.Type_O_ - _ = Type_O_ - return Companion_DafnyCallEvent_.Default(Type_I_.Default(), Type_O_.Default()) -} - -func (_this type_DafnyCallEvent_) String() string { - return "simplepositionalinternaldafnytypes.DafnyCallEvent" -} -func (_this DafnyCallEvent) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = DafnyCallEvent{} - -// End of datatype DafnyCallEvent - -// Definition of datatype GetNameInput -type GetNameInput struct { - Data_GetNameInput_ -} - -func (_this GetNameInput) Get_() Data_GetNameInput_ { - return _this.Data_GetNameInput_ -} - -type Data_GetNameInput_ interface { - isGetNameInput() -} - -type CompanionStruct_GetNameInput_ struct { -} - -var Companion_GetNameInput_ = CompanionStruct_GetNameInput_{} - -type GetNameInput_GetNameInput struct { -} - -func (GetNameInput_GetNameInput) isGetNameInput() {} - -func (CompanionStruct_GetNameInput_) Create_GetNameInput_() GetNameInput { - return GetNameInput{GetNameInput_GetNameInput{}} -} - -func (_this GetNameInput) Is_GetNameInput() bool { - _, ok := _this.Get_().(GetNameInput_GetNameInput) - return ok -} - -func (CompanionStruct_GetNameInput_) Default() GetNameInput { - return Companion_GetNameInput_.Create_GetNameInput_() -} - -func (_ CompanionStruct_GetNameInput_) AllSingletonConstructors() _dafny.Iterator { - i := -1 - return func() (interface{}, bool) { - i++ - switch i { - case 0: - return Companion_GetNameInput_.Create_GetNameInput_(), true - default: - return GetNameInput{}, false - } - } -} - -func (_this GetNameInput) String() string { - switch _this.Get_().(type) { - case nil: - return "null" - case GetNameInput_GetNameInput: - { - return "SimplePositionalTypes.GetNameInput.GetNameInput" - } - default: - { - return "" - } - } -} - -func (_this GetNameInput) Equals(other GetNameInput) bool { - switch _this.Get_().(type) { - case GetNameInput_GetNameInput: - { - _, ok := other.Get_().(GetNameInput_GetNameInput) - return ok - } - default: - { - return false // unexpected - } - } -} - -func (_this GetNameInput) EqualsGeneric(other interface{}) bool { - typed, ok := other.(GetNameInput) - return ok && _this.Equals(typed) -} - -func Type_GetNameInput_() _dafny.TypeDescriptor { - return type_GetNameInput_{} -} - -type type_GetNameInput_ struct { -} - -func (_this type_GetNameInput_) Default() interface{} { - return Companion_GetNameInput_.Default() -} - -func (_this type_GetNameInput_) String() string { - return "simplepositionalinternaldafnytypes.GetNameInput" -} -func (_this GetNameInput) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = GetNameInput{} - -// End of datatype GetNameInput - -// Definition of datatype GetNameOutput -type GetNameOutput struct { - Data_GetNameOutput_ -} - -func (_this GetNameOutput) Get_() Data_GetNameOutput_ { - return _this.Data_GetNameOutput_ -} - -type Data_GetNameOutput_ interface { - isGetNameOutput() -} - -type CompanionStruct_GetNameOutput_ struct { -} - -var Companion_GetNameOutput_ = CompanionStruct_GetNameOutput_{} - -type GetNameOutput_GetNameOutput struct { - Name _dafny.Sequence -} - -func (GetNameOutput_GetNameOutput) isGetNameOutput() {} - -func (CompanionStruct_GetNameOutput_) Create_GetNameOutput_(Name _dafny.Sequence) GetNameOutput { - return GetNameOutput{GetNameOutput_GetNameOutput{Name}} -} - -func (_this GetNameOutput) Is_GetNameOutput() bool { - _, ok := _this.Get_().(GetNameOutput_GetNameOutput) - return ok -} - -func (CompanionStruct_GetNameOutput_) Default() GetNameOutput { - return Companion_GetNameOutput_.Create_GetNameOutput_(_dafny.EmptySeq.SetString()) -} - -func (_this GetNameOutput) Dtor_name() _dafny.Sequence { - return _this.Get_().(GetNameOutput_GetNameOutput).Name -} - -func (_this GetNameOutput) String() string { - switch data := _this.Get_().(type) { - case nil: - return "null" - case GetNameOutput_GetNameOutput: - { - return "SimplePositionalTypes.GetNameOutput.GetNameOutput" + "(" + _dafny.String(data.Name) + ")" - } - default: - { - return "" - } - } -} - -func (_this GetNameOutput) Equals(other GetNameOutput) bool { - switch data1 := _this.Get_().(type) { - case GetNameOutput_GetNameOutput: - { - data2, ok := other.Get_().(GetNameOutput_GetNameOutput) - return ok && data1.Name.Equals(data2.Name) - } - default: - { - return false // unexpected - } - } -} - -func (_this GetNameOutput) EqualsGeneric(other interface{}) bool { - typed, ok := other.(GetNameOutput) - return ok && _this.Equals(typed) -} - -func Type_GetNameOutput_() _dafny.TypeDescriptor { - return type_GetNameOutput_{} -} - -type type_GetNameOutput_ struct { -} - -func (_this type_GetNameOutput_) Default() interface{} { - return Companion_GetNameOutput_.Default() -} - -func (_this type_GetNameOutput_) String() string { - return "simplepositionalinternaldafnytypes.GetNameOutput" -} -func (_this GetNameOutput) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = GetNameOutput{} - -// End of datatype GetNameOutput - -// Definition of datatype GetResourceInput -type GetResourceInput struct { - Data_GetResourceInput_ -} - -func (_this GetResourceInput) Get_() Data_GetResourceInput_ { - return _this.Data_GetResourceInput_ -} - -type Data_GetResourceInput_ interface { - isGetResourceInput() -} - -type CompanionStruct_GetResourceInput_ struct { -} - -var Companion_GetResourceInput_ = CompanionStruct_GetResourceInput_{} - -type GetResourceInput_GetResourceInput struct { - Name _dafny.Sequence -} - -func (GetResourceInput_GetResourceInput) isGetResourceInput() {} - -func (CompanionStruct_GetResourceInput_) Create_GetResourceInput_(Name _dafny.Sequence) GetResourceInput { - return GetResourceInput{GetResourceInput_GetResourceInput{Name}} -} - -func (_this GetResourceInput) Is_GetResourceInput() bool { - _, ok := _this.Get_().(GetResourceInput_GetResourceInput) - return ok -} - -func (CompanionStruct_GetResourceInput_) Default() GetResourceInput { - return Companion_GetResourceInput_.Create_GetResourceInput_(_dafny.EmptySeq.SetString()) -} - -func (_this GetResourceInput) Dtor_name() _dafny.Sequence { - return _this.Get_().(GetResourceInput_GetResourceInput).Name -} - -func (_this GetResourceInput) String() string { - switch data := _this.Get_().(type) { - case nil: - return "null" - case GetResourceInput_GetResourceInput: - { - return "SimplePositionalTypes.GetResourceInput.GetResourceInput" + "(" + _dafny.String(data.Name) + ")" - } - default: - { - return "" - } - } -} - -func (_this GetResourceInput) Equals(other GetResourceInput) bool { - switch data1 := _this.Get_().(type) { - case GetResourceInput_GetResourceInput: - { - data2, ok := other.Get_().(GetResourceInput_GetResourceInput) - return ok && data1.Name.Equals(data2.Name) - } - default: - { - return false // unexpected - } - } -} - -func (_this GetResourceInput) EqualsGeneric(other interface{}) bool { - typed, ok := other.(GetResourceInput) - return ok && _this.Equals(typed) -} - -func Type_GetResourceInput_() _dafny.TypeDescriptor { - return type_GetResourceInput_{} -} - -type type_GetResourceInput_ struct { -} - -func (_this type_GetResourceInput_) Default() interface{} { - return Companion_GetResourceInput_.Default() -} - -func (_this type_GetResourceInput_) String() string { - return "simplepositionalinternaldafnytypes.GetResourceInput" -} -func (_this GetResourceInput) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = GetResourceInput{} - -// End of datatype GetResourceInput - -// Definition of datatype GetResourceOutput -type GetResourceOutput struct { - Data_GetResourceOutput_ -} - -func (_this GetResourceOutput) Get_() Data_GetResourceOutput_ { - return _this.Data_GetResourceOutput_ -} - -type Data_GetResourceOutput_ interface { - isGetResourceOutput() -} - -type CompanionStruct_GetResourceOutput_ struct { -} - -var Companion_GetResourceOutput_ = CompanionStruct_GetResourceOutput_{} - -type GetResourceOutput_GetResourceOutput struct { - Output ISimpleResource -} - -func (GetResourceOutput_GetResourceOutput) isGetResourceOutput() {} - -func (CompanionStruct_GetResourceOutput_) Create_GetResourceOutput_(Output ISimpleResource) GetResourceOutput { - return GetResourceOutput{GetResourceOutput_GetResourceOutput{Output}} -} - -func (_this GetResourceOutput) Is_GetResourceOutput() bool { - _, ok := _this.Get_().(GetResourceOutput_GetResourceOutput) - return ok -} - -func (CompanionStruct_GetResourceOutput_) Default() GetResourceOutput { - return Companion_GetResourceOutput_.Create_GetResourceOutput_((ISimpleResource)(nil)) -} - -func (_this GetResourceOutput) Dtor_output() ISimpleResource { - return _this.Get_().(GetResourceOutput_GetResourceOutput).Output -} - -func (_this GetResourceOutput) String() string { - switch data := _this.Get_().(type) { - case nil: - return "null" - case GetResourceOutput_GetResourceOutput: - { - return "SimplePositionalTypes.GetResourceOutput.GetResourceOutput" + "(" + _dafny.String(data.Output) + ")" - } - default: - { - return "" - } - } -} - -func (_this GetResourceOutput) Equals(other GetResourceOutput) bool { - switch data1 := _this.Get_().(type) { - case GetResourceOutput_GetResourceOutput: - { - data2, ok := other.Get_().(GetResourceOutput_GetResourceOutput) - return ok && _dafny.AreEqual(data1.Output, data2.Output) - } - default: - { - return false // unexpected - } - } -} - -func (_this GetResourceOutput) EqualsGeneric(other interface{}) bool { - typed, ok := other.(GetResourceOutput) - return ok && _this.Equals(typed) -} - -func Type_GetResourceOutput_() _dafny.TypeDescriptor { - return type_GetResourceOutput_{} -} - -type type_GetResourceOutput_ struct { -} - -func (_this type_GetResourceOutput_) Default() interface{} { - return Companion_GetResourceOutput_.Default() -} - -func (_this type_GetResourceOutput_) String() string { - return "simplepositionalinternaldafnytypes.GetResourceOutput" -} -func (_this GetResourceOutput) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = GetResourceOutput{} - -// End of datatype GetResourceOutput - -// Definition of class ISimplePositionalClientCallHistory -type ISimplePositionalClientCallHistory struct { - dummy byte -} - -func New_ISimplePositionalClientCallHistory_() *ISimplePositionalClientCallHistory { - _this := ISimplePositionalClientCallHistory{} - - return &_this -} - -type CompanionStruct_ISimplePositionalClientCallHistory_ struct { -} - -var Companion_ISimplePositionalClientCallHistory_ = CompanionStruct_ISimplePositionalClientCallHistory_{} - -func (_this *ISimplePositionalClientCallHistory) Equals(other *ISimplePositionalClientCallHistory) bool { - return _this == other -} - -func (_this *ISimplePositionalClientCallHistory) EqualsGeneric(x interface{}) bool { - other, ok := x.(*ISimplePositionalClientCallHistory) - return ok && _this.Equals(other) -} - -func (*ISimplePositionalClientCallHistory) String() string { - return "simplepositionalinternaldafnytypes.ISimplePositionalClientCallHistory" -} - -func Type_ISimplePositionalClientCallHistory_() _dafny.TypeDescriptor { - return type_ISimplePositionalClientCallHistory_{} -} - -type type_ISimplePositionalClientCallHistory_ struct { -} - -func (_this type_ISimplePositionalClientCallHistory_) Default() interface{} { - return (*ISimplePositionalClientCallHistory)(nil) -} - -func (_this type_ISimplePositionalClientCallHistory_) String() string { - return "simplepositionalinternaldafnytypes.ISimplePositionalClientCallHistory" -} -func (_this *ISimplePositionalClientCallHistory) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = &ISimplePositionalClientCallHistory{} - -// End of class ISimplePositionalClientCallHistory - -// Definition of trait ISimplePositionalClient -type ISimplePositionalClient interface { - String() string - GetResource(input GetResourceInput) Wrappers.Result - GetResourcePositional(input _dafny.Sequence) Wrappers.Result -} -type CompanionStruct_ISimplePositionalClient_ struct { - TraitID_ *_dafny.TraitID -} - -var Companion_ISimplePositionalClient_ = CompanionStruct_ISimplePositionalClient_{ - TraitID_: &_dafny.TraitID{}, -} - -func (CompanionStruct_ISimplePositionalClient_) CastTo_(x interface{}) ISimplePositionalClient { - var t ISimplePositionalClient - t, _ = x.(ISimplePositionalClient) - return t -} - -// End of trait ISimplePositionalClient - -// Definition of datatype SimplePositionalConfig -type SimplePositionalConfig struct { - Data_SimplePositionalConfig_ -} - -func (_this SimplePositionalConfig) Get_() Data_SimplePositionalConfig_ { - return _this.Data_SimplePositionalConfig_ -} - -type Data_SimplePositionalConfig_ interface { - isSimplePositionalConfig() -} - -type CompanionStruct_SimplePositionalConfig_ struct { -} - -var Companion_SimplePositionalConfig_ = CompanionStruct_SimplePositionalConfig_{} - -type SimplePositionalConfig_SimplePositionalConfig struct { -} - -func (SimplePositionalConfig_SimplePositionalConfig) isSimplePositionalConfig() {} - -func (CompanionStruct_SimplePositionalConfig_) Create_SimplePositionalConfig_() SimplePositionalConfig { - return SimplePositionalConfig{SimplePositionalConfig_SimplePositionalConfig{}} -} - -func (_this SimplePositionalConfig) Is_SimplePositionalConfig() bool { - _, ok := _this.Get_().(SimplePositionalConfig_SimplePositionalConfig) - return ok -} - -func (CompanionStruct_SimplePositionalConfig_) Default() SimplePositionalConfig { - return Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() -} - -func (_ CompanionStruct_SimplePositionalConfig_) AllSingletonConstructors() _dafny.Iterator { - i := -1 - return func() (interface{}, bool) { - i++ - switch i { - case 0: - return Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_(), true - default: - return SimplePositionalConfig{}, false - } - } -} - -func (_this SimplePositionalConfig) String() string { - switch _this.Get_().(type) { - case nil: - return "null" - case SimplePositionalConfig_SimplePositionalConfig: - { - return "SimplePositionalTypes.SimplePositionalConfig.SimplePositionalConfig" - } - default: - { - return "" - } - } -} - -func (_this SimplePositionalConfig) Equals(other SimplePositionalConfig) bool { - switch _this.Get_().(type) { - case SimplePositionalConfig_SimplePositionalConfig: - { - _, ok := other.Get_().(SimplePositionalConfig_SimplePositionalConfig) - return ok - } - default: - { - return false // unexpected - } - } -} - -func (_this SimplePositionalConfig) EqualsGeneric(other interface{}) bool { - typed, ok := other.(SimplePositionalConfig) - return ok && _this.Equals(typed) -} - -func Type_SimplePositionalConfig_() _dafny.TypeDescriptor { - return type_SimplePositionalConfig_{} -} - -type type_SimplePositionalConfig_ struct { -} - -func (_this type_SimplePositionalConfig_) Default() interface{} { - return Companion_SimplePositionalConfig_.Default() -} - -func (_this type_SimplePositionalConfig_) String() string { - return "simplepositionalinternaldafnytypes.SimplePositionalConfig" -} -func (_this SimplePositionalConfig) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = SimplePositionalConfig{} - -// End of datatype SimplePositionalConfig - -// Definition of class ISimpleResourceCallHistory -type ISimpleResourceCallHistory struct { - dummy byte -} - -func New_ISimpleResourceCallHistory_() *ISimpleResourceCallHistory { - _this := ISimpleResourceCallHistory{} - - return &_this -} - -type CompanionStruct_ISimpleResourceCallHistory_ struct { -} - -var Companion_ISimpleResourceCallHistory_ = CompanionStruct_ISimpleResourceCallHistory_{} - -func (_this *ISimpleResourceCallHistory) Equals(other *ISimpleResourceCallHistory) bool { - return _this == other -} - -func (_this *ISimpleResourceCallHistory) EqualsGeneric(x interface{}) bool { - other, ok := x.(*ISimpleResourceCallHistory) - return ok && _this.Equals(other) -} - -func (*ISimpleResourceCallHistory) String() string { - return "simplepositionalinternaldafnytypes.ISimpleResourceCallHistory" -} - -func Type_ISimpleResourceCallHistory_() _dafny.TypeDescriptor { - return type_ISimpleResourceCallHistory_{} -} - -type type_ISimpleResourceCallHistory_ struct { -} - -func (_this type_ISimpleResourceCallHistory_) Default() interface{} { - return (*ISimpleResourceCallHistory)(nil) -} - -func (_this type_ISimpleResourceCallHistory_) String() string { - return "simplepositionalinternaldafnytypes.ISimpleResourceCallHistory" -} -func (_this *ISimpleResourceCallHistory) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = &ISimpleResourceCallHistory{} - -// End of class ISimpleResourceCallHistory - -// Definition of trait ISimpleResource -type ISimpleResource interface { - String() string - GetName(input GetNameInput) Wrappers.Result - GetName_k(input GetNameInput) Wrappers.Result -} - -func (_static *CompanionStruct_ISimpleResource_) GetName(_this ISimpleResource, input GetNameInput) Wrappers.Result { - { - var output Wrappers.Result = Wrappers.Companion_Result_.Default(Companion_GetNameOutput_.Default()) - _ = output - var _out0 Wrappers.Result - _ = _out0 - _out0 = (_this).GetName_k(input) - output = _out0 - return output - } -} - -type CompanionStruct_ISimpleResource_ struct { - TraitID_ *_dafny.TraitID -} - -var Companion_ISimpleResource_ = CompanionStruct_ISimpleResource_{ - TraitID_: &_dafny.TraitID{}, -} - -func (CompanionStruct_ISimpleResource_) CastTo_(x interface{}) ISimpleResource { - var t ISimpleResource - t, _ = x.(ISimpleResource) - return t -} - -// End of trait ISimpleResource - -// Definition of datatype Error -type Error struct { - Data_Error_ -} - -func (_this Error) Get_() Data_Error_ { - return _this.Data_Error_ -} - -type Data_Error_ interface { - isError() -} - -type CompanionStruct_Error_ struct { -} - -var Companion_Error_ = CompanionStruct_Error_{} - -type Error_SimplePositionalException struct { - Message _dafny.Sequence -} - -func (Error_SimplePositionalException) isError() {} - -func (CompanionStruct_Error_) Create_SimplePositionalException_(Message _dafny.Sequence) Error { - return Error{Error_SimplePositionalException{Message}} -} - -func (_this Error) Is_SimplePositionalException() bool { - _, ok := _this.Get_().(Error_SimplePositionalException) - return ok -} - -type Error_CollectionOfErrors struct { - List _dafny.Sequence - Message _dafny.Sequence -} - -func (Error_CollectionOfErrors) isError() {} - -func (CompanionStruct_Error_) Create_CollectionOfErrors_(List _dafny.Sequence, Message _dafny.Sequence) Error { - return Error{Error_CollectionOfErrors{List, Message}} -} - -func (_this Error) Is_CollectionOfErrors() bool { - _, ok := _this.Get_().(Error_CollectionOfErrors) - return ok -} - -type Error_Opaque struct { - Obj interface{} -} - -func (Error_Opaque) isError() {} - -func (CompanionStruct_Error_) Create_Opaque_(Obj interface{}) Error { - return Error{Error_Opaque{Obj}} -} - -func (_this Error) Is_Opaque() bool { - _, ok := _this.Get_().(Error_Opaque) - return ok -} - -func (CompanionStruct_Error_) Default() Error { - return Companion_Error_.Create_SimplePositionalException_(_dafny.EmptySeq.SetString()) -} - -func (_this Error) Dtor_message() _dafny.Sequence { - switch data := _this.Get_().(type) { - case Error_SimplePositionalException: - return data.Message - default: - return data.(Error_CollectionOfErrors).Message - } -} - -func (_this Error) Dtor_list() _dafny.Sequence { - return _this.Get_().(Error_CollectionOfErrors).List -} - -func (_this Error) Dtor_obj() interface{} { - return _this.Get_().(Error_Opaque).Obj -} - -func (_this Error) String() string { - switch data := _this.Get_().(type) { - case nil: - return "null" - case Error_SimplePositionalException: - { - return "SimplePositionalTypes.Error.SimplePositionalException" + "(" + _dafny.String(data.Message) + ")" - } - case Error_CollectionOfErrors: - { - return "SimplePositionalTypes.Error.CollectionOfErrors" + "(" + _dafny.String(data.List) + ", " + _dafny.String(data.Message) + ")" - } - case Error_Opaque: - { - return "SimplePositionalTypes.Error.Opaque" + "(" + _dafny.String(data.Obj) + ")" - } - default: - { - return "" - } - } -} - -func (_this Error) Equals(other Error) bool { - switch data1 := _this.Get_().(type) { - case Error_SimplePositionalException: - { - data2, ok := other.Get_().(Error_SimplePositionalException) - return ok && data1.Message.Equals(data2.Message) - } - case Error_CollectionOfErrors: - { - data2, ok := other.Get_().(Error_CollectionOfErrors) - return ok && data1.List.Equals(data2.List) && data1.Message.Equals(data2.Message) - } - case Error_Opaque: - { - data2, ok := other.Get_().(Error_Opaque) - return ok && _dafny.AreEqual(data1.Obj, data2.Obj) - } - default: - { - return false // unexpected - } - } -} - -func (_this Error) EqualsGeneric(other interface{}) bool { - typed, ok := other.(Error) - return ok && _this.Equals(typed) -} - -func Type_Error_() _dafny.TypeDescriptor { - return type_Error_{} -} - -type type_Error_ struct { -} - -func (_this type_Error_) Default() interface{} { - return Companion_Error_.Default() -} - -func (_this type_Error_) String() string { - return "simplepositionalinternaldafnytypes.Error" -} -func (_this Error) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = Error{} - -// End of datatype Error - -// Definition of class OpaqueError -type OpaqueError struct { -} - -func New_OpaqueError_() *OpaqueError { - _this := OpaqueError{} - - return &_this -} - -type CompanionStruct_OpaqueError_ struct { -} - -var Companion_OpaqueError_ = CompanionStruct_OpaqueError_{} - -func (*OpaqueError) String() string { - return "simplepositionalinternaldafnytypes.OpaqueError" -} - -// End of class OpaqueError - -func Type_OpaqueError_() _dafny.TypeDescriptor { - return type_OpaqueError_{} -} - -type type_OpaqueError_ struct { -} - -func (_this type_OpaqueError_) Default() interface{} { - return Companion_Error_.Default() -} - -func (_this type_OpaqueError_) String() string { - return "simplepositionalinternaldafnytypes.OpaqueError" -} -func (_this *CompanionStruct_OpaqueError_) Is_(__source Error) bool { - var _0_e Error = (__source) - _ = _0_e - return (_0_e).Is_Opaque() -} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnywrapped/shim.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnywrapped/shim.go deleted file mode 100644 index d173c74f17..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionalinternaldafnywrapped/shim.go +++ /dev/null @@ -1,43 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositionalinternaldafnywrapped - -import ( - "context" - - "github.com/Smithy-dafny/TestModels/Positional/simplepositional" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -type Shim struct { - simplepositionalinternaldafnytypes.ISimplePositionalClient - client *simplepositional.Client -} - -func WrappedSimplePositional(inputConfig simplepositionalinternaldafnytypes.SimplePositionalConfig) Wrappers.Result { - var nativeConfig = simplepositional.SimplePositionalConfig_FromDafny(inputConfig) - var nativeClient, nativeError = simplepositional.NewClient(nativeConfig) - if nativeError != nil { - return Wrappers.Companion_Result_.Create_Failure_(simplepositionalinternaldafnytypes.Companion_Error_.Create_Opaque_(nativeError)) - } - return Wrappers.Companion_Result_.Create_Success_(&Shim{client: nativeClient}) -} - -func (shim *Shim) GetResource(input simplepositionalinternaldafnytypes.GetResourceInput) Wrappers.Result { - var native_request = simplepositional.GetResourceInput_FromDafny(input) - var native_response, native_error = shim.client.GetResource(context.Background(), native_request) - if native_error != nil { - return Wrappers.Companion_Result_.Create_Failure_(simplepositional.Error_ToDafny(native_error)) - } - return Wrappers.Companion_Result_.Create_Success_(simplepositional.GetResourceOutput_ToDafny(*native_response)) -} - -func (shim *Shim) GetResourcePositional(input simplepositionalinternaldafnytypes.GetResourcePositionalInput) Wrappers.Result { - var native_request = simplepositional.GetResourcePositionalInput_FromDafny(input) - var native_response, native_error = shim.client.GetResourcePositional(context.Background(), native_request) - if native_error != nil { - return Wrappers.Companion_Result_.Create_Failure_(simplepositional.Error_ToDafny(native_error)) - } - return Wrappers.Companion_Result_.Create_Success_(simplepositional.GetResourcePositionalOutput_ToDafny(*native_response)) -} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/errors.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/errors.go deleted file mode 100644 index a4f1fdaf51..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/errors.go +++ /dev/null @@ -1,18 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositionaltypes - -import ( - "fmt" -) - -type SimplePositionalException struct { - SimplePositionalBaseException - Message *string - - ErrorCodeOverride *string -} - -func (e SimplePositionalException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) -} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/types.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/types.go deleted file mode 100644 index 84ddf62564..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/types.go +++ /dev/null @@ -1,93 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositionaltypes - -import ( - "fmt" -) - -type GetResourceInput struct { - Name *string -} - -func (input GetResourceInput) Validate() error { - if input.Name == nil { - return fmt.Errorf("Name is required but has a nil value.") - } - - return nil -} - -type SimpleResourceReference struct { -} - -func (input SimpleResourceReference) Validate() error { - return nil -} - -type GetResourceOutput struct { - Output ISimpleResource -} - -func (input GetResourceOutput) Validate() error { - - return nil -} - -type GetResourcePositionalInput struct { - Name *string -} - -func (input GetResourcePositionalInput) Validate() error { - if input.Name == nil { - return fmt.Errorf("Name is required but has a nil value.") - } - - return nil -} - -type GetResourcePositionalOutput struct { - Output ISimpleResource -} - -func (input GetResourcePositionalOutput) Validate() error { - - return nil -} - -type SimplePositionalConfig struct { -} - -func (input SimplePositionalConfig) Validate() error { - return nil -} - -type SimplePositionalBaseException interface { - // This is a dummy method to allow type assertion since Go empty interfaces - // aren't useful for type assertion checks. No concrete class is expected to implement - // this method. This is also not exported. - interfaceBindingMethod() -} - -type ISimpleResource interface { - GetName(GetNameInput) (*GetNameOutput, error) -} - -type GetNameInput struct { -} - -func (input GetNameInput) Validate() error { - return nil -} - -type GetNameOutput struct { - Name *string -} - -func (input GetNameOutput) Validate() error { - if input.Name == nil { - return fmt.Errorf("Name is required but has a nil value.") - } - - return nil -} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/unmodelled_errors.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/unmodelled_errors.go deleted file mode 100644 index 33aff14a2c..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/simplepositionaltypes/unmodelled_errors.go +++ /dev/null @@ -1,26 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositionaltypes - -import ( - "fmt" -) - -type CollectionOfErrors struct { - SimplePositionalBaseException - ListOfErrors []error - Message string -} - -func (e CollectionOfErrors) Error() string { - return fmt.Sprintf("message: %s\n err %v", e.Message, e.ListOfErrors) -} - -type OpaqueError struct { - SimplePositionalBaseException - ErrObject interface{} -} - -func (e OpaqueError) Error() string { - return fmt.Sprintf("message: %v", e.ErrObject) -} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_dafny.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_dafny.go deleted file mode 100644 index 39442e0038..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_dafny.go +++ /dev/null @@ -1,144 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" - "github.com/dafny-lang/DafnyRuntimeGo/dafny" -) - -func GetResourceInput_ToDafny(nativeInput simplepositionaltypes.GetResourceInput) simplepositionalinternaldafnytypes.GetResourceInput { - - return func() simplepositionalinternaldafnytypes.GetResourceInput { - - return simplepositionalinternaldafnytypes.Companion_GetResourceInput_.Create_GetResourceInput_(func() dafny.Sequence { - if nativeInput.Name == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) - }()) - }() - -} - -func GetResourceOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourceOutput) simplepositionalinternaldafnytypes.GetResourceOutput { - - return func() simplepositionalinternaldafnytypes.GetResourceOutput { - - return simplepositionalinternaldafnytypes.Companion_GetResourceOutput_.Create_GetResourceOutput_(SimpleResource_ToDafny(nativeOutput.Output)) - }() - -} - -func GetResourcePositionalInput_ToDafny(nativeInput simplepositionaltypes.GetResourcePositionalInput) simplepositionalinternaldafnytypes.GetResourcePositionalInput { - - return func() simplepositionalinternaldafnytypes.GetResourcePositionalInput { - - return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalInput_.Create_GetResourcePositionalInput_(func() dafny.Sequence { - if nativeInput.Name == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) - }()) - }() - -} - -func GetResourcePositionalOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourcePositionalOutput) simplepositionalinternaldafnytypes.GetResourcePositionalOutput { - - return func() simplepositionalinternaldafnytypes.GetResourcePositionalOutput { - - return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalOutput_.Create_GetResourcePositionalOutput_(SimpleResource_ToDafny(nativeOutput.Output)) - }() - -} - -func GetNameInput_ToDafny(nativeInput simplepositionaltypes.GetNameInput) simplepositionalinternaldafnytypes.GetNameInput { - - return func() simplepositionalinternaldafnytypes.GetNameInput { - - return simplepositionalinternaldafnytypes.Companion_GetNameInput_.Create_GetNameInput_() - }() - -} - -func GetNameOutput_ToDafny(nativeOutput simplepositionaltypes.GetNameOutput) simplepositionalinternaldafnytypes.GetNameOutput { - - return func() simplepositionalinternaldafnytypes.GetNameOutput { - - return simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Create_GetNameOutput_(func() dafny.Sequence { - if nativeOutput.Name == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeOutput.Name)...) - }()) - }() - -} - -func SimpleResource_ToDafny(nativeResource simplepositionaltypes.ISimpleResource) simplepositionalinternaldafnytypes.ISimpleResource { - return nativeResource.(*SimpleResource).Impl - -} - -func SimplePositionalException_ToDafny(nativeInput simplepositionaltypes.SimplePositionalException) simplepositionalinternaldafnytypes.Error { - return func() simplepositionalinternaldafnytypes.Error { - - return simplepositionalinternaldafnytypes.Companion_Error_.Create_SimplePositionalException_(func() dafny.Sequence { - if nativeInput.Message == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeInput.Message)...) - }()) - }() - -} - -func CollectionOfErrors_Input_ToDafny(nativeInput simplepositionaltypes.CollectionOfErrors) simplepositionalinternaldafnytypes.Error { - var e []interface{} - for _, i2 := range nativeInput.ListOfErrors { - e = append(e, Error_ToDafny(i2)) - } - return simplepositionalinternaldafnytypes.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) -} -func OpaqueError_Input_ToDafny(nativeInput simplepositionaltypes.OpaqueError) simplepositionalinternaldafnytypes.Error { - return simplepositionalinternaldafnytypes.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) -} - -func Error_ToDafny(err error) simplepositionalinternaldafnytypes.Error { - switch err.(type) { - // Service Errors - case simplepositionaltypes.SimplePositionalException: - return SimplePositionalException_ToDafny(err.(simplepositionaltypes.SimplePositionalException)) - - //DependentErrors - - //Unmodelled Errors - case simplepositionaltypes.CollectionOfErrors: - return CollectionOfErrors_Input_ToDafny(err.(simplepositionaltypes.CollectionOfErrors)) - - default: - // TODO: Is changing from the commented code to this new one reasonable? - // return OpaqueError_Input_ToDafny(err.(*simpleconstraintstypes.OpaqueError)) - - // TODO: why is err a pointer? - error, ok := err.(*simplepositionaltypes.OpaqueError) - - if !ok { - panic("Error is not an OpaqueError") - } - if error == nil { - panic("Error is nil") - } - return OpaqueError_Input_ToDafny(*error) - } -} - -func SimplePositionalConfig_ToDafny(nativeInput simplepositionaltypes.SimplePositionalConfig) simplepositionalinternaldafnytypes.SimplePositionalConfig { - return func() simplepositionalinternaldafnytypes.SimplePositionalConfig { - - return simplepositionalinternaldafnytypes.Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() - }() - -} diff --git a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_native.go b/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_native.go deleted file mode 100644 index 23328bb04f..0000000000 --- a/TestModels/Positional/runtimes/go/ImplementationFromDafny-go/to_native.go +++ /dev/null @@ -1,160 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" - "github.com/dafny-lang/DafnyRuntimeGo/dafny" -) - -func GetResourceInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourceInput) simplepositionaltypes.GetResourceInput { - - return simplepositionaltypes.GetResourceInput{Name: func() *string { - var s string - if dafnyInput.Dtor_name() == nil { - return nil - } - for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func GetResourceOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourceOutput) simplepositionaltypes.GetResourceOutput { - - return simplepositionaltypes.GetResourceOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} - -} - -func GetResourcePositionalInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourcePositionalInput) simplepositionaltypes.GetResourcePositionalInput { - - return simplepositionaltypes.GetResourcePositionalInput{Name: func() *string { - var s string - if dafnyInput.Dtor_name() == nil { - return nil - } - for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func GetResourcePositionalOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourcePositionalOutput) simplepositionaltypes.GetResourcePositionalOutput { - - return simplepositionaltypes.GetResourcePositionalOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} - -} - -func GetNameInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetNameInput) simplepositionaltypes.GetNameInput { - - return simplepositionaltypes.GetNameInput{} - -} - -func GetNameOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetNameOutput) simplepositionaltypes.GetNameOutput { - - return simplepositionaltypes.GetNameOutput{Name: func() *string { - var s string - if dafnyOutput.Dtor_name() == nil { - return nil - } - for i := dafny.Iterate(dafnyOutput.Dtor_name()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func SimpleResource_FromDafny(dafnyResource simplepositionalinternaldafnytypes.ISimpleResource) simplepositionaltypes.ISimpleResource { - - return &SimpleResource{dafnyResource} -} - -func SimplePositionalException_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.SimplePositionalException { - return simplepositionaltypes.SimplePositionalException{Message: func() *string { - var s string - if dafnyOutput.Dtor_message() == nil { - return nil - } - for i := dafny.Iterate(dafnyOutput.Dtor_message()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func CollectionOfErrors_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.CollectionOfErrors { - listOfErrors := dafnyOutput.Dtor_list() - message := dafnyOutput.Dtor_message() - t := simplepositionaltypes.CollectionOfErrors{} - for i := dafny.Iterate(listOfErrors); ; { - val, ok := i() - if !ok { - break - } - err := val.(simplepositionalinternaldafnytypes.Error) - t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) - - } - t.Message = func() string { - var s string - for i := dafny.Iterate(message); ; { - val, ok := i() - if !ok { - return s - } else { - s = s + string(val.(dafny.Char)) - } - } - }() - return t -} -func OpaqueError_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.OpaqueError { - return simplepositionaltypes.OpaqueError{ - ErrObject: dafnyOutput.Dtor_obj(), - } -} - -func Error_FromDafny(err simplepositionalinternaldafnytypes.Error) error { - // Service Errors - if err.Is_SimplePositionalException() { - return SimplePositionalException_FromDafny(err) - } - - //DependentErrors - - //Unmodelled Errors - if err.Is_CollectionOfErrors() { - return CollectionOfErrors_Output_FromDafny(err) - } - - return OpaqueError_Output_FromDafny(err) -} - -func SimplePositionalConfig_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.SimplePositionalConfig) simplepositionaltypes.SimplePositionalConfig { - return simplepositionaltypes.SimplePositionalConfig{} - -} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go deleted file mode 100644 index 44525fdabd..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImpl/SimplePositionalImpl.go +++ /dev/null @@ -1,213 +0,0 @@ -// Package SimplePositionalImpl -// Dafny module SimplePositionalImpl compiled into Go - -package SimplePositionalImpl - -import ( - "fmt" - os "os" - - SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" - simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - _System "github.com/dafny-lang/DafnyRuntimeGo/System_" - _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" - StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" - StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" - StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" - Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -var _ = os.Args -var _ _dafny.Dummy__ -var _ _System.Dummy__ -var _ Wrappers.Dummy__ -var _ StandardLibrary_UInt.Dummy__ -var _ StandardLibrary.Dummy__ -var _ StandardLibraryInterop.Dummy__ -var _ SimpleResource.Dummy__ - -type Dummy__ struct{} - -// Definition of class Default__ -type Default__ struct { - dummy byte -} - -func New_Default___() *Default__ { - _this := Default__{} - - return &_this -} - -type CompanionStruct_Default___ struct { -} - -var Companion_Default___ = CompanionStruct_Default___{} - -func (_this *Default__) Equals(other *Default__) bool { - return _this == other -} - -func (_this *Default__) EqualsGeneric(x interface{}) bool { - other, ok := x.(*Default__) - return ok && _this.Equals(other) -} - -func (*Default__) String() string { - return "SimplePositionalImpl.Default__" -} -func (_this *Default__) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = &Default__{} - -func (_static *CompanionStruct_Default___) GetResource(config Config, input simplepositionalinternaldafnytypes.GetResourceInput) Wrappers.Result { - var output Wrappers.Result = Wrappers.Result{} - _ = output - var _1_resource *SimpleResource.SimpleResource - _ = _1_resource - var _nw0 *SimpleResource.SimpleResource = SimpleResource.New_SimpleResource_() - _ = _nw0 - _nw0.Ctor__((input).Dtor_name()) - _1_resource = _nw0 - var _2_result simplepositionalinternaldafnytypes.GetResourceOutput - _ = _2_result - _2_result = simplepositionalinternaldafnytypes.Companion_GetResourceOutput_.Create_GetResourceOutput_(_1_resource) - output = Wrappers.Companion_Result_.Create_Success_(_2_result) - return output - return output -} - -// recover function to handle panic -func handlePanic() { - - // detect if panic occurs or not - a := recover() - - if a != nil { - fmt.Println("RECOVER Impl", a) - } - -} -func (_static *CompanionStruct_Default___) GetResourcePositional(config Config, input _dafny.Sequence) Wrappers.Result { - defer handlePanic() - var output Wrappers.Result = Wrappers.Result{} - _ = output - var _3_resource *SimpleResource.SimpleResource - _ = _3_resource - var _nw1 *SimpleResource.SimpleResource = SimpleResource.New_SimpleResource_() - _ = _nw1 - _nw1.Ctor__(input) - _3_resource = _nw1 - output = Wrappers.Companion_Result_.Create_Success_(_3_resource) - return output - return output -} - -// End of class Default__ - -// Definition of datatype Config -type Config struct { - Data_Config_ -} - -func (_this Config) Get_() Data_Config_ { - return _this.Data_Config_ -} - -type Data_Config_ interface { - isConfig() -} - -type CompanionStruct_Config_ struct { -} - -var Companion_Config_ = CompanionStruct_Config_{} - -type Config_Config struct { -} - -func (Config_Config) isConfig() {} - -func (CompanionStruct_Config_) Create_Config_() Config { - return Config{Config_Config{}} -} - -func (_this Config) Is_Config() bool { - _, ok := _this.Get_().(Config_Config) - return ok -} - -func (CompanionStruct_Config_) Default() Config { - return Companion_Config_.Create_Config_() -} - -func (_ CompanionStruct_Config_) AllSingletonConstructors() _dafny.Iterator { - i := -1 - return func() (interface{}, bool) { - i++ - switch i { - case 0: - return Companion_Config_.Create_Config_(), true - default: - return Config{}, false - } - } -} - -func (_this Config) String() string { - switch _this.Get_().(type) { - case nil: - return "null" - case Config_Config: - { - return "SimplePositionalImpl.Config.Config" - } - default: - { - return "" - } - } -} - -func (_this Config) Equals(other Config) bool { - switch _this.Get_().(type) { - case Config_Config: - { - _, ok := other.Get_().(Config_Config) - return ok - } - default: - { - return false // unexpected - } - } -} - -func (_this Config) EqualsGeneric(other interface{}) bool { - typed, ok := other.(Config) - return ok && _this.Equals(typed) -} - -func Type_Config_() _dafny.TypeDescriptor { - return type_Config_{} -} - -type type_Config_ struct { -} - -func (_this type_Config_) Default() interface{} { - return Companion_Config_.Default() -} - -func (_this type_Config_) String() string { - return "SimplePositionalImpl.Config" -} -func (_this Config) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = Config{} - -// End of datatype Config diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImplTest/SimplePositionalImplTest.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImplTest/SimplePositionalImplTest.go deleted file mode 100644 index 5df5cd63a8..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimplePositionalImplTest/SimplePositionalImplTest.go +++ /dev/null @@ -1,170 +0,0 @@ -// Package SimplePositionalImplTest -// Dafny module SimplePositionalImplTest compiled into Go - -package SimplePositionalImplTest - -import ( - "fmt" - os "os" - - SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" - SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" - simplepositionalinternaldafny "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafny" - simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - _System "github.com/dafny-lang/DafnyRuntimeGo/System_" - _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" - StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" - StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" - StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" - Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -var _ = os.Args -var _ _dafny.Dummy__ -var _ _System.Dummy__ -var _ Wrappers.Dummy__ -var _ StandardLibrary_UInt.Dummy__ -var _ StandardLibrary.Dummy__ -var _ StandardLibraryInterop.Dummy__ -var _ SimpleResource.Dummy__ -var _ SimplePositionalImpl.Dummy__ - -type Dummy__ struct{} - -// Definition of class Default__ -type Default__ struct { - dummy byte -} - -func New_Default___() *Default__ { - _this := Default__{} - - return &_this -} - -type CompanionStruct_Default___ struct { -} - -var Companion_Default___ = CompanionStruct_Default___{} - -func (_this *Default__) Equals(other *Default__) bool { - return _this == other -} - -func (_this *Default__) EqualsGeneric(x interface{}) bool { - other, ok := x.(*Default__) - return ok && _this.Equals(other) -} - -func (*Default__) String() string { - return "SimplePositionalImplTest.Default__" -} -func (_this *Default__) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = &Default__{} - -func (_static *CompanionStruct_Default___) TestClient(client simplepositionalinternaldafnytypes.ISimplePositionalClient) { - Companion_Default___.TestGetResource(client) - Companion_Default___.TestGetResourcePositional(client) -} -func (_static *CompanionStruct_Default___) TestGetResource(client simplepositionalinternaldafnytypes.ISimplePositionalClient) { - var _5_input simplepositionalinternaldafnytypes.GetResourceInput - _ = _5_input - _5_input = simplepositionalinternaldafnytypes.Companion_GetResourceInput_.Create_GetResourceInput_(_dafny.SeqOfString("Test")) - var _6_output simplepositionalinternaldafnytypes.GetResourceOutput - _ = _6_output - var _7_valueOrError0 Wrappers.Result = Wrappers.Result{} - _ = _7_valueOrError0 - var _out4 Wrappers.Result - _ = _out4 - _out4 = (client).GetResource(_5_input) - _7_valueOrError0 = _out4 - if !(!((_7_valueOrError0).IsFailure())) { - panic("test/SimplePositionalImplTest.dfy(27,22): " + (_7_valueOrError0).String()) - } - _6_output = (_7_valueOrError0).Extract().(simplepositionalinternaldafnytypes.GetResourceOutput) - var _8_resource simplepositionalinternaldafnytypes.ISimpleResource - _ = _8_resource - _8_resource = (_6_output).Dtor_output() - var _9_getNameOutput simplepositionalinternaldafnytypes.GetNameOutput - _ = _9_getNameOutput - var _10_valueOrError1 Wrappers.Result = Wrappers.Companion_Result_.Default(simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Default()) - _ = _10_valueOrError1 - var _out5 Wrappers.Result - _ = _out5 - _out5 = (_8_resource).GetName(simplepositionalinternaldafnytypes.Companion_GetNameInput_.Create_GetNameInput_()) - _10_valueOrError1 = _out5 - if !(!((_10_valueOrError1).IsFailure())) { - panic("test/SimplePositionalImplTest.dfy(29,29): " + (_10_valueOrError1).String()) - } - _9_getNameOutput = (_10_valueOrError1).Extract().(simplepositionalinternaldafnytypes.GetNameOutput) - if !(_dafny.Companion_Sequence_.Equal((_9_getNameOutput).Dtor_name(), _dafny.SeqOfString("Test"))) { - panic("test/SimplePositionalImplTest.dfy(30,8): " + (_dafny.SeqOfString("expectation violation")).String()) - } -} - -// recover function to handle panic -func handlePanic() { - - // detect if panic occurs or not - a := recover() - - if a != nil { - fmt.Println("RECOVER impl test", a) - } - -} -func (_static *CompanionStruct_Default___) TestGetResourcePositional(client simplepositionalinternaldafnytypes.ISimplePositionalClient) { - defer handlePanic() - var _11_input _dafny.Sequence - _ = _11_input - _11_input = _dafny.SeqOfString("TestPositional") - var _12_resource simplepositionalinternaldafnytypes.ISimpleResource - _ = _12_resource - var _13_valueOrError0 Wrappers.Result = Wrappers.Result{} - _ = _13_valueOrError0 - var _out6 Wrappers.Result - _ = _out6 - _out6 = (client).GetResourcePositional(_11_input) - _13_valueOrError0 = _out6 - if !(!((_13_valueOrError0).IsFailure())) { - panic("test/SimplePositionalImplTest.dfy(39,47): " + (_13_valueOrError0).String()) - } - _12_resource = simplepositionalinternaldafnytypes.Companion_ISimpleResource_.CastTo_((_13_valueOrError0).Extract()) - var _14_getNameOutput simplepositionalinternaldafnytypes.GetNameOutput - _ = _14_getNameOutput - var _15_valueOrError1 Wrappers.Result = Wrappers.Companion_Result_.Default(simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Default()) - _ = _15_valueOrError1 - var _out7 Wrappers.Result - _ = _out7 - - _out7 = (_12_resource).GetName(simplepositionalinternaldafnytypes.Companion_GetNameInput_.Create_GetNameInput_()) - _15_valueOrError1 = _out7 - if !(!((_15_valueOrError1).IsFailure())) { - panic("test/SimplePositionalImplTest.dfy(40,29): " + (_15_valueOrError1).String()) - } - _14_getNameOutput = (_15_valueOrError1).Extract().(simplepositionalinternaldafnytypes.GetNameOutput) - - if !(_dafny.Companion_Sequence_.Equal((_14_getNameOutput).Dtor_name(), _dafny.SeqOfString("TestPositional"))) { - panic("test/SimplePositionalImplTest.dfy(41,8): " + (_dafny.SeqOfString("expectation violation")).String()) - } -} -func (_static *CompanionStruct_Default___) TestDefaultConfig() { - var _16_client *simplepositionalinternaldafny.SimplePositionalClient - _ = _16_client - var _17_valueOrError0 Wrappers.Result = Wrappers.Result{} - _ = _17_valueOrError0 - var _out8 Wrappers.Result - _ = _out8 - _out8 = simplepositionalinternaldafny.Companion_Default___.SimplePositional(simplepositionalinternaldafny.Companion_Default___.DefaultSimplePositionalConfig()) - _17_valueOrError0 = _out8 - if !(!((_17_valueOrError0).IsFailure())) { - panic("test/SimplePositionalImplTest.dfy(45,22): " + (_17_valueOrError0).String()) - } - _16_client = (_17_valueOrError0).Extract().(*simplepositionalinternaldafny.SimplePositionalClient) - Companion_Default___.TestClient(_16_client) -} - -// End of class Default__ diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource.go deleted file mode 100644 index 53f16e63ab..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource.go +++ /dev/null @@ -1,34 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" -) - -type SimpleResource struct { - Impl simplepositionalinternaldafnytypes.ISimpleResource -} - -func (this *SimpleResource) GetName(params simplepositionaltypes.GetNameInput) (*simplepositionaltypes.GetNameOutput, error) { - var dafny_request simplepositionalinternaldafnytypes.GetNameInput = GetNameInput_ToDafny(params) - var dafny_response = this.Impl.GetName(dafny_request) - - if dafny_response.Is_Failure() { - err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) - if err.Is_SimplePositionalException() { - return nil, SimplePositionalException_FromDafny(err) - } - - if err.Is_CollectionOfErrors() { - return nil, CollectionOfErrors_Output_FromDafny(err) - } - if err.Is_Opaque() { - return nil, OpaqueError_Output_FromDafny(err) - } - } - var native_response = GetNameOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetNameOutput)) - return &native_response, nil - -} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource/SimpleResource.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource/SimpleResource.go deleted file mode 100644 index 023c79b61e..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/SimpleResource/SimpleResource.go +++ /dev/null @@ -1,107 +0,0 @@ -// Package SimpleResource -// Dafny module SimpleResource compiled into Go - -package SimpleResource - -import ( - "fmt" - os "os" - - simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - _System "github.com/dafny-lang/DafnyRuntimeGo/System_" - _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" - StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" - StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" - StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" - Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -var _ = os.Args -var _ _dafny.Dummy__ -var _ _System.Dummy__ -var _ Wrappers.Dummy__ -var _ StandardLibrary_UInt.Dummy__ -var _ StandardLibrary.Dummy__ -var _ StandardLibraryInterop.Dummy__ - -type Dummy__ struct{} - -// Definition of class SimpleResource -type SimpleResource struct { - _name _dafny.Sequence -} - -func New_SimpleResource_() *SimpleResource { - _this := SimpleResource{} - - _this._name = _dafny.EmptySeq.SetString() - return &_this -} - -type CompanionStruct_SimpleResource_ struct { -} - -var Companion_SimpleResource_ = CompanionStruct_SimpleResource_{} - -func (_this *SimpleResource) Equals(other *SimpleResource) bool { - return _this == other -} - -func (_this *SimpleResource) EqualsGeneric(x interface{}) bool { - other, ok := x.(*SimpleResource) - return ok && _this.Equals(other) -} - -func (_this *SimpleResource) String() string { - fmt.Println(_this._name) - return "SimpleResource.SimpleResource" -} - -func Type_SimpleResource_() _dafny.TypeDescriptor { - return type_SimpleResource_{} -} - -type type_SimpleResource_ struct { -} - -func (_this type_SimpleResource_) Default() interface{} { - return (*SimpleResource)(nil) -} - -func (_this type_SimpleResource_) String() string { - return "SimpleResource.SimpleResource" -} -func (_this *SimpleResource) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){simplepositionalinternaldafnytypes.Companion_ISimpleResource_.TraitID_} -} - -var _ simplepositionalinternaldafnytypes.ISimpleResource = &SimpleResource{} -var _ _dafny.TraitOffspring = &SimpleResource{} - -func (_this *SimpleResource) GetName(input simplepositionalinternaldafnytypes.GetNameInput) Wrappers.Result { - var _out1 Wrappers.Result - _ = _out1 - _out1 = simplepositionalinternaldafnytypes.Companion_ISimpleResource_.GetName(_this, input) - return _out1 -} -func (_this *SimpleResource) Ctor__(name _dafny.Sequence) { - { - (_this)._name = name - } -} -func (_this *SimpleResource) GetName_k(input simplepositionalinternaldafnytypes.GetNameInput) Wrappers.Result { - { - var output Wrappers.Result = Wrappers.Companion_Result_.Default(simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Default()) - _ = output - output = Wrappers.Companion_Result_.Create_Success_(simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Create_GetNameOutput_((_this).Name())) - return output - return output - } -} -func (_this *SimpleResource) Name() _dafny.Sequence { - { - return _this._name - } -} - -// End of class SimpleResource diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny-go.dtr b/TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny-go.dtr deleted file mode 100644 index 546347e43c..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny-go.dtr +++ /dev/null @@ -1,22 +0,0 @@ -file_format_version = "1.0" -dafny_version = "4.6.0.0" -[options_by_module.SimplePositionalTypes] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" -[options_by_module.AbstractSimplePositionalOperations] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" -[options_by_module.SimpleResource] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" -[options_by_module.SimplePositionalImpl] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" -[options_by_module.AbstractSimplePositionalService] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" -[options_by_module.SimplePositional] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" -[options_by_module.WrappedAbstractSimplePositionalService] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" -[options_by_module.WrappedSimplePositionalService] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" -[options_by_module.SimplePositionalImplTest] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" -[options_by_module.WrappedSimplePositionalTest] -go-module-name = "github.com/Smithy-dafny/TestModels/Positional" diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny.go deleted file mode 100644 index fb1949b6ac..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/TestsFromDafny.go +++ /dev/null @@ -1,118 +0,0 @@ -// Dafny program the_program compiled into Go -package main - -import ( - os "os" - - SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" - SimplePositionalImplTest "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImplTest" - SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" - WrappedSimplePositionalTest "github.com/Smithy-dafny/TestModels/Positional/WrappedSimplePositionalTest" - _System "github.com/dafny-lang/DafnyRuntimeGo/System_" - _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" - StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" - StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" - StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" - Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -var _ = os.Args -var _ _dafny.Dummy__ -var _ _System.Dummy__ -var _ Wrappers.Dummy__ -var _ StandardLibrary_UInt.Dummy__ -var _ StandardLibrary.Dummy__ -var _ StandardLibraryInterop.Dummy__ -var _ SimpleResource.Dummy__ -var _ SimplePositionalImpl.Dummy__ -var _ SimplePositionalImplTest.Dummy__ -var _ WrappedSimplePositionalTest.Dummy__ - -// Definition of class Default__ -type Default__ struct { - dummy byte -} - -func New_Default___() *Default__ { - _this := Default__{} - - return &_this -} - -type CompanionStruct_Default___ struct { -} - -var Companion_Default___ = CompanionStruct_Default___{} - -func (_this *Default__) Equals(other *Default__) bool { - return _this == other -} - -func (_this *Default__) EqualsGeneric(x interface{}) bool { - other, ok := x.(*Default__) - return ok && _this.Equals(other) -} - -func (*Default__) String() string { - return "_module.Default__" -} -func (_this *Default__) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = &Default__{} - -func (_static *CompanionStruct_Default___) Test____Main____(__noArgsParameter _dafny.Sequence) { - var _20_success bool - _ = _20_success - _20_success = true - _dafny.Print((_dafny.SeqOfString("SimplePositionalImplTest.TestDefaultConfig: ")).SetString()) - func() { - defer func() { - if r := recover(); r != nil { - var _21_haltMessage = _dafny.SeqOfString(r.(string)) - { - _dafny.Print((_dafny.SeqOfString("FAILED\n ")).SetString()) - _dafny.Print((_21_haltMessage).SetString()) - _dafny.Print((_dafny.SeqOfString("\n")).SetString()) - _20_success = false - } - } - }() - { - SimplePositionalImplTest.Companion_Default___.TestDefaultConfig() - { - _dafny.Print((_dafny.SeqOfString("PASSED\n")).SetString()) - } - } - }() - _dafny.Print((_dafny.SeqOfString("WrappedSimplePositionalTest.TestWrappedClient: ")).SetString()) - func() { - defer func() { - if r := recover(); r != nil { - var _22_haltMessage = _dafny.SeqOfString(r.(string)) - { - _dafny.Print((_dafny.SeqOfString("FAILED\n ")).SetString()) - _dafny.Print((_22_haltMessage).SetString()) - _dafny.Print((_dafny.SeqOfString("\n")).SetString()) - _20_success = false - } - } - }() - { - WrappedSimplePositionalTest.Companion_Default___.TestWrappedClient() - { - _dafny.Print((_dafny.SeqOfString("PASSED\n")).SetString()) - } - } - }() - if !(_20_success) { - panic("(1,0): " + (_dafny.SeqOfString("Test failures occurred: see above.\n")).String()) - } -} - -// End of class Default__ -func main() { - defer _dafny.CatchHalt() - Companion_Default___.Test____Main____(_dafny.FromMainArguments(os.Args)) -} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/WrappedSimplePositionalTest/WrappedSimplePositionalTest.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/WrappedSimplePositionalTest/WrappedSimplePositionalTest.go deleted file mode 100644 index 3213830225..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/WrappedSimplePositionalTest/WrappedSimplePositionalTest.go +++ /dev/null @@ -1,85 +0,0 @@ -// Package WrappedSimplePositionalTest -// Dafny module WrappedSimplePositionalTest compiled into Go - -package WrappedSimplePositionalTest - -import ( - os "os" - - SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" - SimplePositionalImplTest "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImplTest" - SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" - simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - simplepositionalinternaldafnywrapped "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnywrapped" - _System "github.com/dafny-lang/DafnyRuntimeGo/System_" - _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" - StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" - StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" - StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" - Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -var _ = os.Args -var _ _dafny.Dummy__ -var _ _System.Dummy__ -var _ Wrappers.Dummy__ -var _ StandardLibrary_UInt.Dummy__ -var _ StandardLibrary.Dummy__ -var _ StandardLibraryInterop.Dummy__ -var _ SimpleResource.Dummy__ -var _ SimplePositionalImpl.Dummy__ -var _ SimplePositionalImplTest.Dummy__ - -type Dummy__ struct{} - -// Definition of class Default__ -type Default__ struct { - dummy byte -} - -func New_Default___() *Default__ { - _this := Default__{} - - return &_this -} - -type CompanionStruct_Default___ struct { -} - -var Companion_Default___ = CompanionStruct_Default___{} - -func (_this *Default__) Equals(other *Default__) bool { - return _this == other -} - -func (_this *Default__) EqualsGeneric(x interface{}) bool { - other, ok := x.(*Default__) - return ok && _this.Equals(other) -} - -func (*Default__) String() string { - return "WrappedSimplePositionalTest.Default__" -} -func (_this *Default__) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = &Default__{} - -func (_static *CompanionStruct_Default___) TestWrappedClient() { - var _18_client simplepositionalinternaldafnytypes.ISimplePositionalClient - _ = _18_client - var _19_valueOrError0 Wrappers.Result = Wrappers.Result{} - _ = _19_valueOrError0 - var _out9 Wrappers.Result - _ = _out9 - _out9 = simplepositionalinternaldafnywrapped.WrappedSimplePositional(simplepositionalinternaldafnywrapped.Companion_Default___.WrappedDefaultSimplePositionalConfig()) - _19_valueOrError0 = _out9 - if !(!((_19_valueOrError0).IsFailure())) { - panic("test/WrappedSimplePositionalTest.dfy(12,22): " + (_19_valueOrError0).String()) - } - _18_client = simplepositionalinternaldafnytypes.Companion_ISimplePositionalClient_.CastTo_((_19_valueOrError0).Extract()) - SimplePositionalImplTest.Companion_Default___.TestClient(_18_client) -} - -// End of class Default__ diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/api_client.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/api_client.go deleted file mode 100644 index 8419c833fc..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/api_client.go +++ /dev/null @@ -1,66 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "context" - - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafny" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" -) - -type Client struct { - DafnyClient *simplepositionalinternaldafny.SimplePositionalClient -} - -func NewClient(clientConfig simplepositionaltypes.SimplePositionalConfig) (*Client, error) { - var dafnyConfig = SimplePositionalConfig_ToDafny(clientConfig) - var dafny_response = simplepositionalinternaldafny.Companion_Default___.SimplePositional(dafnyConfig) - if dafny_response.Is_Failure() { - panic("Client construction failed. This should never happen") - } - var dafnyClient = dafny_response.Extract().(*simplepositionalinternaldafny.SimplePositionalClient) - client := &Client{dafnyClient} - return client, nil -} - -func (client *Client) GetResource(ctx context.Context, params simplepositionaltypes.GetResourceInput) (*simplepositionaltypes.GetResourceOutput, error) { - err := params.Validate() - if err != nil { - opaqueErr := &simplepositionaltypes.OpaqueError{ - ErrObject: err, - } - return nil, opaqueErr - } - var dafny_request simplepositionalinternaldafnytypes.GetResourceInput = GetResourceInput_ToDafny(params) - var dafny_response = client.DafnyClient.GetResource(dafny_request) - - if dafny_response.Is_Failure() { - err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) - return nil, Error_FromDafny(err) - } - var native_response = GetResourceOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourceOutput)) - return &native_response, nil - -} - -func (client *Client) GetResourcePositional(ctx context.Context, params simplepositionaltypes.GetResourcePositionalInput) (*simplepositionaltypes.GetResourcePositionalOutput, error) { - err := params.Validate() - if err != nil { - opaqueErr := &simplepositionaltypes.OpaqueError{ - ErrObject: err, - } - return nil, opaqueErr - } - var dafny_request simplepositionalinternaldafnytypes.GetResourcePositionalInput = GetResourcePositionalInput_ToDafny(params) - var dafny_response = client.DafnyClient.GetResourcePositional(dafny_request) - - if dafny_response.Is_Failure() { - err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) - return nil, Error_FromDafny(err) - } - var native_response = GetResourcePositionalOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourcePositionalOutput)) - return &native_response, nil - -} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/go.mod b/TestModels/Positional/runtimes/go/TestsFromDafny-go/go.mod deleted file mode 100644 index e852819557..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/go.mod +++ /dev/null @@ -1,11 +0,0 @@ -module github.com/Smithy-dafny/TestModels/Positional - -go 1.22.2 - -require github.com/dafny-lang/DafnyStandardLibGo v0.0.0 - -require github.com/dafny-lang/DafnyRuntimeGo v0.0.0 - -replace github.com/dafny-lang/DafnyRuntimeGo => ../../../../../DafnyRuntimeGo/ - -replace github.com/dafny-lang/DafnyStandardLibGo => ../../../../dafny-dependencies/StandardLibrary/runtimes/go/ImplementationFromDafny-go/ diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/SimpleResource.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/SimpleResource.go deleted file mode 100644 index 53f16e63ab..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/SimpleResource.go +++ /dev/null @@ -1,34 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" -) - -type SimpleResource struct { - Impl simplepositionalinternaldafnytypes.ISimpleResource -} - -func (this *SimpleResource) GetName(params simplepositionaltypes.GetNameInput) (*simplepositionaltypes.GetNameOutput, error) { - var dafny_request simplepositionalinternaldafnytypes.GetNameInput = GetNameInput_ToDafny(params) - var dafny_response = this.Impl.GetName(dafny_request) - - if dafny_response.Is_Failure() { - err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) - if err.Is_SimplePositionalException() { - return nil, SimplePositionalException_FromDafny(err) - } - - if err.Is_CollectionOfErrors() { - return nil, CollectionOfErrors_Output_FromDafny(err) - } - if err.Is_Opaque() { - return nil, OpaqueError_Output_FromDafny(err) - } - } - var native_response = GetNameOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetNameOutput)) - return &native_response, nil - -} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/api_client.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/api_client.go deleted file mode 100644 index 5c09273c0e..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/api_client.go +++ /dev/null @@ -1,73 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "context" - "fmt" - "reflect" - - SimpleResources "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" - - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafny" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" - "github.com/dafny-lang/DafnyRuntimeGo/dafny" -) - -type Client struct { - DafnyClient *simplepositionalinternaldafny.SimplePositionalClient -} - -func NewClient(clientConfig simplepositionaltypes.SimplePositionalConfig) (*Client, error) { - var dafnyConfig = SimplePositionalConfig_ToDafny(clientConfig) - var dafny_response = simplepositionalinternaldafny.Companion_Default___.SimplePositional(dafnyConfig) - if dafny_response.Is_Failure() { - panic("Client construction failed. This should never happen") - } - var dafnyClient = dafny_response.Extract().(*simplepositionalinternaldafny.SimplePositionalClient) - client := &Client{dafnyClient} - return client, nil -} - -func (client *Client) GetResource(ctx context.Context, params simplepositionaltypes.GetResourceInput) (*simplepositionaltypes.GetResourceOutput, error) { - err := params.Validate() - if err != nil { - opaqueErr := &simplepositionaltypes.OpaqueError{ - ErrObject: err, - } - return nil, opaqueErr - } - var dafny_request simplepositionalinternaldafnytypes.GetResourceInput = GetResourceInput_ToDafny(params) - var dafny_response = client.DafnyClient.GetResource(dafny_request) - - if dafny_response.Is_Failure() { - err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) - return nil, Error_FromDafny(err) - } - var native_response = GetResourceOutput_FromDafny(dafny_response.Extract().(simplepositionalinternaldafnytypes.GetResourceOutput)) - return &native_response, nil - -} - -func (client *Client) GetResourcePositional(ctx context.Context, params simplepositionaltypes.GetResourcePositionalInput) (*SimpleResources.SimpleResource, error) { - - err := params.Validate() - if err != nil { - opaqueErr := &simplepositionaltypes.OpaqueError{ - ErrObject: err, - } - return nil, opaqueErr - } - var dafny_request dafny.Sequence = GetResourcePositionalInput_ToDafny(params) - var dafny_response = client.DafnyClient.GetResourcePositional(dafny_request) - - if dafny_response.Is_Failure() { - err := dafny_response.Dtor_error().(simplepositionalinternaldafnytypes.Error) - return nil, Error_FromDafny(err) - } - fmt.Println(reflect.TypeOf(dafny_response.Extract())) - var native_response = dafny_response.Extract().(*SimpleResources.SimpleResource) - return native_response, nil - -} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_dafny.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_dafny.go deleted file mode 100644 index 223329b664..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_dafny.go +++ /dev/null @@ -1,130 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" - "github.com/dafny-lang/DafnyRuntimeGo/dafny" -) - -func GetResourceInput_ToDafny(nativeInput simplepositionaltypes.GetResourceInput) simplepositionalinternaldafnytypes.GetResourceInput { - - return func() simplepositionalinternaldafnytypes.GetResourceInput { - - return simplepositionalinternaldafnytypes.Companion_GetResourceInput_.Create_GetResourceInput_(func() dafny.Sequence { - if nativeInput.Name == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) - }()) - }() - -} - -func GetResourceOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourceOutput) simplepositionalinternaldafnytypes.GetResourceOutput { - - return func() simplepositionalinternaldafnytypes.GetResourceOutput { - - return simplepositionalinternaldafnytypes.Companion_GetResourceOutput_.Create_GetResourceOutput_(SimpleResource_ToDafny(nativeOutput.Output)) - }() - -} - -func GetResourcePositionalInput_ToDafny(nativeInput simplepositionaltypes.GetResourcePositionalInput) dafny.Sequence { - if nativeInput.Name == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) - - -} - -func GetNameInput_ToDafny(nativeInput simplepositionaltypes.GetNameInput) simplepositionalinternaldafnytypes.GetNameInput { - - return func() simplepositionalinternaldafnytypes.GetNameInput { - - return simplepositionalinternaldafnytypes.Companion_GetNameInput_.Create_GetNameInput_() - }() - -} - -func GetNameOutput_ToDafny(nativeOutput simplepositionaltypes.GetNameOutput) simplepositionalinternaldafnytypes.GetNameOutput { - - return func() simplepositionalinternaldafnytypes.GetNameOutput { - - return simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Create_GetNameOutput_(func() dafny.Sequence { - if nativeOutput.Name == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeOutput.Name)...) - }()) - }() - -} - -func SimpleResource_ToDafny(nativeResource simplepositionaltypes.ISimpleResource) simplepositionalinternaldafnytypes.ISimpleResource { - return nativeResource.(*SimpleResource).Impl - -} - -func SimplePositionalException_ToDafny(nativeInput simplepositionaltypes.SimplePositionalException) simplepositionalinternaldafnytypes.Error { - return func() simplepositionalinternaldafnytypes.Error { - - return simplepositionalinternaldafnytypes.Companion_Error_.Create_SimplePositionalException_(func() dafny.Sequence { - if nativeInput.Message == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeInput.Message)...) - }()) - }() - -} - -func CollectionOfErrors_Input_ToDafny(nativeInput simplepositionaltypes.CollectionOfErrors) simplepositionalinternaldafnytypes.Error { - var e []interface{} - for _, i2 := range nativeInput.ListOfErrors { - e = append(e, Error_ToDafny(i2)) - } - return simplepositionalinternaldafnytypes.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) -} -func OpaqueError_Input_ToDafny(nativeInput simplepositionaltypes.OpaqueError) simplepositionalinternaldafnytypes.Error { - return simplepositionalinternaldafnytypes.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) -} - -func Error_ToDafny(err error) simplepositionalinternaldafnytypes.Error { - switch err.(type) { - // Service Errors - case simplepositionaltypes.SimplePositionalException: - return SimplePositionalException_ToDafny(err.(simplepositionaltypes.SimplePositionalException)) - - //DependentErrors - - //Unmodelled Errors - case simplepositionaltypes.CollectionOfErrors: - return CollectionOfErrors_Input_ToDafny(err.(simplepositionaltypes.CollectionOfErrors)) - - default: - // TODO: Is changing from the commented code to this new one reasonable? - // return OpaqueError_Input_ToDafny(err.(*simpleconstraintstypes.OpaqueError)) - - // TODO: why is err a pointer? - error, ok := err.(*simplepositionaltypes.OpaqueError) - - if !ok { - panic("Error is not an OpaqueError") - } - if error == nil { - panic("Error is nil") - } - return OpaqueError_Input_ToDafny(*error) - } -} - -func SimplePositionalConfig_ToDafny(nativeInput simplepositionaltypes.SimplePositionalConfig) simplepositionalinternaldafnytypes.SimplePositionalConfig { - return func() simplepositionalinternaldafnytypes.SimplePositionalConfig { - - return simplepositionalinternaldafnytypes.Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() - }() - -} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_native.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_native.go deleted file mode 100644 index 06921c5122..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositional/to_native.go +++ /dev/null @@ -1,154 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" - "github.com/dafny-lang/DafnyRuntimeGo/dafny" -) - -func GetResourceInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourceInput) simplepositionaltypes.GetResourceInput { - - return simplepositionaltypes.GetResourceInput{Name: func() *string { - var s string - if dafnyInput.Dtor_name() == nil { - return nil - } - for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func GetResourceOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourceOutput) simplepositionaltypes.GetResourceOutput { - - return simplepositionaltypes.GetResourceOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} - -} - -func GetResourcePositionalInput_FromDafny(dafnyInput dafny.Sequence) simplepositionaltypes.GetResourcePositionalInput { - - return simplepositionaltypes.GetResourcePositionalInput{Name: func() *string { - var s string - if dafnyInput == nil { - return nil - } - for i := dafny.Iterate(dafnyInput); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func GetNameInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetNameInput) simplepositionaltypes.GetNameInput { - - return simplepositionaltypes.GetNameInput{} - -} - -func GetNameOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetNameOutput) simplepositionaltypes.GetNameOutput { - - return simplepositionaltypes.GetNameOutput{Name: func() *string { - var s string - if dafnyOutput.Dtor_name() == nil { - return nil - } - for i := dafny.Iterate(dafnyOutput.Dtor_name()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func SimpleResource_FromDafny(dafnyResource simplepositionalinternaldafnytypes.ISimpleResource) simplepositionaltypes.ISimpleResource { - - return &SimpleResource{dafnyResource} -} - -func SimplePositionalException_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.SimplePositionalException { - return simplepositionaltypes.SimplePositionalException{Message: func() *string { - var s string - if dafnyOutput.Dtor_message() == nil { - return nil - } - for i := dafny.Iterate(dafnyOutput.Dtor_message()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func CollectionOfErrors_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.CollectionOfErrors { - listOfErrors := dafnyOutput.Dtor_list() - message := dafnyOutput.Dtor_message() - t := simplepositionaltypes.CollectionOfErrors{} - for i := dafny.Iterate(listOfErrors); ; { - val, ok := i() - if !ok { - break - } - err := val.(simplepositionalinternaldafnytypes.Error) - t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) - - } - t.Message = func() string { - var s string - for i := dafny.Iterate(message); ; { - val, ok := i() - if !ok { - return s - } else { - s = s + string(val.(dafny.Char)) - } - } - }() - return t -} -func OpaqueError_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.OpaqueError { - return simplepositionaltypes.OpaqueError{ - ErrObject: dafnyOutput.Dtor_obj(), - } -} - -func Error_FromDafny(err simplepositionalinternaldafnytypes.Error) error { - // Service Errors - if err.Is_SimplePositionalException() { - return SimplePositionalException_FromDafny(err) - } - - //DependentErrors - - //Unmodelled Errors - if err.Is_CollectionOfErrors() { - return CollectionOfErrors_Output_FromDafny(err) - } - - return OpaqueError_Output_FromDafny(err) -} - -func SimplePositionalConfig_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.SimplePositionalConfig) simplepositionaltypes.SimplePositionalConfig { - return simplepositionaltypes.SimplePositionalConfig{} - -} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go deleted file mode 100644 index 86c81ba831..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafny/simplepositionalinternaldafny.go +++ /dev/null @@ -1,188 +0,0 @@ -// Package simplepositionalinternaldafny -// Dafny module simplepositionalinternaldafny compiled into Go - -package simplepositionalinternaldafny - -import ( - "fmt" - os "os" - - SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" - SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" - simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - _System "github.com/dafny-lang/DafnyRuntimeGo/System_" - _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" - StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" - StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" - StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" - Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -var _ = os.Args -var _ _dafny.Dummy__ -var _ _System.Dummy__ -var _ Wrappers.Dummy__ -var _ StandardLibrary_UInt.Dummy__ -var _ StandardLibrary.Dummy__ -var _ StandardLibraryInterop.Dummy__ -var _ SimpleResource.Dummy__ -var _ SimplePositionalImpl.Dummy__ - -type Dummy__ struct{} - -// Definition of class Default__ -type Default__ struct { - dummy byte -} - -func New_Default___() *Default__ { - _this := Default__{} - - return &_this -} - -type CompanionStruct_Default___ struct { -} - -var Companion_Default___ = CompanionStruct_Default___{} - -func (_this *Default__) Equals(other *Default__) bool { - return _this == other -} - -func (_this *Default__) EqualsGeneric(x interface{}) bool { - other, ok := x.(*Default__) - return ok && _this.Equals(other) -} - -func (*Default__) String() string { - return "simplepositionalinternaldafny.Default__" -} -func (_this *Default__) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = &Default__{} - -func (_static *CompanionStruct_Default___) DefaultSimplePositionalConfig() simplepositionalinternaldafnytypes.SimplePositionalConfig { - return simplepositionalinternaldafnytypes.Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() -} -func (_static *CompanionStruct_Default___) SimplePositional(config simplepositionalinternaldafnytypes.SimplePositionalConfig) Wrappers.Result { - var res Wrappers.Result = Wrappers.Result{} - _ = res - var _4_client *SimplePositionalClient - _ = _4_client - var _nw2 *SimplePositionalClient = New_SimplePositionalClient_() - _ = _nw2 - _nw2.Ctor__(SimplePositionalImpl.Companion_Config_.Create_Config_()) - _4_client = _nw2 - res = Wrappers.Companion_Result_.Create_Success_(_4_client) - return res - return res -} -func (_static *CompanionStruct_Default___) CreateSuccessOfClient(client simplepositionalinternaldafnytypes.ISimplePositionalClient) Wrappers.Result { - return Wrappers.Companion_Result_.Create_Success_(client) -} -func (_static *CompanionStruct_Default___) CreateFailureOfError(error_ simplepositionalinternaldafnytypes.Error) Wrappers.Result { - return Wrappers.Companion_Result_.Create_Failure_(error_) -} - -// End of class Default__ - -// Definition of class SimplePositionalClient -type SimplePositionalClient struct { - _config SimplePositionalImpl.Config -} - -func New_SimplePositionalClient_() *SimplePositionalClient { - _this := SimplePositionalClient{} - - _this._config = SimplePositionalImpl.Companion_Config_.Default() - return &_this -} - -type CompanionStruct_SimplePositionalClient_ struct { -} - -var Companion_SimplePositionalClient_ = CompanionStruct_SimplePositionalClient_{} - -func (_this *SimplePositionalClient) Equals(other *SimplePositionalClient) bool { - return _this == other -} - -func (_this *SimplePositionalClient) EqualsGeneric(x interface{}) bool { - other, ok := x.(*SimplePositionalClient) - return ok && _this.Equals(other) -} - -func (*SimplePositionalClient) String() string { - return "simplepositionalinternaldafny.SimplePositionalClient" -} - -func Type_SimplePositionalClient_() _dafny.TypeDescriptor { - return type_SimplePositionalClient_{} -} - -type type_SimplePositionalClient_ struct { -} - -func (_this type_SimplePositionalClient_) Default() interface{} { - return (*SimplePositionalClient)(nil) -} - -func (_this type_SimplePositionalClient_) String() string { - return "simplepositionalinternaldafny.SimplePositionalClient" -} -func (_this *SimplePositionalClient) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){simplepositionalinternaldafnytypes.Companion_ISimplePositionalClient_.TraitID_} -} - -var _ simplepositionalinternaldafnytypes.ISimplePositionalClient = &SimplePositionalClient{} -var _ _dafny.TraitOffspring = &SimplePositionalClient{} - -func (_this *SimplePositionalClient) Ctor__(config SimplePositionalImpl.Config) { - { - (_this)._config = config - } -} -func (_this *SimplePositionalClient) GetResource(input simplepositionalinternaldafnytypes.GetResourceInput) Wrappers.Result { - { - var output Wrappers.Result = Wrappers.Result{} - _ = output - var _out2 Wrappers.Result - _ = _out2 - _out2 = SimplePositionalImpl.Companion_Default___.GetResource((_this).Config(), input) - output = _out2 - return output - } -} - -// recover function to handle panic -func handlePanic() { - - // detect if panic occurs or not - a := recover() - - if a != nil { - fmt.Println("RECOVERED IN INTERNAL DAFNY", a) - } - -} -func (_this *SimplePositionalClient) GetResourcePositional(input _dafny.Sequence) Wrappers.Result { - { - var output Wrappers.Result = Wrappers.Result{} - _ = output - var _out3 Wrappers.Result - _ = _out3 - _out3 = SimplePositionalImpl.Companion_Default___.GetResourcePositional((_this).Config(), input) - output = _out3 - return output - } -} -func (_this *SimplePositionalClient) Config() SimplePositionalImpl.Config { - { - return _this._config - } -} - -// End of class SimplePositionalClient diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go deleted file mode 100644 index 45ca0af901..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnytypes/simplepositionalinternaldafnytypes.go +++ /dev/null @@ -1,993 +0,0 @@ -// Package simplepositionalinternaldafnytypes -// Dafny module simplepositionalinternaldafnytypes compiled into Go - -package simplepositionalinternaldafnytypes - -import ( - os "os" - - _System "github.com/dafny-lang/DafnyRuntimeGo/System_" - _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" - StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" - StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" - StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" - Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -var _ = os.Args -var _ _dafny.Dummy__ -var _ _System.Dummy__ -var _ Wrappers.Dummy__ -var _ StandardLibrary_UInt.Dummy__ -var _ StandardLibrary.Dummy__ -var _ StandardLibraryInterop.Dummy__ - -type Dummy__ struct{} - -// Definition of datatype DafnyCallEvent -type DafnyCallEvent struct { - Data_DafnyCallEvent_ -} - -func (_this DafnyCallEvent) Get_() Data_DafnyCallEvent_ { - return _this.Data_DafnyCallEvent_ -} - -type Data_DafnyCallEvent_ interface { - isDafnyCallEvent() -} - -type CompanionStruct_DafnyCallEvent_ struct { -} - -var Companion_DafnyCallEvent_ = CompanionStruct_DafnyCallEvent_{} - -type DafnyCallEvent_DafnyCallEvent struct { - Input interface{} - Output interface{} -} - -func (DafnyCallEvent_DafnyCallEvent) isDafnyCallEvent() {} - -func (CompanionStruct_DafnyCallEvent_) Create_DafnyCallEvent_(Input interface{}, Output interface{}) DafnyCallEvent { - return DafnyCallEvent{DafnyCallEvent_DafnyCallEvent{Input, Output}} -} - -func (_this DafnyCallEvent) Is_DafnyCallEvent() bool { - _, ok := _this.Get_().(DafnyCallEvent_DafnyCallEvent) - return ok -} - -func (CompanionStruct_DafnyCallEvent_) Default(_default_I interface{}, _default_O interface{}) DafnyCallEvent { - return Companion_DafnyCallEvent_.Create_DafnyCallEvent_(_default_I, _default_O) -} - -func (_this DafnyCallEvent) Dtor_input() interface{} { - return _this.Get_().(DafnyCallEvent_DafnyCallEvent).Input -} - -func (_this DafnyCallEvent) Dtor_output() interface{} { - return _this.Get_().(DafnyCallEvent_DafnyCallEvent).Output -} - -func (_this DafnyCallEvent) String() string { - switch data := _this.Get_().(type) { - case nil: - return "null" - case DafnyCallEvent_DafnyCallEvent: - { - return "SimplePositionalTypes.DafnyCallEvent.DafnyCallEvent" + "(" + _dafny.String(data.Input) + ", " + _dafny.String(data.Output) + ")" - } - default: - { - return "" - } - } -} - -func (_this DafnyCallEvent) Equals(other DafnyCallEvent) bool { - switch data1 := _this.Get_().(type) { - case DafnyCallEvent_DafnyCallEvent: - { - data2, ok := other.Get_().(DafnyCallEvent_DafnyCallEvent) - return ok && _dafny.AreEqual(data1.Input, data2.Input) && _dafny.AreEqual(data1.Output, data2.Output) - } - default: - { - return false // unexpected - } - } -} - -func (_this DafnyCallEvent) EqualsGeneric(other interface{}) bool { - typed, ok := other.(DafnyCallEvent) - return ok && _this.Equals(typed) -} - -func Type_DafnyCallEvent_(Type_I_ _dafny.TypeDescriptor, Type_O_ _dafny.TypeDescriptor) _dafny.TypeDescriptor { - return type_DafnyCallEvent_{Type_I_, Type_O_} -} - -type type_DafnyCallEvent_ struct { - Type_I_ _dafny.TypeDescriptor - Type_O_ _dafny.TypeDescriptor -} - -func (_this type_DafnyCallEvent_) Default() interface{} { - Type_I_ := _this.Type_I_ - _ = Type_I_ - Type_O_ := _this.Type_O_ - _ = Type_O_ - return Companion_DafnyCallEvent_.Default(Type_I_.Default(), Type_O_.Default()) -} - -func (_this type_DafnyCallEvent_) String() string { - return "simplepositionalinternaldafnytypes.DafnyCallEvent" -} -func (_this DafnyCallEvent) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = DafnyCallEvent{} - -// End of datatype DafnyCallEvent - -// Definition of datatype GetNameInput -type GetNameInput struct { - Data_GetNameInput_ -} - -func (_this GetNameInput) Get_() Data_GetNameInput_ { - return _this.Data_GetNameInput_ -} - -type Data_GetNameInput_ interface { - isGetNameInput() -} - -type CompanionStruct_GetNameInput_ struct { -} - -var Companion_GetNameInput_ = CompanionStruct_GetNameInput_{} - -type GetNameInput_GetNameInput struct { -} - -func (GetNameInput_GetNameInput) isGetNameInput() {} - -func (CompanionStruct_GetNameInput_) Create_GetNameInput_() GetNameInput { - return GetNameInput{GetNameInput_GetNameInput{}} -} - -func (_this GetNameInput) Is_GetNameInput() bool { - _, ok := _this.Get_().(GetNameInput_GetNameInput) - return ok -} - -func (CompanionStruct_GetNameInput_) Default() GetNameInput { - return Companion_GetNameInput_.Create_GetNameInput_() -} - -func (_ CompanionStruct_GetNameInput_) AllSingletonConstructors() _dafny.Iterator { - i := -1 - return func() (interface{}, bool) { - i++ - switch i { - case 0: - return Companion_GetNameInput_.Create_GetNameInput_(), true - default: - return GetNameInput{}, false - } - } -} - -func (_this GetNameInput) String() string { - switch _this.Get_().(type) { - case nil: - return "null" - case GetNameInput_GetNameInput: - { - return "SimplePositionalTypes.GetNameInput.GetNameInput" - } - default: - { - return "" - } - } -} - -func (_this GetNameInput) Equals(other GetNameInput) bool { - switch _this.Get_().(type) { - case GetNameInput_GetNameInput: - { - _, ok := other.Get_().(GetNameInput_GetNameInput) - return ok - } - default: - { - return false // unexpected - } - } -} - -func (_this GetNameInput) EqualsGeneric(other interface{}) bool { - typed, ok := other.(GetNameInput) - return ok && _this.Equals(typed) -} - -func Type_GetNameInput_() _dafny.TypeDescriptor { - return type_GetNameInput_{} -} - -type type_GetNameInput_ struct { -} - -func (_this type_GetNameInput_) Default() interface{} { - return Companion_GetNameInput_.Default() -} - -func (_this type_GetNameInput_) String() string { - return "simplepositionalinternaldafnytypes.GetNameInput" -} -func (_this GetNameInput) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = GetNameInput{} - -// End of datatype GetNameInput - -// Definition of datatype GetNameOutput -type GetNameOutput struct { - Data_GetNameOutput_ -} - -func (_this GetNameOutput) Get_() Data_GetNameOutput_ { - return _this.Data_GetNameOutput_ -} - -type Data_GetNameOutput_ interface { - isGetNameOutput() -} - -type CompanionStruct_GetNameOutput_ struct { -} - -var Companion_GetNameOutput_ = CompanionStruct_GetNameOutput_{} - -type GetNameOutput_GetNameOutput struct { - Name _dafny.Sequence -} - -func (GetNameOutput_GetNameOutput) isGetNameOutput() {} - -func (CompanionStruct_GetNameOutput_) Create_GetNameOutput_(Name _dafny.Sequence) GetNameOutput { - return GetNameOutput{GetNameOutput_GetNameOutput{Name}} -} - -func (_this GetNameOutput) Is_GetNameOutput() bool { - _, ok := _this.Get_().(GetNameOutput_GetNameOutput) - return ok -} - -func (CompanionStruct_GetNameOutput_) Default() GetNameOutput { - return Companion_GetNameOutput_.Create_GetNameOutput_(_dafny.EmptySeq.SetString()) -} - -func (_this GetNameOutput) Dtor_name() _dafny.Sequence { - return _this.Get_().(GetNameOutput_GetNameOutput).Name -} - -func (_this GetNameOutput) String() string { - switch data := _this.Get_().(type) { - case nil: - return "null" - case GetNameOutput_GetNameOutput: - { - return "SimplePositionalTypes.GetNameOutput.GetNameOutput" + "(" + _dafny.String(data.Name) + ")" - } - default: - { - return "" - } - } -} - -func (_this GetNameOutput) Equals(other GetNameOutput) bool { - switch data1 := _this.Get_().(type) { - case GetNameOutput_GetNameOutput: - { - data2, ok := other.Get_().(GetNameOutput_GetNameOutput) - return ok && data1.Name.Equals(data2.Name) - } - default: - { - return false // unexpected - } - } -} - -func (_this GetNameOutput) EqualsGeneric(other interface{}) bool { - typed, ok := other.(GetNameOutput) - return ok && _this.Equals(typed) -} - -func Type_GetNameOutput_() _dafny.TypeDescriptor { - return type_GetNameOutput_{} -} - -type type_GetNameOutput_ struct { -} - -func (_this type_GetNameOutput_) Default() interface{} { - return Companion_GetNameOutput_.Default() -} - -func (_this type_GetNameOutput_) String() string { - return "simplepositionalinternaldafnytypes.GetNameOutput" -} -func (_this GetNameOutput) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = GetNameOutput{} - -// End of datatype GetNameOutput - -// Definition of datatype GetResourceInput -type GetResourceInput struct { - Data_GetResourceInput_ -} - -func (_this GetResourceInput) Get_() Data_GetResourceInput_ { - return _this.Data_GetResourceInput_ -} - -type Data_GetResourceInput_ interface { - isGetResourceInput() -} - -type CompanionStruct_GetResourceInput_ struct { -} - -var Companion_GetResourceInput_ = CompanionStruct_GetResourceInput_{} - -type GetResourceInput_GetResourceInput struct { - Name _dafny.Sequence -} - -func (GetResourceInput_GetResourceInput) isGetResourceInput() {} - -func (CompanionStruct_GetResourceInput_) Create_GetResourceInput_(Name _dafny.Sequence) GetResourceInput { - return GetResourceInput{GetResourceInput_GetResourceInput{Name}} -} - -func (_this GetResourceInput) Is_GetResourceInput() bool { - _, ok := _this.Get_().(GetResourceInput_GetResourceInput) - return ok -} - -func (CompanionStruct_GetResourceInput_) Default() GetResourceInput { - return Companion_GetResourceInput_.Create_GetResourceInput_(_dafny.EmptySeq.SetString()) -} - -func (_this GetResourceInput) Dtor_name() _dafny.Sequence { - return _this.Get_().(GetResourceInput_GetResourceInput).Name -} - -func (_this GetResourceInput) String() string { - switch data := _this.Get_().(type) { - case nil: - return "null" - case GetResourceInput_GetResourceInput: - { - return "SimplePositionalTypes.GetResourceInput.GetResourceInput" + "(" + _dafny.String(data.Name) + ")" - } - default: - { - return "" - } - } -} - -func (_this GetResourceInput) Equals(other GetResourceInput) bool { - switch data1 := _this.Get_().(type) { - case GetResourceInput_GetResourceInput: - { - data2, ok := other.Get_().(GetResourceInput_GetResourceInput) - return ok && data1.Name.Equals(data2.Name) - } - default: - { - return false // unexpected - } - } -} - -func (_this GetResourceInput) EqualsGeneric(other interface{}) bool { - typed, ok := other.(GetResourceInput) - return ok && _this.Equals(typed) -} - -func Type_GetResourceInput_() _dafny.TypeDescriptor { - return type_GetResourceInput_{} -} - -type type_GetResourceInput_ struct { -} - -func (_this type_GetResourceInput_) Default() interface{} { - return Companion_GetResourceInput_.Default() -} - -func (_this type_GetResourceInput_) String() string { - return "simplepositionalinternaldafnytypes.GetResourceInput" -} -func (_this GetResourceInput) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = GetResourceInput{} - -// End of datatype GetResourceInput - -// Definition of datatype GetResourceOutput -type GetResourceOutput struct { - Data_GetResourceOutput_ -} - -func (_this GetResourceOutput) Get_() Data_GetResourceOutput_ { - return _this.Data_GetResourceOutput_ -} - -type Data_GetResourceOutput_ interface { - isGetResourceOutput() -} - -type CompanionStruct_GetResourceOutput_ struct { -} - -var Companion_GetResourceOutput_ = CompanionStruct_GetResourceOutput_{} - -type GetResourceOutput_GetResourceOutput struct { - Output ISimpleResource -} - -func (GetResourceOutput_GetResourceOutput) isGetResourceOutput() {} - -func (CompanionStruct_GetResourceOutput_) Create_GetResourceOutput_(Output ISimpleResource) GetResourceOutput { - return GetResourceOutput{GetResourceOutput_GetResourceOutput{Output}} -} - -func (_this GetResourceOutput) Is_GetResourceOutput() bool { - _, ok := _this.Get_().(GetResourceOutput_GetResourceOutput) - return ok -} - -func (CompanionStruct_GetResourceOutput_) Default() GetResourceOutput { - return Companion_GetResourceOutput_.Create_GetResourceOutput_((ISimpleResource)(nil)) -} - -func (_this GetResourceOutput) Dtor_output() ISimpleResource { - return _this.Get_().(GetResourceOutput_GetResourceOutput).Output -} - -func (_this GetResourceOutput) String() string { - switch data := _this.Get_().(type) { - case nil: - return "null" - case GetResourceOutput_GetResourceOutput: - { - return "SimplePositionalTypes.GetResourceOutput.GetResourceOutput" + "(" + _dafny.String(data.Output) + ")" - } - default: - { - return "" - } - } -} - -func (_this GetResourceOutput) Equals(other GetResourceOutput) bool { - switch data1 := _this.Get_().(type) { - case GetResourceOutput_GetResourceOutput: - { - data2, ok := other.Get_().(GetResourceOutput_GetResourceOutput) - return ok && _dafny.AreEqual(data1.Output, data2.Output) - } - default: - { - return false // unexpected - } - } -} - -func (_this GetResourceOutput) EqualsGeneric(other interface{}) bool { - typed, ok := other.(GetResourceOutput) - return ok && _this.Equals(typed) -} - -func Type_GetResourceOutput_() _dafny.TypeDescriptor { - return type_GetResourceOutput_{} -} - -type type_GetResourceOutput_ struct { -} - -func (_this type_GetResourceOutput_) Default() interface{} { - return Companion_GetResourceOutput_.Default() -} - -func (_this type_GetResourceOutput_) String() string { - return "simplepositionalinternaldafnytypes.GetResourceOutput" -} -func (_this GetResourceOutput) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = GetResourceOutput{} - -// End of datatype GetResourceOutput - -// Definition of class ISimplePositionalClientCallHistory -type ISimplePositionalClientCallHistory struct { - dummy byte -} - -func New_ISimplePositionalClientCallHistory_() *ISimplePositionalClientCallHistory { - _this := ISimplePositionalClientCallHistory{} - - return &_this -} - -type CompanionStruct_ISimplePositionalClientCallHistory_ struct { -} - -var Companion_ISimplePositionalClientCallHistory_ = CompanionStruct_ISimplePositionalClientCallHistory_{} - -func (_this *ISimplePositionalClientCallHistory) Equals(other *ISimplePositionalClientCallHistory) bool { - return _this == other -} - -func (_this *ISimplePositionalClientCallHistory) EqualsGeneric(x interface{}) bool { - other, ok := x.(*ISimplePositionalClientCallHistory) - return ok && _this.Equals(other) -} - -func (*ISimplePositionalClientCallHistory) String() string { - return "simplepositionalinternaldafnytypes.ISimplePositionalClientCallHistory" -} - -func Type_ISimplePositionalClientCallHistory_() _dafny.TypeDescriptor { - return type_ISimplePositionalClientCallHistory_{} -} - -type type_ISimplePositionalClientCallHistory_ struct { -} - -func (_this type_ISimplePositionalClientCallHistory_) Default() interface{} { - return (*ISimplePositionalClientCallHistory)(nil) -} - -func (_this type_ISimplePositionalClientCallHistory_) String() string { - return "simplepositionalinternaldafnytypes.ISimplePositionalClientCallHistory" -} -func (_this *ISimplePositionalClientCallHistory) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = &ISimplePositionalClientCallHistory{} - -// End of class ISimplePositionalClientCallHistory - -// Definition of trait ISimplePositionalClient -type ISimplePositionalClient interface { - String() string - GetResource(input GetResourceInput) Wrappers.Result - GetResourcePositional(input _dafny.Sequence) Wrappers.Result -} -type CompanionStruct_ISimplePositionalClient_ struct { - TraitID_ *_dafny.TraitID -} - -var Companion_ISimplePositionalClient_ = CompanionStruct_ISimplePositionalClient_{ - TraitID_: &_dafny.TraitID{}, -} - -func (CompanionStruct_ISimplePositionalClient_) CastTo_(x interface{}) ISimplePositionalClient { - var t ISimplePositionalClient - t, _ = x.(ISimplePositionalClient) - return t -} - -// End of trait ISimplePositionalClient - -// Definition of datatype SimplePositionalConfig -type SimplePositionalConfig struct { - Data_SimplePositionalConfig_ -} - -func (_this SimplePositionalConfig) Get_() Data_SimplePositionalConfig_ { - return _this.Data_SimplePositionalConfig_ -} - -type Data_SimplePositionalConfig_ interface { - isSimplePositionalConfig() -} - -type CompanionStruct_SimplePositionalConfig_ struct { -} - -var Companion_SimplePositionalConfig_ = CompanionStruct_SimplePositionalConfig_{} - -type SimplePositionalConfig_SimplePositionalConfig struct { -} - -func (SimplePositionalConfig_SimplePositionalConfig) isSimplePositionalConfig() {} - -func (CompanionStruct_SimplePositionalConfig_) Create_SimplePositionalConfig_() SimplePositionalConfig { - return SimplePositionalConfig{SimplePositionalConfig_SimplePositionalConfig{}} -} - -func (_this SimplePositionalConfig) Is_SimplePositionalConfig() bool { - _, ok := _this.Get_().(SimplePositionalConfig_SimplePositionalConfig) - return ok -} - -func (CompanionStruct_SimplePositionalConfig_) Default() SimplePositionalConfig { - return Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() -} - -func (_ CompanionStruct_SimplePositionalConfig_) AllSingletonConstructors() _dafny.Iterator { - i := -1 - return func() (interface{}, bool) { - i++ - switch i { - case 0: - return Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_(), true - default: - return SimplePositionalConfig{}, false - } - } -} - -func (_this SimplePositionalConfig) String() string { - switch _this.Get_().(type) { - case nil: - return "null" - case SimplePositionalConfig_SimplePositionalConfig: - { - return "SimplePositionalTypes.SimplePositionalConfig.SimplePositionalConfig" - } - default: - { - return "" - } - } -} - -func (_this SimplePositionalConfig) Equals(other SimplePositionalConfig) bool { - switch _this.Get_().(type) { - case SimplePositionalConfig_SimplePositionalConfig: - { - _, ok := other.Get_().(SimplePositionalConfig_SimplePositionalConfig) - return ok - } - default: - { - return false // unexpected - } - } -} - -func (_this SimplePositionalConfig) EqualsGeneric(other interface{}) bool { - typed, ok := other.(SimplePositionalConfig) - return ok && _this.Equals(typed) -} - -func Type_SimplePositionalConfig_() _dafny.TypeDescriptor { - return type_SimplePositionalConfig_{} -} - -type type_SimplePositionalConfig_ struct { -} - -func (_this type_SimplePositionalConfig_) Default() interface{} { - return Companion_SimplePositionalConfig_.Default() -} - -func (_this type_SimplePositionalConfig_) String() string { - return "simplepositionalinternaldafnytypes.SimplePositionalConfig" -} -func (_this SimplePositionalConfig) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = SimplePositionalConfig{} - -// End of datatype SimplePositionalConfig - -// Definition of class ISimpleResourceCallHistory -type ISimpleResourceCallHistory struct { - dummy byte -} - -func New_ISimpleResourceCallHistory_() *ISimpleResourceCallHistory { - _this := ISimpleResourceCallHistory{} - - return &_this -} - -type CompanionStruct_ISimpleResourceCallHistory_ struct { -} - -var Companion_ISimpleResourceCallHistory_ = CompanionStruct_ISimpleResourceCallHistory_{} - -func (_this *ISimpleResourceCallHistory) Equals(other *ISimpleResourceCallHistory) bool { - return _this == other -} - -func (_this *ISimpleResourceCallHistory) EqualsGeneric(x interface{}) bool { - other, ok := x.(*ISimpleResourceCallHistory) - return ok && _this.Equals(other) -} - -func (*ISimpleResourceCallHistory) String() string { - return "simplepositionalinternaldafnytypes.ISimpleResourceCallHistory" -} - -func Type_ISimpleResourceCallHistory_() _dafny.TypeDescriptor { - return type_ISimpleResourceCallHistory_{} -} - -type type_ISimpleResourceCallHistory_ struct { -} - -func (_this type_ISimpleResourceCallHistory_) Default() interface{} { - return (*ISimpleResourceCallHistory)(nil) -} - -func (_this type_ISimpleResourceCallHistory_) String() string { - return "simplepositionalinternaldafnytypes.ISimpleResourceCallHistory" -} -func (_this *ISimpleResourceCallHistory) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = &ISimpleResourceCallHistory{} - -// End of class ISimpleResourceCallHistory - -// Definition of trait ISimpleResource -type ISimpleResource interface { - String() string - GetName(input GetNameInput) Wrappers.Result - GetName_k(input GetNameInput) Wrappers.Result -} - -func (_static *CompanionStruct_ISimpleResource_) GetName(_this ISimpleResource, input GetNameInput) Wrappers.Result { - { - var output Wrappers.Result = Wrappers.Companion_Result_.Default(Companion_GetNameOutput_.Default()) - _ = output - var _out0 Wrappers.Result - _ = _out0 - _out0 = (_this).GetName_k(input) - output = _out0 - return output - } -} - -type CompanionStruct_ISimpleResource_ struct { - TraitID_ *_dafny.TraitID -} - -var Companion_ISimpleResource_ = CompanionStruct_ISimpleResource_{ - TraitID_: &_dafny.TraitID{}, -} - -func (CompanionStruct_ISimpleResource_) CastTo_(x interface{}) ISimpleResource { - var t ISimpleResource - t, _ = x.(ISimpleResource) - return t -} - -// End of trait ISimpleResource - -// Definition of datatype Error -type Error struct { - Data_Error_ -} - -func (_this Error) Get_() Data_Error_ { - return _this.Data_Error_ -} - -type Data_Error_ interface { - isError() -} - -type CompanionStruct_Error_ struct { -} - -var Companion_Error_ = CompanionStruct_Error_{} - -type Error_SimplePositionalException struct { - Message _dafny.Sequence -} - -func (Error_SimplePositionalException) isError() {} - -func (CompanionStruct_Error_) Create_SimplePositionalException_(Message _dafny.Sequence) Error { - return Error{Error_SimplePositionalException{Message}} -} - -func (_this Error) Is_SimplePositionalException() bool { - _, ok := _this.Get_().(Error_SimplePositionalException) - return ok -} - -type Error_CollectionOfErrors struct { - List _dafny.Sequence - Message _dafny.Sequence -} - -func (Error_CollectionOfErrors) isError() {} - -func (CompanionStruct_Error_) Create_CollectionOfErrors_(List _dafny.Sequence, Message _dafny.Sequence) Error { - return Error{Error_CollectionOfErrors{List, Message}} -} - -func (_this Error) Is_CollectionOfErrors() bool { - _, ok := _this.Get_().(Error_CollectionOfErrors) - return ok -} - -type Error_Opaque struct { - Obj interface{} -} - -func (Error_Opaque) isError() {} - -func (CompanionStruct_Error_) Create_Opaque_(Obj interface{}) Error { - return Error{Error_Opaque{Obj}} -} - -func (_this Error) Is_Opaque() bool { - _, ok := _this.Get_().(Error_Opaque) - return ok -} - -func (CompanionStruct_Error_) Default() Error { - return Companion_Error_.Create_SimplePositionalException_(_dafny.EmptySeq.SetString()) -} - -func (_this Error) Dtor_message() _dafny.Sequence { - switch data := _this.Get_().(type) { - case Error_SimplePositionalException: - return data.Message - default: - return data.(Error_CollectionOfErrors).Message - } -} - -func (_this Error) Dtor_list() _dafny.Sequence { - return _this.Get_().(Error_CollectionOfErrors).List -} - -func (_this Error) Dtor_obj() interface{} { - return _this.Get_().(Error_Opaque).Obj -} - -func (_this Error) String() string { - switch data := _this.Get_().(type) { - case nil: - return "null" - case Error_SimplePositionalException: - { - return "SimplePositionalTypes.Error.SimplePositionalException" + "(" + _dafny.String(data.Message) + ")" - } - case Error_CollectionOfErrors: - { - return "SimplePositionalTypes.Error.CollectionOfErrors" + "(" + _dafny.String(data.List) + ", " + _dafny.String(data.Message) + ")" - } - case Error_Opaque: - { - return "SimplePositionalTypes.Error.Opaque" + "(" + _dafny.String(data.Obj) + ")" - } - default: - { - return "" - } - } -} - -func (_this Error) Equals(other Error) bool { - switch data1 := _this.Get_().(type) { - case Error_SimplePositionalException: - { - data2, ok := other.Get_().(Error_SimplePositionalException) - return ok && data1.Message.Equals(data2.Message) - } - case Error_CollectionOfErrors: - { - data2, ok := other.Get_().(Error_CollectionOfErrors) - return ok && data1.List.Equals(data2.List) && data1.Message.Equals(data2.Message) - } - case Error_Opaque: - { - data2, ok := other.Get_().(Error_Opaque) - return ok && _dafny.AreEqual(data1.Obj, data2.Obj) - } - default: - { - return false // unexpected - } - } -} - -func (_this Error) EqualsGeneric(other interface{}) bool { - typed, ok := other.(Error) - return ok && _this.Equals(typed) -} - -func Type_Error_() _dafny.TypeDescriptor { - return type_Error_{} -} - -type type_Error_ struct { -} - -func (_this type_Error_) Default() interface{} { - return Companion_Error_.Default() -} - -func (_this type_Error_) String() string { - return "simplepositionalinternaldafnytypes.Error" -} -func (_this Error) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = Error{} - -// End of datatype Error - -// Definition of class OpaqueError -type OpaqueError struct { -} - -func New_OpaqueError_() *OpaqueError { - _this := OpaqueError{} - - return &_this -} - -type CompanionStruct_OpaqueError_ struct { -} - -var Companion_OpaqueError_ = CompanionStruct_OpaqueError_{} - -func (*OpaqueError) String() string { - return "simplepositionalinternaldafnytypes.OpaqueError" -} - -// End of class OpaqueError - -func Type_OpaqueError_() _dafny.TypeDescriptor { - return type_OpaqueError_{} -} - -type type_OpaqueError_ struct { -} - -func (_this type_OpaqueError_) Default() interface{} { - return Companion_Error_.Default() -} - -func (_this type_OpaqueError_) String() string { - return "simplepositionalinternaldafnytypes.OpaqueError" -} -func (_this *CompanionStruct_OpaqueError_) Is_(__source Error) bool { - var _0_e Error = (__source) - _ = _0_e - return (_0_e).Is_Opaque() -} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/shim.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/shim.go deleted file mode 100644 index 04c3907139..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/shim.go +++ /dev/null @@ -1,59 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositionalinternaldafnywrapped - -import ( - "context" - "fmt" - "github.com/Smithy-dafny/TestModels/Positional/simplepositional" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/dafny-lang/DafnyRuntimeGo/dafny" - "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -type Shim struct { - simplepositionalinternaldafnytypes.ISimplePositionalClient - client *simplepositional.Client -} - -func WrappedSimplePositional(inputConfig simplepositionalinternaldafnytypes.SimplePositionalConfig) Wrappers.Result { - var nativeConfig = simplepositional.SimplePositionalConfig_FromDafny(inputConfig) - var nativeClient, nativeError = simplepositional.NewClient(nativeConfig) - if nativeError != nil { - return Wrappers.Companion_Result_.Create_Failure_(simplepositionalinternaldafnytypes.Companion_Error_.Create_Opaque_(nativeError)) - } - return Wrappers.Companion_Result_.Create_Success_(&Shim{client: nativeClient}) -} - -func (shim *Shim) GetResource(input simplepositionalinternaldafnytypes.GetResourceInput) Wrappers.Result { - var native_request = simplepositional.GetResourceInput_FromDafny(input) - var native_response, native_error = shim.client.GetResource(context.Background(), native_request) - if native_error != nil { - return Wrappers.Companion_Result_.Create_Failure_(simplepositional.Error_ToDafny(native_error)) - } - return Wrappers.Companion_Result_.Create_Success_(simplepositional.GetResourceOutput_ToDafny(*native_response)) -} - -// recover function to handle panic -func handlePanic() { - - // detect if panic occurs or not - a := recover() - - if a != nil { - fmt.Println("RECOVER IN SHIM", a) - } - - } - -func (shim *Shim) GetResourcePositional(input dafny.Sequence) Wrappers.Result { - defer handlePanic() - - var native_request = simplepositional.GetResourcePositionalInput_FromDafny(input) - var native_response, native_error = shim.client.GetResourcePositional(context.Background(), native_request) - fmt.Println(native_response) - if native_error != nil { - return Wrappers.Companion_Result_.Create_Failure_(simplepositional.Error_ToDafny(native_error)) - } - return Wrappers.Companion_Result_.Create_Success_(native_response) -} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/simplepositionalinternaldafnywrapped.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/simplepositionalinternaldafnywrapped.go deleted file mode 100644 index 0aaee5aa66..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionalinternaldafnywrapped/simplepositionalinternaldafnywrapped.go +++ /dev/null @@ -1,70 +0,0 @@ -// Package simplepositionalinternaldafnywrapped -// Dafny module simplepositionalinternaldafnywrapped compiled into Go - -package simplepositionalinternaldafnywrapped - -import ( - os "os" - - SimplePositionalImpl "github.com/Smithy-dafny/TestModels/Positional/SimplePositionalImpl" - SimpleResource "github.com/Smithy-dafny/TestModels/Positional/SimpleResource" - simplepositionalinternaldafnytypes "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - _System "github.com/dafny-lang/DafnyRuntimeGo/System_" - _dafny "github.com/dafny-lang/DafnyRuntimeGo/dafny" - StandardLibrary "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary" - StandardLibraryInterop "github.com/dafny-lang/DafnyStandardLibGo/StandardLibraryInterop" - StandardLibrary_UInt "github.com/dafny-lang/DafnyStandardLibGo/StandardLibrary_UInt" - Wrappers "github.com/dafny-lang/DafnyStandardLibGo/Wrappers" -) - -var _ = os.Args -var _ _dafny.Dummy__ -var _ _System.Dummy__ -var _ Wrappers.Dummy__ -var _ StandardLibrary_UInt.Dummy__ -var _ StandardLibrary.Dummy__ -var _ StandardLibraryInterop.Dummy__ -var _ SimpleResource.Dummy__ -var _ SimplePositionalImpl.Dummy__ - -type Dummy__ struct{} - -// Definition of class Default__ -type Default__ struct { - dummy byte -} - -func New_Default___() *Default__ { - _this := Default__{} - - return &_this -} - -type CompanionStruct_Default___ struct { -} - -var Companion_Default___ = CompanionStruct_Default___{} - -func (_this *Default__) Equals(other *Default__) bool { - return _this == other -} - -func (_this *Default__) EqualsGeneric(x interface{}) bool { - other, ok := x.(*Default__) - return ok && _this.Equals(other) -} - -func (*Default__) String() string { - return "simplepositionalinternaldafnywrapped.Default__" -} -func (_this *Default__) ParentTraits_() []*_dafny.TraitID { - return [](*_dafny.TraitID){} -} - -var _ _dafny.TraitOffspring = &Default__{} - -func (_static *CompanionStruct_Default___) WrappedDefaultSimplePositionalConfig() simplepositionalinternaldafnytypes.SimplePositionalConfig { - return simplepositionalinternaldafnytypes.Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() -} - -// End of class Default__ diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/errors.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/errors.go deleted file mode 100644 index a4f1fdaf51..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/errors.go +++ /dev/null @@ -1,18 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositionaltypes - -import ( - "fmt" -) - -type SimplePositionalException struct { - SimplePositionalBaseException - Message *string - - ErrorCodeOverride *string -} - -func (e SimplePositionalException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) -} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/types.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/types.go deleted file mode 100644 index 84ddf62564..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/types.go +++ /dev/null @@ -1,93 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositionaltypes - -import ( - "fmt" -) - -type GetResourceInput struct { - Name *string -} - -func (input GetResourceInput) Validate() error { - if input.Name == nil { - return fmt.Errorf("Name is required but has a nil value.") - } - - return nil -} - -type SimpleResourceReference struct { -} - -func (input SimpleResourceReference) Validate() error { - return nil -} - -type GetResourceOutput struct { - Output ISimpleResource -} - -func (input GetResourceOutput) Validate() error { - - return nil -} - -type GetResourcePositionalInput struct { - Name *string -} - -func (input GetResourcePositionalInput) Validate() error { - if input.Name == nil { - return fmt.Errorf("Name is required but has a nil value.") - } - - return nil -} - -type GetResourcePositionalOutput struct { - Output ISimpleResource -} - -func (input GetResourcePositionalOutput) Validate() error { - - return nil -} - -type SimplePositionalConfig struct { -} - -func (input SimplePositionalConfig) Validate() error { - return nil -} - -type SimplePositionalBaseException interface { - // This is a dummy method to allow type assertion since Go empty interfaces - // aren't useful for type assertion checks. No concrete class is expected to implement - // this method. This is also not exported. - interfaceBindingMethod() -} - -type ISimpleResource interface { - GetName(GetNameInput) (*GetNameOutput, error) -} - -type GetNameInput struct { -} - -func (input GetNameInput) Validate() error { - return nil -} - -type GetNameOutput struct { - Name *string -} - -func (input GetNameOutput) Validate() error { - if input.Name == nil { - return fmt.Errorf("Name is required but has a nil value.") - } - - return nil -} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/unmodelled_errors.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/unmodelled_errors.go deleted file mode 100644 index 33aff14a2c..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/simplepositionaltypes/unmodelled_errors.go +++ /dev/null @@ -1,26 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositionaltypes - -import ( - "fmt" -) - -type CollectionOfErrors struct { - SimplePositionalBaseException - ListOfErrors []error - Message string -} - -func (e CollectionOfErrors) Error() string { - return fmt.Sprintf("message: %s\n err %v", e.Message, e.ListOfErrors) -} - -type OpaqueError struct { - SimplePositionalBaseException - ErrObject interface{} -} - -func (e OpaqueError) Error() string { - return fmt.Sprintf("message: %v", e.ErrObject) -} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/to_dafny.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/to_dafny.go deleted file mode 100644 index 39442e0038..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/to_dafny.go +++ /dev/null @@ -1,144 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" - "github.com/dafny-lang/DafnyRuntimeGo/dafny" -) - -func GetResourceInput_ToDafny(nativeInput simplepositionaltypes.GetResourceInput) simplepositionalinternaldafnytypes.GetResourceInput { - - return func() simplepositionalinternaldafnytypes.GetResourceInput { - - return simplepositionalinternaldafnytypes.Companion_GetResourceInput_.Create_GetResourceInput_(func() dafny.Sequence { - if nativeInput.Name == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) - }()) - }() - -} - -func GetResourceOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourceOutput) simplepositionalinternaldafnytypes.GetResourceOutput { - - return func() simplepositionalinternaldafnytypes.GetResourceOutput { - - return simplepositionalinternaldafnytypes.Companion_GetResourceOutput_.Create_GetResourceOutput_(SimpleResource_ToDafny(nativeOutput.Output)) - }() - -} - -func GetResourcePositionalInput_ToDafny(nativeInput simplepositionaltypes.GetResourcePositionalInput) simplepositionalinternaldafnytypes.GetResourcePositionalInput { - - return func() simplepositionalinternaldafnytypes.GetResourcePositionalInput { - - return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalInput_.Create_GetResourcePositionalInput_(func() dafny.Sequence { - if nativeInput.Name == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeInput.Name)...) - }()) - }() - -} - -func GetResourcePositionalOutput_ToDafny(nativeOutput simplepositionaltypes.GetResourcePositionalOutput) simplepositionalinternaldafnytypes.GetResourcePositionalOutput { - - return func() simplepositionalinternaldafnytypes.GetResourcePositionalOutput { - - return simplepositionalinternaldafnytypes.Companion_GetResourcePositionalOutput_.Create_GetResourcePositionalOutput_(SimpleResource_ToDafny(nativeOutput.Output)) - }() - -} - -func GetNameInput_ToDafny(nativeInput simplepositionaltypes.GetNameInput) simplepositionalinternaldafnytypes.GetNameInput { - - return func() simplepositionalinternaldafnytypes.GetNameInput { - - return simplepositionalinternaldafnytypes.Companion_GetNameInput_.Create_GetNameInput_() - }() - -} - -func GetNameOutput_ToDafny(nativeOutput simplepositionaltypes.GetNameOutput) simplepositionalinternaldafnytypes.GetNameOutput { - - return func() simplepositionalinternaldafnytypes.GetNameOutput { - - return simplepositionalinternaldafnytypes.Companion_GetNameOutput_.Create_GetNameOutput_(func() dafny.Sequence { - if nativeOutput.Name == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeOutput.Name)...) - }()) - }() - -} - -func SimpleResource_ToDafny(nativeResource simplepositionaltypes.ISimpleResource) simplepositionalinternaldafnytypes.ISimpleResource { - return nativeResource.(*SimpleResource).Impl - -} - -func SimplePositionalException_ToDafny(nativeInput simplepositionaltypes.SimplePositionalException) simplepositionalinternaldafnytypes.Error { - return func() simplepositionalinternaldafnytypes.Error { - - return simplepositionalinternaldafnytypes.Companion_Error_.Create_SimplePositionalException_(func() dafny.Sequence { - if nativeInput.Message == nil { - return nil - } - return dafny.SeqOfChars([]dafny.Char(*nativeInput.Message)...) - }()) - }() - -} - -func CollectionOfErrors_Input_ToDafny(nativeInput simplepositionaltypes.CollectionOfErrors) simplepositionalinternaldafnytypes.Error { - var e []interface{} - for _, i2 := range nativeInput.ListOfErrors { - e = append(e, Error_ToDafny(i2)) - } - return simplepositionalinternaldafnytypes.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) -} -func OpaqueError_Input_ToDafny(nativeInput simplepositionaltypes.OpaqueError) simplepositionalinternaldafnytypes.Error { - return simplepositionalinternaldafnytypes.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) -} - -func Error_ToDafny(err error) simplepositionalinternaldafnytypes.Error { - switch err.(type) { - // Service Errors - case simplepositionaltypes.SimplePositionalException: - return SimplePositionalException_ToDafny(err.(simplepositionaltypes.SimplePositionalException)) - - //DependentErrors - - //Unmodelled Errors - case simplepositionaltypes.CollectionOfErrors: - return CollectionOfErrors_Input_ToDafny(err.(simplepositionaltypes.CollectionOfErrors)) - - default: - // TODO: Is changing from the commented code to this new one reasonable? - // return OpaqueError_Input_ToDafny(err.(*simpleconstraintstypes.OpaqueError)) - - // TODO: why is err a pointer? - error, ok := err.(*simplepositionaltypes.OpaqueError) - - if !ok { - panic("Error is not an OpaqueError") - } - if error == nil { - panic("Error is nil") - } - return OpaqueError_Input_ToDafny(*error) - } -} - -func SimplePositionalConfig_ToDafny(nativeInput simplepositionaltypes.SimplePositionalConfig) simplepositionalinternaldafnytypes.SimplePositionalConfig { - return func() simplepositionalinternaldafnytypes.SimplePositionalConfig { - - return simplepositionalinternaldafnytypes.Companion_SimplePositionalConfig_.Create_SimplePositionalConfig_() - }() - -} diff --git a/TestModels/Positional/runtimes/go/TestsFromDafny-go/to_native.go b/TestModels/Positional/runtimes/go/TestsFromDafny-go/to_native.go deleted file mode 100644 index 23328bb04f..0000000000 --- a/TestModels/Positional/runtimes/go/TestsFromDafny-go/to_native.go +++ /dev/null @@ -1,160 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package simplepositional - -import ( - "github.com/Smithy-dafny/TestModels/Positional/simplepositionalinternaldafnytypes" - "github.com/Smithy-dafny/TestModels/Positional/simplepositionaltypes" - "github.com/dafny-lang/DafnyRuntimeGo/dafny" -) - -func GetResourceInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourceInput) simplepositionaltypes.GetResourceInput { - - return simplepositionaltypes.GetResourceInput{Name: func() *string { - var s string - if dafnyInput.Dtor_name() == nil { - return nil - } - for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func GetResourceOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourceOutput) simplepositionaltypes.GetResourceOutput { - - return simplepositionaltypes.GetResourceOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} - -} - -func GetResourcePositionalInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetResourcePositionalInput) simplepositionaltypes.GetResourcePositionalInput { - - return simplepositionaltypes.GetResourcePositionalInput{Name: func() *string { - var s string - if dafnyInput.Dtor_name() == nil { - return nil - } - for i := dafny.Iterate(dafnyInput.Dtor_name()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func GetResourcePositionalOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetResourcePositionalOutput) simplepositionaltypes.GetResourcePositionalOutput { - - return simplepositionaltypes.GetResourcePositionalOutput{Output: SimpleResource_FromDafny(dafnyOutput.Dtor_output())} - -} - -func GetNameInput_FromDafny(dafnyInput simplepositionalinternaldafnytypes.GetNameInput) simplepositionaltypes.GetNameInput { - - return simplepositionaltypes.GetNameInput{} - -} - -func GetNameOutput_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.GetNameOutput) simplepositionaltypes.GetNameOutput { - - return simplepositionaltypes.GetNameOutput{Name: func() *string { - var s string - if dafnyOutput.Dtor_name() == nil { - return nil - } - for i := dafny.Iterate(dafnyOutput.Dtor_name()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func SimpleResource_FromDafny(dafnyResource simplepositionalinternaldafnytypes.ISimpleResource) simplepositionaltypes.ISimpleResource { - - return &SimpleResource{dafnyResource} -} - -func SimplePositionalException_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.SimplePositionalException { - return simplepositionaltypes.SimplePositionalException{Message: func() *string { - var s string - if dafnyOutput.Dtor_message() == nil { - return nil - } - for i := dafny.Iterate(dafnyOutput.Dtor_message()); ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - s = s + string(val.(dafny.Char)) - } - } - }()} - -} - -func CollectionOfErrors_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.CollectionOfErrors { - listOfErrors := dafnyOutput.Dtor_list() - message := dafnyOutput.Dtor_message() - t := simplepositionaltypes.CollectionOfErrors{} - for i := dafny.Iterate(listOfErrors); ; { - val, ok := i() - if !ok { - break - } - err := val.(simplepositionalinternaldafnytypes.Error) - t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) - - } - t.Message = func() string { - var s string - for i := dafny.Iterate(message); ; { - val, ok := i() - if !ok { - return s - } else { - s = s + string(val.(dafny.Char)) - } - } - }() - return t -} -func OpaqueError_Output_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.Error) simplepositionaltypes.OpaqueError { - return simplepositionaltypes.OpaqueError{ - ErrObject: dafnyOutput.Dtor_obj(), - } -} - -func Error_FromDafny(err simplepositionalinternaldafnytypes.Error) error { - // Service Errors - if err.Is_SimplePositionalException() { - return SimplePositionalException_FromDafny(err) - } - - //DependentErrors - - //Unmodelled Errors - if err.Is_CollectionOfErrors() { - return CollectionOfErrors_Output_FromDafny(err) - } - - return OpaqueError_Output_FromDafny(err) -} - -func SimplePositionalConfig_FromDafny(dafnyOutput simplepositionalinternaldafnytypes.SimplePositionalConfig) simplepositionaltypes.SimplePositionalConfig { - return simplepositionaltypes.SimplePositionalConfig{} - -} diff --git a/TestModels/Positional/runtimes/java/build.gradle.kts b/TestModels/Positional/runtimes/java/build.gradle.kts deleted file mode 100644 index bd264c0d00..0000000000 --- a/TestModels/Positional/runtimes/java/build.gradle.kts +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -import java.io.File -import java.io.FileInputStream -import java.util.Properties -import java.net.URI -import javax.annotation.Nullable - -tasks.wrapper { - gradleVersion = "7.6" -} - -plugins { - `java-library` - `maven-publish` -} - -var props = Properties().apply { - load(FileInputStream(File(rootProject.rootDir, "../../project.properties"))) -} -var dafnyVersion = props.getProperty("dafnyVersion") - -group = "simple.positional" -version = "1.0-SNAPSHOT" -description = "SimplePositional" - -java { - toolchain.languageVersion.set(JavaLanguageVersion.of(8)) - sourceSets["main"].java { - srcDir("src/main/java") - srcDir("src/main/dafny-generated") - srcDir("src/main/smithy-generated") - } - sourceSets["test"].java { - srcDir("src/test/java") - srcDir("src/test/dafny-generated") - srcDir("src/test/smithy-generated") - } -} - -repositories { - mavenCentral() - mavenLocal() -} - -dependencies { - implementation("org.dafny:DafnyRuntime:${dafnyVersion}") - implementation("software.amazon.smithy.dafny:conversion:0.1") - implementation("software.amazon.cryptography:StandardLibrary:1.0-SNAPSHOT") - testImplementation("org.testng:testng:7.5") -} - -publishing { - publications.create("mavenLocal") { - groupId = group as String? - artifactId = description - from(components["java"]) - } - publications.create("maven") { - groupId = group as String? - artifactId = description - from(components["java"]) - } - repositories { mavenLocal() } -} - -tasks.withType() { - options.encoding = "UTF-8" -} - -tasks { - register("runTests", JavaExec::class.java) { - mainClass.set("TestsFromDafny") - classpath = sourceSets["test"].runtimeClasspath - } -} - -tasks.named("test") { - useTestNG() -} diff --git a/TestModels/Positional/runtimes/java/src/main/java/Dafny/simple/positional/__default.java b/TestModels/Positional/runtimes/java/src/main/java/Dafny/simple/positional/__default.java deleted file mode 100644 index 817d9a442c..0000000000 --- a/TestModels/Positional/runtimes/java/src/main/java/Dafny/simple/positional/__default.java +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -package simple.positional.internaldafny; - -public class __default extends _ExternBase___default {} diff --git a/TestModels/Positional/runtimes/java/src/test/java/simple/positional/internaldafny/wrapped/__default.java b/TestModels/Positional/runtimes/java/src/test/java/simple/positional/internaldafny/wrapped/__default.java deleted file mode 100644 index 6b94d7dd9a..0000000000 --- a/TestModels/Positional/runtimes/java/src/test/java/simple/positional/internaldafny/wrapped/__default.java +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -package simple.positional.internaldafny.wrapped; - -import Wrappers_Compile.Result; -import simple.positional.SimplePositional; -import simple.positional.ToNative; -import simple.positional.internaldafny.types.Error; -import simple.positional.internaldafny.types.ISimplePositionalClient; -import simple.positional.internaldafny.types.SimplePositionalConfig; -import simple.positional.wrapped.TestSimplePositional; - -public class __default extends _ExternBase___default { - - public static Result WrappedSimplePositional( - SimplePositionalConfig config - ) { - simple.positional.model.SimplePositionalConfig wrappedConfig = - ToNative.SimplePositionalConfig(config); - simple.positional.SimplePositional impl = SimplePositional - .builder() - .SimplePositionalConfig(wrappedConfig) - .build(); - TestSimplePositional wrappedClient = TestSimplePositional - .builder() - .impl(impl) - .build(); - return simple.positional.internaldafny.__default.CreateSuccessOfClient( - wrappedClient - ); - } -} From e0e36d3bdeac8982b71bd308fb91c7f50ebaaa45 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Sat, 10 Aug 2024 16:50:17 -0700 Subject: [PATCH 17/44] Add go.mod --- TestModels/Positional/runtimes/go/go.mod | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 TestModels/Positional/runtimes/go/go.mod diff --git a/TestModels/Positional/runtimes/go/go.mod b/TestModels/Positional/runtimes/go/go.mod new file mode 100644 index 0000000000..eb34c6e047 --- /dev/null +++ b/TestModels/Positional/runtimes/go/go.mod @@ -0,0 +1,5 @@ +module github.com/Smithy-dafny/TestModels/Positional + +go 1.22.2 +require github.com/dafny-lang/DafnyStandardLibGo v0.0.0 +require github.com/dafny-lang/DafnyRuntimeGo v0.0.0 From 4870e612898b061948b55e78f7178c790b6a77ef Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Sat, 10 Aug 2024 16:52:36 -0700 Subject: [PATCH 18/44] remove dafny codegen files --- TestModels/Positional/src/Index.dfy | 31 ------------------- .../src/WrappedSimplePositionalImpl.dfy | 10 ------ 2 files changed, 41 deletions(-) delete mode 100644 TestModels/Positional/src/Index.dfy delete mode 100644 TestModels/Positional/src/WrappedSimplePositionalImpl.dfy diff --git a/TestModels/Positional/src/Index.dfy b/TestModels/Positional/src/Index.dfy deleted file mode 100644 index 4b7e7c3561..0000000000 --- a/TestModels/Positional/src/Index.dfy +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -include "SimplePositionalImpl.dfy" - -module {:extern "simplepositionalinternaldafny" } SimplePositional refines AbstractSimplePositionalService { - import Operations = SimplePositionalImpl - - function method DefaultSimplePositionalConfig(): SimplePositionalConfig { - SimplePositionalConfig - } - - method SimplePositional(config: SimplePositionalConfig) - returns (res: Result) - { - var client := new SimplePositionalClient(Operations.Config); - return Success(client); - } - - class SimplePositionalClient... { - predicate ValidState() { - && Operations.ValidInternalConfig?(config) - && Modifies == Operations.ModifiesInternalConfig(config) + {History} - } - - constructor(config: Operations.InternalConfig) { - this.config := config; - History := new ISimplePositionalClientCallHistory(); - Modifies := Operations.ModifiesInternalConfig(config) + {History}; - } - } -} diff --git a/TestModels/Positional/src/WrappedSimplePositionalImpl.dfy b/TestModels/Positional/src/WrappedSimplePositionalImpl.dfy deleted file mode 100644 index c8264f4475..0000000000 --- a/TestModels/Positional/src/WrappedSimplePositionalImpl.dfy +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -include "../Model/SimplePositionalTypesWrapped.dfy" - -module {:options "--function-syntax:4"} {:extern "simplepositionalinternaldafnywrapped"} WrappedSimplePositionalService refines WrappedAbstractSimplePositionalService { - import WrappedService = SimplePositional - function WrappedDefaultSimplePositionalConfig(): SimplePositionalConfig { - SimplePositionalConfig - } -} From c4c346fd46966254f7119dd85b0957aef279621d Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Sat, 10 Aug 2024 21:25:38 -0700 Subject: [PATCH 19/44] Update go mod --- TestModels/Positional/runtimes/go/go.mod | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/TestModels/Positional/runtimes/go/go.mod b/TestModels/Positional/runtimes/go/go.mod index eb34c6e047..b01d81303c 100644 --- a/TestModels/Positional/runtimes/go/go.mod +++ b/TestModels/Positional/runtimes/go/go.mod @@ -1,5 +1,11 @@ module github.com/Smithy-dafny/TestModels/Positional go 1.22.2 + require github.com/dafny-lang/DafnyStandardLibGo v0.0.0 + require github.com/dafny-lang/DafnyRuntimeGo v0.0.0 + +replace github.com/dafny-lang/DafnyRuntimeGo => ../../../../../DafnyRuntimeGo/ + +replace github.com/dafny-lang/DafnyStandardLibGo => ../../../../dafny-dependencies/StandardLibrary/runtimes/go/ImplementationFromDafny-go/ \ No newline at end of file From 80eea0ec36588292c4d7937fef1ed0414eb25103 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Sat, 10 Aug 2024 22:18:21 -0700 Subject: [PATCH 20/44] Fix symbolForPositional --- .../localservice/DafnyLocalServiceTypeConversionProtocol.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java index d454e70693..2d472ad24b 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java @@ -188,7 +188,7 @@ public void generateDeserializers(GenerationContext context) { if (input.hasTrait(PositionalTrait.class)) { // Input type in To native should be unwrapped Shape inputForPositional = context.model().expectShape(input.getAllMembers().values().stream().findFirst().get().getTarget()); - Symbol symbolForPositional = context.symbolProvider().toSymbol(input); + Symbol symbolForPositional = context.symbolProvider().toSymbol(inputForPositional); inputType = DafnyNameResolver.getDafnyType(inputForPositional, symbolForPositional); } else { From fc2464a3c422a8d0b2e1cca9fc759e3389e0fbc7 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Sat, 10 Aug 2024 22:18:48 -0700 Subject: [PATCH 21/44] Update to DafnyNameResolver --- .../nameresolver/DafnyNameResolver.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java index 2f930e954e..5da1a7d77b 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java @@ -33,6 +33,20 @@ public static String getDafnyType(final Shape shape, final Symbol symbol) { else { return "dafny.Sequence"; } + case INTEGER: + return "int32"; + case LONG: + return "int64"; + case BLOB: + case BOOLEAN: + case DOUBLE: + return "*dafny.ArraySequence"; + case MAP: + return "dafny.Map"; + case LIST: + return "dafny.Sequence"; + case STRUCTURE: + case UNION: // case MAP: // return "map"; // case STRUCTURE: From 8338b428a42f93301c4dea0771f23c012ba5d859 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Sat, 10 Aug 2024 22:20:23 -0700 Subject: [PATCH 22/44] Update getSmithyType --- .../smithygo/localservice/nameresolver/SmithyNameResolver.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java index 1cafd47f4d..17d4641b00 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java @@ -52,7 +52,7 @@ public static String smithyTypesNamespaceAws(final Shape shape, boolean isAwsSub } public static String getSmithyType(final Shape shape, final Symbol symbol) { - if(symbol.getNamespace().contains("smithy.")) { + if(symbol.getNamespace().contains("smithy.") || symbol.getName().contains("string")) { return symbol.getName(); } else if (shape.isResourceShape()) { From 918c42e12d7b2945b4e700b2854ae5e6235e4658 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Sat, 10 Aug 2024 22:22:23 -0700 Subject: [PATCH 23/44] Replace with isOptional --- .../localservice/shapevisitor/DafnyToSmithyShapeVisitor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java index dd7487d1ce..ebde3ccad5 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java @@ -299,7 +299,7 @@ public String integerShape(IntegerShape shape) { writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); var isPointable = this.context.symbolProvider().toSymbol(shape).getProperty(POINTABLE).orElse(false); - if ((boolean)isPointable) { + if ((boolean)isOptional) { return (""" func() *int32 { var b int32 From 2f7f0cbb4251ae53e4a798f2a0977f8edbc99c25 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 12 Aug 2024 13:19:05 -0700 Subject: [PATCH 24/44] Replaced isOptional with isPointable --- .../localservice/shapevisitor/DafnyToSmithyShapeVisitor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java index ebde3ccad5..dd7487d1ce 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java @@ -299,7 +299,7 @@ public String integerShape(IntegerShape shape) { writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); var isPointable = this.context.symbolProvider().toSymbol(shape).getProperty(POINTABLE).orElse(false); - if ((boolean)isOptional) { + if ((boolean)isPointable) { return (""" func() *int32 { var b int32 From dec64c77fb2f670ce3b3a2d3fa40ae4d6f8f0b7f Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 12 Aug 2024 21:50:03 -0700 Subject: [PATCH 25/44] Update DafnyNameResolver --- .../nameresolver/DafnyNameResolver.java | 46 ++++++------------- 1 file changed, 15 insertions(+), 31 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java index 5da1a7d77b..48bc20dedf 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java @@ -2,6 +2,8 @@ import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.model.shapes.Shape; + +import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.traits.EnumTrait; import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; @@ -25,44 +27,26 @@ public static String dafnyNamespace(final Shape shape) { public static String getDafnyType(final Shape shape, final Symbol symbol) { - switch (shape.getType()) { - case STRING: - if (shape.hasTrait(EnumTrait.class)) { - return getDafnyTypeDefaultCase(shape, symbol); - } - else { - return "dafny.Sequence"; - } - case INTEGER: - return "int32"; - case LONG: - return "int64"; - case BLOB: - case BOOLEAN: - case DOUBLE: - return "*dafny.ArraySequence"; + ShapeType type = shape.getType(); + if (shape.hasTrait(EnumTrait.class)) { + type = ShapeType.ENUM; + } + switch (type) { + case INTEGER, LONG, BOOLEAN: + return symbol.getName(); case MAP: return "dafny.Map"; - case LIST: + case DOUBLE, STRING, BLOB, LIST: return "dafny.Sequence"; - case STRUCTURE: - case UNION: - // case MAP: - // return "map"; - // case STRUCTURE: - // case UNION: - // return symbol.getName(); + case ENUM, STRUCTURE, UNION: + return DafnyNameResolver.dafnyTypesNamespace(shape) + .concat(DOT) + .concat(symbol.getName()); default: - return getDafnyTypeDefaultCase(shape, symbol); + throw new IllegalArgumentException("Unexpected shape found") ; } - } - private static String getDafnyTypeDefaultCase(final Shape shape, final Symbol symbol) { - return DafnyNameResolver.dafnyTypesNamespace(shape) - .concat(DOT) - .concat(symbol.getName()); - } public static String getDafnySubErrorType(final Shape shape, final Symbol symbol) { return DafnyNameResolver.getDafnyBaseErrorType(shape) .concat("_") From ffa889690c0afa37fbade5d23c81959cc6615dbe Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 12 Aug 2024 21:52:01 -0700 Subject: [PATCH 26/44] Update DafnyNameResolver --- .../smithygo/localservice/nameresolver/DafnyNameResolver.java | 1 - 1 file changed, 1 deletion(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java index 48bc20dedf..c36b919fa8 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java @@ -26,7 +26,6 @@ public static String dafnyNamespace(final Shape shape) { } public static String getDafnyType(final Shape shape, final Symbol symbol) { - ShapeType type = shape.getType(); if (shape.hasTrait(EnumTrait.class)) { type = ShapeType.ENUM; From 470f915c720c071c0c22df61a8e3402311e39123 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Tue, 13 Aug 2024 14:25:06 -0700 Subject: [PATCH 27/44] Copy GoPointableIndex from rishav-union --- .../codegen/knowledge/GoPointableIndex.java | 527 +++++++++--------- 1 file changed, 267 insertions(+), 260 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java index a80352a920..d34e176535 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java @@ -15,263 +15,270 @@ * */ -package software.amazon.polymorph.smithygo.codegen.knowledge; - -import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.knowledge.KnowledgeIndex; -import software.amazon.smithy.model.knowledge.NeighborProviderIndex; -import software.amazon.smithy.model.knowledge.NullableIndex; -import software.amazon.smithy.model.neighbor.NeighborProvider; -import software.amazon.smithy.model.neighbor.Relationship; -import software.amazon.smithy.model.neighbor.RelationshipType; -import software.amazon.smithy.model.shapes.MemberShape; -import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeType; -import software.amazon.smithy.model.shapes.ToShapeId; -import software.amazon.smithy.model.traits.AddedDefaultTrait; -import software.amazon.smithy.model.traits.ClientOptionalTrait; -import software.amazon.smithy.model.traits.DefaultTrait; -import software.amazon.smithy.model.traits.EnumTrait; -import software.amazon.smithy.model.traits.RequiredTrait; -import software.amazon.smithy.model.traits.StreamingTrait; -import software.amazon.smithy.utils.SetUtils; - -import java.util.HashSet; -import java.util.Set; -import java.util.logging.Logger; - -/** - * An index that checks if a member or shape type should be a pointer type in Go. - *

- * Extends the rules of smithy's NullableIndex for Go's translation of the smithy shapes to Go types. - */ -public class GoPointableIndex implements KnowledgeIndex { - private static final Logger LOGGER = Logger.getLogger(GoPointableIndex.class.getName()); - - // All types that are Go value types - private static final Set INHERENTLY_VALUE = SetUtils.of( - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - ShapeType.UNION, - ShapeType.DOCUMENT - ); - - // All types that are Go pointer types - private static final Set INHERENTLY_POINTABLE = SetUtils.of( - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - - // All types that cannot be dereferenced - private static final Set INHERENTLY_NONDEREFERENCABLE = SetUtils.of( - // built in slice/map - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - - // Interfaces - ShapeType.UNION, - ShapeType.DOCUMENT, - - // known pointer types. - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - - // All types types that are comparable to nil - private static final Set INHERENTLY_NILLABLE = SetUtils.of( - // built in slice/map - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - - // Interfaces - ShapeType.UNION, - ShapeType.DOCUMENT, - - // known pointer types. - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - - // All types types that are comparable to nil - private static final Set NUMBER_SHAPE = SetUtils.of( - ShapeType.BYTE, - ShapeType.SHORT, - ShapeType.INTEGER, - ShapeType.LONG, - ShapeType.FLOAT, - ShapeType.DOUBLE, - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - - private final Model model; - private final NullableIndex nullableIndex; - private final Set pointableShapes = new HashSet<>(); - private final Set nillableShapes = new HashSet<>(); - private final Set dereferencableShapes = new HashSet<>(); - - public GoPointableIndex(Model model) { - this.model = model; - this.nullableIndex = NullableIndex.of(model); - - for (Shape shape : model.toSet()) { - if (shape.asMemberShape().isPresent()) { - MemberShape member = shape.asMemberShape().get(); - Shape targetShape = model.expectShape(member.getTarget()); - - if (isMemberPointable(member, targetShape)) { - pointableShapes.add(shape.getId()); - } - if (isMemberNillable(member, targetShape)) { - nillableShapes.add(shape.getId()); - } - if (isMemberDereferencable(member, targetShape)) { - dereferencableShapes.add(shape.getId()); - } - } else { - if (isShapePointable(shape)) { - pointableShapes.add(shape.getId()); - nillableShapes.add(shape.getId()); - } - if (isShapeNillable(shape)) { - nillableShapes.add(shape.getId()); - } - if (isShapeDereferencable(shape)) { - dereferencableShapes.add(shape.getId()); - } - } - } - } - - public static GoPointableIndex of(Model model) { - return model.getKnowledge(GoPointableIndex.class, GoPointableIndex::new); - } - - private boolean isMemberDereferencable(MemberShape member, Shape targetShape) { - return !INHERENTLY_NONDEREFERENCABLE.contains(targetShape.getType()) && isMemberPointable(member, targetShape); - } - - private boolean isMemberNillable(MemberShape member, Shape targetShape) { - return INHERENTLY_NILLABLE.contains(targetShape.getType()) || isMemberPointable(member, targetShape); - } - - private boolean isMemberPointable(MemberShape member, Shape targetShape) { - - // Streamed blob shapes are never pointers because they are interfaces - if (isBlobStream(targetShape)) { - return false; - } - - if (INHERENTLY_VALUE.contains(targetShape.getType())) { - return false; - } - - if (NUMBER_SHAPE.contains(targetShape.getType()) && !member.hasTrait(RequiredTrait.class) && !model.expectShape(member.getContainer()).isMapShape()) { - return true; - } - - return nullableIndex.isMemberNullable(member, NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1_NO_INPUT); - } - - private boolean isShapeDereferencable(Shape shape) { - return !INHERENTLY_NONDEREFERENCABLE.contains(shape.getType()) && isShapePointable(shape); - } - - private boolean isShapeNillable(Shape shape) { - return INHERENTLY_NILLABLE.contains(shape.getType()) || isShapePointable(shape); - } - - private boolean isShapePointable(Shape shape) { - // All operation input and output shapes are pointable. - if (isOperationStruct(shape)) { - return true; - } - - // Streamed blob shapes are never pointers because they are interfaces - if (isBlobStream(shape)) { - return false; - } - - if (shape.isServiceShape()) { - return true; - } - - // This is odd because its not a go type but a function with receiver - if (shape.isOperationShape()) { - return false; - } - - if (INHERENTLY_POINTABLE.contains(shape.getType())) { - return true; - } - - if (INHERENTLY_VALUE.contains(shape.getType())) { - return false; - } - - if (shape.isIntegerShape() && !shape.hasTrait(RequiredTrait.class)) { - return true; - } - - return nullableIndex.isNullable(shape); - } - - private boolean isShapeEnum(Shape shape) { - return shape.getType() == ShapeType.STRING && shape.hasTrait(EnumTrait.class) - || shape.getType() == ShapeType.ENUM - || shape.getType() == ShapeType.INT_ENUM; - } - - private boolean isBlobStream(Shape shape) { - return shape.getType() == ShapeType.BLOB && shape.hasTrait(StreamingTrait.ID); - } - - private boolean isOperationStruct(Shape shape) { - NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); - for (Relationship relationship : provider.getNeighbors(shape)) { - RelationshipType relationshipType = relationship.getRelationshipType(); - if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { - return true; - } - } - - return false; - } - - /** - * Returns if the shape should be generated as a Go pointer type or not. - * - * @param shape the shape to check if should be pointable type. - * @return if the shape is should be a Go pointer type. - */ - public final boolean isPointable(ToShapeId shape) { - return pointableShapes.contains(shape.toShapeId()); - } - - /** - * Returns if the Go type generated for the shape is comparable to nil. - * - * @param shape the shape to check - * @return if the shape's go type is comparable to nil - */ - public final boolean isNillable(ToShapeId shape) { - return nillableShapes.contains(shape.toShapeId()); - } - - /** - * Returns if the Go type generated for the shape can be dereferenced. - * - * @param shape the shape to check - * @return if the shape's go type is dereferencable - */ - public final boolean isDereferencable(ToShapeId shape) { - return dereferencableShapes.contains(shape.toShapeId()); - } -} + package software.amazon.polymorph.smithygo.codegen.knowledge; + + import software.amazon.smithy.model.Model; + import software.amazon.smithy.model.knowledge.KnowledgeIndex; + import software.amazon.smithy.model.knowledge.NeighborProviderIndex; + import software.amazon.smithy.model.knowledge.NullableIndex; + import software.amazon.smithy.model.neighbor.NeighborProvider; + import software.amazon.smithy.model.neighbor.Relationship; + import software.amazon.smithy.model.neighbor.RelationshipType; + import software.amazon.smithy.model.shapes.MemberShape; + import software.amazon.smithy.model.shapes.Shape; + import software.amazon.smithy.model.shapes.ShapeId; + import software.amazon.smithy.model.shapes.ShapeType; + import software.amazon.smithy.model.shapes.ToShapeId; + import software.amazon.smithy.model.traits.EnumTrait; + import software.amazon.smithy.model.traits.RequiredTrait; + import software.amazon.smithy.model.traits.StreamingTrait; + import software.amazon.smithy.utils.SetUtils; + + import java.util.HashSet; + import java.util.Set; + import java.util.logging.Logger; + + /** + * An index that checks if a member or shape type should be a pointer type in Go. + *

+ * Extends the rules of smithy's NullableIndex for Go's translation of the smithy shapes to Go types. + */ + public class GoPointableIndex implements KnowledgeIndex { + private static final Logger LOGGER = Logger.getLogger(GoPointableIndex.class.getName()); + + // All types that are Go value types + private static final Set INHERENTLY_VALUE = SetUtils.of( + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + ShapeType.UNION, + ShapeType.DOCUMENT + ); + + // All types that are Go pointer types + private static final Set INHERENTLY_POINTABLE = SetUtils.of( + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + // All types that cannot be dereferenced + private static final Set INHERENTLY_NONDEREFERENCABLE = SetUtils.of( + // built in slice/map + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + + // Interfaces + ShapeType.UNION, + ShapeType.DOCUMENT, + + // known pointer types. + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + // All types types that are comparable to nil + private static final Set INHERENTLY_NILLABLE = SetUtils.of( + // built in slice/map + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + + // Interfaces + ShapeType.UNION, + ShapeType.DOCUMENT, + + // known pointer types. + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + // Pointer types that are strictly pointer type even if it has required trait + private static final Set STRICT_POINTER_TYPE = SetUtils.of( + ShapeType.STRING + ); + + // All the known pointer type if not required + private static final Set KNOWN_POINTER_TYPE = SetUtils.of( + ShapeType.BYTE, + ShapeType.SHORT, + ShapeType.INTEGER, + ShapeType.LONG, + ShapeType.FLOAT, + ShapeType.DOUBLE, + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + private final Model model; + private final NullableIndex nullableIndex; + private final Set pointableShapes = new HashSet<>(); + private final Set nillableShapes = new HashSet<>(); + private final Set dereferencableShapes = new HashSet<>(); + + public GoPointableIndex(Model model) { + this.model = model; + this.nullableIndex = NullableIndex.of(model); + + for (Shape shape : model.toSet()) { + if (shape.asMemberShape().isPresent()) { + MemberShape member = shape.asMemberShape().get(); + Shape targetShape = model.expectShape(member.getTarget()); + + if (isMemberPointable(member, targetShape)) { + pointableShapes.add(shape.getId()); + } + if (isMemberNillable(member, targetShape)) { + nillableShapes.add(shape.getId()); + } + if (isMemberDereferencable(member, targetShape)) { + dereferencableShapes.add(shape.getId()); + } + } else { + if (isShapePointable(shape)) { + pointableShapes.add(shape.getId()); + nillableShapes.add(shape.getId()); + } + if (isShapeNillable(shape)) { + nillableShapes.add(shape.getId()); + } + if (isShapeDereferencable(shape)) { + dereferencableShapes.add(shape.getId()); + } + } + } + } + + public static GoPointableIndex of(Model model) { + return model.getKnowledge(GoPointableIndex.class, GoPointableIndex::new); + } + + private boolean isMemberDereferencable(MemberShape member, Shape targetShape) { + return !INHERENTLY_NONDEREFERENCABLE.contains(targetShape.getType()) && isMemberPointable(member, targetShape); + } + + private boolean isMemberNillable(MemberShape member, Shape targetShape) { + return INHERENTLY_NILLABLE.contains(targetShape.getType()) || isMemberPointable(member, targetShape); + } + + private boolean isMemberPointable(MemberShape member, Shape targetShape) { + // Streamed blob shapes are never pointers because they are interfaces + if (isBlobStream(targetShape)) { + return false; + } + + if (INHERENTLY_VALUE.contains(targetShape.getType())) { + return false; + } + + //if membershape is required return it is not pointable + if (member.hasTrait(RequiredTrait.class) && !STRICT_POINTER_TYPE.contains(targetShape.getType())) { + return false; + } + + if (KNOWN_POINTER_TYPE.contains(targetShape.getType()) && !model.expectShape(member.getContainer()).isMapShape()) { + return true; + } + + return nullableIndex.isMemberNullable(member, NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1_NO_INPUT); + } + + private boolean isShapeDereferencable(Shape shape) { + return !INHERENTLY_NONDEREFERENCABLE.contains(shape.getType()) && isShapePointable(shape); + } + + private boolean isShapeNillable(Shape shape) { + return INHERENTLY_NILLABLE.contains(shape.getType()) || isShapePointable(shape); + } + + private boolean isShapePointable(Shape shape) { + // All operation input and output shapes are pointable. + if (isOperationStruct(shape)) { + return true; + } + + // Streamed blob shapes are never pointers because they are interfaces + if (isBlobStream(shape)) { + return false; + } + + if (shape.isServiceShape()) { + return true; + } + + // This is odd because its not a go type but a function with receiver + if (shape.isOperationShape()) { + return false; + } + + if (INHERENTLY_POINTABLE.contains(shape.getType())) { + return true; + } + + if (INHERENTLY_VALUE.contains(shape.getType())) { + return false; + } + + if (shape.isIntegerShape() && !shape.hasTrait(RequiredTrait.class)) { + return true; + } + + return nullableIndex.isNullable(shape); + } + + private boolean isShapeEnum(Shape shape) { + return shape.getType() == ShapeType.STRING && shape.hasTrait(EnumTrait.class) + || shape.getType() == ShapeType.ENUM + || shape.getType() == ShapeType.INT_ENUM; + } + + private boolean isBlobStream(Shape shape) { + return shape.getType() == ShapeType.BLOB && shape.hasTrait(StreamingTrait.ID); + } + + private boolean isOperationStruct(Shape shape) { + NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); + for (Relationship relationship : provider.getNeighbors(shape)) { + RelationshipType relationshipType = relationship.getRelationshipType(); + if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { + return true; + } + } + + return false; + } + + /** + * Returns if the shape should be generated as a Go pointer type or not. + * + * @param shape the shape to check if should be pointable type. + * @return if the shape is should be a Go pointer type. + */ + public final boolean isPointable(ToShapeId shape) { + return pointableShapes.contains(shape.toShapeId()); + } + + /** + * Returns if the Go type generated for the shape is comparable to nil. + * + * @param shape the shape to check + * @return if the shape's go type is comparable to nil + */ + public final boolean isNillable(ToShapeId shape) { + return nillableShapes.contains(shape.toShapeId()); + } + + /** + * Returns if the Go type generated for the shape can be dereferenced. + * + * @param shape the shape to check + * @return if the shape's go type is dereferencable + */ + public final boolean isDereferencable(ToShapeId shape) { + return dereferencableShapes.contains(shape.toShapeId()); + } + } + \ No newline at end of file From 817d7a90a6a99ec3e97d49d558d770bb8cf20bab Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 22 Aug 2024 11:57:02 -0700 Subject: [PATCH 28/44] Put check for PositionalTrait outside outputshape check --- .../DafnyLocalServiceGenerator.java | 26 +++++++++---------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java index b1dc1883c4..6e0f0f7cad 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java @@ -265,23 +265,21 @@ void generateShim() { clientResponse = "var native_error"; returnResponse = "dafny.TupleOf()"; writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - inputType = maybeInputType; } else { - if (inputShape.hasTrait(PositionalTrait.class)) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - Shape inputForPositional = model.expectShape(inputShape.getAllMembers().values().stream().findFirst().get().getTarget()); - Symbol symbolForPositional = symbolProvider.toSymbol(inputForPositional); - String dafnyType = DafnyNameResolver.getDafnyType(inputForPositional, symbolForPositional); - inputType = "input %s".formatted(dafnyType); - returnResponse = "(native_response)"; - } - else { - inputType = maybeInputType; - returnResponse = "%s(*native_response)".formatted(SmithyNameResolver.getToDafnyMethodName(outputShape, "")); - } clientResponse = "var native_response, native_error"; + returnResponse = "%s(*native_response)".formatted(SmithyNameResolver.getToDafnyMethodName(outputShape, "")); + } + if (inputShape.hasTrait(PositionalTrait.class)) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + Shape inputForPositional = model.expectShape(inputShape.getAllMembers().values().stream().findFirst().get().getTarget()); + Symbol symbolForPositional = symbolProvider.toSymbol(inputForPositional); + String dafnyType = DafnyNameResolver.getDafnyType(inputForPositional, symbolForPositional); + inputType = "input %s".formatted(dafnyType); + returnResponse = "(native_response)"; + } + else { + inputType = maybeInputType; } - writer.write(""" func (shim *Shim) $L($L) Wrappers.Result { $L From eb8b0c03f9add064e8fdc4ee002c9939542ae535 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 22 Aug 2024 11:59:11 -0700 Subject: [PATCH 29/44] Remove comments --- .../localservice/nameresolver/SmithyNameResolver.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java index fc4f74d2d4..7b8d6910a0 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java @@ -34,10 +34,6 @@ public static String shapeNamespace(final Shape shape) { } public static String smithyTypesNamespace(final Shape shape) { - // if (shape.isResourceShape()) { - // // TypesNamespace for resources are in ShapeName - // return shape.getId().getName(); - // } return shape.toShapeId().getNamespace().replace(DOT, BLANK).toLowerCase().concat("types"); } From d48e10f7c60d3a65d8776c37c12c7836ed3df16d Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 2 Sep 2024 08:39:15 -0700 Subject: [PATCH 30/44] Merge fix --- .../nameresolver/DafnyNameResolver.java | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java index e4a9f245b2..a5fb3118dd 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java @@ -7,7 +7,9 @@ import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.traits.SensitiveTrait; +import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.shapes.UnionShape; +import software.amazon.smithy.model.traits.EnumTrait; import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.DOT; @@ -36,9 +38,25 @@ public static String dafnyNamespace(final Shape shape) { * @return The Dafny type as a String. */ public static String getDafnyType(final Shape shape, final Symbol symbol) { - return DafnyNameResolver.dafnyTypesNamespace(shape) + ShapeType type = shape.getType(); + if (shape.hasTrait(EnumTrait.class)) { + type = ShapeType.ENUM; + } + switch (type) { + case INTEGER, LONG, BOOLEAN: + return symbol.getName(); + case MAP: + return "dafny.Map"; + case DOUBLE, STRING, BLOB, LIST: + return "dafny.Sequence"; + // default catches a case where users may author their own classes that implement and extend resource (ExtendableTrait) + // ENUM, STRUCTURE, UNION can be removed but for posterity it looks great to see all the shapes being covered. + case ENUM, STRUCTURE, UNION: + default: + return DafnyNameResolver.dafnyTypesNamespace(shape) .concat(DOT) .concat(symbol.getName()); + } } public static String getDafnySubErrorType(final Shape shape, final Symbol symbol) { @@ -132,4 +150,4 @@ public static String getDafnyDependentErrorType(final Shape shape, final String .concat(sdkId); } -} +} \ No newline at end of file From 8fde5f40ba98c9cca29df923efcf88281874f2ab Mon Sep 17 00:00:00 2001 From: Alex Chew Date: Mon, 2 Sep 2024 12:00:06 -0700 Subject: [PATCH 31/44] feat: Rust codegen for more SimpleTypes models (#542) --- .../rust/src/standard_library_externs.rs | 80 + .../rust/src/standard_library_externs.rs | 80 + .../rust/src/implementation_from_dafny.rs-e | 1745 --------------- .../rust/src/standard_library_externs.rs | 80 + .../rust/src/standard_library_externs.rs | 80 + .../rust/src/standard_library_externs.rs | 80 + .../rust/src/standard_library_externs.rs | 80 + TestModels/SimpleTypes/SimpleBlob/Makefile | 3 +- .../SimpleBlob/runtimes/rust/Cargo.toml | 8 +- .../SimpleBlob/runtimes/rust/src/client.rs | 16 +- .../runtimes/rust/src/client/get_blob.rs | 8 +- .../rust/src/client/get_blob_known_value.rs | 17 - .../src/client/get_blob_known_value_test.rs | 15 + .../runtimes/rust/src/conversions.rs | 12 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../runtimes/rust/src/conversions/get_blob.rs | 16 +- .../conversions/get_blob/_get_blob_input.rs | 44 +- .../conversions/get_blob/_get_blob_output.rs | 45 +- .../src/conversions/get_blob_known_value.rs | 39 - .../_get_blob_known_value_input.rs | 41 - .../_get_blob_known_value_output.rs | 43 - .../conversions/get_blob_known_value_test.rs | 33 + .../_get_blob_known_value_test_input.rs | 24 + .../_get_blob_known_value_test_output.rs | 24 + .../src/conversions/simple_blob_config.rs | 5 +- .../simple_blob_config/_simple_blob_config.rs | 9 +- .../SimpleBlob/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleBlob/runtimes/rust/src/lib.rs | 19 - .../SimpleBlob/runtimes/rust/src/operation.rs | 9 +- .../runtimes/rust/src/operation/get_blob.rs | 19 +- .../src/operation/get_blob/_get_blob_input.rs | 50 +- .../operation/get_blob/_get_blob_output.rs | 56 +- .../rust/src/operation/get_blob/builders.rs | 38 +- .../_get_blob_known_value_input.rs | 63 - .../_get_blob_known_value_output.rs | 63 - .../get_blob_known_value/builders.rs | 80 - ..._value.rs => get_blob_known_value_test.rs} | 58 +- .../_get_blob_input.rs | 58 + .../_get_blob_output.rs | 58 + .../get_blob_known_value_test/builders.rs | 74 + .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../SimpleBlob/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_blob_config.rs | 5 +- .../SimpleBlob/runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 119 ++ .../runtimes/rust/tests/simple_blob_test.rs | 10 +- .../rust/src/standard_library_externs.rs | 80 + TestModels/SimpleTypes/SimpleDouble/Makefile | 3 +- .../SimpleDouble/runtimes/rust/Cargo.toml | 8 +- .../SimpleDouble/runtimes/rust/src/client.rs | 7 +- .../runtimes/rust/src/client/get_double.rs | 8 +- .../runtimes/rust/src/conversions.rs | 10 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../rust/src/conversions/get_double.rs | 8 +- .../get_double/_get_double_input.rs | 45 +- .../get_double/_get_double_output.rs | 45 +- .../src/conversions/simple_double_config.rs | 5 +- .../_simple_double_config.rs | 6 +- .../SimpleDouble/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleDouble/runtimes/rust/src/lib.rs | 19 - .../runtimes/rust/src/operation.rs | 5 +- .../runtimes/rust/src/operation/get_double.rs | 8 +- .../operation/get_double/_get_double_input.rs | 40 +- .../get_double/_get_double_output.rs | 46 +- .../rust/src/operation/get_double/builders.rs | 32 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../SimpleDouble/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_double_config.rs | 5 +- .../SimpleDouble/runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 89 + TestModels/SimpleTypes/SimpleEnum/Makefile | 3 +- .../SimpleEnum/runtimes/rust/Cargo.toml | 8 +- .../SimpleEnum/runtimes/rust/src/client.rs | 9 +- .../runtimes/rust/src/client/get_enum.rs | 8 +- .../client/get_enum_first_known_value_test.rs | 23 +- .../get_enum_second_known_value_test.rs | 23 +- .../client/get_enum_third_known_value_test.rs | 23 +- .../runtimes/rust/src/conversions.rs | 21 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../runtimes/rust/src/conversions/get_enum.rs | 5 +- .../conversions/get_enum/_get_enum_input.rs | 53 +- .../conversions/get_enum/_get_enum_output.rs | 53 +- .../get_enum_first_known_value_test.rs | 5 +- .../_get_enum_first_known_value_test_input.rs | 57 +- ..._get_enum_first_known_value_test_output.rs | 57 +- .../get_enum_second_known_value_test.rs | 5 +- ..._get_enum_second_known_value_test_input.rs | 57 +- ...get_enum_second_known_value_test_output.rs | 57 +- .../get_enum_third_known_value_test.rs | 5 +- .../_get_enum_third_known_value_test_input.rs | 57 +- ..._get_enum_third_known_value_test_output.rs | 57 +- .../src/conversions/simple_enum_config.rs | 5 +- .../simple_enum_config/_simple_enum_config.rs | 6 +- .../rust/src/conversions/simple_enum_shape.rs | 26 +- .../simple_enum_shape/_simple_enum_shape.rs | 23 - .../SimpleEnum/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleEnum/runtimes/rust/src/lib.rs | 19 - .../SimpleEnum/runtimes/rust/src/operation.rs | 11 +- .../runtimes/rust/src/operation/get_enum.rs | 19 +- .../src/operation/get_enum/_get_enum_input.rs | 55 +- .../operation/get_enum/_get_enum_output.rs | 59 +- .../rust/src/operation/get_enum/builders.rs | 40 +- .../get_enum_first_known_value_test.rs | 36 +- .../_get_enum_first_known_value_test_input.rs | 69 - ..._get_enum_first_known_value_test_output.rs | 69 - .../_get_enum_input.rs | 58 + .../_get_enum_output.rs | 58 + .../builders.rs | 62 +- .../get_enum_second_known_value_test.rs | 40 +- .../_get_enum_input.rs | 58 + .../_get_enum_output.rs | 58 + ..._get_enum_second_known_value_test_input.rs | 69 - ...get_enum_second_known_value_test_output.rs | 69 - .../builders.rs | 61 +- .../get_enum_third_known_value_test.rs | 36 +- .../_get_enum_input.rs | 58 + .../_get_enum_output.rs | 58 + .../_get_enum_third_known_value_test_input.rs | 68 - ..._get_enum_third_known_value_test_output.rs | 69 - .../builders.rs | 62 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../SimpleEnum/runtimes/rust/src/types.rs | 11 +- .../rust/src/types/_simple_enum_shape.rs | 19 + .../rust/src/types/simple_enum_config.rs | 5 +- .../rust/src/types/simple_enum_shape.rs | 6 - .../SimpleEnum/runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 179 ++ .../runtimes/rust/tests/simple_enum_test.rs | 18 +- TestModels/SimpleTypes/SimpleEnumV2/Makefile | 3 +- .../SimpleEnumV2/runtimes/rust/Cargo.toml | 8 +- .../SimpleEnumV2/runtimes/rust/src/client.rs | 9 +- .../runtimes/rust/src/client/get_enum_v2.rs | 8 +- .../get_enum_v2_first_known_value_test.rs | 23 +- .../get_enum_v2_second_known_value_test.rs | 23 +- .../get_enum_v2_third_known_value_test.rs | 23 +- .../runtimes/rust/src/conversions.rs | 21 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../rust/src/conversions/get_enum_v2.rs | 16 +- .../get_enum_v2/_get_enum_v2_input.rs | 53 +- .../get_enum_v2/_get_enum_v2_output.rs | 53 +- .../get_enum_v2_first_known_value_test.rs | 5 +- ...et_enum_v2_first_known_value_test_input.rs | 59 +- ...t_enum_v2_first_known_value_test_output.rs | 59 +- .../get_enum_v2_second_known_value_test.rs | 5 +- ...t_enum_v2_second_known_value_test_input.rs | 59 +- ..._enum_v2_second_known_value_test_output.rs | 59 +- .../get_enum_v2_third_known_value_test.rs | 5 +- ...et_enum_v2_third_known_value_test_input.rs | 59 +- ...t_enum_v2_third_known_value_test_output.rs | 59 +- .../src/conversions/simple_enum_v2_config.rs | 5 +- .../_simple_enum_v2_config.rs | 6 +- .../src/conversions/simple_enum_v2_shape.rs | 26 +- .../_simple_enum_v2_shape.rs | 23 - .../SimpleEnumV2/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleEnumV2/runtimes/rust/src/lib.rs | 19 - .../runtimes/rust/src/operation.rs | 11 +- .../rust/src/operation/get_enum_v2.rs | 8 +- .../get_enum_v2/_get_enum_v2_input.rs | 51 +- .../get_enum_v2/_get_enum_v2_output.rs | 57 +- .../src/operation/get_enum_v2/builders.rs | 40 +- .../get_enum_v2_first_known_value_test.rs | 39 +- ...et_enum_v2_first_known_value_test_input.rs | 71 - ...t_enum_v2_first_known_value_test_output.rs | 71 - .../_get_enum_v2_input.rs | 58 + .../_get_enum_v2_output.rs | 58 + .../builders.rs | 62 +- .../get_enum_v2_second_known_value_test.rs | 39 +- .../_get_enum_v2_input.rs | 58 + .../_get_enum_v2_output.rs | 58 + ...t_enum_v2_second_known_value_test_input.rs | 71 - ..._enum_v2_second_known_value_test_output.rs | 71 - .../builders.rs | 61 +- .../get_enum_v2_third_known_value_test.rs | 39 +- .../_get_enum_v2_input.rs | 58 + .../_get_enum_v2_output.rs | 58 + ...et_enum_v2_third_known_value_test_input.rs | 70 - ...t_enum_v2_third_known_value_test_output.rs | 71 - .../builders.rs | 62 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../SimpleEnumV2/runtimes/rust/src/types.rs | 11 +- .../rust/src/types/_simple_enum_v2_shape.rs | 19 + .../rust/src/types/simple_enum_v2_config.rs | 5 +- .../rust/src/types/simple_enum_v2_shape.rs | 6 - .../SimpleEnumV2/runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 179 ++ .../rust/tests/simple_enum_v2_test.rs | 18 +- TestModels/SimpleTypes/SimpleInteger/Makefile | 3 +- .../SimpleInteger/runtimes/rust/Cargo.toml | 8 +- .../SimpleInteger/runtimes/rust/src/client.rs | 9 +- .../runtimes/rust/src/client/get_integer.rs | 8 +- .../src/client/get_integer_known_value.rs | 18 - .../client/get_integer_known_value_test.rs | 15 + .../runtimes/rust/src/conversions.rs | 12 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../rust/src/conversions/get_integer.rs | 5 +- .../get_integer/_get_integer_input.rs | 35 +- .../get_integer/_get_integer_output.rs | 35 +- .../conversions/get_integer_known_value.rs | 32 - .../_get_integer_known_value_input.rs | 37 - .../_get_integer_known_value_output.rs | 37 - .../get_integer_known_value_test.rs | 33 + .../_get_integer_known_value_test_input.rs | 24 + .../_get_integer_known_value_test_output.rs | 24 + .../src/conversions/simple_integer_config.rs | 5 +- .../_simple_integer_config.rs | 6 +- .../SimpleInteger/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleInteger/runtimes/rust/src/lib.rs | 19 - .../runtimes/rust/src/operation.rs | 9 +- .../rust/src/operation/get_integer.rs | 8 +- .../get_integer/_get_integer_input.rs | 40 +- .../get_integer/_get_integer_output.rs | 46 +- .../src/operation/get_integer/builders.rs | 34 +- .../_get_integer_known_value_input.rs | 59 - .../_get_integer_known_value_output.rs | 60 - .../get_integer_known_value/builders.rs | 78 - ...lue.rs => get_integer_known_value_test.rs} | 65 +- .../_get_integer_input.rs | 58 + .../_get_integer_output.rs | 58 + .../get_integer_known_value_test/builders.rs | 74 + .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../SimpleInteger/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_integer_config.rs | 33 +- .../runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 119 ++ .../rust/tests/simple_integer_test.rs | 2 +- TestModels/SimpleTypes/SimpleLong/Makefile | 3 +- .../SimpleLong/runtimes/rust/Cargo.toml | 8 +- .../SimpleLong/runtimes/rust/src/client.rs | 9 +- .../runtimes/rust/src/client/get_long.rs | 8 +- .../rust/src/client/get_long_known_value.rs | 17 - .../src/client/get_long_known_value_test.rs | 15 + .../runtimes/rust/src/conversions.rs | 12 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../runtimes/rust/src/conversions/get_long.rs | 5 +- .../conversions/get_long/_get_long_input.rs | 35 +- .../conversions/get_long/_get_long_output.rs | 35 +- .../src/conversions/get_long_known_value.rs | 32 - .../_get_long_known_value_input.rs | 37 - .../_get_long_known_value_output.rs | 37 - .../conversions/get_long_known_value_test.rs | 33 + .../_get_long_known_value_test_input.rs | 24 + .../_get_long_known_value_test_output.rs | 24 + .../src/conversions/simple_long_config.rs | 5 +- .../simple_long_config/_simple_long_config.rs | 6 +- .../SimpleLong/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleLong/runtimes/rust/src/lib.rs | 19 - .../SimpleLong/runtimes/rust/src/operation.rs | 9 +- .../runtimes/rust/src/operation/get_long.rs | 19 +- .../src/operation/get_long/_get_long_input.rs | 44 +- .../operation/get_long/_get_long_output.rs | 50 +- .../rust/src/operation/get_long/builders.rs | 32 +- .../_get_long_known_value_input.rs | 57 - .../_get_long_known_value_output.rs | 57 - .../get_long_known_value/builders.rs | 74 - ..._value.rs => get_long_known_value_test.rs} | 58 +- .../_get_long_input.rs | 58 + .../_get_long_output.rs | 58 + .../get_long_known_value_test/builders.rs | 74 + .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../SimpleLong/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_long_config.rs | 5 +- .../SimpleLong/runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 119 ++ .../runtimes/rust/tests/simple_long_test.rs | 2 +- TestModels/SimpleTypes/SimpleString/Makefile | 3 +- .../SimpleString/runtimes/rust/Cargo.toml | 10 +- .../SimpleString/runtimes/rust/src/client.rs | 11 +- .../runtimes/rust/src/client/get_string.rs | 8 +- .../rust/src/client/get_string_known_value.rs | 18 +- .../rust/src/client/get_string_utf8.rs | 12 +- .../src/client/get_string_utf8_known_value.rs | 14 +- .../runtimes/rust/src/conversions.rs | 16 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../rust/src/conversions/get_string.rs | 8 +- .../get_string/_get_string_input.rs | 41 +- .../get_string/_get_string_output.rs | 45 +- .../src/conversions/get_string_known_value.rs | 8 +- .../_get_string_known_value_input.rs | 45 +- .../_get_string_known_value_output.rs | 49 +- .../rust/src/conversions/get_string_utf8.rs | 8 +- .../get_string_utf8/_get_string_utf8_input.rs | 47 +- .../_get_string_utf8_output.rs | 53 +- .../get_string_utf8_known_value.rs | 8 +- .../_get_string_utf8_known_value_input.rs | 51 +- .../_get_string_utf8_known_value_output.rs | 57 +- .../src/conversions/simple_string_config.rs | 5 +- .../_simple_string_config.rs | 6 +- .../SimpleString/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../rust/src/implementation_from_dafny.rs-e | 1880 ----------------- .../SimpleString/runtimes/rust/src/lib.rs | 17 - .../runtimes/rust/src/operation.rs | 6 +- .../runtimes/rust/src/operation/get_string.rs | 8 +- .../operation/get_string/_get_string_input.rs | 38 +- .../get_string/_get_string_output.rs | 38 +- .../rust/src/operation/get_string/builders.rs | 36 +- .../src/operation/get_string_known_value.rs | 35 +- .../_get_string_input.rs | 58 + .../_get_string_known_value_input.rs | 60 - .../_get_string_known_value_output.rs | 59 - .../_get_string_output.rs | 58 + .../get_string_known_value/builders.rs | 59 +- .../rust/src/operation/get_string_utf8.rs | 11 +- .../get_string_utf8/_get_string_utf8_input.rs | 38 +- .../_get_string_utf8_output.rs | 38 +- .../src/operation/get_string_utf8/builders.rs | 42 +- .../operation/get_string_utf8_known_value.rs | 19 +- .../_get_string_utf8_input.rs | 58 + .../_get_string_utf8_known_value_input.rs | 56 - .../_get_string_utf8_known_value_output.rs | 56 - .../_get_string_utf8_output.rs | 58 + .../get_string_utf8_known_value/builders.rs | 52 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../SimpleString/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_string_config.rs | 5 +- .../SimpleString/runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 179 ++ .../SimpleTypes/SimpleTimestamp/Makefile | 5 +- .../SimpleTimestamp/runtimes/rust/Cargo.toml | 11 +- .../runtimes/rust/src/client.rs | 7 +- .../runtimes/rust/src/client/get_timestamp.rs | 12 +- .../runtimes/rust/src/conversions.rs | 10 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../rust/src/conversions/get_timestamp.rs | 8 +- .../get_timestamp/_get_timestamp_input.rs | 39 +- .../get_timestamp/_get_timestamp_output.rs | 39 +- .../conversions/simple_timestamp_config.rs | 5 +- .../_simple_timestamp_config.rs | 8 +- .../runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleTimestamp/runtimes/rust/src/lib.rs | 19 - .../runtimes/rust/src/operation.rs | 5 +- .../rust/src/operation/get_timestamp.rs | 15 +- .../get_timestamp/_get_timestamp_input.rs | 44 +- .../get_timestamp/_get_timestamp_output.rs | 55 +- .../src/operation/get_timestamp/builders.rs | 32 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_timestamp_config.rs | 5 +- .../runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 89 + .../rust/tests/simple_timestamp_test.rs | 2 +- .../src/WrappedSimpleTypesTimestampImpl.dfy | 10 + .../test/SimpleTimestampImplTest.dfy | 22 +- .../test/WrappedSimpleTimestampTest.dfy | 1 + .../rust/src/standard_library_externs.rs | 80 + .../rust/src/conversions/attribute_action.rs | 12 +- .../batch_statement_error_code_enum.rs | 44 +- .../rust/src/conversions/billing_mode.rs | 8 +- .../src/conversions/comparison_operator.rs | 52 +- .../src/conversions/conditional_operator.rs | 8 +- .../rust/src/conversions/index_status.rs | 16 +- .../runtimes/rust/src/conversions/key_type.rs | 8 +- .../rust/src/conversions/projection_type.rs | 12 +- .../rust/src/conversions/replica_status.rs | 28 +- .../conversions/return_consumed_capacity.rs | 12 +- .../return_item_collection_metrics.rs | 8 +- .../rust/src/conversions/return_value.rs | 20 +- ...eturn_values_on_condition_check_failure.rs | 8 +- .../src/conversions/scalar_attribute_type.rs | 12 +- .../runtimes/rust/src/conversions/select.rs | 16 +- .../rust/src/conversions/sse_status.rs | 20 +- .../runtimes/rust/src/conversions/sse_type.rs | 8 +- .../rust/src/conversions/stream_view_type.rs | 16 +- .../rust/src/conversions/table_class.rs | 8 +- .../rust/src/conversions/table_status.rs | 28 +- .../rust/src/standard_library_externs.rs | 80 + .../conversions/customer_master_key_spec.rs | 52 +- .../rust/src/conversions/data_key_spec.rs | 8 +- .../conversions/encryption_algorithm_spec.rs | 12 +- .../key_agreement_algorithm_spec.rs | 4 +- .../conversions/key_encryption_mechanism.rs | 4 +- .../runtimes/rust/src/conversions/key_spec.rs | 52 +- .../rust/src/conversions/key_usage_type.rs | 16 +- .../rust/src/conversions/origin_type.rs | 16 +- .../src/conversions/signing_algorithm_spec.rs | 40 +- .../rust/src/standard_library_externs.rs | 80 + .../amazon/polymorph/CodegenEngine.java | 109 +- .../smithydotnet/TypeConversionCodegen.java | 17 +- .../generator/AbstractRustShimGenerator.java | 402 ++-- .../generator/RustAwsSdkShimGenerator.java | 86 +- .../generator/RustLibraryShimGenerator.java | 163 +- .../amazon/polymorph/utils/ModelUtils.java | 30 + .../runtimes/rust/conversions/operation.rs | 4 +- .../runtimes/rust/operation/outer.rs | 4 +- .../rust/src/standard_library_externs.rs | 80 + .../templates/runtimes/rust/types.rs | 4 +- .../templates/runtimes/rust/types/enum.rs | 12 + .../wrapped/client_operation_impl.part.rs | 4 +- 403 files changed, 9498 insertions(+), 10533 deletions(-) create mode 100644 TestModels/Aggregate/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/Constructor/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/Errors/runtimes/rust/src/implementation_from_dafny.rs-e create mode 100644 TestModels/Errors/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/LanguageSpecificLogic/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/Refinement/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/Resource/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value_test.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_output.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_input.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/lib.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/builders.rs rename TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/{get_blob_known_value.rs => get_blob_known_value_test.rs} (67%) create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_input.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_output.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/builders.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped/client.rs create mode 100644 TestModels/SimpleTypes/SimpleBoolean/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/lib.rs create mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped/client.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape/_simple_enum_shape.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/lib.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/_simple_enum_shape.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_shape.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped/client.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape/_simple_enum_v2_shape.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/lib.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/_simple_enum_v2_shape.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_shape.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped/client.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value_test.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_output.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_input.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/lib.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/builders.rs rename TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/{get_integer_known_value.rs => get_integer_known_value_test.rs} (67%) create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_input.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_output.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/builders.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped/client.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value_test.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_output.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_input.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/lib.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/builders.rs rename TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/{get_long_known_value.rs => get_long_known_value_test.rs} (67%) create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_input.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_output.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/builders.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped/client.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/implementation_from_dafny.rs-e delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/lib.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_output.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_output.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_output.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped/client.rs create mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/lib.rs create mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped/client.rs create mode 100644 TestModels/SimpleTypes/SimpleTimestamp/src/WrappedSimpleTypesTimestampImpl.dfy create mode 100644 TestModels/Union/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/aws-sdks/ddb-lite/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/aws-sdks/kms-lite/runtimes/rust/src/standard_library_externs.rs create mode 100644 codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/src/standard_library_externs.rs create mode 100644 codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types/enum.rs diff --git a/TestModels/Aggregate/runtimes/rust/src/standard_library_externs.rs b/TestModels/Aggregate/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/Aggregate/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/Constructor/runtimes/rust/src/standard_library_externs.rs b/TestModels/Constructor/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/Constructor/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/Errors/runtimes/rust/src/implementation_from_dafny.rs-e b/TestModels/Errors/runtimes/rust/src/implementation_from_dafny.rs-e deleted file mode 100644 index 742c6a6ba8..0000000000 --- a/TestModels/Errors/runtimes/rust/src/implementation_from_dafny.rs-e +++ /dev/null @@ -1,1745 +0,0 @@ -#![allow(warnings, unconditional_panic)] -#![allow(nonstandard_style)] - -pub mod _module { - -} -pub mod simple { - pub mod errors { - pub mod internaldafny { - pub use ::dafny_runtime::UpcastObject; - pub use ::std::any::Any; - pub use crate::simple::errors::internaldafny::types::ISimpleErrorsClient; - - pub struct _default {} - - impl _default { - pub fn DefaultSimpleErrorsConfig() -> ::std::rc::Rc { - ::std::rc::Rc::new(crate::simple::errors::internaldafny::types::SimpleErrorsConfig::SimpleErrorsConfig {}) - } - pub fn SimpleErrors(config: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut res = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut client = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object>::new(); - let mut _nw0: ::dafny_runtime::Object = crate::simple::errors::internaldafny::SimpleErrorsClient::_allocate_object(); - crate::simple::errors::internaldafny::SimpleErrorsClient::_ctor(&_nw0, &::std::rc::Rc::new(crate::r#_SimpleErrorsImpl_Compile::Config::Config {})); - client = ::dafny_runtime::MaybePlacebo::from(_nw0.clone()); - res = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Success { - value: client.read() - })); - return res.read(); - } - pub fn CreateSuccessOfClient(client: &::dafny_runtime::Object) -> ::std::rc::Rc, ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Success { - value: client.clone() - }) - } - pub fn CreateFailureOfError(error: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Failure { - error: error.clone() - }) - } - } - - pub struct SimpleErrorsClient { - pub r#__i_config: ::std::rc::Rc - } - - impl SimpleErrorsClient { - pub fn _allocate_object() -> ::dafny_runtime::Object { - ::dafny_runtime::allocate_object::() - } - pub fn _ctor(this: &::dafny_runtime::Object, config: &::std::rc::Rc) -> () { - let mut _set__i_config: bool = false; - ::dafny_runtime::update_field_uninit_object!(this.clone(), r#__i_config, _set__i_config, config.clone()); - return (); - } - pub fn config(&self) -> ::std::rc::Rc { - self.r#__i_config.clone() - } - } - - impl UpcastObject - for crate::simple::errors::internaldafny::SimpleErrorsClient { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); - } - - impl ISimpleErrorsClient - for crate::simple::errors::internaldafny::SimpleErrorsClient { - fn AlwaysError(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut _out0 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - _out0 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleErrorsImpl_Compile::_default::AlwaysError(&self.config().clone(), input)); - output = ::dafny_runtime::MaybePlacebo::from(_out0.read()); - return output.read(); - } - fn AlwaysMultipleErrors(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut _out1 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - _out1 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleErrorsImpl_Compile::_default::AlwaysMultipleErrors(&self.config().clone(), input)); - output = ::dafny_runtime::MaybePlacebo::from(_out1.read()); - return output.read(); - } - fn AlwaysNativeError(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut _out2 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - _out2 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleErrorsImpl_Compile::_default::AlwaysNativeError(&self.config().clone(), input)); - output = ::dafny_runtime::MaybePlacebo::from(_out2.read()); - return output.read(); - } - } - - impl UpcastObject - for crate::simple::errors::internaldafny::SimpleErrorsClient { - ::dafny_runtime::UpcastObjectFn!(dyn crate::simple::errors::internaldafny::types::ISimpleErrorsClient); - } - - pub mod types { - pub use ::std::fmt::Debug; - pub use ::dafny_runtime::DafnyPrint; - pub use ::std::cmp::Eq; - pub use ::std::hash::Hash; - pub use ::std::default::Default; - pub use ::std::convert::AsRef; - pub use ::dafny_runtime::UpcastObject; - pub use ::std::any::Any; - - #[derive(PartialEq, Clone)] - pub enum DafnyCallEvent { - DafnyCallEvent { - input: I, - output: O - } - } - - impl DafnyCallEvent { - pub fn input(&self) -> &I { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => input, - } - } - pub fn output(&self) -> &O { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => output, - } - } - } - - impl Debug - for DafnyCallEvent { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for DafnyCallEvent { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => { - write!(_formatter, "simple.errors.internaldafny.types.DafnyCallEvent.DafnyCallEvent(")?; - ::dafny_runtime::DafnyPrint::fmt_print(input, _formatter, false)?; - write!(_formatter, ", ")?; - ::dafny_runtime::DafnyPrint::fmt_print(output, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for DafnyCallEvent {} - - impl Hash - for DafnyCallEvent { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => { - ::std::hash::Hash::hash(input, _state); - ::std::hash::Hash::hash(output, _state) - }, - } - } - } - - impl Default - for DafnyCallEvent { - fn default() -> DafnyCallEvent { - DafnyCallEvent::DafnyCallEvent { - input: ::std::default::Default::default(), - output: ::std::default::Default::default() - } - } - } - - impl AsRef> - for &DafnyCallEvent { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum GetErrorsInput { - GetErrorsInput { - value: ::std::rc::Rc>> - } - } - - impl GetErrorsInput { - pub fn value(&self) -> &::std::rc::Rc>> { - match self { - GetErrorsInput::GetErrorsInput{value, } => value, - } - } - } - - impl Debug - for GetErrorsInput { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for GetErrorsInput { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - GetErrorsInput::GetErrorsInput{value, } => { - write!(_formatter, "simple.errors.internaldafny.types.GetErrorsInput.GetErrorsInput(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for GetErrorsInput {} - - impl Hash - for GetErrorsInput { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - GetErrorsInput::GetErrorsInput{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for GetErrorsInput { - fn default() -> GetErrorsInput { - GetErrorsInput::GetErrorsInput { - value: ::std::default::Default::default() - } - } - } - - impl AsRef - for &GetErrorsInput { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum GetErrorsOutput { - GetErrorsOutput { - value: ::std::rc::Rc>> - } - } - - impl GetErrorsOutput { - pub fn value(&self) -> &::std::rc::Rc>> { - match self { - GetErrorsOutput::GetErrorsOutput{value, } => value, - } - } - } - - impl Debug - for GetErrorsOutput { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for GetErrorsOutput { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - GetErrorsOutput::GetErrorsOutput{value, } => { - write!(_formatter, "simple.errors.internaldafny.types.GetErrorsOutput.GetErrorsOutput(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for GetErrorsOutput {} - - impl Hash - for GetErrorsOutput { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - GetErrorsOutput::GetErrorsOutput{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for GetErrorsOutput { - fn default() -> GetErrorsOutput { - GetErrorsOutput::GetErrorsOutput { - value: ::std::default::Default::default() - } - } - } - - impl AsRef - for &GetErrorsOutput { - fn as_ref(&self) -> Self { - self - } - } - - pub struct ISimpleErrorsClientCallHistory {} - - impl ISimpleErrorsClientCallHistory { - pub fn _allocate_object() -> ::dafny_runtime::Object { - ::dafny_runtime::allocate_object::() - } - } - - impl UpcastObject - for crate::simple::errors::internaldafny::types::ISimpleErrorsClientCallHistory { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); - } - - pub trait ISimpleErrorsClient: ::std::any::Any + ::dafny_runtime::UpcastObject { - fn AlwaysError(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; - fn AlwaysMultipleErrors(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; - fn AlwaysNativeError(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; - } - - #[derive(PartialEq, Clone)] - pub enum SimpleErrorsConfig { - SimpleErrorsConfig {} - } - - impl SimpleErrorsConfig {} - - impl Debug - for SimpleErrorsConfig { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for SimpleErrorsConfig { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - SimpleErrorsConfig::SimpleErrorsConfig{} => { - write!(_formatter, "simple.errors.internaldafny.types.SimpleErrorsConfig.SimpleErrorsConfig")?; - Ok(()) - }, - } - } - } - - impl SimpleErrorsConfig { - pub fn _AllSingletonConstructors() -> ::dafny_runtime::SequenceIter<::std::rc::Rc> { - ::dafny_runtime::seq![::std::rc::Rc::new(SimpleErrorsConfig::SimpleErrorsConfig {})].iter() - } - } - - impl Eq - for SimpleErrorsConfig {} - - impl Hash - for SimpleErrorsConfig { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - SimpleErrorsConfig::SimpleErrorsConfig{} => { - - }, - } - } - } - - impl Default - for SimpleErrorsConfig { - fn default() -> SimpleErrorsConfig { - SimpleErrorsConfig::SimpleErrorsConfig {} - } - } - - impl AsRef - for &SimpleErrorsConfig { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum Error { - SimpleErrorsException { - message: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> - }, - CollectionOfErrors { - list: ::dafny_runtime::Sequence<::std::rc::Rc>, - message: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> - }, - Opaque { - obj: ::dafny_runtime::Object - } - } - - impl Error { - pub fn message(&self) -> &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - match self { - Error::SimpleErrorsException{message, } => message, - Error::CollectionOfErrors{list, message, } => message, - Error::Opaque{obj, } => panic!("field does not exist on this variant"), - } - } - pub fn list(&self) -> &::dafny_runtime::Sequence<::std::rc::Rc> { - match self { - Error::SimpleErrorsException{message, } => panic!("field does not exist on this variant"), - Error::CollectionOfErrors{list, message, } => list, - Error::Opaque{obj, } => panic!("field does not exist on this variant"), - } - } - pub fn obj(&self) -> &::dafny_runtime::Object { - match self { - Error::SimpleErrorsException{message, } => panic!("field does not exist on this variant"), - Error::CollectionOfErrors{list, message, } => panic!("field does not exist on this variant"), - Error::Opaque{obj, } => obj, - } - } - } - - impl Debug - for Error { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Error { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Error::SimpleErrorsException{message, } => { - write!(_formatter, "simple.errors.internaldafny.types.Error.SimpleErrorsException(")?; - ::dafny_runtime::DafnyPrint::fmt_print(message, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - Error::CollectionOfErrors{list, message, } => { - write!(_formatter, "simple.errors.internaldafny.types.Error.CollectionOfErrors(")?; - ::dafny_runtime::DafnyPrint::fmt_print(list, _formatter, false)?; - write!(_formatter, ", ")?; - ::dafny_runtime::DafnyPrint::fmt_print(message, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - Error::Opaque{obj, } => { - write!(_formatter, "simple.errors.internaldafny.types.Error.Opaque(")?; - ::dafny_runtime::DafnyPrint::fmt_print(obj, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for Error {} - - impl Hash - for Error { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Error::SimpleErrorsException{message, } => { - ::std::hash::Hash::hash(message, _state) - }, - Error::CollectionOfErrors{list, message, } => { - ::std::hash::Hash::hash(list, _state); - ::std::hash::Hash::hash(message, _state) - }, - Error::Opaque{obj, } => { - ::std::hash::Hash::hash(obj, _state) - }, - } - } - } - - impl Default - for Error { - fn default() -> Error { - Error::SimpleErrorsException { - message: ::std::default::Default::default() - } - } - } - - impl AsRef - for &Error { - fn as_ref(&self) -> Self { - self - } - } - - pub type OpaqueError = ::std::rc::Rc; - } - } - } -} -pub mod r#_SimpleErrorsImpl_Compile { - pub use ::std::fmt::Debug; - pub use ::dafny_runtime::DafnyPrint; - pub use ::std::cmp::Eq; - pub use ::std::hash::Hash; - pub use ::std::default::Default; - pub use ::std::convert::AsRef; - pub use ::dafny_runtime::UpcastObject; - pub use ::std::any::Any; - - pub struct _default {} - - impl _default { - pub fn AlwaysError(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { - panic!("Halt") - }; - let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::errors::internaldafny::types::Error::SimpleErrorsException { - message: input.value().value().clone() - }); - output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Failure { - error: res.clone() - })); - return output.read(); - } - pub fn AlwaysMultipleErrors(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { - panic!("Halt") - }; - let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::errors::internaldafny::types::Error::CollectionOfErrors { - list: ::dafny_runtime::seq![::std::rc::Rc::new(crate::simple::errors::internaldafny::types::Error::SimpleErrorsException { - message: input.value().value().clone() - })], - message: ::dafny_runtime::string_utf16_of("Something") - }); - output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Failure { - error: res.clone() - })); - return output.read(); - } - pub fn AlwaysNativeError(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut opaqueObject = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object>::new(); - let mut _nw1: ::dafny_runtime::Object = crate::r#_SimpleErrorsImpl_Compile::SomeOpaqueGeneratedTypeForTesting::_allocate_object(); - crate::r#_SimpleErrorsImpl_Compile::SomeOpaqueGeneratedTypeForTesting::_ctor(&_nw1); - opaqueObject = ::dafny_runtime::MaybePlacebo::from(_nw1.clone()); - let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::errors::internaldafny::types::Error::Opaque { - obj: ::dafny_runtime::upcast_object::()(opaqueObject.read()) - }); - output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Failure { - error: res.clone() - })); - return output.read(); - } - } - - #[derive(PartialEq, Clone)] - pub enum Config { - Config {} - } - - impl Config {} - - impl Debug - for Config { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Config { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Config::Config{} => { - write!(_formatter, "SimpleErrorsImpl_Compile.Config.Config")?; - Ok(()) - }, - } - } - } - - impl Config { - pub fn _AllSingletonConstructors() -> ::dafny_runtime::SequenceIter<::std::rc::Rc> { - ::dafny_runtime::seq![::std::rc::Rc::new(Config::Config {})].iter() - } - } - - impl Eq - for Config {} - - impl Hash - for Config { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Config::Config{} => { - - }, - } - } - } - - impl Default - for Config { - fn default() -> Config { - Config::Config {} - } - } - - impl AsRef - for &Config { - fn as_ref(&self) -> Self { - self - } - } - - pub struct SomeOpaqueGeneratedTypeForTesting {} - - impl SomeOpaqueGeneratedTypeForTesting { - pub fn _allocate_object() -> ::dafny_runtime::Object { - ::dafny_runtime::allocate_object::() - } - pub fn _ctor(this: &::dafny_runtime::Object) -> () { - return (); - } - } - - impl UpcastObject - for SomeOpaqueGeneratedTypeForTesting { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); - } -} -pub mod r#_StandardLibrary_Compile { - pub struct _default {} - - impl _default { - pub fn Join<_T: ::dafny_runtime::DafnyType>(ss: &::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>, joiner: &::dafny_runtime::Sequence<_T>) -> ::dafny_runtime::Sequence<_T> { - let mut _accumulator: ::dafny_runtime::Sequence<_T> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>; - let mut _r0 = ss.clone(); - let mut _r1 = joiner.clone(); - 'TAIL_CALL_START: loop { - let ss = _r0; - let joiner = _r1; - if ss.cardinality() == ::dafny_runtime::int!(1) { - return _accumulator.concat(&ss.get(&::dafny_runtime::int!(0))); - } else { - _accumulator = _accumulator.concat(&ss.get(&::dafny_runtime::int!(0)).concat(&joiner)); - let mut _in0: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ss.drop(&::dafny_runtime::int!(1)); - let mut _in1: ::dafny_runtime::Sequence<_T> = joiner.clone(); - _r0 = _in0.clone(); - _r1 = _in1.clone(); - continue 'TAIL_CALL_START; - } - } - } - pub fn Split<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> { - let mut _accumulator: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>; - let mut _r0 = s.clone(); - let mut _r1 = delim.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let delim = _r1; - let mut i: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(&s, &delim, &::dafny_runtime::int!(0)); - if matches!((&i).as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { - _accumulator = _accumulator.concat(&::dafny_runtime::seq![s.take(i.value())]); - let mut _in2: ::dafny_runtime::Sequence<_T> = s.drop(&(i.value().clone() + ::dafny_runtime::int!(1))); - let mut _in3: _T = delim.clone(); - _r0 = _in2.clone(); - _r1 = _in3.clone(); - continue 'TAIL_CALL_START; - } else { - return _accumulator.concat(&::dafny_runtime::seq![s.clone()]); - } - } - } - pub fn SplitOnce<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> (::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>) { - let mut i: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(s, delim, &::dafny_runtime::int!(0)); - ( - s.take(i.value()), - s.drop(&(i.value().clone() + ::dafny_runtime::int!(1))) - ) - } - pub fn r#_SplitOnce_q<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> ::std::rc::Rc, ::dafny_runtime::Sequence<_T>)>> { - let mut valueOrError0: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(s, delim, &::dafny_runtime::int!(0)); - if valueOrError0.IsFailure() { - valueOrError0.PropagateFailure::<(::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>)>() - } else { - let mut i: ::dafny_runtime::_System::nat = valueOrError0.Extract(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<(::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>)>::Some { - value: ( - s.take(&i), - s.drop(&(i.clone() + ::dafny_runtime::int!(1))) - ) - }) - } - } - pub fn FindIndexMatching<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, c: &_T, i: &::dafny_runtime::_System::nat) -> ::std::rc::Rc> { - crate::r#_StandardLibrary_Compile::_default::FindIndex::<_T>(s, { - let c: _T = c.clone(); - &({ - let mut c = c.clone(); - ::std::rc::Rc::new(move |x: &_T| -> bool{ - x.clone() == c.clone() - }) - }) - }, i) - } - pub fn FindIndex<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>, f: &::std::rc::Rc bool>, i: &::dafny_runtime::_System::nat) -> ::std::rc::Rc> { - let mut _r0 = s.clone(); - let mut _r1 = f.clone(); - let mut _r2 = i.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let f = _r1; - let i = _r2; - if i.clone() == s.cardinality() { - return ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::_System::nat>::None {}); - } else { - if (&f)(&s.get(&i)) { - return ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::_System::nat>::Some { - value: i.clone() - }); - } else { - let mut _in4: ::dafny_runtime::Sequence<_T> = s.clone(); - let mut _in5: ::std::rc::Rc bool> = f.clone(); - let mut _in6: ::dafny_runtime::DafnyInt = i.clone() + ::dafny_runtime::int!(1); - _r0 = _in4.clone(); - _r1 = _in5.clone(); - _r2 = _in6.clone(); - continue 'TAIL_CALL_START; - } - } - } - } - pub fn Filter<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>, f: &::std::rc::Rc bool>) -> ::dafny_runtime::Sequence<_T> { - let mut _accumulator: ::dafny_runtime::Sequence<_T> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>; - let mut _r0 = s.clone(); - let mut _r1 = f.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let f = _r1; - if s.cardinality() == ::dafny_runtime::int!(0) { - return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>)); - } else { - if (&f)(&s.get(&::dafny_runtime::int!(0))) { - _accumulator = _accumulator.concat(&::dafny_runtime::seq![s.get(&::dafny_runtime::int!(0))]); - let mut _in7: ::dafny_runtime::Sequence<_T> = s.drop(&::dafny_runtime::int!(1)); - let mut _in8: ::std::rc::Rc bool> = f.clone(); - _r0 = _in7.clone(); - _r1 = _in8.clone(); - continue 'TAIL_CALL_START; - } else { - let mut _in9: ::dafny_runtime::Sequence<_T> = s.drop(&::dafny_runtime::int!(1)); - let mut _in10: ::std::rc::Rc bool> = f.clone(); - _r0 = _in9.clone(); - _r1 = _in10.clone(); - continue 'TAIL_CALL_START; - } - } - } - } - pub fn Min(a: &::dafny_runtime::DafnyInt, b: &::dafny_runtime::DafnyInt) -> ::dafny_runtime::DafnyInt { - if a.clone() < b.clone() { - a.clone() - } else { - b.clone() - } - } - pub fn Fill<_T: ::dafny_runtime::DafnyType>(value: &_T, n: &::dafny_runtime::_System::nat) -> ::dafny_runtime::Sequence<_T> { - { - let _initializer = { - let value: _T = value.clone(); - { - let mut value = value.clone(); - ::std::rc::Rc::new(move |_v0: &::dafny_runtime::DafnyInt| -> _T{ - value.clone() - }) - } - }; - ::dafny_runtime::integer_range(::dafny_runtime::Zero::zero(), n.clone()).map(|i| _initializer(&i)).collect::<::dafny_runtime::Sequence<_>>() - } - } - pub fn SeqToArray<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> ::dafny_runtime::Object<[_T]> { - let mut a = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object<[_T]>>::new(); - let mut _init0: ::std::rc::Rc _T> = { - let s: ::dafny_runtime::Sequence<_T> = s.clone(); - { - let mut s = s.clone(); - ::std::rc::Rc::new(move |i: &::dafny_runtime::DafnyInt| -> _T{ - s.get(i) - }) - } - }; - let mut _nw2: ::dafny_runtime::Object<[::std::mem::MaybeUninit<_T>]> = ::dafny_runtime::array::placebos_usize_object::<_T>(::dafny_runtime::DafnyUsize::into_usize(s.cardinality())); - for r#__i0_0 in ::dafny_runtime::integer_range(0, ::dafny_runtime::rd!(_nw2.clone()).len()) { - { - let __idx0 = ::dafny_runtime::DafnyUsize::into_usize(r#__i0_0.clone()); - ::dafny_runtime::md!(_nw2)[__idx0] = ::std::mem::MaybeUninit::new((&_init0)(&::dafny_runtime::int!(r#__i0_0.clone()))); - } - } - a = ::dafny_runtime::MaybePlacebo::from(::dafny_runtime::array::construct_object(_nw2.clone())); - return a.read(); - } - pub fn LexicographicLessOrEqual<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, b: &::dafny_runtime::Sequence<_T>, less: &::std::rc::Rc bool>) -> bool { - ::dafny_runtime::integer_range(::dafny_runtime::int!(0), a.cardinality() + ::dafny_runtime::int!(1)).any(({ - let mut a = a.clone(); - let mut b = b.clone(); - let mut less = less.clone(); - ::std::rc::Rc::new(move |r#__exists_var_0: ::dafny_runtime::DafnyInt| -> bool{ - let mut k: ::dafny_runtime::DafnyInt = r#__exists_var_0.clone(); - ::dafny_runtime::int!(0) <= k.clone() && k.clone() <= a.cardinality() && crate::r#_StandardLibrary_Compile::_default::LexicographicLessOrEqualAux::<_T>(&a, &b, &less, &k) - }) - }).as_ref()) - } - pub fn LexicographicLessOrEqualAux<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, b: &::dafny_runtime::Sequence<_T>, less: &::std::rc::Rc bool>, lengthOfCommonPrefix: &::dafny_runtime::_System::nat) -> bool { - lengthOfCommonPrefix.clone() <= b.cardinality() && ::dafny_runtime::integer_range(::dafny_runtime::int!(0), lengthOfCommonPrefix.clone()).all(({ - let mut lengthOfCommonPrefix = lengthOfCommonPrefix.clone(); - let mut a = a.clone(); - let mut b = b.clone(); - ::std::rc::Rc::new(move |r#__forall_var_0: ::dafny_runtime::DafnyInt| -> bool{ - let mut i: ::dafny_runtime::DafnyInt = r#__forall_var_0.clone(); - !(::dafny_runtime::int!(0) <= i.clone() && i.clone() < lengthOfCommonPrefix.clone()) || a.get(&i) == b.get(&i) - }) - }).as_ref()) && (lengthOfCommonPrefix.clone() == a.cardinality() || lengthOfCommonPrefix.clone() < b.cardinality() && less(&a.get(lengthOfCommonPrefix), &b.get(lengthOfCommonPrefix))) - } - pub fn SetToOrderedSequence<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Set<::dafny_runtime::Sequence<_T>>, less: &::std::rc::Rc bool>) -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> { - let mut _accumulator: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>; - let mut _r0 = s.clone(); - let mut _r1 = less.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let less = _r1; - if s.clone() == ::dafny_runtime::set!{} { - return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>)); - } else { - return (&({ - let mut s = s.clone(); - let mut less = less.clone(); - ::std::rc::Rc::new(move |r#__let_dummy_0: &::dafny_runtime::DafnyInt| -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>{ - let mut a = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Sequence<_T>>::new(); - 'label_goto__ASSIGN_SUCH_THAT_0: loop { - for r#__assign_such_that_0 in (&s).iter().cloned() { - a = ::dafny_runtime::MaybePlacebo::from(r#__assign_such_that_0.clone()); - if s.contains(&a.read()) && crate::r#_StandardLibrary_Compile::_default::IsMinimum::<_T>(&a.read(), &s, &less) { - break 'label_goto__ASSIGN_SUCH_THAT_0; - } - } - panic!("Halt"); - break; - }; - ::dafny_runtime::seq![a.read()].concat(&crate::r#_StandardLibrary_Compile::_default::SetToOrderedSequence::<_T>(&s.subtract(&::dafny_runtime::set!{a.read()}), &less)) - }) - }))(&::dafny_runtime::int!(0)); - } - } - } - pub fn IsMinimum<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, s: &::dafny_runtime::Set<::dafny_runtime::Sequence<_T>>, less: &::std::rc::Rc bool>) -> bool { - s.contains(a) && s.iter().all(({ - let mut a = a.clone(); - let mut s = s.clone(); - let mut less = less.clone(); - ::std::rc::Rc::new(move |r#__forall_var_1: &::dafny_runtime::Sequence<_T>| -> bool{ - let mut z: ::dafny_runtime::Sequence<_T> = r#__forall_var_1.clone(); - !s.contains(&z) || crate::r#_StandardLibrary_Compile::_default::LexicographicLessOrEqual::<_T>(&a, &z, &less) - }) - }).as_ref()) - } - } - - pub mod r#_UInt_Compile { - pub use ::std::default::Default; - pub use ::dafny_runtime::DafnyPrint; - - pub struct _default {} - - impl _default { - pub fn UInt8Less(a: u8, b: u8) -> bool { - a < b - } - pub fn HasUint16Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { - s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT16_LIMIT() - } - pub fn HasUint32Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { - s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT32_LIMIT() - } - pub fn HasUint64Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { - s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT64_LIMIT() - } - pub fn UInt16ToSeq(x: u16) -> ::dafny_runtime::Sequence { - let mut b0: u8 = (x / 256) as u8; - let mut b1: u8 = (x % 256) as u8; - ::dafny_runtime::seq![b0, b1] - } - pub fn SeqToUInt16(s: &::dafny_runtime::Sequence) -> u16 { - let mut x0: u16 = s.get(&::dafny_runtime::int!(0)) as u16 * 256; - x0 + s.get(&::dafny_runtime::int!(1)) as u16 - } - pub fn UInt32ToSeq(x: u32) -> ::dafny_runtime::Sequence { - let mut b0: u8 = (x / 16777216) as u8; - let mut x0: u32 = x - b0 as u32 * 16777216; - let mut b1: u8 = (x0 / 65536) as u8; - let mut x1: u32 = x0 - b1 as u32 * 65536; - let mut b2: u8 = (x1 / 256) as u8; - let mut b3: u8 = (x1 % 256) as u8; - ::dafny_runtime::seq![b0, b1, b2, b3] - } - pub fn SeqToUInt32(s: &::dafny_runtime::Sequence) -> u32 { - let mut x0: u32 = s.get(&::dafny_runtime::int!(0)) as u32 * 16777216; - let mut x1: u32 = x0 + s.get(&::dafny_runtime::int!(1)) as u32 * 65536; - let mut x2: u32 = x1 + s.get(&::dafny_runtime::int!(2)) as u32 * 256; - x2 + s.get(&::dafny_runtime::int!(3)) as u32 - } - pub fn UInt64ToSeq(x: u64) -> ::dafny_runtime::Sequence { - let mut b0: u8 = (x / 72057594037927936) as u8; - let mut x0: u64 = x - b0 as u64 * 72057594037927936; - let mut b1: u8 = (x0 / 281474976710656) as u8; - let mut x1: u64 = x0 - b1 as u64 * 281474976710656; - let mut b2: u8 = (x1 / 1099511627776) as u8; - let mut x2: u64 = x1 - b2 as u64 * 1099511627776; - let mut b3: u8 = (x2 / 4294967296) as u8; - let mut x3: u64 = x2 - b3 as u64 * 4294967296; - let mut b4: u8 = (x3 / 16777216) as u8; - let mut x4: u64 = x3 - b4 as u64 * 16777216; - let mut b5: u8 = (x4 / 65536) as u8; - let mut x5: u64 = x4 - b5 as u64 * 65536; - let mut b6: u8 = (x5 / 256) as u8; - let mut b7: u8 = (x5 % 256) as u8; - ::dafny_runtime::seq![b0, b1, b2, b3, b4, b5, b6, b7] - } - pub fn SeqToUInt64(s: &::dafny_runtime::Sequence) -> u64 { - let mut x0: u64 = s.get(&::dafny_runtime::int!(0)) as u64 * 72057594037927936; - let mut x1: u64 = x0 + s.get(&::dafny_runtime::int!(1)) as u64 * 281474976710656; - let mut x2: u64 = x1 + s.get(&::dafny_runtime::int!(2)) as u64 * 1099511627776; - let mut x3: u64 = x2 + s.get(&::dafny_runtime::int!(3)) as u64 * 4294967296; - let mut x4: u64 = x3 + s.get(&::dafny_runtime::int!(4)) as u64 * 16777216; - let mut x5: u64 = x4 + s.get(&::dafny_runtime::int!(5)) as u64 * 65536; - let mut x6: u64 = x5 + s.get(&::dafny_runtime::int!(6)) as u64 * 256; - let mut x: u64 = x6 + s.get(&::dafny_runtime::int!(7)) as u64; - x - } - pub fn UINT16_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"65536") - } - pub fn UINT32_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"4294967296") - } - pub fn UINT64_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"18446744073709551616") - } - pub fn INT32_MAX_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"2147483648") - } - pub fn INT64_MAX_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"9223372036854775808") - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint8(pub u8); - - impl uint8 { - pub fn is(_source: u8) -> bool { - return true; - } - } - - impl Default - for uint8 { - fn default() -> Self { - uint8(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint8 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint8 { - type Target = u8; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint16(pub u16); - - impl uint16 { - pub fn is(_source: u16) -> bool { - return true; - } - } - - impl Default - for uint16 { - fn default() -> Self { - uint16(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint16 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint16 { - type Target = u16; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint32(pub u32); - - impl uint32 { - pub fn is(_source: u32) -> bool { - return true; - } - } - - impl Default - for uint32 { - fn default() -> Self { - uint32(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint32 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint32 { - type Target = u32; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint64(pub u64); - - impl uint64 { - pub fn is(_source: u64) -> bool { - return true; - } - } - - impl Default - for uint64 { - fn default() -> Self { - uint64(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint64 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint64 { - type Target = u64; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct int32(pub i32); - - impl int32 { - pub fn is(_source: i32) -> bool { - return true; - } - } - - impl Default - for int32 { - fn default() -> Self { - int32(::std::default::Default::default()) - } - } - - impl DafnyPrint - for int32 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for int32 { - type Target = i32; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct int64(pub i64); - - impl int64 { - pub fn is(_source: i64) -> bool { - return true; - } - } - - impl Default - for int64 { - fn default() -> Self { - int64(::std::default::Default::default()) - } - } - - impl DafnyPrint - for int64 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for int64 { - type Target = i64; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct posInt64(pub u64); - - impl posInt64 { - pub fn is(_source: u64) -> bool { - let mut x: ::dafny_runtime::DafnyInt = ::std::convert::Into::<::dafny_runtime::DafnyInt>::into(_source.clone()); - return ::dafny_runtime::int!(0) < x.clone() && x.clone() < ::dafny_runtime::int!(b"9223372036854775808"); - } - } - - impl Default - for posInt64 { - fn default() -> Self { - posInt64(1) - } - } - - impl DafnyPrint - for posInt64 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for posInt64 { - type Target = u64; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - pub type seq16 = ::dafny_runtime::Sequence; - - pub type seq32 = ::dafny_runtime::Sequence; - - pub type seq64 = ::dafny_runtime::Sequence; - } -} -pub mod r#_StandardLibraryInterop_Compile { - pub use ::dafny_runtime::UpcastObject; - pub use ::std::any::Any; - - pub struct WrappersInterop {} - - impl WrappersInterop { - pub fn _allocate_object() -> ::dafny_runtime::Object { - ::dafny_runtime::allocate_object::() - } - pub fn CreateStringSome(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Some { - value: s.clone() - }) - } - pub fn CreateStringNone() -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::None {}) - } - pub fn CreateBooleanSome(b: bool) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::Some { - value: b - }) - } - pub fn CreateBooleanNone() -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::None {}) - } - } - - impl UpcastObject - for WrappersInterop { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); - } -} -pub mod UTF8 { - pub struct _default {} - - impl _default { - pub fn CreateEncodeSuccess(bytes: &crate::UTF8::ValidUTF8Bytes) -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Success { - value: bytes.clone() - }) - } - pub fn CreateEncodeFailure(error: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Failure { - error: error.clone() - }) - } - pub fn CreateDecodeSuccess(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: s.clone() - }) - } - pub fn CreateDecodeFailure(error: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: error.clone() - }) - } - pub fn IsASCIIString(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> bool { - let mut _hresult: bool = ::default(); - let mut _hi0: ::dafny_runtime::DafnyInt = s.cardinality(); - for i in ::dafny_runtime::integer_range(::dafny_runtime::int!(0), _hi0.clone()) { - if !(::dafny_runtime::int!(s.get(&i).0) < ::dafny_runtime::int!(128)) { - _hresult = false; - return _hresult; - } - } - _hresult = true; - return _hresult; - } - pub fn EncodeAscii(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> crate::UTF8::ValidUTF8Bytes { - let mut _accumulator: crate::UTF8::ValidUTF8Bytes = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence; - let mut _r0 = s.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - if s.cardinality() == ::dafny_runtime::int!(0) { - return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence)); - } else { - let mut x: ::dafny_runtime::Sequence = ::dafny_runtime::seq![s.get(&::dafny_runtime::int!(0)).0 as u8]; - _accumulator = _accumulator.concat(&x); - let mut _in11: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> = s.drop(&::dafny_runtime::int!(1)); - _r0 = _in11.clone(); - continue 'TAIL_CALL_START; - } - } - } - pub fn Uses1Byte(s: &::dafny_runtime::Sequence) -> bool { - 0 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 127 - } - pub fn Uses2Bytes(s: &::dafny_runtime::Sequence) -> bool { - 194 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 223 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) - } - pub fn Uses3Bytes(s: &::dafny_runtime::Sequence) -> bool { - s.get(&::dafny_runtime::int!(0)) == 224 && (160 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || 225 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 236 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || s.get(&::dafny_runtime::int!(0)) == 237 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 159) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || 238 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 239 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) - } - pub fn Uses4Bytes(s: &::dafny_runtime::Sequence) -> bool { - s.get(&::dafny_runtime::int!(0)) == 240 && (144 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) || 241 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 243 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) || s.get(&::dafny_runtime::int!(0)) == 244 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 143) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) - } - pub fn ValidUTF8Range(a: &::dafny_runtime::Sequence, lo: &::dafny_runtime::_System::nat, hi: &::dafny_runtime::_System::nat) -> bool { - let mut _r0 = a.clone(); - let mut _r1 = lo.clone(); - let mut _r2 = hi.clone(); - 'TAIL_CALL_START: loop { - let a = _r0; - let lo = _r1; - let hi = _r2; - if lo.clone() == hi.clone() { - return true; - } else { - let mut r: ::dafny_runtime::Sequence = a.slice(&lo, &hi); - if crate::UTF8::_default::Uses1Byte(&r) { - let mut _in12: ::dafny_runtime::Sequence = a.clone(); - let mut _in13: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(1); - let mut _in14: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in12.clone(); - _r1 = _in13.clone(); - _r2 = _in14.clone(); - continue 'TAIL_CALL_START; - } else { - if ::dafny_runtime::int!(2) <= r.cardinality() && crate::UTF8::_default::Uses2Bytes(&r) { - let mut _in15: ::dafny_runtime::Sequence = a.clone(); - let mut _in16: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(2); - let mut _in17: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in15.clone(); - _r1 = _in16.clone(); - _r2 = _in17.clone(); - continue 'TAIL_CALL_START; - } else { - if ::dafny_runtime::int!(3) <= r.cardinality() && crate::UTF8::_default::Uses3Bytes(&r) { - let mut _in18: ::dafny_runtime::Sequence = a.clone(); - let mut _in19: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(3); - let mut _in20: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in18.clone(); - _r1 = _in19.clone(); - _r2 = _in20.clone(); - continue 'TAIL_CALL_START; - } else { - if ::dafny_runtime::int!(4) <= r.cardinality() && crate::UTF8::_default::Uses4Bytes(&r) { - let mut _in21: ::dafny_runtime::Sequence = a.clone(); - let mut _in22: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(4); - let mut _in23: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in21.clone(); - _r1 = _in22.clone(); - _r2 = _in23.clone(); - continue 'TAIL_CALL_START; - } else { - return false; - } - } - } - } - } - } - } - pub fn ValidUTF8Seq(s: &::dafny_runtime::Sequence) -> bool { - crate::UTF8::_default::ValidUTF8Range(s, &::dafny_runtime::int!(0), &s.cardinality()) - } - } - - pub type ValidUTF8Bytes = ::dafny_runtime::Sequence; - - pub fn r#__init_ValidUTF8Bytes() -> ::dafny_runtime::Sequence { - ::dafny_runtime::seq![] as ::dafny_runtime::Sequence - } -} -pub mod r#_Wrappers_Compile { - pub use ::std::fmt::Debug; - pub use ::dafny_runtime::DafnyPrint; - pub use ::std::cmp::Eq; - pub use ::std::hash::Hash; - pub use ::std::default::Default; - pub use ::std::convert::AsRef; - - pub struct _default {} - - impl _default { - pub fn Need<_E: ::dafny_runtime::DafnyType>(condition: bool, error: &_E) -> ::std::rc::Rc> { - if condition { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Outcome::<_E>::Pass {}) - } else { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Outcome::<_E>::Fail { - error: error.clone() - }) - } - } - } - - #[derive(PartialEq, Clone)] - pub enum Option { - None {}, - Some { - value: T - } - } - - impl Option { - pub fn ToResult(self: &::std::rc::Rc) -> ::std::rc::Rc>> { - let mut _source0: ::std::rc::Rc> = self.clone(); - if matches!((&_source0).as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::string_utf16_of("Option is None") - }) - } else { - let mut r#___mcc_h0: T = _source0.value().clone(); - let mut v: T = r#___mcc_h0.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Success { - value: v.clone() - }) - } - } - pub fn UnwrapOr(self: &::std::rc::Rc, default: &T) -> T { - let mut _source1: ::std::rc::Rc> = self.clone(); - if matches!((&_source1).as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) { - default.clone() - } else { - let mut r#___mcc_h0: T = _source1.value().clone(); - let mut v: T = r#___mcc_h0.clone(); - v.clone() - } - } - pub fn IsFailure(self: &::std::rc::Rc) -> bool { - matches!(self.as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) - } - pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<_U>::None {}) - } - pub fn Extract(self: &::std::rc::Rc) -> T { - self.value().clone() - } - pub fn value(&self) -> &T { - match self { - Option::None{} => panic!("field does not exist on this variant"), - Option::Some{value, } => value, - } - } - } - - impl Debug - for Option { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Option { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Option::None{} => { - write!(_formatter, "Wrappers_Compile.Option.None")?; - Ok(()) - }, - Option::Some{value, } => { - write!(_formatter, "Wrappers_Compile.Option.Some(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Option { - pub fn coerce(f_0: ::std::rc::Rc r#__T0 + 'static>) -> ::std::rc::Rc) -> Option> { - ::std::rc::Rc::new(move |this: Self| -> Option{ - match this { - Option::None{} => { - Option::None {} - }, - Option::Some{value, } => { - Option::Some { - value: f_0.clone()(value) - } - }, - } - }) - } - } - - impl Eq - for Option {} - - impl Hash - for Option { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Option::None{} => { - - }, - Option::Some{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for Option { - fn default() -> Option { - Option::None {} - } - } - - impl AsRef> - for &Option { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum Result { - Success { - value: T - }, - Failure { - error: R - } - } - - impl Result { - pub fn ToOption(self: &::std::rc::Rc) -> ::std::rc::Rc> { - let mut _source2: ::std::rc::Rc> = self.clone(); - if matches!((&_source2).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { - let mut r#___mcc_h0: T = _source2.value().clone(); - let mut s: T = r#___mcc_h0.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::Some { - value: s.clone() - }) - } else { - let mut r#___mcc_h1: R = _source2.error().clone(); - let mut e: R = r#___mcc_h1.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::None {}) - } - } - pub fn UnwrapOr(self: &::std::rc::Rc, default: &T) -> T { - let mut _source3: ::std::rc::Rc> = self.clone(); - if matches!((&_source3).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { - let mut r#___mcc_h0: T = _source3.value().clone(); - let mut s: T = r#___mcc_h0.clone(); - s.clone() - } else { - let mut r#___mcc_h1: R = _source3.error().clone(); - let mut e: R = r#___mcc_h1.clone(); - default.clone() - } - } - pub fn IsFailure(self: &::std::rc::Rc) -> bool { - matches!(self.as_ref(), crate::r#_Wrappers_Compile::Result::Failure{ .. }) - } - pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<_U, R>::Failure { - error: self.error().clone() - }) - } - pub fn MapFailure<_NewR: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc, reWrap: &::std::rc::Rc _NewR>) -> ::std::rc::Rc> { - let mut _source4: ::std::rc::Rc> = self.clone(); - if matches!((&_source4).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { - let mut r#___mcc_h0: T = _source4.value().clone(); - let mut s: T = r#___mcc_h0.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::::Success { - value: s.clone() - }) - } else { - let mut r#___mcc_h1: R = _source4.error().clone(); - let mut e: R = r#___mcc_h1.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::::Failure { - error: reWrap(&e) - }) - } - } - pub fn Extract(self: &::std::rc::Rc) -> T { - self.value().clone() - } - pub fn value(&self) -> &T { - match self { - Result::Success{value, } => value, - Result::Failure{error, } => panic!("field does not exist on this variant"), - } - } - pub fn error(&self) -> &R { - match self { - Result::Success{value, } => panic!("field does not exist on this variant"), - Result::Failure{error, } => error, - } - } - } - - impl Debug - for Result { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Result { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Result::Success{value, } => { - write!(_formatter, "Wrappers_Compile.Result.Success(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - Result::Failure{error, } => { - write!(_formatter, "Wrappers_Compile.Result.Failure(")?; - ::dafny_runtime::DafnyPrint::fmt_print(error, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Result { - pub fn coerce(f_0: ::std::rc::Rc r#__T0 + 'static>, f_1: ::std::rc::Rc r#__T1 + 'static>) -> ::std::rc::Rc) -> Result> { - ::std::rc::Rc::new(move |this: Self| -> Result{ - match this { - Result::Success{value, } => { - Result::Success { - value: f_0.clone()(value) - } - }, - Result::Failure{error, } => { - Result::Failure { - error: f_1.clone()(error) - } - }, - } - }) - } - } - - impl Eq - for Result {} - - impl Hash - for Result { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Result::Success{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - Result::Failure{error, } => { - ::std::hash::Hash::hash(error, _state) - }, - } - } - } - - impl Default - for Result { - fn default() -> Result { - Result::Success { - value: ::std::default::Default::default() - } - } - } - - impl AsRef> - for &Result { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum Outcome { - Pass {}, - Fail { - error: E - } - } - - impl Outcome { - pub fn IsFailure(self: &::std::rc::Rc) -> bool { - matches!(self.as_ref(), crate::r#_Wrappers_Compile::Outcome::Fail{ .. }) - } - pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<_U, E>::Failure { - error: self.error().clone() - }) - } - pub fn error(&self) -> &E { - match self { - Outcome::Pass{} => panic!("field does not exist on this variant"), - Outcome::Fail{error, } => error, - } - } - } - - impl Debug - for Outcome { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Outcome { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Outcome::Pass{} => { - write!(_formatter, "Wrappers_Compile.Outcome.Pass")?; - Ok(()) - }, - Outcome::Fail{error, } => { - write!(_formatter, "Wrappers_Compile.Outcome.Fail(")?; - ::dafny_runtime::DafnyPrint::fmt_print(error, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for Outcome {} - - impl Hash - for Outcome { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Outcome::Pass{} => { - - }, - Outcome::Fail{error, } => { - ::std::hash::Hash::hash(error, _state) - }, - } - } - } - - impl Default - for Outcome { - fn default() -> Outcome { - Outcome::Pass {} - } - } - - impl AsRef> - for &Outcome { - fn as_ref(&self) -> Self { - self - } - } -} \ No newline at end of file diff --git a/TestModels/Errors/runtimes/rust/src/standard_library_externs.rs b/TestModels/Errors/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/Errors/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/LanguageSpecificLogic/runtimes/rust/src/standard_library_externs.rs b/TestModels/LanguageSpecificLogic/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/LanguageSpecificLogic/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/Refinement/runtimes/rust/src/standard_library_externs.rs b/TestModels/Refinement/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/Refinement/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/Resource/runtimes/rust/src/standard_library_externs.rs b/TestModels/Resource/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/Resource/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/Makefile b/TestModels/SimpleTypes/SimpleBlob/Makefile index b19193a777..c0d33c2e1b 100644 --- a/TestModels/SimpleTypes/SimpleBlob/Makefile +++ b/TestModels/SimpleTypes/SimpleBlob/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/Cargo.toml index 7db289b458..743b97c036 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/Cargo.toml @@ -5,13 +5,19 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies.tokio] +[dev-dependencies] +simple_blob = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client.rs index 0e7fbefea4..71235fc03b 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -13,9 +14,10 @@ impl Client { pub fn from_conf( conf: crate::types::simple_blob_config::SimpleBlobConfig, ) -> Result { - let inner = crate::simple::types::blob::internaldafny::_default::SimpleBlob( - &crate::conversions::simple_blob_config::_simple_blob_config::to_dafny(conf), - ); + let inner = + crate::simple::types::blob::internaldafny::_default::SimpleBlob( + &crate::conversions::simple_blob_config::_simple_blob_config::to_dafny(conf), + ); if matches!( inner.as_ref(), crate::_Wrappers_Compile::Result::Failure { .. } @@ -28,11 +30,11 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } mod get_blob; -mod get_blob_known_value; +mod get_blob_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob.rs index c09128d419..4247bbc32d 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetBlob`](crate::operation::get_blob::builders::GetBlobFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into<::dafny_runtime::Sequence>)`](crate::operation::get_blob::builders::GetBlobFluentBuilder::value) / [`set_value(Option<::dafny_runtime::Sequence>)`](crate::operation::get_blob::builders::GetBlobFluentBuilder::set_value):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_blob::builders::GetBlobFluentBuilder::value) / [`set_value(Option<::aws_smithy_types::Blob>)`](crate::operation::get_blob::builders::GetBlobFluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetBlobOutput`](crate::operation::get_blob::GetBlobOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_blob::GetBlobOutput::value): (undocumented) + /// - [`value(Option<::aws_smithy_types::Blob>)`](crate::operation::get_blob::GetBlobOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_blob::GetBlobError) pub fn get_blob(&self) -> crate::operation::get_blob::builders::GetBlobFluentBuilder { crate::operation::get_blob::builders::GetBlobFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value.rs deleted file mode 100644 index a8831d2421..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value.rs +++ /dev/null @@ -1,17 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -impl super::Client { - /// Constructs a fluent builder for the [`GetBlob`](crate::operation::get_blob_known_value::builders::GetBlobFluentBuilder) operation. - /// - /// - The fluent builder is configurable: - /// - [`value(impl Into<::dafny_runtime::Sequence>)`](crate::operation::get_blob_known_value::builders::GetBlobFluentBuilder::value) / [`set_value(Option<::dafny_runtime::Sequence>)`](crate::operation::get_blob_known_value::builders::GetBlobFluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetBlobOutput`](crate::operation::get_blob_known_value::GetBlobOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_blob_known_value::GetBlobOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_blob_known_value::GetBlobError) - pub fn get_blob_known_value( - &self, - ) -> crate::operation::get_blob_known_value::builders::GetBlobKnownValueFluentBuilder { - crate::operation::get_blob_known_value::builders::GetBlobKnownValueFluentBuilder::new( - self.clone(), - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value_test.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value_test.rs new file mode 100644 index 0000000000..eec5e197f0 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value_test.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +impl super::Client { + /// Constructs a fluent builder for the [`GetBlobKnownValueTest`](crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder) operation. + /// + /// - The fluent builder is configurable: + /// - [`value(impl Into>)`](crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder::value) / [`set_value(Option<::aws_smithy_types::Blob>)`](crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetBlobOutput`](crate::operation::get_blob_known_value_test::GetBlobOutput) with field(s): + /// - [`value(Option<::aws_smithy_types::Blob>)`](crate::operation::get_blob_known_value_test::GetBlobOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError) + pub fn get_blob_known_value_test(&self) -> crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder { + crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder::new(self.clone()) + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions.rs index 1cd4ad224e..cf1c199d5b 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions.rs @@ -1,6 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_blob; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod get_blob_known_value; + pub mod get_blob; -pub mod simple_blob_config; + pub mod get_blob_known_value_test; + + pub mod simple_blob_config; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..6d52bba84a --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::blob::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob.rs index 43479fd3c9..d38674b069 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] @@ -7,14 +8,9 @@ pub fn to_dafny_error( value: crate::operation::get_blob::GetBlobError, ) -> ::std::rc::Rc { match value { - crate::operation::get_blob::GetBlobError::Unhandled(unhandled) => ::std::rc::Rc::new( - crate::r#simple::types::blob::internaldafny::types::Error::Opaque { - obj: ::dafny_runtime::upcast_object()( - ::dafny_runtime::object::new(unhandled), - ), - }, - ), - } + crate::operation::get_blob::GetBlobError::Unhandled(unhandled) => + ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) + } } #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_input.rs index 4e91b06d53..d37000fe2b 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_input.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_input.rs @@ -1,42 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_blob::GetBlobInput, -) -> ::std::rc::Rc -{ - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&v, |x| *x), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +) -> ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobInput, +>{ ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobInput::GetBlobInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::oblob_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::blob::internaldafny::types::GetBlobInput, >, ) -> crate::operation::get_blob::GetBlobInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - ::std::rc::Rc::try_unwrap(dafny_value.value().Extract().to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - - crate::operation::get_blob::GetBlobInput { value } + crate::operation::get_blob::GetBlobInput::builder() + .set_value(crate::standard_library_conversions::oblob_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_output.rs index e9770da2c5..a36a0e65c7 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_output.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_output.rs @@ -1,43 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_blob::GetBlobOutput, -) -> ::std::rc::Rc -{ - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&b, |e| *e), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +) -> ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, +>{ ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobOutput::GetBlobOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::oblob_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, >, ) -> crate::operation::get_blob::GetBlobOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), - |e| *e, - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_blob::GetBlobOutput { value } + crate::operation::get_blob::GetBlobOutput::builder() + .set_value(crate::standard_library_conversions::oblob_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value.rs deleted file mode 100644 index 50a67357d0..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value.rs +++ /dev/null @@ -1,39 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -use std::any::Any; - -#[allow(dead_code)] -pub fn to_dafny_error( - value: crate::operation::get_blob_known_value::GetBlobKnownValueError, -) -> ::std::rc::Rc { - match value { - crate::operation::get_blob_known_value::GetBlobKnownValueError::Unhandled(unhandled) => { - ::std::rc::Rc::new( - crate::r#simple::types::blob::internaldafny::types::Error::Opaque { - obj: ::dafny_runtime::upcast_object()( - ::dafny_runtime::object::new(unhandled), - ), - }, - ) - } - } -} - -#[allow(dead_code)] -pub fn from_dafny_error( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::Error, - >, -) -> crate::operation::get_blob_known_value::GetBlobKnownValueError { - // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error - if matches!(&dafny_value.as_ref(), crate::r#simple::types::blob::internaldafny::types::Error::CollectionOfErrors { .. }) { - let error_message = "TODO: can't get message yet"; - crate::operation::get_blob_known_value::GetBlobKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) - } else { - crate::operation::get_blob_known_value::GetBlobKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) - } -} - -pub mod _get_blob_known_value_input; - -pub mod _get_blob_known_value_output; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_input.rs deleted file mode 100644 index 1e939e99a8..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_input.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_blob_known_value::GetBlobKnownValueInput, -) -> ::std::rc::Rc -{ - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&v, |x| *x), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobInput::GetBlobInput { - value: ::std::rc::Rc::new(dafny_value) - }) -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::GetBlobInput, - >, -) -> crate::operation::get_blob_known_value::GetBlobKnownValueInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - ::std::rc::Rc::try_unwrap(dafny_value.value().Extract().to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_blob_known_value::GetBlobKnownValueInput { value } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_output.rs deleted file mode 100644 index 19cf635501..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_output.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_blob_known_value::GetBlobKnownValueOutput, -) -> ::std::rc::Rc -{ - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&v, |e| *e), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobOutput::GetBlobOutput { - value: ::std::rc::Rc::new(dafny_value) - }) -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, - >, -) -> crate::operation::get_blob_known_value::GetBlobKnownValueOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), - |e| *e, - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_blob_known_value::GetBlobKnownValueOutput { value } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test.rs new file mode 100644 index 0000000000..7ff941094b --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test.rs @@ -0,0 +1,33 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +#[allow(dead_code)] +pub fn to_dafny_error( + value: crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError, +) -> ::std::rc::Rc { + match value { + crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError::Unhandled(unhandled) => + ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) + } +} + +#[allow(dead_code)] +pub fn from_dafny_error( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::Error, + >, +) -> crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError { + // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error + if matches!(&dafny_value.as_ref(), crate::r#simple::types::blob::internaldafny::types::Error::CollectionOfErrors { .. }) { + let error_message = "TODO: can't get message yet"; + crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) + } else { + crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) + } +} + +pub mod _get_blob_known_value_test_input; + +pub mod _get_blob_known_value_test_output; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_input.rs new file mode 100644 index 0000000000..49d2466ee7 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_input.rs @@ -0,0 +1,24 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_blob_known_value_test::GetBlobInput, +) -> ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobInput, +>{ + ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobInput::GetBlobInput { + value: crate::standard_library_conversions::oblob_to_dafny(&value.value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobInput, + >, +) -> crate::operation::get_blob_known_value_test::GetBlobInput { + crate::operation::get_blob_known_value_test::GetBlobInput::builder() + .set_value(crate::standard_library_conversions::oblob_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_output.rs new file mode 100644 index 0000000000..499929ee0a --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_output.rs @@ -0,0 +1,24 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_blob_known_value_test::GetBlobOutput, +) -> ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, +>{ + ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobOutput::GetBlobOutput { + value: crate::standard_library_conversions::oblob_to_dafny(&value.value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, + >, +) -> crate::operation::get_blob_known_value_test::GetBlobOutput { + crate::operation::get_blob_known_value_test::GetBlobOutput::builder() + .set_value(crate::standard_library_conversions::oblob_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config.rs index 89599c3f8c..7852c4ae19 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_blob_config; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config/_simple_blob_config.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config/_simple_blob_config.rs index d0a4cd5c44..a9e1abdffe 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config/_simple_blob_config.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config/_simple_blob_config.rs @@ -1,10 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_blob_config::SimpleBlobConfig, -) -> ::std::rc::Rc -{ +) -> ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::SimpleBlobConfig, +> { ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::SimpleBlobConfig::SimpleBlobConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/lib.rs deleted file mode 100644 index 3938142e1c..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub mod implementation_from_dafny; - -pub use client::Client; -pub use types::simple_blob_config::SimpleBlobConfig; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation.rs index a72267eda2..64ee269b55 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation.rs @@ -1,7 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetBlob` operation. pub mod get_blob; -/// Types for the `GetBlobKnownValue` operation. -pub mod get_blob_known_value; +/// Types for the `GetBlobKnownValueTest` operation. +pub mod get_blob_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob.rs index 2c923f1aa7..037e8b83af 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetBlob`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -16,14 +18,17 @@ impl GetBlob { crate::operation::get_blob::GetBlobError, > { let inner_input = crate::conversions::get_blob::_get_blob_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetBlob(&inner_input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetBlob(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - Ok(crate::conversions::get_blob::_get_blob_output::from_dafny( - inner_result.value().clone(), - )) + Ok( + crate::conversions::get_blob::_get_blob_output::from_dafny( + inner_result.value().clone(), + ), + ) } else { Err(crate::conversions::get_blob::from_dafny_error( inner_result.error().clone(), @@ -134,9 +139,9 @@ pub use crate::operation::get_blob::_get_blob_output::GetBlobOutput; pub use crate::operation::get_blob::_get_blob_input::GetBlobInput; -mod _get_blob_input; +pub(crate) mod _get_blob_output; -mod _get_blob_output; +pub(crate) mod _get_blob_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_input.rs index 6a0d554b13..335f1e1a36 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_input.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_input.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetBlobInput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, +pub value: ::std::option::Option<::aws_smithy_types::Blob>, } impl GetBlobInput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::Blob> { + self.value.clone() +} } impl GetBlobInput { /// Creates a new builder-style object to manufacture [`GetBlobInput`](crate::operation::operation::GetBlobInput). @@ -25,29 +27,23 @@ impl GetBlobInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetBlobInputBuilder { - pub(crate) value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, + pub(crate) value: ::std::option::Option<::aws_smithy_types::Blob>, } impl GetBlobInputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { - self.value.as_ref() - } +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { + &self.value +} /// Consumes the builder and constructs a [`GetBlobInput`](crate::operation::operation::GetBlobInput). pub fn build( self, @@ -55,6 +51,8 @@ impl GetBlobInputBuilder { crate::operation::get_blob::GetBlobInput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_blob::GetBlobInput { value: self.value }) + ::std::result::Result::Ok(crate::operation::get_blob::GetBlobInput { + value: self.value, + }) } } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_output.rs index b071eb836e..7de15870c4 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_output.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_output.rs @@ -1,19 +1,19 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetBlobOutput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, +pub value: ::std::option::Option<::aws_smithy_types::Blob>, } - impl GetBlobOutput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::Blob> { + self.value.clone() +} } - impl GetBlobOutput { /// Creates a new builder-style object to manufacture [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). pub fn builder() -> crate::operation::get_blob::builders::GetBlobOutputBuilder { @@ -27,33 +27,23 @@ impl GetBlobOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetBlobOutputBuilder { - pub(crate) value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, + pub(crate) value: ::std::option::Option<::aws_smithy_types::Blob>, } - impl GetBlobOutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = input; - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { - self.value.as_ref() - } - +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { + &self.value +} /// Consumes the builder and constructs a [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). pub fn build( self, @@ -61,6 +51,8 @@ impl GetBlobOutputBuilder { crate::operation::get_blob::GetBlobOutput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_blob::GetBlobOutput { value: self.value }) + ::std::result::Result::Ok(crate::operation::get_blob::GetBlobOutput { + value: self.value, + }) } } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/builders.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/builders.rs index bedb57b108..7fd6ca61e8 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/builders.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/builders.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_blob::_get_blob_output::GetBlobOutputBuilder; pub use crate::operation::get_blob::_get_blob_input::GetBlobInputBuilder; @@ -22,7 +24,7 @@ impl GetBlobInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetBlobFluentBuilder { client: crate::client::Client, - inner: crate::operation::get_blob::builders::GetBlobInputBuilder, + pub(crate) inner: crate::operation::get_blob::builders::GetBlobInputBuilder, } impl GetBlobFluentBuilder { /// Creates a new `GetBlob`. @@ -56,23 +58,17 @@ impl GetBlobFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.inner = self.inner.value(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_input.rs deleted file mode 100644 index be28c19c10..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_input.rs +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetBlobKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, -} -impl GetBlobKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { - self.value.as_ref() - } -} -impl GetBlobKnownValueInput { - /// Creates a new builder-style object to manufacture [`GetBlobKnownValueInput`](crate::operation::operation::GetBlobKnownValueInput). - pub fn builder( - ) -> crate::operation::get_blob_known_value::builders::GetBlobKnownValueInputBuilder { - crate::operation::get_blob_known_value::builders::GetBlobKnownValueInputBuilder::default() - } -} - -/// A builder for [`GetBlobKnownValueInput`](crate::operation::operation::GetBlobKnownValueInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetBlobKnownValueInputBuilder { - pub(crate) value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, -} -impl GetBlobKnownValueInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::vec::Vec<::std::primitive::u8>> { - &self.value - } - /// Consumes the builder and constructs a [`GetBlobKnownValueInput`](crate::operation::operation::GetBlobKnownValueInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_blob_known_value::GetBlobKnownValueInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_blob_known_value::GetBlobKnownValueInput { value: self.value }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_output.rs deleted file mode 100644 index 794b83ce46..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_output.rs +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetBlobKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, -} -impl GetBlobKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { - self.value.as_ref() - } -} -impl GetBlobKnownValueOutput { - /// Creates a new builder-style object to manufacture [`GetBlobKnownValueOutput`](crate::operation::operation::GetBlobKnownValueOutput). - pub fn builder( - ) -> crate::operation::get_blob_known_value::builders::GetBlobKnownValueOutputBuilder { - crate::operation::get_blob_known_value::builders::GetBlobKnownValueOutputBuilder::default() - } -} - -/// A builder for [`GetBlobKnownValueOutput`](crate::operation::operation::GetBlobKnownValueOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetBlobKnownValueOutputBuilder { - pub(crate) value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, -} -impl GetBlobKnownValueOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::vec::Vec<::std::primitive::u8>> { - &self.value - } - /// Consumes the builder and constructs a [`GetBlobKnownValueOutput`](crate::operation::operation::GetBlobKnownValueOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_blob_known_value::GetBlobKnownValueOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_blob_known_value::GetBlobKnownValueOutput { value: self.value }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/builders.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/builders.rs deleted file mode 100644 index 274bb3f376..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/builders.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_blob_known_value::_get_blob_known_value_output::GetBlobKnownValueOutputBuilder; - -pub use crate::operation::get_blob_known_value::_get_blob_known_value_input::GetBlobKnownValueInputBuilder; - -impl GetBlobKnownValueInputBuilder { - /// Sends a request with this input using the given client. - pub async fn send_with( - self, - client: &crate::Client, - ) -> ::std::result::Result< - crate::operation::get_blob_known_value::GetBlobKnownValueOutput, - crate::operation::get_blob_known_value::GetBlobKnownValueError, - > { - let mut fluent_builder = client.get_blob_known_value(); - fluent_builder.inner = self; - fluent_builder.send().await - } -} -/// Fluent builder constructing a request to `GetBlobKnownValue`. -/// -#[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct GetBlobKnownValueFluentBuilder { - client: crate::client::Client, - inner: crate::operation::get_blob_known_value::builders::GetBlobKnownValueInputBuilder, -} -impl GetBlobKnownValueFluentBuilder { - /// Creates a new `GetBlobKnownValue`. - pub(crate) fn new(client: crate::client::Client) -> Self { - Self { - client, - inner: ::std::default::Default::default(), - } - } - /// Access the GetBlobKnownValue as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_blob_known_value::builders::GetBlobKnownValueInputBuilder { - &self.inner - } - /// Sends the request and returns the response. - pub async fn send( - self, - ) -> ::std::result::Result< - crate::operation::get_blob_known_value::GetBlobKnownValueOutput, - crate::operation::get_blob_known_value::GetBlobKnownValueError, - > { - let input = self - .inner - .build() - // Using unhandled since GetBlob doesn't declare any validation, - // and smithy-rs seems to not generate a ValidationError case unless there is - // (but isn't that a backwards compatibility problem for output structures?) - // Vanilla smithy-rs uses SdkError::construction_failure, - // but we aren't using SdkError. - .map_err(crate::operation::get_blob_known_value::GetBlobKnownValueError::unhandled)?; - crate::operation::get_blob_known_value::GetBlobKnownValue::send(&self.client, input).await - } - - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.inner = self.inner.value(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::vec::Vec<::std::primitive::u8>> { - self.inner.get_value() - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test.rs similarity index 67% rename from TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value.rs rename to TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test.rs index ee1819d4fd..32709dd754 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test.rs @@ -1,44 +1,46 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -/// Orchestration and serialization glue logic for `GetBlobKnownValue`. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +/// Orchestration and serialization glue logic for `GetBlobKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] -pub struct GetBlobKnownValue; -impl GetBlobKnownValue { - /// Creates a new `GetBlobKnownValue` +pub struct GetBlobKnownValueTest; +impl GetBlobKnownValueTest { + /// Creates a new `GetBlobKnownValueTest` pub fn new() -> Self { Self } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_blob_known_value::GetBlobKnownValueInput, + input: crate::operation::get_blob_known_value_test::GetBlobInput, ) -> ::std::result::Result< - crate::operation::get_blob_known_value::GetBlobKnownValueOutput, - crate::operation::get_blob_known_value::GetBlobKnownValueError, + crate::operation::get_blob_known_value_test::GetBlobOutput, + crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError, > { - let inner_input = - crate::conversions::get_blob_known_value::_get_blob_known_value_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetBlob(&inner_input); + let inner_input = crate::conversions::get_blob_known_value_test::_get_blob_known_value_test_input::to_dafny(input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetBlobKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { Ok( - crate::conversions::get_blob_known_value::_get_blob_known_value_output::from_dafny( + crate::conversions::get_blob_known_value_test::_get_blob_known_value_test_output::from_dafny( inner_result.value().clone(), ), ) } else { - Err(crate::conversions::get_blob_known_value::from_dafny_error( + Err(crate::conversions::get_blob_known_value_test::from_dafny_error( inner_result.error().clone(), )) } } } -/// Error type for the `GetBlobKnownValue` operation. +/// Error type for the `GetBlobKnownValueTest` operation. #[non_exhaustive] #[derive(::std::fmt::Debug)] -pub enum GetBlobKnownValueError { +pub enum GetBlobKnownValueTestError { /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ @@ -46,12 +48,12 @@ pub enum GetBlobKnownValueError { \    `err if err.code() == Some(\"SpecificExceptionCode\") => { /* handle the error */ }` \ - See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetBlobKnownValueError) for what information is available for the error." + See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetBlobKnownValueTestError) for what information is available for the error." )] Unhandled(crate::error::sealed_unhandled::Unhandled), } -impl GetBlobKnownValueError { - /// Creates the `GetBlobKnownValueError::Unhandled` variant from any error type. +impl GetBlobKnownValueTestError { + /// Creates the `GetBlobKnownValueTestError::Unhandled` variant from any error type. pub fn unhandled( err: impl ::std::convert::Into< ::std::boxed::Box< @@ -65,7 +67,7 @@ impl GetBlobKnownValueError { }) } - /// Creates the `GetBlobKnownValueError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). + /// Creates the `GetBlobKnownValueTestError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). pub fn generic(err: ::aws_smithy_types::error::ErrorMetadata) -> Self { Self::Unhandled(crate::error::sealed_unhandled::Unhandled { source: err.clone().into(), @@ -82,14 +84,14 @@ impl GetBlobKnownValueError { } } } -impl ::std::error::Error for GetBlobKnownValueError { +impl ::std::error::Error for GetBlobKnownValueTestError { fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> { match self { Self::Unhandled(_inner) => ::std::option::Option::Some(&*_inner.source), } } } -impl ::std::fmt::Display for GetBlobKnownValueError { +impl ::std::fmt::Display for GetBlobKnownValueTestError { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self { Self::Unhandled(_inner) => { @@ -104,7 +106,7 @@ impl ::std::fmt::Display for GetBlobKnownValueError { } } } -impl ::aws_smithy_types::retry::ProvideErrorKind for GetBlobKnownValueError { +impl ::aws_smithy_types::retry::ProvideErrorKind for GetBlobKnownValueTestError { fn code(&self) -> ::std::option::Option<&str> { ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self) } @@ -112,14 +114,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetBlobKnownValueError { ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetBlobKnownValueError { +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetBlobKnownValueTestError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetBlobKnownValueError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetBlobKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -133,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetBlobK } } -pub use crate::operation::get_blob_known_value::_get_blob_known_value_output::GetBlobKnownValueOutput; +pub use crate::operation::get_blob_known_value_test::_get_blob_output::GetBlobOutput; -pub use crate::operation::get_blob_known_value::_get_blob_known_value_input::GetBlobKnownValueInput; +pub use crate::operation::get_blob_known_value_test::_get_blob_input::GetBlobInput; -mod _get_blob_known_value_input; +pub(crate) mod _get_blob_output; -mod _get_blob_known_value_output; +pub(crate) mod _get_blob_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_input.rs new file mode 100644 index 0000000000..9eb9a55b98 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetBlobInput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::aws_smithy_types::Blob>, +} +impl GetBlobInput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::Blob> { + self.value.clone() +} +} +impl GetBlobInput { + /// Creates a new builder-style object to manufacture [`GetBlobInput`](crate::operation::operation::GetBlobInput). + pub fn builder() -> crate::operation::get_blob_known_value_test::builders::GetBlobInputBuilder { + crate::operation::get_blob_known_value_test::builders::GetBlobInputBuilder::default() + } +} + +/// A builder for [`GetBlobInput`](crate::operation::operation::GetBlobInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetBlobInputBuilder { + pub(crate) value: ::std::option::Option<::aws_smithy_types::Blob>, +} +impl GetBlobInputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { + &self.value +} + /// Consumes the builder and constructs a [`GetBlobInput`](crate::operation::operation::GetBlobInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_blob_known_value_test::GetBlobInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_blob_known_value_test::GetBlobInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_output.rs new file mode 100644 index 0000000000..81cb83d89b --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetBlobOutput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::aws_smithy_types::Blob>, +} +impl GetBlobOutput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::Blob> { + self.value.clone() +} +} +impl GetBlobOutput { + /// Creates a new builder-style object to manufacture [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). + pub fn builder() -> crate::operation::get_blob_known_value_test::builders::GetBlobOutputBuilder { + crate::operation::get_blob_known_value_test::builders::GetBlobOutputBuilder::default() + } +} + +/// A builder for [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetBlobOutputBuilder { + pub(crate) value: ::std::option::Option<::aws_smithy_types::Blob>, +} +impl GetBlobOutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { + &self.value +} + /// Consumes the builder and constructs a [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_blob_known_value_test::GetBlobOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_blob_known_value_test::GetBlobOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/builders.rs new file mode 100644 index 0000000000..b7ef06d065 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/builders.rs @@ -0,0 +1,74 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_blob_known_value_test::_get_blob_output::GetBlobOutputBuilder; + +pub use crate::operation::get_blob_known_value_test::_get_blob_input::GetBlobInputBuilder; + +impl GetBlobInputBuilder { + /// Sends a request with this input using the given client. + pub async fn send_with( + self, + client: &crate::Client, + ) -> ::std::result::Result< + crate::operation::get_blob_known_value_test::GetBlobOutput, + crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError, + > { + let mut fluent_builder = client.get_blob_known_value_test(); + fluent_builder.inner = self; + fluent_builder.send().await + } +} +/// Fluent builder constructing a request to `GetBlobKnownValueTest`. +/// +#[derive(::std::clone::Clone, ::std::fmt::Debug)] +pub struct GetBlobKnownValueTestFluentBuilder { + client: crate::client::Client, + pub(crate) inner: crate::operation::get_blob_known_value_test::builders::GetBlobInputBuilder, +} +impl GetBlobKnownValueTestFluentBuilder { + /// Creates a new `GetBlobKnownValueTest`. + pub(crate) fn new(client: crate::client::Client) -> Self { + Self { + client, + inner: ::std::default::Default::default(), + } + } + /// Access the GetBlobKnownValueTest as a reference. + pub fn as_input(&self) -> &crate::operation::get_blob_known_value_test::builders::GetBlobInputBuilder { + &self.inner + } + /// Sends the request and returns the response. + pub async fn send( + self, + ) -> ::std::result::Result< + crate::operation::get_blob_known_value_test::GetBlobOutput, + crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError, + > { + let input = self + .inner + .build() + // Using unhandled since GetBlobKnownValueTest doesn't declare any validation, + // and smithy-rs seems to not generate a ValidationError case unless there is + // (but isn't that a backwards compatibility problem for output structures?) + // Vanilla smithy-rs uses SdkError::construction_failure, + // but we aren't using SdkError. + .map_err(crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError::unhandled)?; + crate::operation::get_blob_known_value_test::GetBlobKnownValueTest::send(&self.client, input).await + } + + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { + self.inner.get_value() +} +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types.rs index 1dca219a01..ce57ffa44f 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `SimpleBlobConfig` pub mod simple_blob_config; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types/simple_blob_config.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types/simple_blob_config.rs index 0709ccb7ee..8386df9739 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types/simple_blob_config.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types/simple_blob_config.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleBlobConfig {} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..5c03253bfb --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::blob::internaldafny::wrapped::_default { + pub fn WrappedSimpleBlob(config: &::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::SimpleBlobConfig, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..1cfbbbb813 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,119 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::blob::internaldafny::types::ISimpleTypesBlobClient); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::SimpleBlobConfig, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_blob_config::_simple_blob_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::blob::internaldafny::types::ISimpleTypesBlobClient for Client { + fn GetBlob( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_blob::_get_blob_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_blob::GetBlob::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_blob::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_blob::_get_blob_output::to_dafny(client), + }, + ), + } + } + + fn GetBlobKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_blob_known_value_test::_get_blob_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_blob_known_value_test::GetBlobKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_blob_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_blob_known_value_test::_get_blob_known_value_test_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/tests/simple_blob_test.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/tests/simple_blob_test.rs index bf6ce9675d..b9c9ed9970 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/tests/simple_blob_test.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/tests/simple_blob_test.rs @@ -32,11 +32,11 @@ use simple_blob::*; */ #[tokio::test] async fn test_get_blob() { - let s = vec![0x0, 0x1, 0x2]; + let s = aws_smithy_types::Blob::new(vec![0x0, 0x1, 0x2]); let result = client().get_blob().value(s.clone()).send().await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, &s); + assert_eq!(value, s); } /* @@ -64,15 +64,15 @@ async fn test_get_blob() { #[tokio::test] async fn test_get_known_value() { - let s = vec![0x0, 0x2, 0x4]; + let s = aws_smithy_types::Blob::new(vec![0x0, 0x2, 0x4]); let result = client() - .get_blob_known_value() + .get_blob_known_value_test() .value(s.clone()) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, &s); + assert_eq!(value, s); } pub fn client() -> Client { diff --git a/TestModels/SimpleTypes/SimpleBoolean/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleBoolean/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBoolean/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleDouble/Makefile b/TestModels/SimpleTypes/SimpleDouble/Makefile index 75eec0f36c..722e7e5411 100644 --- a/TestModels/SimpleTypes/SimpleDouble/Makefile +++ b/TestModels/SimpleTypes/SimpleDouble/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/Cargo.toml index 3bb72ebe2d..0135a1e231 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/Cargo.toml @@ -5,13 +5,19 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies.tokio] +[dev-dependencies] +simple_double = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client.rs index 5827083463..a858580317 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -29,7 +30,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client/get_double.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client/get_double.rs index db3ce635ea..a41fdf754f 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client/get_double.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client/get_double.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetDouble`](crate::operation::get_double::builders::GetDoubleFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(f64)`](crate::operation::get_double::builders::GetDoubleFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_double::builders::GetDoubleFluentBuilder::set_value):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_double::builders::GetDoubleFluentBuilder::value) / [`set_value(Option<::std::primitive::f64>)`](crate::operation::get_double::builders::GetDoubleFluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetDoubleOutput`](crate::operation::get_double::GetDoubleOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_double::GetDoubleOutput::value): (undocumented) + /// - [`value(Option<::std::primitive::f64>)`](crate::operation::get_double::GetDoubleOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_double::GetDoubleError) pub fn get_double(&self) -> crate::operation::get_double::builders::GetDoubleFluentBuilder { crate::operation::get_double::builders::GetDoubleFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions.rs index 08430ee335..f861ad1749 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions.rs @@ -1,4 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_double; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod simple_double_config; + pub mod get_double; + + pub mod simple_double_config; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..1003d3aed9 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::smithydouble::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double.rs index 45f3afc17c..e886c559a7 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double.rs @@ -1,12 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_double::GetDoubleError, -) -> ::std::rc::Rc -{ +) -> ::std::rc::Rc { match value { crate::operation::get_double::GetDoubleError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithydouble::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_input.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_input.rs index 1a6a82f8ef..a0b6588355 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_input.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_input.rs @@ -1,47 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_double::GetDoubleInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::dafny_runtime::Sequence::ArraySequence { - values: std::rc::Rc::new(f64::to_be_bytes(v).to_vec()), - }, - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleInput::GetDoubleInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::odouble_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleInput, >, ) -> crate::operation::get_double::GetDoubleInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - let my_vec = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), - |x| *x, - ); - Some(f64::from_be_bytes( - my_vec.try_into().expect("Error converting Sequence to f64"), - )) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_double::GetDoubleInput { value } + crate::operation::get_double::GetDoubleInput::builder() + .set_value(crate::standard_library_conversions::odouble_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_output.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_output.rs index 5dcd0eb48a..6607d6788e 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_output.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_output.rs @@ -1,47 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_double::GetDoubleOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleOutput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::dafny_runtime::Sequence::ArraySequence { - values: std::rc::Rc::new(f64::to_be_bytes(v).to_vec()), - }, - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleOutput::GetDoubleOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::odouble_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleOutput, >, ) -> crate::operation::get_double::GetDoubleOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - let my_vec = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), - |x| *x, - ); - Some(f64::from_be_bytes( - my_vec.try_into().expect("Error converting Sequence to f64"), - )) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_double::GetDoubleOutput { value } + crate::operation::get_double::GetDoubleOutput::builder() + .set_value(crate::standard_library_conversions::odouble_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config.rs index 52a68a7b0e..4289c31fa4 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_double_config; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config/_simple_double_config.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config/_simple_double_config.rs index f726f08b6d..4dd5aa6c03 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config/_simple_double_config.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config/_simple_double_config.rs @@ -1,10 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_double_config::SimpleDoubleConfig, ) -> ::std::rc::Rc< - crate::simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig, + crate::r#simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig, > { ::std::rc::Rc::new(crate::r#simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig::SimpleDoubleConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/lib.rs deleted file mode 100644 index 94379fc047..0000000000 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub mod implementation_from_dafny; - -pub use client::Client; -pub use types::simple_double_config::SimpleDoubleConfig; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation.rs index 134175f816..3b489e6c92 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetDouble` operation. pub mod get_double; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double.rs index 8b6d980d91..38c65eb849 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetDouble`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -137,9 +139,9 @@ pub use crate::operation::get_double::_get_double_output::GetDoubleOutput; pub use crate::operation::get_double::_get_double_input::GetDoubleInput; -mod _get_double_input; +pub(crate) mod _get_double_output; -mod _get_double_output; +pub(crate) mod _get_double_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_input.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_input.rs index af1cc4102d..598b2c0b07 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_input.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_input.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetDoubleInput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option<::std::primitive::f64>, } impl GetDoubleInput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&f64> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option<::std::primitive::f64> { + self.value +} } impl GetDoubleInput { /// Creates a new builder-style object to manufacture [`GetDoubleInput`](crate::operation::operation::GetDoubleInput). @@ -25,23 +27,23 @@ impl GetDoubleInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetDoubleInputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option<::std::primitive::f64>, } impl GetDoubleInputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::f64>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::f64>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::f64> { + &self.value +} /// Consumes the builder and constructs a [`GetDoubleInput`](crate::operation::operation::GetDoubleInput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_output.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_output.rs index bf850acd35..20305255c7 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_output.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_output.rs @@ -1,19 +1,19 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetDoubleOutput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option<::std::primitive::f64>, } - impl GetDoubleOutput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } +pub fn value(&self) -> ::std::option::Option<::std::primitive::f64> { + self.value +} } - impl GetDoubleOutput { /// Creates a new builder-style object to manufacture [`GetDoubleOutput`](crate::operation::operation::GetDoubleOutput). pub fn builder() -> crate::operation::get_double::builders::GetDoubleOutputBuilder { @@ -27,27 +27,23 @@ impl GetDoubleOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetDoubleOutputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option<::std::primitive::f64>, } - impl GetDoubleOutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } - +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::f64>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::f64>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::f64> { + &self.value +} /// Consumes the builder and constructs a [`GetDoubleOutput`](crate::operation::operation::GetDoubleOutput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/builders.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/builders.rs index ed9fd9a40b..dd6f7e015f 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/builders.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/builders.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_double::_get_double_output::GetDoubleOutputBuilder; pub use crate::operation::get_double::_get_double_input::GetDoubleInputBuilder; @@ -22,7 +24,7 @@ impl GetDoubleInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetDoubleFluentBuilder { client: crate::client::Client, - inner: crate::operation::get_double::builders::GetDoubleInputBuilder, + pub(crate) inner: crate::operation::get_double::builders::GetDoubleInputBuilder, } impl GetDoubleFluentBuilder { /// Creates a new `GetDouble`. @@ -56,17 +58,17 @@ impl GetDoubleFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: f64) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::f64>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::f64>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::f64> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types.rs index 92447294d0..3154f39ef3 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `SimpleDoubleConfig` pub mod simple_double_config; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types/simple_double_config.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types/simple_double_config.rs index b776656296..46db0da2e6 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types/simple_double_config.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types/simple_double_config.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleDoubleConfig {} diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..2b7522dd24 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::smithydouble::internaldafny::wrapped::_default { + pub fn WrappedSimpleDouble(config: &::std::rc::Rc< + crate::r#simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..281878c6a9 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,89 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::smithydouble::internaldafny::types::ISimpleTypesDoubleClient); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_double_config::_simple_double_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::smithydouble::internaldafny::types::ISimpleTypesDoubleClient for Client { + fn GetDouble( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_double::_get_double_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_double::GetDouble::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_double::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_double::_get_double_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/Makefile b/TestModels/SimpleTypes/SimpleEnum/Makefile index a9e1e6bec8..3a51f57190 100644 --- a/TestModels/SimpleTypes/SimpleEnum/Makefile +++ b/TestModels/SimpleTypes/SimpleEnum/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/Cargo.toml index a3026b8a68..fb5b567bbf 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/Cargo.toml @@ -5,13 +5,19 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies.tokio] +[dev-dependencies] +simple_enum = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client.rs index 9649346b6f..3357e68544 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -29,7 +30,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } @@ -37,5 +38,7 @@ impl Client { mod get_enum; mod get_enum_first_known_value_test; + mod get_enum_second_known_value_test; + mod get_enum_third_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum.rs index f0c395251e..1f8ad39bc1 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetEnum`](crate::operation::get_enum::builders::GetEnumFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumShape)`](crate::operation::get_enum::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum::builders::GetEnumFluentBuilder::set_value):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_enum::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum::builders::GetEnumFluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum::GetEnumOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_enum::GetEnumOutput::value): (undocumented) + /// - [`value(Option)`](crate::operation::get_enum::GetEnumOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_enum::GetEnumError) pub fn get_enum(&self) -> crate::operation::get_enum::builders::GetEnumFluentBuilder { crate::operation::get_enum::builders::GetEnumFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_first_known_value_test.rs index a169931d82..fe5b423fa2 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_first_known_value_test.rs @@ -1,18 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { - /// Constructs a fluent builder for the [`GetEnum`](crate::operation::get_enum_first_known_value::builders::GetEnumFluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumFirstKnownValueTest`](crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumShape)`](crate::operation::get_enum_first_known_value::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_first_known_value::builders::GetEnumFluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_first_known_value::GetEnumOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_first_known_value::GetEnumOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_first_known_value::GetEnumError) - pub fn get_enum_first_known_value_test( - &self, - ) -> crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder - { - crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder::new( - self.clone(), - ) + /// - [`value(impl Into>)`](crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_first_known_value_test::GetEnumOutput) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_first_known_value_test::GetEnumOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError) + pub fn get_enum_first_known_value_test(&self) -> crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder { + crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_second_known_value_test.rs index 8e4ec068d2..4e9a16e551 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_second_known_value_test.rs @@ -1,18 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { - /// Constructs a fluent builder for the [`GetEnum`](crate::operation::get_enum_second_known_value::builders::GetEnumFluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumSecondKnownValueTest`](crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumShape)`](crate::operation::get_enum_second_known_value::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_second_known_value::builders::GetEnumFluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_second_known_value::GetEnumOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_second_known_value::GetEnumOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_second_known_value::GetEnumError) - pub fn get_enum_second_known_value_test( - &self, - ) -> crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder - { - crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder::new( - self.clone(), - ) + /// - [`value(impl Into>)`](crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_second_known_value_test::GetEnumOutput) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_second_known_value_test::GetEnumOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError) + pub fn get_enum_second_known_value_test(&self) -> crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder { + crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_third_known_value_test.rs index 47bdeb2fd5..01060bfee7 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_third_known_value_test.rs @@ -1,18 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { - /// Constructs a fluent builder for the [`GetEnum`](crate::operation::get_enum_third_known_value::builders::GetEnumFluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumThirdKnownValueTest`](crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumShape)`](crate::operation::get_enum_third_known_value::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_third_known_value::builders::GetEnumFluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_third_known_value::GetEnumOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_third_known_value::GetEnumOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_third_known_value::GetEnumError) - pub fn get_enum_third_known_value_test( - &self, - ) -> crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder - { - crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder::new( - self.clone(), - ) + /// - [`value(impl Into>)`](crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_third_known_value_test::GetEnumOutput) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_third_known_value_test::GetEnumOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError) + pub fn get_enum_third_known_value_test(&self) -> crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder { + crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions.rs index 7361ee56f3..23444400ba 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions.rs @@ -1,9 +1,16 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_enum; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod get_enum_first_known_value_test; -pub mod get_enum_second_known_value_test; -pub mod get_enum_third_known_value_test; + pub mod get_enum; -pub mod simple_enum_config; -pub mod simple_enum_shape; + pub mod get_enum_first_known_value_test; + + pub mod get_enum_second_known_value_test; + + pub mod get_enum_third_known_value_test; + + pub mod simple_enum_config; + + pub mod simple_enum_shape; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..b16869c834 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::smithyenum::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum.rs index ef493d1195..6d75d851f5 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_input.rs index 3bbf16021f..6d65b89526 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_input.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_enum::GetEnumInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput::GetEnumInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, >, ) -> crate::operation::get_enum::GetEnumInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum::GetEnumInput { value } + crate::operation::get_enum::GetEnumInput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_output.rs index 1ae04378cc..8511c2d0ba 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_output.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_enum::GetEnumOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput::GetEnumOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, >, ) -> crate::operation::get_enum::GetEnumOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum::GetEnumOutput { value } + crate::operation::get_enum::GetEnumOutput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test.rs index 5e3e946f36..51b4ad7bd9 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs index 453989647e..bd024fe5c6 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput, + value: crate::operation::get_enum_first_known_value_test::GetEnumInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput::GetEnumInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, >, -) -> crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput { value } +) -> crate::operation::get_enum_first_known_value_test::GetEnumInput { + crate::operation::get_enum_first_known_value_test::GetEnumInput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs index c31403c9c8..0b94ed08ad 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, + value: crate::operation::get_enum_first_known_value_test::GetEnumOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput::GetEnumOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, >, -) -> crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput { value } +) -> crate::operation::get_enum_first_known_value_test::GetEnumOutput { + crate::operation::get_enum_first_known_value_test::GetEnumOutput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test.rs index afa0c42cd6..37724a3683 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs index c73d8a6308..0124095fbf 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput, + value: crate::operation::get_enum_second_known_value_test::GetEnumInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput::GetEnumInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, >, -) -> crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput { value } +) -> crate::operation::get_enum_second_known_value_test::GetEnumInput { + crate::operation::get_enum_second_known_value_test::GetEnumInput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs index fbb2809ed3..6f9b39a9ab 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, + value: crate::operation::get_enum_second_known_value_test::GetEnumOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput::GetEnumOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, >, -) -> crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput { value } +) -> crate::operation::get_enum_second_known_value_test::GetEnumOutput { + crate::operation::get_enum_second_known_value_test::GetEnumOutput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test.rs index b3d8d1186e..8860c8548a 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs index 73c9d9b6f0..bf7ce0415c 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput, + value: crate::operation::get_enum_third_known_value_test::GetEnumInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput::GetEnumInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, >, -) -> crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput { value } +) -> crate::operation::get_enum_third_known_value_test::GetEnumInput { + crate::operation::get_enum_third_known_value_test::GetEnumInput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs index aafc1403e6..0199b60a8e 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, + value: crate::operation::get_enum_third_known_value_test::GetEnumOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput::GetEnumOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, >, -) -> crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput { value } +) -> crate::operation::get_enum_third_known_value_test::GetEnumOutput { + crate::operation::get_enum_third_known_value_test::GetEnumOutput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config.rs index 973679ee23..6b6b7d9e31 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_enum_config; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config/_simple_enum_config.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config/_simple_enum_config.rs index a1e48e7f0e..3fcaeb06a4 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config/_simple_enum_config.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config/_simple_enum_config.rs @@ -1,10 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_enum_config::SimpleEnumConfig, ) -> ::std::rc::Rc< - crate::simple::types::smithyenum::internaldafny::types::SimpleEnumConfig, + crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumConfig, > { ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumConfig::SimpleEnumConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape.rs index f531b5531f..994d63ed8a 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape.rs @@ -1,3 +1,25 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] -pub mod _simple_enum_shape; +pub fn to_dafny( + value: crate::types::SimpleEnumShape, +) -> ::std::rc::Rc{ + ::std::rc::Rc::new(match value { + crate::types::SimpleEnumShape::First => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::FIRST {}, +crate::types::SimpleEnumShape::Second => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::SECOND {}, +crate::types::SimpleEnumShape::Third => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::THIRD {}, + _ => panic!("Unknown enum variant: {}", value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: &crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape, +) -> crate::types::SimpleEnumShape { + match dafny_value { + crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::FIRST {} => crate::types::SimpleEnumShape::First, +crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::SECOND {} => crate::types::SimpleEnumShape::Second, +crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::THIRD {} => crate::types::SimpleEnumShape::Third, + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape/_simple_enum_shape.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape/_simple_enum_shape.rs deleted file mode 100644 index 8519605a7c..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape/_simple_enum_shape.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] - -pub fn to_dafny( - value: &crate::types::simple_enum_shape::SimpleEnumShape, -) -> crate::simple::types::smithyenum::internaldafny::types::SimpleEnumShape { - match value { - crate::types::simple_enum_shape::SimpleEnumShape::FIRST => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::FIRST {}, - crate::types::simple_enum_shape::SimpleEnumShape::SECOND => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::SECOND {}, - crate::types::simple_enum_shape::SimpleEnumShape::THIRD => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::THIRD {}, - } -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: &crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape, -) -> crate::types::simple_enum_shape::SimpleEnumShape { - match dafny_value { - crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::FIRST {} => crate::types::simple_enum_shape::SimpleEnumShape::FIRST, - crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::SECOND {} => crate::types::simple_enum_shape::SimpleEnumShape::SECOND, - crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::THIRD {} => crate::types::simple_enum_shape::SimpleEnumShape::THIRD, - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/lib.rs deleted file mode 100644 index f914e7ba96..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub mod implementation_from_dafny; - -pub use client::Client; -pub use types::simple_enum_config::SimpleEnumConfig; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation.rs index 560af2715d..febf44fb04 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation.rs @@ -1,9 +1,14 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetEnum` operation. pub mod get_enum; -/// Types for the `GetEnumKnownValue` operation. +/// Types for the `GetEnumFirstKnownValueTest` operation. pub mod get_enum_first_known_value_test; + +/// Types for the `GetEnumSecondKnownValueTest` operation. pub mod get_enum_second_known_value_test; + +/// Types for the `GetEnumThirdKnownValueTest` operation. pub mod get_enum_third_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum.rs index d75b5ac448..58f7c64109 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnum`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -16,14 +18,17 @@ impl GetEnum { crate::operation::get_enum::GetEnumError, > { let inner_input = crate::conversions::get_enum::_get_enum_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - Ok(crate::conversions::get_enum::_get_enum_output::from_dafny( - inner_result.value().clone(), - )) + Ok( + crate::conversions::get_enum::_get_enum_output::from_dafny( + inner_result.value().clone(), + ), + ) } else { Err(crate::conversions::get_enum::from_dafny_error( inner_result.error().clone(), @@ -134,9 +139,9 @@ pub use crate::operation::get_enum::_get_enum_output::GetEnumOutput; pub use crate::operation::get_enum::_get_enum_input::GetEnumInput; -mod _get_enum_input; +pub(crate) mod _get_enum_output; -mod _get_enum_output; +pub(crate) mod _get_enum_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_input.rs index 37b1f16c17..5308a7b969 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_input.rs @@ -1,19 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetEnumInput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option, } impl GetEnumInput { #[allow(missing_docs)] // documentation missing in model - pub fn message( - &self, - ) -> ::std::option::Option<&crate::types::simple_enum_shape::SimpleEnumShape> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} } impl GetEnumInput { /// Creates a new builder-style object to manufacture [`GetEnumInput`](crate::operation::operation::GetEnumInput). @@ -28,31 +27,23 @@ impl GetEnumInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetEnumInputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option, } impl GetEnumInputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} /// Consumes the builder and constructs a [`GetEnumInput`](crate::operation::operation::GetEnumInput). pub fn build( self, @@ -60,6 +51,8 @@ impl GetEnumInputBuilder { crate::operation::get_enum::GetEnumInput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_enum::GetEnumInput { value: self.value }) + ::std::result::Result::Ok(crate::operation::get_enum::GetEnumInput { + value: self.value, + }) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_output.rs index 9675cc2c25..7a05b95d39 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_output.rs @@ -1,20 +1,19 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetEnumOutput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option, } - impl GetEnumOutput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} } - impl GetEnumOutput { /// Creates a new builder-style object to manufacture [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). pub fn builder() -> crate::operation::get_enum::builders::GetEnumOutputBuilder { @@ -28,35 +27,23 @@ impl GetEnumOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetEnumOutputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option, } - impl GetEnumOutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} /// Consumes the builder and constructs a [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). pub fn build( self, @@ -64,6 +51,8 @@ impl GetEnumOutputBuilder { crate::operation::get_enum::GetEnumOutput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_enum::GetEnumOutput { value: self.value }) + ::std::result::Result::Ok(crate::operation::get_enum::GetEnumOutput { + value: self.value, + }) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/builders.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/builders.rs index 11e371c133..34ee4503e4 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/builders.rs @@ -1,7 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum::_get_enum_input::GetEnumInputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_enum::_get_enum_output::GetEnumOutputBuilder; +pub use crate::operation::get_enum::_get_enum_input::GetEnumInputBuilder; + impl GetEnumInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( @@ -21,7 +24,7 @@ impl GetEnumInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumFluentBuilder { client: crate::client::Client, - inner: crate::operation::get_enum::builders::GetEnumInputBuilder, + pub(crate) inner: crate::operation::get_enum::builders::GetEnumInputBuilder, } impl GetEnumFluentBuilder { /// Creates a new `GetEnum`. @@ -55,22 +58,17 @@ impl GetEnumFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_shape::SimpleEnumShape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test.rs index 106ec1702c..43bf7cd236 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnumFirstKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,14 +12,14 @@ impl GetEnumFirstKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput, + input: crate::operation::get_enum_first_known_value_test::GetEnumInput, ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, + crate::operation::get_enum_first_known_value_test::GetEnumOutput, crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError, > { - let inner_input = - crate::conversions::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); + let inner_input = crate::conversions::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::to_dafny(input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumFirstKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -28,11 +30,9 @@ impl GetEnumFirstKnownValueTest { ), ) } else { - Err( - crate::conversions::get_enum_first_known_value_test::from_dafny_error( - inner_result.error().clone(), - ), - ) + Err(crate::conversions::get_enum_first_known_value_test::from_dafny_error( + inner_result.error().clone(), + )) } } } @@ -41,7 +41,7 @@ impl GetEnumFirstKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumFirstKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unfirst_known error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -121,9 +121,7 @@ impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumFirstK } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError - for GetEnumFirstKnownValueTestError -{ +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumFirstKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -137,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError } } -pub use crate::operation::get_enum_first_known_value_test::_get_enum_first_known_value_test_output::GetEnumFirstKnownValueTestOutput; +pub use crate::operation::get_enum_first_known_value_test::_get_enum_output::GetEnumOutput; -pub use crate::operation::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::GetEnumFirstKnownValueTestInput; +pub use crate::operation::get_enum_first_known_value_test::_get_enum_input::GetEnumInput; -mod _get_enum_first_known_value_test_input; +pub(crate) mod _get_enum_output; -mod _get_enum_first_known_value_test_output; +pub(crate) mod _get_enum_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs deleted file mode 100644 index 866727550e..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumFirstKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumFirstKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetEnumFirstKnownValueTestInput { - /// Creates a new builder-style object to manufacture [`GetEnumFirstKnownValueTestInput`](crate::operation::operation::GetEnumFirstKnownValueTestInput). - pub fn builder( - ) -> crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestInputBuilder - { - crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestInputBuilder::default() - } -} - -/// A builder for [`GetEnumFirstKnownValueTestInput`](crate::operation::operation::GetEnumFirstKnownValueTestInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumFirstKnownValueTestInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumFirstKnownValueTestInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumFirstKnownValueTestInput`](crate::operation::operation::GetEnumFirstKnownValueTestInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs deleted file mode 100644 index 65154c9626..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumFirstKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumFirstKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetEnumFirstKnownValueTestOutput { - /// Creates a new builder-style object to manufacture [`GetEnumFirstKnownValueTestOutput`](crate::operation::operation::GetEnumFirstKnownValueTestOutput). - pub fn builder( - ) -> crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestOutputBuilder - { - crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestOutputBuilder::default() - } -} - -/// A builder for [`GetEnumFirstKnownValueTestOutput`](crate::operation::operation::GetEnumFirstKnownValueTestOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumFirstKnownValueTestOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumFirstKnownValueTestOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumFirstKnownValueTestOutput`](crate::operation::operation::GetEnumFirstKnownValueTestOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_input.rs new file mode 100644 index 0000000000..9ebdf0a653 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumInput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumInput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumInput { + /// Creates a new builder-style object to manufacture [`GetEnumInput`](crate::operation::operation::GetEnumInput). + pub fn builder() -> crate::operation::get_enum_first_known_value_test::builders::GetEnumInputBuilder { + crate::operation::get_enum_first_known_value_test::builders::GetEnumInputBuilder::default() + } +} + +/// A builder for [`GetEnumInput`](crate::operation::operation::GetEnumInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumInputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumInputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumInput`](crate::operation::operation::GetEnumInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_first_known_value_test::GetEnumInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_first_known_value_test::GetEnumInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_output.rs new file mode 100644 index 0000000000..78d1bf2081 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumOutput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumOutput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumOutput { + /// Creates a new builder-style object to manufacture [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). + pub fn builder() -> crate::operation::get_enum_first_known_value_test::builders::GetEnumOutputBuilder { + crate::operation::get_enum_first_known_value_test::builders::GetEnumOutputBuilder::default() + } +} + +/// A builder for [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumOutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumOutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_first_known_value_test::GetEnumOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_first_known_value_test::GetEnumOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/builders.rs index ca84c9774f..4da9155d3b 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/builders.rs @@ -1,14 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::GetEnumFirstKnownValueTestInputBuilder; -pub use crate::operation::get_enum_first_known_value_test::_get_enum_first_known_value_test_output::GetEnumFirstKnownValueTestOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_enum_first_known_value_test::_get_enum_output::GetEnumOutputBuilder; -impl GetEnumFirstKnownValueTestInputBuilder { +pub use crate::operation::get_enum_first_known_value_test::_get_enum_input::GetEnumInputBuilder; + +impl GetEnumInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, + crate::operation::get_enum_first_known_value_test::GetEnumOutput, crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError, > { let mut fluent_builder = client.get_enum_first_known_value_test(); @@ -21,8 +24,7 @@ impl GetEnumFirstKnownValueTestInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumFirstKnownValueTestFluentBuilder { client: crate::client::Client, - inner: - crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestInputBuilder, + pub(crate) inner: crate::operation::get_enum_first_known_value_test::builders::GetEnumInputBuilder, } impl GetEnumFirstKnownValueTestFluentBuilder { /// Creates a new `GetEnumFirstKnownValueTest`. @@ -33,52 +35,40 @@ impl GetEnumFirstKnownValueTestFluentBuilder { } } /// Access the GetEnumFirstKnownValueTest as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestInputBuilder - { + pub fn as_input(&self) -> &crate::operation::get_enum_first_known_value_test::builders::GetEnumInputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, + crate::operation::get_enum_first_known_value_test::GetEnumOutput, crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnum doesn't declare any validation, + // Using unhandled since GetEnumFirstKnownValueTest doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError::unhandled)?; - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTest::send( - &self.client, - input, - ) - .await + crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTest::send(&self.client, input).await } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_shape::SimpleEnumShape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test.rs index b59e0ce569..af28939f9c 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnumSecondKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,14 +12,14 @@ impl GetEnumSecondKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput, + input: crate::operation::get_enum_second_known_value_test::GetEnumInput, ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, + crate::operation::get_enum_second_known_value_test::GetEnumOutput, crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError, > { - let inner_input = - crate::conversions::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); + let inner_input = crate::conversions::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::to_dafny(input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumSecondKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -28,11 +30,9 @@ impl GetEnumSecondKnownValueTest { ), ) } else { - Err( - crate::conversions::get_enum_second_known_value_test::from_dafny_error( - inner_result.error().clone(), - ), - ) + Err(crate::conversions::get_enum_second_known_value_test::from_dafny_error( + inner_result.error().clone(), + )) } } } @@ -41,7 +41,7 @@ impl GetEnumSecondKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumSecondKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unsecond_known error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -114,18 +114,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetEnumSecondKnownValueTest ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata - for GetEnumSecondKnownValueTestError -{ +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumSecondKnownValueTestError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError - for GetEnumSecondKnownValueTestError -{ +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumSecondKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -139,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError } } -pub use crate::operation::get_enum_second_known_value_test::_get_enum_second_known_value_test_output::GetEnumSecondKnownValueTestOutput; +pub use crate::operation::get_enum_second_known_value_test::_get_enum_output::GetEnumOutput; -pub use crate::operation::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::GetEnumSecondKnownValueTestInput; +pub use crate::operation::get_enum_second_known_value_test::_get_enum_input::GetEnumInput; -mod _get_enum_second_known_value_test_input; +pub(crate) mod _get_enum_output; -mod _get_enum_second_known_value_test_output; +pub(crate) mod _get_enum_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_input.rs new file mode 100644 index 0000000000..494cb01579 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumInput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumInput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumInput { + /// Creates a new builder-style object to manufacture [`GetEnumInput`](crate::operation::operation::GetEnumInput). + pub fn builder() -> crate::operation::get_enum_second_known_value_test::builders::GetEnumInputBuilder { + crate::operation::get_enum_second_known_value_test::builders::GetEnumInputBuilder::default() + } +} + +/// A builder for [`GetEnumInput`](crate::operation::operation::GetEnumInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumInputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumInputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumInput`](crate::operation::operation::GetEnumInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_second_known_value_test::GetEnumInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_second_known_value_test::GetEnumInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_output.rs new file mode 100644 index 0000000000..355865e935 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumOutput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumOutput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumOutput { + /// Creates a new builder-style object to manufacture [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). + pub fn builder() -> crate::operation::get_enum_second_known_value_test::builders::GetEnumOutputBuilder { + crate::operation::get_enum_second_known_value_test::builders::GetEnumOutputBuilder::default() + } +} + +/// A builder for [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumOutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumOutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_second_known_value_test::GetEnumOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_second_known_value_test::GetEnumOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs deleted file mode 100644 index 3fb03429b0..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumSecondKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumSecondKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetEnumSecondKnownValueTestInput { - /// Creates a new builder-style object to manufacture [`GetEnumSecondKnownValueTestInput`](crate::operation::operation::GetEnumSecondKnownValueTestInput). - pub fn builder( - ) -> crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestInputBuilder - { - crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestInputBuilder::default() - } -} - -/// A builder for [`GetEnumSecondKnownValueTestInput`](crate::operation::operation::GetEnumSecondKnownValueTestInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumSecondKnownValueTestInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumSecondKnownValueTestInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumSecondKnownValueTestInput`](crate::operation::operation::GetEnumSecondKnownValueTestInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs deleted file mode 100644 index 6937025052..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumSecondKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumSecondKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetEnumSecondKnownValueTestOutput { - /// Creates a new builder-style object to manufacture [`GetEnumSecondKnownValueTestOutput`](crate::operation::operation::GetEnumSecondKnownValueTestOutput). - pub fn builder( - ) -> crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestOutputBuilder - { - crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestOutputBuilder::default() - } -} - -/// A builder for [`GetEnumSecondKnownValueTestOutput`](crate::operation::operation::GetEnumSecondKnownValueTestOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumSecondKnownValueTestOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumSecondKnownValueTestOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumSecondKnownValueTestOutput`](crate::operation::operation::GetEnumSecondKnownValueTestOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/builders.rs index e54348b361..1d0afa3fc5 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/builders.rs @@ -1,14 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::GetEnumSecondKnownValueTestInputBuilder; -pub use crate::operation::get_enum_second_known_value_test::_get_enum_second_known_value_test_output::GetEnumSecondKnownValueTestOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_enum_second_known_value_test::_get_enum_output::GetEnumOutputBuilder; -impl GetEnumSecondKnownValueTestInputBuilder { +pub use crate::operation::get_enum_second_known_value_test::_get_enum_input::GetEnumInputBuilder; + +impl GetEnumInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, + crate::operation::get_enum_second_known_value_test::GetEnumOutput, crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError, > { let mut fluent_builder = client.get_enum_second_known_value_test(); @@ -21,7 +24,7 @@ impl GetEnumSecondKnownValueTestInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumSecondKnownValueTestFluentBuilder { client: crate::client::Client, - inner: crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestInputBuilder, + pub(crate) inner: crate::operation::get_enum_second_known_value_test::builders::GetEnumInputBuilder, } impl GetEnumSecondKnownValueTestFluentBuilder { /// Creates a new `GetEnumSecondKnownValueTest`. @@ -32,52 +35,40 @@ impl GetEnumSecondKnownValueTestFluentBuilder { } } /// Access the GetEnumSecondKnownValueTest as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestInputBuilder - { + pub fn as_input(&self) -> &crate::operation::get_enum_second_known_value_test::builders::GetEnumInputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, + crate::operation::get_enum_second_known_value_test::GetEnumOutput, crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnum doesn't declare any validation, + // Using unhandled since GetEnumSecondKnownValueTest doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError::unhandled)?; - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTest::send( - &self.client, - input, - ) - .await + crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTest::send(&self.client, input).await } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_shape::SimpleEnumShape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test.rs index d5def6ff29..0b3f627823 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnumThirdKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,14 +12,14 @@ impl GetEnumThirdKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput, + input: crate::operation::get_enum_third_known_value_test::GetEnumInput, ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, + crate::operation::get_enum_third_known_value_test::GetEnumOutput, crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError, > { - let inner_input = - crate::conversions::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); + let inner_input = crate::conversions::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::to_dafny(input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumThirdKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -28,11 +30,9 @@ impl GetEnumThirdKnownValueTest { ), ) } else { - Err( - crate::conversions::get_enum_third_known_value_test::from_dafny_error( - inner_result.error().clone(), - ), - ) + Err(crate::conversions::get_enum_third_known_value_test::from_dafny_error( + inner_result.error().clone(), + )) } } } @@ -41,7 +41,7 @@ impl GetEnumThirdKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumThirdKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unthird_known error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -121,9 +121,7 @@ impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumThirdK } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError - for GetEnumThirdKnownValueTestError -{ +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumThirdKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -137,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError } } -pub use crate::operation::get_enum_third_known_value_test::_get_enum_third_known_value_test_output::GetEnumThirdKnownValueTestOutput; +pub use crate::operation::get_enum_third_known_value_test::_get_enum_output::GetEnumOutput; -pub use crate::operation::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::GetEnumThirdKnownValueTestInput; +pub use crate::operation::get_enum_third_known_value_test::_get_enum_input::GetEnumInput; -mod _get_enum_third_known_value_test_input; +pub(crate) mod _get_enum_output; -mod _get_enum_third_known_value_test_output; +pub(crate) mod _get_enum_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_input.rs new file mode 100644 index 0000000000..5529bb5f1d --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumInput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumInput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumInput { + /// Creates a new builder-style object to manufacture [`GetEnumInput`](crate::operation::operation::GetEnumInput). + pub fn builder() -> crate::operation::get_enum_third_known_value_test::builders::GetEnumInputBuilder { + crate::operation::get_enum_third_known_value_test::builders::GetEnumInputBuilder::default() + } +} + +/// A builder for [`GetEnumInput`](crate::operation::operation::GetEnumInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumInputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumInputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumInput`](crate::operation::operation::GetEnumInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_third_known_value_test::GetEnumInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_third_known_value_test::GetEnumInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_output.rs new file mode 100644 index 0000000000..87d794f537 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumOutput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumOutput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumOutput { + /// Creates a new builder-style object to manufacture [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). + pub fn builder() -> crate::operation::get_enum_third_known_value_test::builders::GetEnumOutputBuilder { + crate::operation::get_enum_third_known_value_test::builders::GetEnumOutputBuilder::default() + } +} + +/// A builder for [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumOutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumOutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_third_known_value_test::GetEnumOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_third_known_value_test::GetEnumOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs deleted file mode 100644 index 275d472c06..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs +++ /dev/null @@ -1,68 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumThirdKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumThirdKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetEnumThirdKnownValueTestInput { - /// Creates a new builder-style object to manufacture [`GetEnumThirdKnownValueTestInput`](crate::operation::operation::GetEnumThirdKnownValueTestInput). - pub fn builder( - ) -> crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestInputBuilder - { - crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestInputBuilder::default() - } -} - -/// A builder for [`GetEnumThirdKnownValueTestInput`](crate::operation::operation::GetEnumThirdKnownValueTestInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumThirdKnownValueTestInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumThirdKnownValueTestInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumThirdKnownValueTestInput`](crate::operation::operation::GetEnumThirdKnownValueTestInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs deleted file mode 100644 index e1d498d3e5..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumThirdKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumThirdKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetEnumThirdKnownValueTestOutput { - /// Creates a new builder-style object to manufacture [`GetEnumThirdKnownValueTestOutput`](crate::operation::operation::GetEnumThirdKnownValueTestOutput). - pub fn builder( - ) -> crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestOutputBuilder - { - crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestOutputBuilder::default() - } -} - -/// A builder for [`GetEnumThirdKnownValueTestOutput`](crate::operation::operation::GetEnumThirdKnownValueTestOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumThirdKnownValueTestOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumThirdKnownValueTestOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumThirdKnownValueTestOutput`](crate::operation::operation::GetEnumThirdKnownValueTestOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/builders.rs index db835240b0..f51c94119c 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/builders.rs @@ -1,14 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::GetEnumThirdKnownValueTestInputBuilder; -pub use crate::operation::get_enum_third_known_value_test::_get_enum_third_known_value_test_output::GetEnumThirdKnownValueTestOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_enum_third_known_value_test::_get_enum_output::GetEnumOutputBuilder; -impl GetEnumThirdKnownValueTestInputBuilder { +pub use crate::operation::get_enum_third_known_value_test::_get_enum_input::GetEnumInputBuilder; + +impl GetEnumInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, + crate::operation::get_enum_third_known_value_test::GetEnumOutput, crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError, > { let mut fluent_builder = client.get_enum_third_known_value_test(); @@ -21,8 +24,7 @@ impl GetEnumThirdKnownValueTestInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumThirdKnownValueTestFluentBuilder { client: crate::client::Client, - inner: - crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestInputBuilder, + pub(crate) inner: crate::operation::get_enum_third_known_value_test::builders::GetEnumInputBuilder, } impl GetEnumThirdKnownValueTestFluentBuilder { /// Creates a new `GetEnumThirdKnownValueTest`. @@ -33,52 +35,40 @@ impl GetEnumThirdKnownValueTestFluentBuilder { } } /// Access the GetEnumThirdKnownValueTest as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestInputBuilder - { + pub fn as_input(&self) -> &crate::operation::get_enum_third_known_value_test::builders::GetEnumInputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, + crate::operation::get_enum_third_known_value_test::GetEnumOutput, crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnum doesn't declare any validation, + // Using unhandled since GetEnumThirdKnownValueTest doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError::unhandled)?; - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTest::send( - &self.client, - input, - ) - .await + crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTest::send(&self.client, input).await } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_shape::SimpleEnumShape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types.rs index de39101208..0f9d2788bd 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types.rs @@ -1,5 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -/// Types for the `SimpleIntegerConfig` +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +/// Types for the `SimpleEnumConfig` pub mod simple_enum_config; -pub mod simple_enum_shape; + +mod _simple_enum_shape; +pub use crate::types::_simple_enum_shape::SimpleEnumShape; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/_simple_enum_shape.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/_simple_enum_shape.rs new file mode 100644 index 0000000000..fd2b3fdce2 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/_simple_enum_shape.rs @@ -0,0 +1,19 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[derive(Debug, PartialEq, Copy, Clone)] +pub enum SimpleEnumShape { + First, +Second, +Third, +} + +impl ::std::fmt::Display for SimpleEnumShape { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match self { + SimpleEnumShape::First => write!(f, "FIRST"), +SimpleEnumShape::Second => write!(f, "SECOND"), +SimpleEnumShape::Third => write!(f, "THIRD"), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_config.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_config.rs index fd3ea0e14c..7fd6368cb2 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_config.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_config.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleEnumConfig {} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_shape.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_shape.rs deleted file mode 100644 index dba3140596..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_shape.rs +++ /dev/null @@ -1,6 +0,0 @@ -#[derive(Debug, PartialEq, Copy, Clone)] -pub enum SimpleEnumShape { - FIRST, - SECOND, - THIRD, -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..fe5929068a --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::smithyenum::internaldafny::wrapped::_default { + pub fn WrappedSimpleEnum(config: &::std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumConfig, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..d35f39e8c1 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,179 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::smithyenum::internaldafny::types::ISimpleTypesEnumClient); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumConfig, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_enum_config::_simple_enum_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::smithyenum::internaldafny::types::ISimpleTypesEnumClient for Client { + fn GetEnum( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum::_get_enum_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum::GetEnum::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum::_get_enum_output::to_dafny(client), + }, + ), + } + } + + fn GetEnumFirstKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum_first_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum_first_known_value_test::_get_enum_first_known_value_test_output::to_dafny(client), + }, + ), + } + } + + fn GetEnumSecondKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum_second_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum_second_known_value_test::_get_enum_second_known_value_test_output::to_dafny(client), + }, + ), + } + } + + fn GetEnumThirdKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum_third_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum_third_known_value_test::_get_enum_third_known_value_test_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/tests/simple_enum_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/tests/simple_enum_test.rs index 8e53533ea3..0e8259e737 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/tests/simple_enum_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/tests/simple_enum_test.rs @@ -1,48 +1,48 @@ -use simple_enum::types::simple_enum_shape::SimpleEnumShape::*; +use simple_enum::types::SimpleEnumShape::*; use simple_enum::*; #[tokio::test] async fn test_get_enum() { - let result = client().get_enum().value(SECOND).send().await; + let result = client().get_enum().value(Second).send().await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, SECOND); + assert_eq!(value, Second); } #[tokio::test] async fn test_get_first_known_value() { let result = client() .get_enum_first_known_value_test() - .value(FIRST) + .value(First) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, FIRST); + assert_eq!(value, First); } #[tokio::test] async fn test_get_second_known_value() { let result = client() .get_enum_second_known_value_test() - .value(SECOND) + .value(Second) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, SECOND); + assert_eq!(value, Second); } #[tokio::test] async fn test_get_third_known_value() { let result = client() .get_enum_third_known_value_test() - .value(THIRD) + .value(Third) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, THIRD); + assert_eq!(value, Third); } pub fn client() -> Client { diff --git a/TestModels/SimpleTypes/SimpleEnumV2/Makefile b/TestModels/SimpleTypes/SimpleEnumV2/Makefile index c7a5acd8a5..bdb7b0e583 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/Makefile +++ b/TestModels/SimpleTypes/SimpleEnumV2/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/Cargo.toml index dbaad13bfd..291c1fd915 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/Cargo.toml @@ -5,13 +5,19 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies.tokio] +[dev-dependencies] +simple_enum_v2 = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client.rs index f7bbdbfacb..83490767ce 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -29,7 +30,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } @@ -37,5 +38,7 @@ impl Client { mod get_enum_v2; mod get_enum_v2_first_known_value_test; + mod get_enum_v2_second_known_value_test; + mod get_enum_v2_third_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2.rs index c9a688bd85..7cc559b930 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetEnumV2`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumV2Shape)`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::set_value):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2::GetEnumV2Output) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_v2::GetEnumV2Output::value): (undocumented) + /// - [`value(Option)`](crate::operation::get_enum_v2::GetEnumV2Output::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2::GetEnumV2Error) pub fn get_enum_v2(&self) -> crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder { crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_first_known_value_test.rs index ebde767b2c..896b404709 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_first_known_value_test.rs @@ -1,18 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { - /// Constructs a fluent builder for the [`GetEnumV2`](crate::operation::get_enum_v2_first_known_value::builders::GetEnumV2FluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumV2FirstKnownValueTest`](crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumV2Shape)`](crate::operation::get_enum_v2_first_known_value::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_first_known_value::builders::GetEnumV2FluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_first_known_value::GetEnumV2Output) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_v2_first_known_value::GetEnumV2Output::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_first_known_value::GetEnumV2Error) - pub fn get_enum_v2_first_known_value_test( - &self, - ) -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder - { - crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder::new( - self.clone(), - ) + /// - [`value(impl Into>)`](crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError) + pub fn get_enum_v2_first_known_value_test(&self) -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder { + crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_second_known_value_test.rs index f4981c29d3..3bbcda3c1f 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_second_known_value_test.rs @@ -1,18 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { - /// Constructs a fluent builder for the [`GetEnumV2`](crate::operation::get_enum_v2_second_known_value::builders::GetEnumV2FluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumV2SecondKnownValueTest`](crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumV2Shape)`](crate::operation::get_enum_v2_second_known_value::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_second_known_value::builders::GetEnumV2FluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_second_known_value::GetEnumV2Output) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_v2_second_known_value::GetEnumV2Output::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_second_known_value::GetEnumV2Error) - pub fn get_enum_v2_second_known_value_test( - &self, - ) -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder - { - crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder::new( - self.clone(), - ) + /// - [`value(impl Into>)`](crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError) + pub fn get_enum_v2_second_known_value_test(&self) -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder { + crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_third_known_value_test.rs index afc875f376..c37fe8c75e 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_third_known_value_test.rs @@ -1,18 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { - /// Constructs a fluent builder for the [`GetEnumV2`](crate::operation::get_enum_v2_third_known_value::builders::GetEnumV2FluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumV2ThirdKnownValueTest`](crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumV2Shape)`](crate::operation::get_enum_v2_third_known_value::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_third_known_value::builders::GetEnumV2FluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_third_known_value::GetEnumV2Output) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_v2_third_known_value::GetEnumV2Output::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_third_known_value::GetEnumV2Error) - pub fn get_enum_v2_third_known_value_test( - &self, - ) -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder - { - crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder::new( - self.clone(), - ) + /// - [`value(impl Into>)`](crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError) + pub fn get_enum_v2_third_known_value_test(&self) -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder { + crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions.rs index 323761ef25..ae84ee4f2d 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions.rs @@ -1,9 +1,16 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_enum_v2; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod get_enum_v2_first_known_value_test; -pub mod get_enum_v2_second_known_value_test; -pub mod get_enum_v2_third_known_value_test; + pub mod get_enum_v2; -pub mod simple_enum_v2_config; -pub mod simple_enum_v2_shape; + pub mod get_enum_v2_first_known_value_test; + + pub mod get_enum_v2_second_known_value_test; + + pub mod get_enum_v2_third_known_value_test; + + pub mod simple_enum_v2_config; + + pub mod simple_enum_v2_shape; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..fd8f69459c --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::enumv2::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2.rs index e9b9909b5d..b6ad1638f4 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] @@ -7,14 +8,9 @@ pub fn to_dafny_error( value: crate::operation::get_enum_v2::GetEnumV2Error, ) -> ::std::rc::Rc { match value { - crate::operation::get_enum_v2::GetEnumV2Error::Unhandled(unhandled) => ::std::rc::Rc::new( - crate::r#simple::types::enumv2::internaldafny::types::Error::Opaque { - obj: ::dafny_runtime::upcast_object()( - ::dafny_runtime::object::new(unhandled), - ), - }, - ), - } + crate::operation::get_enum_v2::GetEnumV2Error::Unhandled(unhandled) => + ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) + } } #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_input.rs index 236bf35509..00959d1e89 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_input.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_enum_v2::GetEnumV2Input, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input::GetEnumV2Input { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, >, ) -> crate::operation::get_enum_v2::GetEnumV2Input { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2::GetEnumV2Input { value } + crate::operation::get_enum_v2::GetEnumV2Input::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_output.rs index 84d950d915..08130c3e9b 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_output.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_enum_v2::GetEnumV2Output, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output::GetEnumV2Output { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, >, ) -> crate::operation::get_enum_v2::GetEnumV2Output { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2::GetEnumV2Output { value } + crate::operation::get_enum_v2::GetEnumV2Output::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test.rs index 9e85094466..e7bfe032d6 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs index 043d693333..96fe41e22f 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs @@ -1,47 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput, + value: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input::GetEnumV2Input { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, >, -) -> crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput { - value, - } +) -> crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input { + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs index 7378e11786..268a2afa6b 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs @@ -1,47 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, + value: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output::GetEnumV2Output { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, >, -) -> crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput { - value, - } +) -> crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output { + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test.rs index b6de63fad1..e64c315050 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs index a7a40bf49c..74e95d15a7 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs @@ -1,47 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput, + value: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input::GetEnumV2Input { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, >, -) -> crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput { - value, - } +) -> crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input { + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs index 07bec26645..0b68410110 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs @@ -1,47 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, + value: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output::GetEnumV2Output { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, >, -) -> crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput { - value, - } +) -> crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output { + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test.rs index a1ddd7dab5..d190f09074 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs index 8adc054b04..1b60f1e579 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs @@ -1,47 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput, + value: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input::GetEnumV2Input { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, >, -) -> crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput { - value, - } +) -> crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input { + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs index 1607c8003e..ca7d68c38a 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs @@ -1,47 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, + value: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output::GetEnumV2Output { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, >, -) -> crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput { - value, - } +) -> crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output { + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config.rs index 3eaacd610f..e280adea26 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_enum_v2_config; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config/_simple_enum_v2_config.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config/_simple_enum_v2_config.rs index f0a6804513..005e3ea6e6 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config/_simple_enum_v2_config.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config/_simple_enum_v2_config.rs @@ -1,10 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_enum_v2_config::SimpleEnumV2Config, ) -> ::std::rc::Rc< - crate::simple::types::enumv2::internaldafny::types::SimpleEnumV2Config, + crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Config, > { ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Config::SimpleEnumV2Config {}) } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape.rs index b4f4a50f80..d2e61a3673 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape.rs @@ -1,3 +1,25 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] -pub mod _simple_enum_v2_shape; +pub fn to_dafny( + value: crate::types::SimpleEnumV2Shape, +) -> ::std::rc::Rc{ + ::std::rc::Rc::new(match value { + crate::types::SimpleEnumV2Shape::First => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::FIRST {}, +crate::types::SimpleEnumV2Shape::Second => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::SECOND {}, +crate::types::SimpleEnumV2Shape::Third => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::THIRD {}, + _ => panic!("Unknown enum variant: {}", value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: &crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape, +) -> crate::types::SimpleEnumV2Shape { + match dafny_value { + crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::FIRST {} => crate::types::SimpleEnumV2Shape::First, +crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::SECOND {} => crate::types::SimpleEnumV2Shape::Second, +crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::THIRD {} => crate::types::SimpleEnumV2Shape::Third, + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape/_simple_enum_v2_shape.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape/_simple_enum_v2_shape.rs deleted file mode 100644 index d48a6337b0..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape/_simple_enum_v2_shape.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] - -pub fn to_dafny( - value: &crate::types::simple_enum_v2_shape::SimpleEnumV2Shape, -) -> crate::simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape { - match value { - crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::FIRST => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::FIRST {}, - crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::SECOND => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::SECOND {}, - crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::THIRD => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::THIRD {}, - } -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: &crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape, -) -> crate::types::simple_enum_v2_shape::SimpleEnumV2Shape { - match dafny_value { - crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::FIRST {} => crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::FIRST, - crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::SECOND {} => crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::SECOND, - crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::THIRD {} => crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::THIRD, - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/lib.rs deleted file mode 100644 index fcb015ba30..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub mod implementation_from_dafny; - -pub use client::Client; -pub use types::simple_enum_v2_config::SimpleEnumV2Config; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation.rs index 565298a1a7..a4dc395b89 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation.rs @@ -1,9 +1,14 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetEnumV2` operation. pub mod get_enum_v2; -/// Types for the `GetEnumV2KnownValue` operation. +/// Types for the `GetEnumV2FirstKnownValueTest` operation. pub mod get_enum_v2_first_known_value_test; + +/// Types for the `GetEnumV2SecondKnownValueTest` operation. pub mod get_enum_v2_second_known_value_test; + +/// Types for the `GetEnumV2ThirdKnownValueTest` operation. pub mod get_enum_v2_third_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2.rs index f556fbe3ec..d35d560f15 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnumV2`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -137,9 +139,9 @@ pub use crate::operation::get_enum_v2::_get_enum_v2_output::GetEnumV2Output; pub use crate::operation::get_enum_v2::_get_enum_v2_input::GetEnumV2Input; -mod _get_enum_v2_input; +pub(crate) mod _get_enum_v2_output; -mod _get_enum_v2_output; +pub(crate) mod _get_enum_v2_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_input.rs index a842022680..dfb86df68c 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_input.rs @@ -1,19 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetEnumV2Input { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option, } impl GetEnumV2Input { #[allow(missing_docs)] // documentation missing in model - pub fn message( - &self, - ) -> ::std::option::Option<&crate::types::simple_enum_v2_shape::SimpleEnumV2Shape> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} } impl GetEnumV2Input { /// Creates a new builder-style object to manufacture [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). @@ -28,31 +27,23 @@ impl GetEnumV2Input { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetEnumV2InputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option, } impl GetEnumV2InputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} /// Consumes the builder and constructs a [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_output.rs index 002769f657..3037a73e7d 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_output.rs @@ -1,22 +1,19 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetEnumV2Output { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option, } - impl GetEnumV2Output { #[allow(missing_docs)] // documentation missing in model - pub fn value( - &self, - ) -> ::std::option::Option { - self.value - } +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} } - impl GetEnumV2Output { /// Creates a new builder-style object to manufacture [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). pub fn builder() -> crate::operation::get_enum_v2::builders::GetEnumV2OutputBuilder { @@ -30,35 +27,23 @@ impl GetEnumV2Output { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetEnumV2OutputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option, } - impl GetEnumV2OutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} /// Consumes the builder and constructs a [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/builders.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/builders.rs index e742b3d97c..89b6e6ef12 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/builders.rs @@ -1,7 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum_v2::_get_enum_v2_input::GetEnumV2InputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_enum_v2::_get_enum_v2_output::GetEnumV2OutputBuilder; +pub use crate::operation::get_enum_v2::_get_enum_v2_input::GetEnumV2InputBuilder; + impl GetEnumV2InputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( @@ -21,7 +24,7 @@ impl GetEnumV2InputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumV2FluentBuilder { client: crate::client::Client, - inner: crate::operation::get_enum_v2::builders::GetEnumV2InputBuilder, + pub(crate) inner: crate::operation::get_enum_v2::builders::GetEnumV2InputBuilder, } impl GetEnumV2FluentBuilder { /// Creates a new `GetEnumV2`. @@ -55,22 +58,17 @@ impl GetEnumV2FluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_v2_shape::SimpleEnumV2Shape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test.rs index 57c67e00bc..eae709de44 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnumV2FirstKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,15 +12,14 @@ impl GetEnumV2FirstKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput, + input: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input, ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError, > { - let inner_input = - crate::conversions::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::to_dafny(input); + let inner_input = crate::conversions::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::to_dafny(input); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2FirstKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -29,11 +30,9 @@ impl GetEnumV2FirstKnownValueTest { ), ) } else { - Err( - crate::conversions::get_enum_v2_first_known_value_test::from_dafny_error( - inner_result.error().clone(), - ), - ) + Err(crate::conversions::get_enum_v2_first_known_value_test::from_dafny_error( + inner_result.error().clone(), + )) } } } @@ -42,7 +41,7 @@ impl GetEnumV2FirstKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumV2FirstKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unfirst_known error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -115,18 +114,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetEnumV2FirstKnownValueTes ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata - for GetEnumV2FirstKnownValueTestError -{ +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumV2FirstKnownValueTestError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError - for GetEnumV2FirstKnownValueTestError -{ +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumV2FirstKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -140,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError } } -pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_output::GetEnumV2FirstKnownValueTestOutput; +pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_output::GetEnumV2Output; -pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::GetEnumV2FirstKnownValueTestInput; +pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_input::GetEnumV2Input; -mod _get_enum_v2_first_known_value_test_input; +pub(crate) mod _get_enum_v2_output; -mod _get_enum_v2_first_known_value_test_output; +pub(crate) mod _get_enum_v2_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs deleted file mode 100644 index a367fd776e..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2FirstKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumV2FirstKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - &self, - ) -> ::std::option::Option { - self.value - } -} -impl GetEnumV2FirstKnownValueTestInput { - /// Creates a new builder-style object to manufacture [`GetEnumV2FirstKnownValueTestInput`](crate::operation::operation::GetEnumV2FirstKnownValueTestInput). - pub fn builder( - ) -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestInputBuilder - { - crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestInputBuilder::default() - } -} - -/// A builder for [`GetEnumV2FirstKnownValueTestInput`](crate::operation::operation::GetEnumV2FirstKnownValueTestInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2FirstKnownValueTestInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2FirstKnownValueTestInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumV2FirstKnownValueTestInput`](crate::operation::operation::GetEnumV2FirstKnownValueTestInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs deleted file mode 100644 index f665704ab0..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2FirstKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumV2FirstKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - &self, - ) -> ::std::option::Option { - self.value - } -} -impl GetEnumV2FirstKnownValueTestOutput { - /// Creates a new builder-style object to manufacture [`GetEnumV2FirstKnownValueTestOutput`](crate::operation::operation::GetEnumV2FirstKnownValueTestOutput). - pub fn builder( - ) -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestOutputBuilder - { - crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestOutputBuilder::default() - } -} - -/// A builder for [`GetEnumV2FirstKnownValueTestOutput`](crate::operation::operation::GetEnumV2FirstKnownValueTestOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2FirstKnownValueTestOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2FirstKnownValueTestOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumV2FirstKnownValueTestOutput`](crate::operation::operation::GetEnumV2FirstKnownValueTestOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_input.rs new file mode 100644 index 0000000000..fab2d07d14 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2Input { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumV2Input { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumV2Input { + /// Creates a new builder-style object to manufacture [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). + pub fn builder() -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2InputBuilder { + crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2InputBuilder::default() + } +} + +/// A builder for [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2InputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2InputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_output.rs new file mode 100644 index 0000000000..ee11f4792d --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2Output { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumV2Output { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumV2Output { + /// Creates a new builder-style object to manufacture [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). + pub fn builder() -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2OutputBuilder { + crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2OutputBuilder::default() + } +} + +/// A builder for [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2OutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2OutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/builders.rs index c88ff6efee..548fdeb7d2 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/builders.rs @@ -1,14 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::GetEnumV2FirstKnownValueTestInputBuilder; -pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_output::GetEnumV2FirstKnownValueTestOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_output::GetEnumV2OutputBuilder; -impl GetEnumV2FirstKnownValueTestInputBuilder { +pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_input::GetEnumV2InputBuilder; + +impl GetEnumV2InputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError, > { let mut fluent_builder = client.get_enum_v2_first_known_value_test(); @@ -21,8 +24,7 @@ impl GetEnumV2FirstKnownValueTestInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumV2FirstKnownValueTestFluentBuilder { client: crate::client::Client, - inner: - crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestInputBuilder, + pub(crate) inner: crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2InputBuilder, } impl GetEnumV2FirstKnownValueTestFluentBuilder { /// Creates a new `GetEnumV2FirstKnownValueTest`. @@ -33,52 +35,40 @@ impl GetEnumV2FirstKnownValueTestFluentBuilder { } } /// Access the GetEnumV2FirstKnownValueTest as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestInputBuilder - { + pub fn as_input(&self) -> &crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2InputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnumV2 doesn't declare any validation, + // Using unhandled since GetEnumV2FirstKnownValueTest doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError::unhandled)?; - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTest::send( - &self.client, - input, - ) - .await + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTest::send(&self.client, input).await } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_v2_shape::SimpleEnumV2Shape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test.rs index 9fecf26d24..915d3dd2c7 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnumV2SecondKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,15 +12,14 @@ impl GetEnumV2SecondKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput, + input: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input, ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError, > { - let inner_input = - crate::conversions::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::to_dafny(input); + let inner_input = crate::conversions::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::to_dafny(input); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2SecondKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -29,11 +30,9 @@ impl GetEnumV2SecondKnownValueTest { ), ) } else { - Err( - crate::conversions::get_enum_v2_second_known_value_test::from_dafny_error( - inner_result.error().clone(), - ), - ) + Err(crate::conversions::get_enum_v2_second_known_value_test::from_dafny_error( + inner_result.error().clone(), + )) } } } @@ -42,7 +41,7 @@ impl GetEnumV2SecondKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumV2SecondKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unsecond_known error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -115,18 +114,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetEnumV2SecondKnownValueTe ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata - for GetEnumV2SecondKnownValueTestError -{ +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumV2SecondKnownValueTestError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError - for GetEnumV2SecondKnownValueTestError -{ +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumV2SecondKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -140,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError } } -pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_output::GetEnumV2SecondKnownValueTestOutput; +pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_output::GetEnumV2Output; -pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::GetEnumV2SecondKnownValueTestInput; +pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_input::GetEnumV2Input; -mod _get_enum_v2_second_known_value_test_input; +pub(crate) mod _get_enum_v2_output; -mod _get_enum_v2_second_known_value_test_output; +pub(crate) mod _get_enum_v2_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_input.rs new file mode 100644 index 0000000000..925024a036 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2Input { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumV2Input { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumV2Input { + /// Creates a new builder-style object to manufacture [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). + pub fn builder() -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2InputBuilder { + crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2InputBuilder::default() + } +} + +/// A builder for [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2InputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2InputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_output.rs new file mode 100644 index 0000000000..2e6fc555ed --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2Output { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumV2Output { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumV2Output { + /// Creates a new builder-style object to manufacture [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). + pub fn builder() -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2OutputBuilder { + crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2OutputBuilder::default() + } +} + +/// A builder for [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2OutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2OutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs deleted file mode 100644 index d13dfd188e..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2SecondKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumV2SecondKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - &self, - ) -> ::std::option::Option { - self.value - } -} -impl GetEnumV2SecondKnownValueTestInput { - /// Creates a new builder-style object to manufacture [`GetEnumV2SecondKnownValueTestInput`](crate::operation::operation::GetEnumV2SecondKnownValueTestInput). - pub fn builder( - ) -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestInputBuilder - { - crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestInputBuilder::default() - } -} - -/// A builder for [`GetEnumV2SecondKnownValueTestInput`](crate::operation::operation::GetEnumV2SecondKnownValueTestInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2SecondKnownValueTestInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2SecondKnownValueTestInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumV2SecondKnownValueTestInput`](crate::operation::operation::GetEnumV2SecondKnownValueTestInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs deleted file mode 100644 index 39218e3ad0..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2SecondKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumV2SecondKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - &self, - ) -> ::std::option::Option { - self.value - } -} -impl GetEnumV2SecondKnownValueTestOutput { - /// Creates a new builder-style object to manufacture [`GetEnumV2SecondKnownValueTestOutput`](crate::operation::operation::GetEnumV2SecondKnownValueTestOutput). - pub fn builder( - ) -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestOutputBuilder - { - crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestOutputBuilder::default() - } -} - -/// A builder for [`GetEnumV2SecondKnownValueTestOutput`](crate::operation::operation::GetEnumV2SecondKnownValueTestOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2SecondKnownValueTestOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2SecondKnownValueTestOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumV2SecondKnownValueTestOutput`](crate::operation::operation::GetEnumV2SecondKnownValueTestOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/builders.rs index 5137b217e9..13b3676202 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/builders.rs @@ -1,14 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::GetEnumV2SecondKnownValueTestInputBuilder; -pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_output::GetEnumV2SecondKnownValueTestOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_output::GetEnumV2OutputBuilder; -impl GetEnumV2SecondKnownValueTestInputBuilder { +pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_input::GetEnumV2InputBuilder; + +impl GetEnumV2InputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError, > { let mut fluent_builder = client.get_enum_v2_second_known_value_test(); @@ -21,7 +24,7 @@ impl GetEnumV2SecondKnownValueTestInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumV2SecondKnownValueTestFluentBuilder { client: crate::client::Client, - inner: crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestInputBuilder, + pub(crate) inner: crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2InputBuilder, } impl GetEnumV2SecondKnownValueTestFluentBuilder { /// Creates a new `GetEnumV2SecondKnownValueTest`. @@ -32,52 +35,40 @@ impl GetEnumV2SecondKnownValueTestFluentBuilder { } } /// Access the GetEnumV2SecondKnownValueTest as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestInputBuilder - { + pub fn as_input(&self) -> &crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2InputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnumV2 doesn't declare any validation, + // Using unhandled since GetEnumV2SecondKnownValueTest doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError::unhandled)?; - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTest::send( - &self.client, - input, - ) - .await + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTest::send(&self.client, input).await } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_v2_shape::SimpleEnumV2Shape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test.rs index bf5efb30b6..188442ad28 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnumV2ThirdKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,15 +12,14 @@ impl GetEnumV2ThirdKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput, + input: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input, ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError, > { - let inner_input = - crate::conversions::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::to_dafny(input); + let inner_input = crate::conversions::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::to_dafny(input); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2ThirdKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -29,11 +30,9 @@ impl GetEnumV2ThirdKnownValueTest { ), ) } else { - Err( - crate::conversions::get_enum_v2_third_known_value_test::from_dafny_error( - inner_result.error().clone(), - ), - ) + Err(crate::conversions::get_enum_v2_third_known_value_test::from_dafny_error( + inner_result.error().clone(), + )) } } } @@ -42,7 +41,7 @@ impl GetEnumV2ThirdKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumV2ThirdKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unthird_known error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -115,18 +114,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetEnumV2ThirdKnownValueTes ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata - for GetEnumV2ThirdKnownValueTestError -{ +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumV2ThirdKnownValueTestError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError - for GetEnumV2ThirdKnownValueTestError -{ +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumV2ThirdKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -140,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError } } -pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_output::GetEnumV2ThirdKnownValueTestOutput; +pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_output::GetEnumV2Output; -pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::GetEnumV2ThirdKnownValueTestInput; +pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_input::GetEnumV2Input; -mod _get_enum_v2_third_known_value_test_input; +pub(crate) mod _get_enum_v2_output; -mod _get_enum_v2_third_known_value_test_output; +pub(crate) mod _get_enum_v2_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_input.rs new file mode 100644 index 0000000000..cdfce6ed40 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2Input { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumV2Input { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumV2Input { + /// Creates a new builder-style object to manufacture [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). + pub fn builder() -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2InputBuilder { + crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2InputBuilder::default() + } +} + +/// A builder for [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2InputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2InputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_output.rs new file mode 100644 index 0000000000..1799bb2d27 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2Output { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumV2Output { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumV2Output { + /// Creates a new builder-style object to manufacture [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). + pub fn builder() -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2OutputBuilder { + crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2OutputBuilder::default() + } +} + +/// A builder for [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2OutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2OutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs deleted file mode 100644 index 573fb3c14b..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2ThirdKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumV2ThirdKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - &self, - ) -> ::std::option::Option { - self.value - } -} -impl GetEnumV2ThirdKnownValueTestInput { - /// Creates a new builder-style object to manufacture [`GetEnumV2ThirdKnownValueTestInput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestInput). - pub fn builder( - ) -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestInputBuilder - { - crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestInputBuilder::default() - } -} - -/// A builder for [`GetEnumV2ThirdKnownValueTestInput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2ThirdKnownValueTestInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2ThirdKnownValueTestInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumV2ThirdKnownValueTestInput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs deleted file mode 100644 index 588e636c9c..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2ThirdKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumV2ThirdKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - &self, - ) -> ::std::option::Option { - self.value - } -} -impl GetEnumV2ThirdKnownValueTestOutput { - /// Creates a new builder-style object to manufacture [`GetEnumV2ThirdKnownValueTestOutput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestOutput). - pub fn builder( - ) -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestOutputBuilder - { - crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestOutputBuilder::default() - } -} - -/// A builder for [`GetEnumV2ThirdKnownValueTestOutput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2ThirdKnownValueTestOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2ThirdKnownValueTestOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumV2ThirdKnownValueTestOutput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/builders.rs index f1bbbe0581..84838695de 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/builders.rs @@ -1,14 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::GetEnumV2ThirdKnownValueTestInputBuilder; -pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_output::GetEnumV2ThirdKnownValueTestOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_output::GetEnumV2OutputBuilder; -impl GetEnumV2ThirdKnownValueTestInputBuilder { +pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_input::GetEnumV2InputBuilder; + +impl GetEnumV2InputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError, > { let mut fluent_builder = client.get_enum_v2_third_known_value_test(); @@ -21,8 +24,7 @@ impl GetEnumV2ThirdKnownValueTestInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumV2ThirdKnownValueTestFluentBuilder { client: crate::client::Client, - inner: - crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestInputBuilder, + pub(crate) inner: crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2InputBuilder, } impl GetEnumV2ThirdKnownValueTestFluentBuilder { /// Creates a new `GetEnumV2ThirdKnownValueTest`. @@ -33,52 +35,40 @@ impl GetEnumV2ThirdKnownValueTestFluentBuilder { } } /// Access the GetEnumV2ThirdKnownValueTest as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestInputBuilder - { + pub fn as_input(&self) -> &crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2InputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnumV2 doesn't declare any validation, + // Using unhandled since GetEnumV2ThirdKnownValueTest doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError::unhandled)?; - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTest::send( - &self.client, - input, - ) - .await + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTest::send(&self.client, input).await } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_v2_shape::SimpleEnumV2Shape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types.rs index 951f1e5c4a..bd9720ed21 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types.rs @@ -1,5 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -/// Types for the `SimpleIntegerConfig` +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +/// Types for the `SimpleEnumV2Config` pub mod simple_enum_v2_config; -pub mod simple_enum_v2_shape; + +mod _simple_enum_v2_shape; +pub use crate::types::_simple_enum_v2_shape::SimpleEnumV2Shape; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/_simple_enum_v2_shape.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/_simple_enum_v2_shape.rs new file mode 100644 index 0000000000..6747128c1b --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/_simple_enum_v2_shape.rs @@ -0,0 +1,19 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[derive(Debug, PartialEq, Copy, Clone)] +pub enum SimpleEnumV2Shape { + First, +Second, +Third, +} + +impl ::std::fmt::Display for SimpleEnumV2Shape { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match self { + SimpleEnumV2Shape::First => write!(f, "FIRST"), +SimpleEnumV2Shape::Second => write!(f, "SECOND"), +SimpleEnumV2Shape::Third => write!(f, "THIRD"), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_config.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_config.rs index 37b2d81ac2..d03031da87 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_config.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_config.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleEnumV2Config {} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_shape.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_shape.rs deleted file mode 100644 index b1eb347281..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_shape.rs +++ /dev/null @@ -1,6 +0,0 @@ -#[derive(Debug, PartialEq, Copy, Clone)] -pub enum SimpleEnumV2Shape { - FIRST, - SECOND, - THIRD, -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..4bcdd7d0f8 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::enumv2::internaldafny::wrapped::_default { + pub fn WrappedSimpleEnumV2(config: &::std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Config, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..5beee2ab3f --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,179 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::enumv2::internaldafny::types::ISimpleTypesEnumV2Client); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Config, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_enum_v2_config::_simple_enum_v2_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::enumv2::internaldafny::types::ISimpleTypesEnumV2Client for Client { + fn GetEnumV2( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum_v2::_get_enum_v2_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum_v2::GetEnumV2::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum_v2::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum_v2::_get_enum_v2_output::to_dafny(client), + }, + ), + } + } + + fn GetEnumV2FirstKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum_v2_first_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_output::to_dafny(client), + }, + ), + } + } + + fn GetEnumV2SecondKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum_v2_second_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_output::to_dafny(client), + }, + ), + } + } + + fn GetEnumV2ThirdKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum_v2_third_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/tests/simple_enum_v2_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/tests/simple_enum_v2_test.rs index ddf89e15e4..4ce5192c09 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/tests/simple_enum_v2_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/tests/simple_enum_v2_test.rs @@ -1,48 +1,48 @@ -use simple_enum_v2::types::simple_enum_v2_shape::SimpleEnumV2Shape::*; +use simple_enum_v2::types::SimpleEnumV2Shape::*; use simple_enum_v2::*; #[tokio::test] async fn test_get_enum() { - let result = client().get_enum_v2().value(SECOND).send().await; + let result = client().get_enum_v2().value(Second).send().await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, SECOND); + assert_eq!(value, Second); } #[tokio::test] async fn test_get_first_known_value() { let result = client() .get_enum_v2_first_known_value_test() - .value(FIRST) + .value(First) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, FIRST); + assert_eq!(value, First); } #[tokio::test] async fn test_get_second_known_value() { let result = client() .get_enum_v2_second_known_value_test() - .value(SECOND) + .value(Second) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, SECOND); + assert_eq!(value, Second); } #[tokio::test] async fn test_get_third_known_value() { let result = client() .get_enum_v2_third_known_value_test() - .value(THIRD) + .value(Third) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, THIRD); + assert_eq!(value, Third); } pub fn client() -> Client { diff --git a/TestModels/SimpleTypes/SimpleInteger/Makefile b/TestModels/SimpleTypes/SimpleInteger/Makefile index 8eb6373ed5..d16e178928 100644 --- a/TestModels/SimpleTypes/SimpleInteger/Makefile +++ b/TestModels/SimpleTypes/SimpleInteger/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/Cargo.toml index d14ad003b2..3ef7587f62 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/Cargo.toml @@ -5,13 +5,19 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies.tokio] +[dev-dependencies] +simple_integer = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client.rs index a82eefe997..077a869866 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -29,11 +30,11 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } mod get_integer; -mod get_integer_known_value; +mod get_integer_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer.rs index ac241528f2..11767e3f95 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetInteger`](crate::operation::get_integer::builders::GetIntegerFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(i32)`](crate::operation::get_integer::builders::GetIntegerFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_integer::builders::GetIntegerFluentBuilder::set_value):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_integer::builders::GetIntegerFluentBuilder::value) / [`set_value(Option<::std::primitive::i32>)`](crate::operation::get_integer::builders::GetIntegerFluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetIntegerOutput`](crate::operation::get_integer::GetIntegerOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_integer::GetIntegerOutput::value): (undocumented) + /// - [`value(Option<::std::primitive::i32>)`](crate::operation::get_integer::GetIntegerOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_integer::GetIntegerError) pub fn get_integer(&self) -> crate::operation::get_integer::builders::GetIntegerFluentBuilder { crate::operation::get_integer::builders::GetIntegerFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value.rs deleted file mode 100644 index 82695c20fe..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -impl super::Client { - /// Constructs a fluent builder for the [`GetInteger`](crate::operation::get_integer_known_value::builders::GetIntegerFluentBuilder) operation. - /// - /// - The fluent builder is configurable: - /// - [`value(i32)`](crate::operation::get_integer_known_value::builders::GetIntegerFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_integer_known_value::builders::GetIntegerFluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetIntegerOutput`](crate::operation::get_integer_known_value::GetIntegerOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_integer_known_value::GetIntegerOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_integer_known_value::GetIntegerError) - pub fn get_integer_known_value( - &self, - ) -> crate::operation::get_integer_known_value::builders::GetIntegerKnownValueFluentBuilder - { - crate::operation::get_integer_known_value::builders::GetIntegerKnownValueFluentBuilder::new( - self.clone(), - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value_test.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value_test.rs new file mode 100644 index 0000000000..7612ae9e55 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value_test.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +impl super::Client { + /// Constructs a fluent builder for the [`GetIntegerKnownValueTest`](crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder) operation. + /// + /// - The fluent builder is configurable: + /// - [`value(impl Into>)`](crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder::value) / [`set_value(Option<::std::primitive::i32>)`](crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetIntegerOutput`](crate::operation::get_integer_known_value_test::GetIntegerOutput) with field(s): + /// - [`value(Option<::std::primitive::i32>)`](crate::operation::get_integer_known_value_test::GetIntegerOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError) + pub fn get_integer_known_value_test(&self) -> crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder { + crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder::new(self.clone()) + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions.rs index 9d397cd054..0af6bf6b95 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions.rs @@ -1,6 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_integer; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod get_integer_known_value; + pub mod get_integer; -pub mod simple_integer_config; + pub mod get_integer_known_value_test; + + pub mod simple_integer_config; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..77c44d4372 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::integer::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer.rs index 3637ac26fa..465334c3ec 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_input.rs index 9b5403e088..03797dbbe0 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_input.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_input.rs @@ -1,37 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_integer::GetIntegerInput, ) -> ::std::rc::Rc< crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { value: v }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerInput::GetIntegerInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::oint_to_dafny(value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, >, ) -> crate::operation::get_integer::GetIntegerInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_integer::GetIntegerInput { value } + crate::operation::get_integer::GetIntegerInput::builder() + .set_value(crate::standard_library_conversions::oint_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_output.rs index 0883177221..9b8946b2ba 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_output.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_output.rs @@ -1,37 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_integer::GetIntegerOutput, ) -> ::std::rc::Rc< crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput::GetIntegerOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::oint_to_dafny(value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, >, ) -> crate::operation::get_integer::GetIntegerOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_integer::GetIntegerOutput { value } + crate::operation::get_integer::GetIntegerOutput::builder() + .set_value(crate::standard_library_conversions::oint_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value.rs deleted file mode 100644 index 15c6b7c8b2..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -use std::any::Any; - -#[allow(dead_code)] -pub fn to_dafny_error( - value: crate::operation::get_integer_known_value::GetIntegerKnownValueError, -) -> ::std::rc::Rc { - match value { - crate::operation::get_integer_known_value::GetIntegerKnownValueError::Unhandled(unhandled) => - ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) - } -} - -#[allow(dead_code)] -pub fn from_dafny_error( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::Error, - >, -) -> crate::operation::get_integer_known_value::GetIntegerKnownValueError { - // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error - if matches!(&dafny_value.as_ref(), crate::r#simple::types::integer::internaldafny::types::Error::CollectionOfErrors { .. }) { - let error_message = "TODO: can't get message yet"; - crate::operation::get_integer_known_value::GetIntegerKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) - } else { - crate::operation::get_integer_known_value::GetIntegerKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) - } -} - -pub mod _get_integer_known_value_input; - -pub mod _get_integer_known_value_output; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_input.rs deleted file mode 100644 index 40db6820d4..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_input.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_integer_known_value::GetIntegerKnownValueInput, -) -> ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { value: v }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerInput::GetIntegerInput { - value: ::std::rc::Rc::new(dafny_value) - }) -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, - >, -) -> crate::operation::get_integer_known_value::GetIntegerKnownValueInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_integer_known_value::GetIntegerKnownValueInput { value } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_output.rs deleted file mode 100644 index c122e6bee4..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_output.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, -) -> ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput::GetIntegerOutput { - value: ::std::rc::Rc::new(dafny_value) - }) -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, - >, -) -> crate::operation::get_integer_known_value::GetIntegerKnownValueOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_integer_known_value::GetIntegerKnownValueOutput { value } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test.rs new file mode 100644 index 0000000000..553b0b3725 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test.rs @@ -0,0 +1,33 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +#[allow(dead_code)] +pub fn to_dafny_error( + value: crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError, +) -> ::std::rc::Rc { + match value { + crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError::Unhandled(unhandled) => + ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) + } +} + +#[allow(dead_code)] +pub fn from_dafny_error( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::Error, + >, +) -> crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError { + // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error + if matches!(&dafny_value.as_ref(), crate::r#simple::types::integer::internaldafny::types::Error::CollectionOfErrors { .. }) { + let error_message = "TODO: can't get message yet"; + crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) + } else { + crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) + } +} + +pub mod _get_integer_known_value_test_input; + +pub mod _get_integer_known_value_test_output; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_input.rs new file mode 100644 index 0000000000..0b004b785b --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_input.rs @@ -0,0 +1,24 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_integer_known_value_test::GetIntegerInput, +) -> ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, +>{ + ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerInput::GetIntegerInput { + value: crate::standard_library_conversions::oint_to_dafny(value.value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, + >, +) -> crate::operation::get_integer_known_value_test::GetIntegerInput { + crate::operation::get_integer_known_value_test::GetIntegerInput::builder() + .set_value(crate::standard_library_conversions::oint_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_output.rs new file mode 100644 index 0000000000..19f8b437b6 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_output.rs @@ -0,0 +1,24 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_integer_known_value_test::GetIntegerOutput, +) -> ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, +>{ + ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput::GetIntegerOutput { + value: crate::standard_library_conversions::oint_to_dafny(value.value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, + >, +) -> crate::operation::get_integer_known_value_test::GetIntegerOutput { + crate::operation::get_integer_known_value_test::GetIntegerOutput::builder() + .set_value(crate::standard_library_conversions::oint_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config.rs index f3cdb7384b..f25f66bfec 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_integer_config; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config/_simple_integer_config.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config/_simple_integer_config.rs index 360d19898b..a712be2fba 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config/_simple_integer_config.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config/_simple_integer_config.rs @@ -1,10 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_integer_config::SimpleIntegerConfig, ) -> ::std::rc::Rc< - crate::simple::types::integer::internaldafny::types::SimpleIntegerConfig, + crate::r#simple::types::integer::internaldafny::types::SimpleIntegerConfig, > { ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::SimpleIntegerConfig::SimpleIntegerConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/lib.rs deleted file mode 100644 index e427bffab8..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub mod implementation_from_dafny; - -pub use client::Client; -pub use types::simple_integer_config::SimpleIntegerConfig; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation.rs index faaa994cb8..94588bbdb2 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation.rs @@ -1,7 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetInteger` operation. pub mod get_integer; -/// Types for the `GetIntegerKnownValue` operation. -pub mod get_integer_known_value; +/// Types for the `GetIntegerKnownValueTest` operation. +pub mod get_integer_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer.rs index 3cb49535a7..1887a2158b 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetInteger`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -137,9 +139,9 @@ pub use crate::operation::get_integer::_get_integer_output::GetIntegerOutput; pub use crate::operation::get_integer::_get_integer_input::GetIntegerInput; -mod _get_integer_input; +pub(crate) mod _get_integer_output; -mod _get_integer_output; +pub(crate) mod _get_integer_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_input.rs index ab0c63e080..ae911475a7 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_input.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_input.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetIntegerInput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option<::std::primitive::i32>, } impl GetIntegerInput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&i32> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option<::std::primitive::i32> { + self.value +} } impl GetIntegerInput { /// Creates a new builder-style object to manufacture [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). @@ -25,23 +27,23 @@ impl GetIntegerInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetIntegerInputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option<::std::primitive::i32>, } impl GetIntegerInputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { + &self.value +} /// Consumes the builder and constructs a [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_output.rs index 49ae58c834..354b4fb6af 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_output.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_output.rs @@ -1,19 +1,19 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetIntegerOutput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option<::std::primitive::i32>, } - impl GetIntegerOutput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } +pub fn value(&self) -> ::std::option::Option<::std::primitive::i32> { + self.value +} } - impl GetIntegerOutput { /// Creates a new builder-style object to manufacture [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). pub fn builder() -> crate::operation::get_integer::builders::GetIntegerOutputBuilder { @@ -27,27 +27,23 @@ impl GetIntegerOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetIntegerOutputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option<::std::primitive::i32>, } - impl GetIntegerOutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } - +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { + &self.value +} /// Consumes the builder and constructs a [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/builders.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/builders.rs index 74d985a93a..f96df4a71d 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/builders.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/builders.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_integer::_get_integer_output::GetIntegerOutputBuilder; pub use crate::operation::get_integer::_get_integer_input::GetIntegerInputBuilder; @@ -21,8 +23,8 @@ impl GetIntegerInputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetIntegerFluentBuilder { - client: crate::Client, - inner: crate::operation::get_integer::builders::GetIntegerInputBuilder, + client: crate::client::Client, + pub(crate) inner: crate::operation::get_integer::builders::GetIntegerInputBuilder, } impl GetIntegerFluentBuilder { /// Creates a new `GetInteger`. @@ -56,17 +58,17 @@ impl GetIntegerFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: i32) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_input.rs deleted file mode 100644 index 83a4b82918..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_input.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetIntegerKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetIntegerKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetIntegerKnownValueInput { - /// Creates a new builder-style object to manufacture [`GetIntegerKnownValueInput`](crate::operation::operation::GetIntegerKnownValueInput). - pub fn builder( - ) -> crate::operation::get_integer_known_value::builders::GetIntegerKnownValueInputBuilder { - crate::operation::get_integer_known_value::builders::GetIntegerKnownValueInputBuilder::default() - } -} - -/// A builder for [`GetIntegerKnownValueInput`](crate::operation::operation::GetIntegerKnownValueInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetIntegerKnownValueInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetIntegerKnownValueInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetIntegerKnownValueInput`](crate::operation::operation::GetIntegerKnownValueInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_integer_known_value::GetIntegerKnownValueInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_integer_known_value::GetIntegerKnownValueInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_output.rs deleted file mode 100644 index f80e3163bf..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_output.rs +++ /dev/null @@ -1,60 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetIntegerKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetIntegerKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetIntegerKnownValueOutput { - /// Creates a new builder-style object to manufacture [`GetIntegerKnownValueOutput`](crate::operation::operation::GetIntegerKnownValueOutput). - pub fn builder( - ) -> crate::operation::get_integer_known_value::builders::GetIntegerKnownValueOutputBuilder - { - crate::operation::get_integer_known_value::builders::GetIntegerKnownValueOutputBuilder::default() - } -} - -/// A builder for [`GetIntegerKnownValueOutput`](crate::operation::operation::GetIntegerKnownValueOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetIntegerKnownValueOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetIntegerKnownValueOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetIntegerKnownValueOutput`](crate::operation::operation::GetIntegerKnownValueOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_integer_known_value::GetIntegerKnownValueOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/builders.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/builders.rs deleted file mode 100644 index 9cfc99ee3a..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/builders.rs +++ /dev/null @@ -1,78 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_integer_known_value::_get_integer_known_value_output::GetIntegerKnownValueOutputBuilder; - -pub use crate::operation::get_integer_known_value::_get_integer_known_value_input::GetIntegerKnownValueInputBuilder; - -impl GetIntegerKnownValueInputBuilder { - /// Sends a request with this input using the given client. - pub async fn send_with( - self, - client: &crate::Client, - ) -> ::std::result::Result< - crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, - crate::operation::get_integer_known_value::GetIntegerKnownValueError, - > { - let mut fluent_builder = client.get_integer_known_value(); - fluent_builder.inner = self; - fluent_builder.send().await - } -} -/// Fluent builder constructing a request to `GetIntegerKnownValue`. -/// -#[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct GetIntegerKnownValueFluentBuilder { - client: crate::client::Client, - inner: crate::operation::get_integer_known_value::builders::GetIntegerKnownValueInputBuilder, -} -impl GetIntegerKnownValueFluentBuilder { - /// Creates a new `GetIntegerKnownValue`. - pub(crate) fn new(client: crate::client::Client) -> Self { - Self { - client, - inner: ::std::default::Default::default(), - } - } - /// Access the GetIntegerKnownValue as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_integer_known_value::builders::GetIntegerKnownValueInputBuilder - { - &self.inner - } - /// Sends the request and returns the response. - pub async fn send( - self, - ) -> ::std::result::Result< - crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, - crate::operation::get_integer_known_value::GetIntegerKnownValueError, - > { - let input = self - .inner - .build() - // Using unhandled since GetInteger doesn't declare any validation, - // and smithy-rs seems to not generate a ValidationError case unless there is - // (but isn't that a backwards compatibility problem for output structures?) - // Vanilla smithy-rs uses SdkError::construction_failure, - // but we aren't using SdkError. - .map_err( - crate::operation::get_integer_known_value::GetIntegerKnownValueError::unhandled, - )?; - crate::operation::get_integer_known_value::GetIntegerKnownValue::send(&self.client, input) - .await - } - - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: i32) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() - } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test.rs similarity index 67% rename from TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value.rs rename to TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test.rs index 06e0fa0cb4..0a0f7a5080 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test.rs @@ -1,49 +1,46 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -/// Orchestration and serialization glue logic for `GetIntegerKnownValue`. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +/// Orchestration and serialization glue logic for `GetIntegerKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] -pub struct GetIntegerKnownValue; -impl GetIntegerKnownValue { - /// Creates a new `GetIntegerKnownValue` +pub struct GetIntegerKnownValueTest; +impl GetIntegerKnownValueTest { + /// Creates a new `GetIntegerKnownValueTest` pub fn new() -> Self { Self } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_integer_known_value::GetIntegerKnownValueInput, + input: crate::operation::get_integer_known_value_test::GetIntegerInput, ) -> ::std::result::Result< - crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, - crate::operation::get_integer_known_value::GetIntegerKnownValueError, + crate::operation::get_integer_known_value_test::GetIntegerOutput, + crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError, > { - let inner_input = - crate::conversions::get_integer_known_value::_get_integer_known_value_input::to_dafny( - input, - ); + let inner_input = crate::conversions::get_integer_known_value_test::_get_integer_known_value_test_input::to_dafny(input); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetInteger(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetIntegerKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { Ok( - crate::conversions::get_integer_known_value::_get_integer_known_value_output::from_dafny( + crate::conversions::get_integer_known_value_test::_get_integer_known_value_test_output::from_dafny( inner_result.value().clone(), ), ) } else { - Err( - crate::conversions::get_integer_known_value::from_dafny_error( - inner_result.error().clone(), - ), - ) + Err(crate::conversions::get_integer_known_value_test::from_dafny_error( + inner_result.error().clone(), + )) } } } -/// Error type for the `GetIntegerKnownValue` operation. +/// Error type for the `GetIntegerKnownValueTest` operation. #[non_exhaustive] #[derive(::std::fmt::Debug)] -pub enum GetIntegerKnownValueError { +pub enum GetIntegerKnownValueTestError { /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ @@ -51,12 +48,12 @@ pub enum GetIntegerKnownValueError { \    `err if err.code() == Some(\"SpecificExceptionCode\") => { /* handle the error */ }` \ - See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetIntegerKnownValueError) for what information is available for the error." + See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetIntegerKnownValueTestError) for what information is available for the error." )] Unhandled(crate::error::sealed_unhandled::Unhandled), } -impl GetIntegerKnownValueError { - /// Creates the `GetIntegerKnownValueError::Unhandled` variant from any error type. +impl GetIntegerKnownValueTestError { + /// Creates the `GetIntegerKnownValueTestError::Unhandled` variant from any error type. pub fn unhandled( err: impl ::std::convert::Into< ::std::boxed::Box< @@ -70,7 +67,7 @@ impl GetIntegerKnownValueError { }) } - /// Creates the `GetIntegerKnownValueError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). + /// Creates the `GetIntegerKnownValueTestError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). pub fn generic(err: ::aws_smithy_types::error::ErrorMetadata) -> Self { Self::Unhandled(crate::error::sealed_unhandled::Unhandled { source: err.clone().into(), @@ -87,14 +84,14 @@ impl GetIntegerKnownValueError { } } } -impl ::std::error::Error for GetIntegerKnownValueError { +impl ::std::error::Error for GetIntegerKnownValueTestError { fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> { match self { Self::Unhandled(_inner) => ::std::option::Option::Some(&*_inner.source), } } } -impl ::std::fmt::Display for GetIntegerKnownValueError { +impl ::std::fmt::Display for GetIntegerKnownValueTestError { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self { Self::Unhandled(_inner) => { @@ -109,7 +106,7 @@ impl ::std::fmt::Display for GetIntegerKnownValueError { } } } -impl ::aws_smithy_types::retry::ProvideErrorKind for GetIntegerKnownValueError { +impl ::aws_smithy_types::retry::ProvideErrorKind for GetIntegerKnownValueTestError { fn code(&self) -> ::std::option::Option<&str> { ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self) } @@ -117,14 +114,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetIntegerKnownValueError { ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetIntegerKnownValueError { +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetIntegerKnownValueTestError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetIntegerKnownValueError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetIntegerKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -138,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetInteg } } -pub use crate::operation::get_integer_known_value::_get_integer_known_value_output::GetIntegerKnownValueOutput; +pub use crate::operation::get_integer_known_value_test::_get_integer_output::GetIntegerOutput; -pub use crate::operation::get_integer_known_value::_get_integer_known_value_input::GetIntegerKnownValueInput; +pub use crate::operation::get_integer_known_value_test::_get_integer_input::GetIntegerInput; -mod _get_integer_known_value_input; +pub(crate) mod _get_integer_output; -mod _get_integer_known_value_output; +pub(crate) mod _get_integer_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_input.rs new file mode 100644 index 0000000000..43e834f3de --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetIntegerInput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::primitive::i32>, +} +impl GetIntegerInput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::primitive::i32> { + self.value +} +} +impl GetIntegerInput { + /// Creates a new builder-style object to manufacture [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). + pub fn builder() -> crate::operation::get_integer_known_value_test::builders::GetIntegerInputBuilder { + crate::operation::get_integer_known_value_test::builders::GetIntegerInputBuilder::default() + } +} + +/// A builder for [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetIntegerInputBuilder { + pub(crate) value: ::std::option::Option<::std::primitive::i32>, +} +impl GetIntegerInputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { + &self.value +} + /// Consumes the builder and constructs a [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_integer_known_value_test::GetIntegerInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_integer_known_value_test::GetIntegerInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_output.rs new file mode 100644 index 0000000000..c1c00f46eb --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetIntegerOutput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::primitive::i32>, +} +impl GetIntegerOutput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::primitive::i32> { + self.value +} +} +impl GetIntegerOutput { + /// Creates a new builder-style object to manufacture [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). + pub fn builder() -> crate::operation::get_integer_known_value_test::builders::GetIntegerOutputBuilder { + crate::operation::get_integer_known_value_test::builders::GetIntegerOutputBuilder::default() + } +} + +/// A builder for [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetIntegerOutputBuilder { + pub(crate) value: ::std::option::Option<::std::primitive::i32>, +} +impl GetIntegerOutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { + &self.value +} + /// Consumes the builder and constructs a [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_integer_known_value_test::GetIntegerOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_integer_known_value_test::GetIntegerOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/builders.rs new file mode 100644 index 0000000000..a7554ca939 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/builders.rs @@ -0,0 +1,74 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_integer_known_value_test::_get_integer_output::GetIntegerOutputBuilder; + +pub use crate::operation::get_integer_known_value_test::_get_integer_input::GetIntegerInputBuilder; + +impl GetIntegerInputBuilder { + /// Sends a request with this input using the given client. + pub async fn send_with( + self, + client: &crate::Client, + ) -> ::std::result::Result< + crate::operation::get_integer_known_value_test::GetIntegerOutput, + crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError, + > { + let mut fluent_builder = client.get_integer_known_value_test(); + fluent_builder.inner = self; + fluent_builder.send().await + } +} +/// Fluent builder constructing a request to `GetIntegerKnownValueTest`. +/// +#[derive(::std::clone::Clone, ::std::fmt::Debug)] +pub struct GetIntegerKnownValueTestFluentBuilder { + client: crate::client::Client, + pub(crate) inner: crate::operation::get_integer_known_value_test::builders::GetIntegerInputBuilder, +} +impl GetIntegerKnownValueTestFluentBuilder { + /// Creates a new `GetIntegerKnownValueTest`. + pub(crate) fn new(client: crate::client::Client) -> Self { + Self { + client, + inner: ::std::default::Default::default(), + } + } + /// Access the GetIntegerKnownValueTest as a reference. + pub fn as_input(&self) -> &crate::operation::get_integer_known_value_test::builders::GetIntegerInputBuilder { + &self.inner + } + /// Sends the request and returns the response. + pub async fn send( + self, + ) -> ::std::result::Result< + crate::operation::get_integer_known_value_test::GetIntegerOutput, + crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError, + > { + let input = self + .inner + .build() + // Using unhandled since GetIntegerKnownValueTest doesn't declare any validation, + // and smithy-rs seems to not generate a ValidationError case unless there is + // (but isn't that a backwards compatibility problem for output structures?) + // Vanilla smithy-rs uses SdkError::construction_failure, + // but we aren't using SdkError. + .map_err(crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError::unhandled)?; + crate::operation::get_integer_known_value_test::GetIntegerKnownValueTest::send(&self.client, input).await + } + + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { + self.inner.get_value() +} +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types.rs index 0ab755433a..646cdced26 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `SimpleIntegerConfig` pub mod simple_integer_config; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types/simple_integer_config.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types/simple_integer_config.rs index 15a5df4737..4851f5748c 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types/simple_integer_config.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types/simple_integer_config.rs @@ -1,9 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct SimpleIntegerConfig { - // XXX : ::std::option::Option -} +pub struct SimpleIntegerConfig {} impl SimpleIntegerConfig { pub fn builder() -> SimpleIntegerConfigBuilder { @@ -12,17 +11,12 @@ impl SimpleIntegerConfig { } #[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct SimpleIntegerConfigBuilder { - // XXX : ::std::option::Option -} +pub struct SimpleIntegerConfigBuilder {} impl SimpleIntegerConfigBuilder { /// Creates a new `SimpleIntegerConfigBuilder`. pub(crate) fn new() -> Self { - Self { - // XXX = ::std::option::Option::None - // somewhere get default values for things? - } + Self {} } pub fn build( self, @@ -30,19 +24,4 @@ impl SimpleIntegerConfigBuilder { { ::std::result::Result::Ok(SimpleIntegerConfig {}) } - /* - pub fn XXX(mut self, input: impl ::std::convert::Into) -> Self { - self.XXX = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_XXX(mut self, input: ::std::option::Option) -> Self { - self.XXX = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_XXX(&self) -> &::std::option::Option { - &self.XXX - } - */ } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..77a3cb4cd4 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::integer::internaldafny::wrapped::_default { + pub fn WrappedSimpleInteger(config: &::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::SimpleIntegerConfig, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..2df771a408 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,119 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::integer::internaldafny::types::ISimpleTypesIntegerClient); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::SimpleIntegerConfig, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_integer_config::_simple_integer_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::integer::internaldafny::types::ISimpleTypesIntegerClient for Client { + fn GetInteger( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_integer::_get_integer_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_integer::GetInteger::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_integer::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_integer::_get_integer_output::to_dafny(client), + }, + ), + } + } + + fn GetIntegerKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_integer_known_value_test::_get_integer_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_integer_known_value_test::GetIntegerKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_integer_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_integer_known_value_test::_get_integer_known_value_test_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/tests/simple_integer_test.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/tests/simple_integer_test.rs index 432eb5450c..a48b2d5df6 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/tests/simple_integer_test.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/tests/simple_integer_test.rs @@ -10,7 +10,7 @@ async fn test_get_integer() { #[tokio::test] async fn test_get_known_value() { - let result = client().get_integer_known_value().value(20).send().await; + let result = client().get_integer_known_value_test().value(20).send().await; let output = result.unwrap(); let value = output.value().unwrap(); assert_eq!(value, 20); diff --git a/TestModels/SimpleTypes/SimpleLong/Makefile b/TestModels/SimpleTypes/SimpleLong/Makefile index 0dd260a2b4..c09454c434 100644 --- a/TestModels/SimpleTypes/SimpleLong/Makefile +++ b/TestModels/SimpleTypes/SimpleLong/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/Cargo.toml index 6fa3747d29..9c0ced7f0a 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/Cargo.toml @@ -5,13 +5,19 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies.tokio] +[dev-dependencies] +simple_long = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client.rs index 0529ead1f9..6ec9bcc3e4 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -29,11 +30,11 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } mod get_long; -mod get_long_known_value; +mod get_long_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long.rs index acd51ffb21..d420786f93 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetLong`](crate::operation::get_long::builders::GetLongFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(i64)`](crate::operation::get_long::builders::GetLongFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_long::builders::GetLongFluentBuilder::set_value):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_long::builders::GetLongFluentBuilder::value) / [`set_value(Option<::std::primitive::i64>)`](crate::operation::get_long::builders::GetLongFluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetLongOutput`](crate::operation::get_long::GetLongOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_long::GetLongOutput::value): (undocumented) + /// - [`value(Option<::std::primitive::i64>)`](crate::operation::get_long::GetLongOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_long::GetLongError) pub fn get_long(&self) -> crate::operation::get_long::builders::GetLongFluentBuilder { crate::operation::get_long::builders::GetLongFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value.rs deleted file mode 100644 index 197e3f5bef..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value.rs +++ /dev/null @@ -1,17 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -impl super::Client { - /// Constructs a fluent builder for the [`GetLong`](crate::operation::get_long_known_value::builders::GetLongFluentBuilder) operation. - /// - /// - The fluent builder is configurable: - /// - [`value(i64)`](crate::operation::get_long_known_value::builders::GetLongFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_long_known_value::builders::GetLongFluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetLongOutput`](crate::operation::get_long_known_value::GetLongOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_long_known_value::GetLongOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_long_known_value::GetLongError) - pub fn get_long_known_value( - &self, - ) -> crate::operation::get_long_known_value::builders::GetLongKnownValueFluentBuilder { - crate::operation::get_long_known_value::builders::GetLongKnownValueFluentBuilder::new( - self.clone(), - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value_test.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value_test.rs new file mode 100644 index 0000000000..d0cc474cc5 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value_test.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +impl super::Client { + /// Constructs a fluent builder for the [`GetLongKnownValueTest`](crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder) operation. + /// + /// - The fluent builder is configurable: + /// - [`value(impl Into>)`](crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder::value) / [`set_value(Option<::std::primitive::i64>)`](crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetLongOutput`](crate::operation::get_long_known_value_test::GetLongOutput) with field(s): + /// - [`value(Option<::std::primitive::i64>)`](crate::operation::get_long_known_value_test::GetLongOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_long_known_value_test::GetLongKnownValueTestError) + pub fn get_long_known_value_test(&self) -> crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder { + crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder::new(self.clone()) + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions.rs index 4ff5bcbc92..a0cb33c551 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions.rs @@ -1,6 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_long; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod get_long_known_value; + pub mod get_long; -pub mod simple_long_config; + pub mod get_long_known_value_test; + + pub mod simple_long_config; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..4d0aeedd1a --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::smithylong::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long.rs index 59558ca19b..210e9a6d0d 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_input.rs index 8392959724..9b4211a3da 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_input.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_input.rs @@ -1,37 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_long::GetLongInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { value: v }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongInput::GetLongInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::olong_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, >, ) -> crate::operation::get_long::GetLongInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_long::GetLongInput { value } + crate::operation::get_long::GetLongInput::builder() + .set_value(crate::standard_library_conversions::olong_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_output.rs index 68ff34defe..4bbf353650 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_output.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_output.rs @@ -1,37 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_long::GetLongOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput::GetLongOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::olong_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, >, ) -> crate::operation::get_long::GetLongOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_long::GetLongOutput { value } + crate::operation::get_long::GetLongOutput::builder() + .set_value(crate::standard_library_conversions::olong_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value.rs deleted file mode 100644 index f4c90a3a2b..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -use std::any::Any; - -#[allow(dead_code)] -pub fn to_dafny_error( - value: crate::operation::get_long_known_value::GetLongKnownValueError, -) -> ::std::rc::Rc { - match value { - crate::operation::get_long_known_value::GetLongKnownValueError::Unhandled(unhandled) => - ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) - } -} - -#[allow(dead_code)] -pub fn from_dafny_error( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::Error, - >, -) -> crate::operation::get_long_known_value::GetLongKnownValueError { - // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error - if matches!(&dafny_value.as_ref(), crate::r#simple::types::smithylong::internaldafny::types::Error::CollectionOfErrors { .. }) { - let error_message = "TODO: can't get message yet"; - crate::operation::get_long_known_value::GetLongKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) - } else { - crate::operation::get_long_known_value::GetLongKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) - } -} - -pub mod _get_long_known_value_input; - -pub mod _get_long_known_value_output; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_input.rs deleted file mode 100644 index aae399058f..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_input.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_long_known_value::GetLongKnownValueInput, -) -> ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { value: v }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongInput::GetLongInput { - value: ::std::rc::Rc::new(dafny_value) - }) -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, - >, -) -> crate::operation::get_long_known_value::GetLongKnownValueInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_long_known_value::GetLongKnownValueInput { value } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_output.rs deleted file mode 100644 index bdc927aae1..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_output.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_long_known_value::GetLongKnownValueOutput, -) -> ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput::GetLongOutput { - value: ::std::rc::Rc::new(dafny_value) - }) -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, - >, -) -> crate::operation::get_long_known_value::GetLongKnownValueOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_long_known_value::GetLongKnownValueOutput { value } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test.rs new file mode 100644 index 0000000000..5550a2e767 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test.rs @@ -0,0 +1,33 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +#[allow(dead_code)] +pub fn to_dafny_error( + value: crate::operation::get_long_known_value_test::GetLongKnownValueTestError, +) -> ::std::rc::Rc { + match value { + crate::operation::get_long_known_value_test::GetLongKnownValueTestError::Unhandled(unhandled) => + ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) + } +} + +#[allow(dead_code)] +pub fn from_dafny_error( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::Error, + >, +) -> crate::operation::get_long_known_value_test::GetLongKnownValueTestError { + // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error + if matches!(&dafny_value.as_ref(), crate::r#simple::types::smithylong::internaldafny::types::Error::CollectionOfErrors { .. }) { + let error_message = "TODO: can't get message yet"; + crate::operation::get_long_known_value_test::GetLongKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) + } else { + crate::operation::get_long_known_value_test::GetLongKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) + } +} + +pub mod _get_long_known_value_test_input; + +pub mod _get_long_known_value_test_output; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_input.rs new file mode 100644 index 0000000000..67c44ec3c3 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_input.rs @@ -0,0 +1,24 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_long_known_value_test::GetLongInput, +) -> ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, +>{ + ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongInput::GetLongInput { + value: crate::standard_library_conversions::olong_to_dafny(&value.value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, + >, +) -> crate::operation::get_long_known_value_test::GetLongInput { + crate::operation::get_long_known_value_test::GetLongInput::builder() + .set_value(crate::standard_library_conversions::olong_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_output.rs new file mode 100644 index 0000000000..859142fbf6 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_output.rs @@ -0,0 +1,24 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_long_known_value_test::GetLongOutput, +) -> ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, +>{ + ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput::GetLongOutput { + value: crate::standard_library_conversions::olong_to_dafny(&value.value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, + >, +) -> crate::operation::get_long_known_value_test::GetLongOutput { + crate::operation::get_long_known_value_test::GetLongOutput::builder() + .set_value(crate::standard_library_conversions::olong_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config.rs index 129c7eb442..644ecd05da 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_long_config; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config/_simple_long_config.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config/_simple_long_config.rs index 4bb610c4d2..1371539ba8 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config/_simple_long_config.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config/_simple_long_config.rs @@ -1,10 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_long_config::SimpleLongConfig, ) -> ::std::rc::Rc< - crate::simple::types::smithylong::internaldafny::types::SimpleLongConfig, + crate::r#simple::types::smithylong::internaldafny::types::SimpleLongConfig, > { ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::SimpleLongConfig::SimpleLongConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/lib.rs deleted file mode 100644 index 1248f58305..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub mod implementation_from_dafny; - -pub use client::Client; -pub use types::simple_long_config::SimpleLongConfig; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation.rs index 9378720071..4584907aea 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation.rs @@ -1,7 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetLong` operation. pub mod get_long; -/// Types for the `GetLongKnownValue` operation. -pub mod get_long_known_value; +/// Types for the `GetLongKnownValueTest` operation. +pub mod get_long_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long.rs index 44259e5ba4..a7387cce96 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetLong`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -16,14 +18,17 @@ impl GetLong { crate::operation::get_long::GetLongError, > { let inner_input = crate::conversions::get_long::_get_long_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetLong(&inner_input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetLong(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - Ok(crate::conversions::get_long::_get_long_output::from_dafny( - inner_result.value().clone(), - )) + Ok( + crate::conversions::get_long::_get_long_output::from_dafny( + inner_result.value().clone(), + ), + ) } else { Err(crate::conversions::get_long::from_dafny_error( inner_result.error().clone(), @@ -134,9 +139,9 @@ pub use crate::operation::get_long::_get_long_output::GetLongOutput; pub use crate::operation::get_long::_get_long_input::GetLongInput; -mod _get_long_input; +pub(crate) mod _get_long_output; -mod _get_long_output; +pub(crate) mod _get_long_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_input.rs index cf4ca97a0f..0f9e90cd9c 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_input.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_input.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetLongInput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option<::std::primitive::i64>, } impl GetLongInput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&i64> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option<::std::primitive::i64> { + self.value +} } impl GetLongInput { /// Creates a new builder-style object to manufacture [`GetLongInput`](crate::operation::operation::GetLongInput). @@ -25,23 +27,23 @@ impl GetLongInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetLongInputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option<::std::primitive::i64>, } impl GetLongInputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { + &self.value +} /// Consumes the builder and constructs a [`GetLongInput`](crate::operation::operation::GetLongInput). pub fn build( self, @@ -49,6 +51,8 @@ impl GetLongInputBuilder { crate::operation::get_long::GetLongInput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_long::GetLongInput { value: self.value }) + ::std::result::Result::Ok(crate::operation::get_long::GetLongInput { + value: self.value, + }) } } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_output.rs index 5a2814c686..86950e84ce 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_output.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_output.rs @@ -1,19 +1,19 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetLongOutput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option<::std::primitive::i64>, } - impl GetLongOutput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } +pub fn value(&self) -> ::std::option::Option<::std::primitive::i64> { + self.value +} } - impl GetLongOutput { /// Creates a new builder-style object to manufacture [`GetLongOutput`](crate::operation::operation::GetLongOutput). pub fn builder() -> crate::operation::get_long::builders::GetLongOutputBuilder { @@ -27,27 +27,23 @@ impl GetLongOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetLongOutputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option<::std::primitive::i64>, } - impl GetLongOutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } - +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { + &self.value +} /// Consumes the builder and constructs a [`GetLongOutput`](crate::operation::operation::GetLongOutput). pub fn build( self, @@ -55,6 +51,8 @@ impl GetLongOutputBuilder { crate::operation::get_long::GetLongOutput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_long::GetLongOutput { value: self.value }) + ::std::result::Result::Ok(crate::operation::get_long::GetLongOutput { + value: self.value, + }) } } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/builders.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/builders.rs index cf89d6b34d..5cdbbd256e 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/builders.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/builders.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_long::_get_long_output::GetLongOutputBuilder; pub use crate::operation::get_long::_get_long_input::GetLongInputBuilder; @@ -22,7 +24,7 @@ impl GetLongInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetLongFluentBuilder { client: crate::client::Client, - inner: crate::operation::get_long::builders::GetLongInputBuilder, + pub(crate) inner: crate::operation::get_long::builders::GetLongInputBuilder, } impl GetLongFluentBuilder { /// Creates a new `GetLong`. @@ -56,17 +58,17 @@ impl GetLongFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: i64) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_input.rs deleted file mode 100644 index b1b4d3bece..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_input.rs +++ /dev/null @@ -1,57 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetLongKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetLongKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetLongKnownValueInput { - /// Creates a new builder-style object to manufacture [`GetLongKnownValueInput`](crate::operation::operation::GetLongKnownValueInput). - pub fn builder( - ) -> crate::operation::get_long_known_value::builders::GetLongKnownValueInputBuilder { - crate::operation::get_long_known_value::builders::GetLongKnownValueInputBuilder::default() - } -} - -/// A builder for [`GetLongKnownValueInput`](crate::operation::operation::GetLongKnownValueInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetLongKnownValueInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetLongKnownValueInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetLongKnownValueInput`](crate::operation::operation::GetLongKnownValueInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_long_known_value::GetLongKnownValueInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_long_known_value::GetLongKnownValueInput { value: self.value }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_output.rs deleted file mode 100644 index b18b9c89a4..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_output.rs +++ /dev/null @@ -1,57 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetLongKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetLongKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetLongKnownValueOutput { - /// Creates a new builder-style object to manufacture [`GetLongKnownValueOutput`](crate::operation::operation::GetLongKnownValueOutput). - pub fn builder( - ) -> crate::operation::get_long_known_value::builders::GetLongKnownValueOutputBuilder { - crate::operation::get_long_known_value::builders::GetLongKnownValueOutputBuilder::default() - } -} - -/// A builder for [`GetLongKnownValueOutput`](crate::operation::operation::GetLongKnownValueOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetLongKnownValueOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetLongKnownValueOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetLongKnownValueOutput`](crate::operation::operation::GetLongKnownValueOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_long_known_value::GetLongKnownValueOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_long_known_value::GetLongKnownValueOutput { value: self.value }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/builders.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/builders.rs deleted file mode 100644 index 46a4de5e36..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/builders.rs +++ /dev/null @@ -1,74 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_long_known_value::_get_long_known_value_output::GetLongKnownValueOutputBuilder; - -pub use crate::operation::get_long_known_value::_get_long_known_value_input::GetLongKnownValueInputBuilder; - -impl GetLongKnownValueInputBuilder { - /// Sends a request with this input using the given client. - pub async fn send_with( - self, - client: &crate::Client, - ) -> ::std::result::Result< - crate::operation::get_long_known_value::GetLongKnownValueOutput, - crate::operation::get_long_known_value::GetLongKnownValueError, - > { - let mut fluent_builder = client.get_long_known_value(); - fluent_builder.inner = self; - fluent_builder.send().await - } -} -/// Fluent builder constructing a request to `GetLongKnownValue`. -/// -#[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct GetLongKnownValueFluentBuilder { - client: crate::client::Client, - inner: crate::operation::get_long_known_value::builders::GetLongKnownValueInputBuilder, -} -impl GetLongKnownValueFluentBuilder { - /// Creates a new `GetLongKnownValue`. - pub(crate) fn new(client: crate::client::Client) -> Self { - Self { - client, - inner: ::std::default::Default::default(), - } - } - /// Access the GetLongKnownValue as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_long_known_value::builders::GetLongKnownValueInputBuilder { - &self.inner - } - /// Sends the request and returns the response. - pub async fn send( - self, - ) -> ::std::result::Result< - crate::operation::get_long_known_value::GetLongKnownValueOutput, - crate::operation::get_long_known_value::GetLongKnownValueError, - > { - let input = self - .inner - .build() - // Using unhandled since GetLong doesn't declare any validation, - // and smithy-rs seems to not generate a ValidationError case unless there is - // (but isn't that a backwards compatibility problem for output structures?) - // Vanilla smithy-rs uses SdkError::construction_failure, - // but we aren't using SdkError. - .map_err(crate::operation::get_long_known_value::GetLongKnownValueError::unhandled)?; - crate::operation::get_long_known_value::GetLongKnownValue::send(&self.client, input).await - } - - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: i64) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() - } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test.rs similarity index 67% rename from TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value.rs rename to TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test.rs index b434182d0d..ce1f24b47b 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test.rs @@ -1,44 +1,46 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -/// Orchestration and serialization glue logic for `GetLongKnownValue`. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +/// Orchestration and serialization glue logic for `GetLongKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] -pub struct GetLongKnownValue; -impl GetLongKnownValue { - /// Creates a new `GetLongKnownValue` +pub struct GetLongKnownValueTest; +impl GetLongKnownValueTest { + /// Creates a new `GetLongKnownValueTest` pub fn new() -> Self { Self } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_long_known_value::GetLongKnownValueInput, + input: crate::operation::get_long_known_value_test::GetLongInput, ) -> ::std::result::Result< - crate::operation::get_long_known_value::GetLongKnownValueOutput, - crate::operation::get_long_known_value::GetLongKnownValueError, + crate::operation::get_long_known_value_test::GetLongOutput, + crate::operation::get_long_known_value_test::GetLongKnownValueTestError, > { - let inner_input = - crate::conversions::get_long_known_value::_get_long_known_value_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetLong(&inner_input); + let inner_input = crate::conversions::get_long_known_value_test::_get_long_known_value_test_input::to_dafny(input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetLongKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { Ok( - crate::conversions::get_long_known_value::_get_long_known_value_output::from_dafny( + crate::conversions::get_long_known_value_test::_get_long_known_value_test_output::from_dafny( inner_result.value().clone(), ), ) } else { - Err(crate::conversions::get_long_known_value::from_dafny_error( + Err(crate::conversions::get_long_known_value_test::from_dafny_error( inner_result.error().clone(), )) } } } -/// Error type for the `GetLongKnownValue` operation. +/// Error type for the `GetLongKnownValueTest` operation. #[non_exhaustive] #[derive(::std::fmt::Debug)] -pub enum GetLongKnownValueError { +pub enum GetLongKnownValueTestError { /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ @@ -46,12 +48,12 @@ pub enum GetLongKnownValueError { \    `err if err.code() == Some(\"SpecificExceptionCode\") => { /* handle the error */ }` \ - See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetLongKnownValueError) for what information is available for the error." + See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetLongKnownValueTestError) for what information is available for the error." )] Unhandled(crate::error::sealed_unhandled::Unhandled), } -impl GetLongKnownValueError { - /// Creates the `GetLongKnownValueError::Unhandled` variant from any error type. +impl GetLongKnownValueTestError { + /// Creates the `GetLongKnownValueTestError::Unhandled` variant from any error type. pub fn unhandled( err: impl ::std::convert::Into< ::std::boxed::Box< @@ -65,7 +67,7 @@ impl GetLongKnownValueError { }) } - /// Creates the `GetLongKnownValueError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). + /// Creates the `GetLongKnownValueTestError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). pub fn generic(err: ::aws_smithy_types::error::ErrorMetadata) -> Self { Self::Unhandled(crate::error::sealed_unhandled::Unhandled { source: err.clone().into(), @@ -82,14 +84,14 @@ impl GetLongKnownValueError { } } } -impl ::std::error::Error for GetLongKnownValueError { +impl ::std::error::Error for GetLongKnownValueTestError { fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> { match self { Self::Unhandled(_inner) => ::std::option::Option::Some(&*_inner.source), } } } -impl ::std::fmt::Display for GetLongKnownValueError { +impl ::std::fmt::Display for GetLongKnownValueTestError { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self { Self::Unhandled(_inner) => { @@ -104,7 +106,7 @@ impl ::std::fmt::Display for GetLongKnownValueError { } } } -impl ::aws_smithy_types::retry::ProvideErrorKind for GetLongKnownValueError { +impl ::aws_smithy_types::retry::ProvideErrorKind for GetLongKnownValueTestError { fn code(&self) -> ::std::option::Option<&str> { ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self) } @@ -112,14 +114,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetLongKnownValueError { ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetLongKnownValueError { +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetLongKnownValueTestError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetLongKnownValueError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetLongKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -133,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetLongK } } -pub use crate::operation::get_long_known_value::_get_long_known_value_output::GetLongKnownValueOutput; +pub use crate::operation::get_long_known_value_test::_get_long_output::GetLongOutput; -pub use crate::operation::get_long_known_value::_get_long_known_value_input::GetLongKnownValueInput; +pub use crate::operation::get_long_known_value_test::_get_long_input::GetLongInput; -mod _get_long_known_value_input; +pub(crate) mod _get_long_output; -mod _get_long_known_value_output; +pub(crate) mod _get_long_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_input.rs new file mode 100644 index 0000000000..3549b72552 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetLongInput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::primitive::i64>, +} +impl GetLongInput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::primitive::i64> { + self.value +} +} +impl GetLongInput { + /// Creates a new builder-style object to manufacture [`GetLongInput`](crate::operation::operation::GetLongInput). + pub fn builder() -> crate::operation::get_long_known_value_test::builders::GetLongInputBuilder { + crate::operation::get_long_known_value_test::builders::GetLongInputBuilder::default() + } +} + +/// A builder for [`GetLongInput`](crate::operation::operation::GetLongInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetLongInputBuilder { + pub(crate) value: ::std::option::Option<::std::primitive::i64>, +} +impl GetLongInputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { + &self.value +} + /// Consumes the builder and constructs a [`GetLongInput`](crate::operation::operation::GetLongInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_long_known_value_test::GetLongInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_long_known_value_test::GetLongInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_output.rs new file mode 100644 index 0000000000..60d05a1481 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetLongOutput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::primitive::i64>, +} +impl GetLongOutput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::primitive::i64> { + self.value +} +} +impl GetLongOutput { + /// Creates a new builder-style object to manufacture [`GetLongOutput`](crate::operation::operation::GetLongOutput). + pub fn builder() -> crate::operation::get_long_known_value_test::builders::GetLongOutputBuilder { + crate::operation::get_long_known_value_test::builders::GetLongOutputBuilder::default() + } +} + +/// A builder for [`GetLongOutput`](crate::operation::operation::GetLongOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetLongOutputBuilder { + pub(crate) value: ::std::option::Option<::std::primitive::i64>, +} +impl GetLongOutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { + &self.value +} + /// Consumes the builder and constructs a [`GetLongOutput`](crate::operation::operation::GetLongOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_long_known_value_test::GetLongOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_long_known_value_test::GetLongOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/builders.rs new file mode 100644 index 0000000000..a79b8a361b --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/builders.rs @@ -0,0 +1,74 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_long_known_value_test::_get_long_output::GetLongOutputBuilder; + +pub use crate::operation::get_long_known_value_test::_get_long_input::GetLongInputBuilder; + +impl GetLongInputBuilder { + /// Sends a request with this input using the given client. + pub async fn send_with( + self, + client: &crate::Client, + ) -> ::std::result::Result< + crate::operation::get_long_known_value_test::GetLongOutput, + crate::operation::get_long_known_value_test::GetLongKnownValueTestError, + > { + let mut fluent_builder = client.get_long_known_value_test(); + fluent_builder.inner = self; + fluent_builder.send().await + } +} +/// Fluent builder constructing a request to `GetLongKnownValueTest`. +/// +#[derive(::std::clone::Clone, ::std::fmt::Debug)] +pub struct GetLongKnownValueTestFluentBuilder { + client: crate::client::Client, + pub(crate) inner: crate::operation::get_long_known_value_test::builders::GetLongInputBuilder, +} +impl GetLongKnownValueTestFluentBuilder { + /// Creates a new `GetLongKnownValueTest`. + pub(crate) fn new(client: crate::client::Client) -> Self { + Self { + client, + inner: ::std::default::Default::default(), + } + } + /// Access the GetLongKnownValueTest as a reference. + pub fn as_input(&self) -> &crate::operation::get_long_known_value_test::builders::GetLongInputBuilder { + &self.inner + } + /// Sends the request and returns the response. + pub async fn send( + self, + ) -> ::std::result::Result< + crate::operation::get_long_known_value_test::GetLongOutput, + crate::operation::get_long_known_value_test::GetLongKnownValueTestError, + > { + let input = self + .inner + .build() + // Using unhandled since GetLongKnownValueTest doesn't declare any validation, + // and smithy-rs seems to not generate a ValidationError case unless there is + // (but isn't that a backwards compatibility problem for output structures?) + // Vanilla smithy-rs uses SdkError::construction_failure, + // but we aren't using SdkError. + .map_err(crate::operation::get_long_known_value_test::GetLongKnownValueTestError::unhandled)?; + crate::operation::get_long_known_value_test::GetLongKnownValueTest::send(&self.client, input).await + } + + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { + self.inner.get_value() +} +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types.rs index f8ff6d665a..d9223fcb30 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `SimpleLongConfig` pub mod simple_long_config; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types/simple_long_config.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types/simple_long_config.rs index 7def54c032..5df8e1ebfc 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types/simple_long_config.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types/simple_long_config.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleLongConfig {} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..ef8910b03c --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::smithylong::internaldafny::wrapped::_default { + pub fn WrappedSimpleLong(config: &::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::SimpleLongConfig, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..5b4a2bf9c4 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,119 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::smithylong::internaldafny::types::ISimpleTypesLongClient); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::SimpleLongConfig, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_long_config::_simple_long_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::smithylong::internaldafny::types::ISimpleTypesLongClient for Client { + fn GetLong( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_long::_get_long_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_long::GetLong::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_long::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_long::_get_long_output::to_dafny(client), + }, + ), + } + } + + fn GetLongKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_long_known_value_test::_get_long_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_long_known_value_test::GetLongKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_long_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_long_known_value_test::_get_long_known_value_test_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/tests/simple_long_test.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/tests/simple_long_test.rs index d63548ae69..e48d52d5fd 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/tests/simple_long_test.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/tests/simple_long_test.rs @@ -10,7 +10,7 @@ async fn test_get_long() { #[tokio::test] async fn test_get_known_value() { - let result = client().get_long_known_value().value(33i64).send().await; + let result = client().get_long_known_value_test().value(33i64).send().await; let output = result.unwrap(); let value = output.value().unwrap(); assert_eq!(value, 33i64); diff --git a/TestModels/SimpleTypes/SimpleString/Makefile b/TestModels/SimpleTypes/SimpleString/Makefile index 549a8995d9..8bcdf25d30 100644 --- a/TestModels/SimpleTypes/SimpleString/Makefile +++ b/TestModels/SimpleTypes/SimpleString/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleString/runtimes/rust/Cargo.toml index 3f66bd6aa2..65ef7a3960 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/Cargo.toml @@ -5,15 +5,21 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies.tokio] +[dev-dependencies] +simple_string = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] version = "1.26.0" features = ["full"] [lib] -path = "src/implementation_from_dafny.rs" \ No newline at end of file +path = "src/implementation_from_dafny.rs" diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client.rs index 2d5b76bf25..88a144918b 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -13,8 +14,6 @@ impl Client { pub fn from_conf( conf: crate::types::simple_string_config::SimpleStringConfig, ) -> Result { - // If this service had any configuration properties, - // they would need converting here too. let inner = crate::simple::types::smithystring::internaldafny::_default::SimpleString( &crate::conversions::simple_string_config::_simple_string_config::to_dafny(conf), @@ -31,7 +30,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } @@ -42,4 +41,4 @@ mod get_string_known_value; mod get_string_utf8; -mod get_string_utf8_known_value; \ No newline at end of file +mod get_string_utf8_known_value; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string.rs index da262534e9..fe18db0b8c 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetString`](crate::operation::get_string::builders::GetStringFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_string::builders::GetStringFluentBuilder::name) / [`set_name(Option)`](crate::operation::get_string::builders::GetStringFluentBuilder::set_name):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_string::builders::GetStringFluentBuilder::value) / [`set_value(Option<::std::string::String>)`](crate::operation::get_string::builders::GetStringFluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetStringOutput`](crate::operation::get_string::GetStringOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_string::GetStringOutput::value): (undocumented) + /// - [`value(Option<::std::string::String>)`](crate::operation::get_string::GetStringOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_string::GetStringError) pub fn get_string(&self) -> crate::operation::get_string::builders::GetStringFluentBuilder { crate::operation::get_string::builders::GetStringFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_known_value.rs index 8c13c6ad59..6ddfcadaa5 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_known_value.rs @@ -1,17 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetStringKnownValue`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::name) / [`set_name(Option)`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::set_name):(undocumented)
- /// - On success, responds with [`GetStringKnownValueOutput`](crate::operation::get_string_known_value::GetStringKnownValueOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_string_known_value::GetStringKnownValueOutput::value): (undocumented) + /// - [`value(impl Into>)`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::value) / [`set_value(Option<::std::string::String>)`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetStringOutput`](crate::operation::get_string_known_value::GetStringOutput) with field(s): + /// - [`value(Option<::std::string::String>)`](crate::operation::get_string_known_value::GetStringOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_string_known_value::GetStringKnownValueError) - pub fn get_string_known_value( - &self, - ) -> crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder { - crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::new( - self.clone(), - ) + pub fn get_string_known_value(&self) -> crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder { + crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8.rs index 3a487be091..010a0547e6 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8.rs @@ -1,15 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetStringUTF8`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::name) / [`set_name(Option)`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::set_name):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::value) / [`set_value(Option<::std::string::String>)`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetStringUTF8Output`](crate::operation::get_string_utf8::GetStringUTF8Output) with field(s): - /// - [`value(Option)`](crate::operation::get_string_utf8::GetStringUTF8Output::value): (undocumented) + /// - [`value(Option<::std::string::String>)`](crate::operation::get_string_utf8::GetStringUTF8Output::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_string_utf8::GetStringUTF8Error) - pub fn get_string_utf8( - &self, - ) -> crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder { + pub fn get_string_utf8(&self) -> crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder { crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8_known_value.rs index 205f24ff5f..dab2fd15fb 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8_known_value.rs @@ -1,15 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetStringUTF8KnownValue`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::name) / [`set_name(Option)`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::set_name):(undocumented)
- /// - On success, responds with [`GetStringUTF8KnownValueOutput`](crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput::value): (undocumented) + /// - [`value(impl Into>)`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::value) / [`set_value(Option<::std::string::String>)`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetStringUTF8Output`](crate::operation::get_string_utf8_known_value::GetStringUTF8Output) with field(s): + /// - [`value(Option<::std::string::String>)`](crate::operation::get_string_utf8_known_value::GetStringUTF8Output::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError) - pub fn get_string_utf8_known_value( - &self, - ) -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder { + pub fn get_string_utf8_known_value(&self) -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder { crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions.rs index e48982f580..c994c2ec1b 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions.rs @@ -1,10 +1,14 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_string; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod get_string_known_value; + pub mod get_string; -pub mod get_string_utf8; + pub mod get_string_known_value; -pub mod get_string_utf8_known_value; + pub mod get_string_utf8; -pub mod simple_string_config; + pub mod get_string_utf8_known_value; + + pub mod simple_string_config; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..ec72eaf961 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string.rs index 4a11ce9324..28eedb4163 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string.rs @@ -1,12 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_string::GetStringError, -) -> ::std::rc::Rc -{ +) -> ::std::rc::Rc { match value { crate::operation::get_string::GetStringError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_input.rs index 2b7ac1e68b..504704b4f8 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_input.rs @@ -1,43 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_string::GetStringInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringInput::GetStringInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::ostring_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, >, ) -> crate::operation::get_string::GetStringInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string::GetStringInput { value } + crate::operation::get_string::GetStringInput::builder() + .set_value(crate::standard_library_conversions::ostring_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_output.rs index 66cfd60615..9f993cd584 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_output.rs @@ -1,41 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_string::GetStringOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::ostring_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( - dafny_value: ::std::rc::Rc, + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, + >, ) -> crate::operation::get_string::GetStringOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string::GetStringOutput { value } + crate::operation::get_string::GetStringOutput::builder() + .set_value(crate::standard_library_conversions::ostring_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value.rs index 680fd6ad86..9f4018f6fa 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value.rs @@ -1,12 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_string_known_value::GetStringKnownValueError, -) -> ::std::rc::Rc -{ +) -> ::std::rc::Rc { match value { crate::operation::get_string_known_value::GetStringKnownValueError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_input.rs index 2a638911d9..cc34124d85 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_input.rs @@ -1,43 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_string_known_value::GetStringKnownValueInput, + value: crate::operation::get_string_known_value::GetStringInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringInput::GetStringInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::ostring_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, >, -) -> crate::operation::get_string_known_value::GetStringKnownValueInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string_known_value::GetStringKnownValueInput { value } +) -> crate::operation::get_string_known_value::GetStringInput { + crate::operation::get_string_known_value::GetStringInput::builder() + .set_value(crate::standard_library_conversions::ostring_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_output.rs index 00f53c20bc..1507eeb3f4 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_output.rs @@ -1,41 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_string_known_value::GetStringKnownValueOutput, + value: crate::operation::get_string_known_value::GetStringOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::ostring_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( - dafny_value: ::std::rc::Rc, -) -> crate::operation::get_string_known_value::GetStringKnownValueOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string_known_value::GetStringKnownValueOutput { value } + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, + >, +) -> crate::operation::get_string_known_value::GetStringOutput { + crate::operation::get_string_known_value::GetStringOutput::builder() + .set_value(crate::standard_library_conversions::ostring_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8.rs index 1f3d581ec4..855e9697cd 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8.rs @@ -1,12 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_string_utf8::GetStringUTF8Error, -) -> ::std::rc::Rc -{ +) -> ::std::rc::Rc { match value { crate::operation::get_string_utf8::GetStringUTF8Error::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_input.rs index c6b8fc2ae2..c70b83f7bf 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_input.rs @@ -1,43 +1,30 @@ -use core::str; - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_string_utf8::GetStringUTF8Input, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input::GetStringUTF8Input { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) }, + None => crate::_Wrappers_Compile::Option::None {}, +}), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, >, ) -> crate::operation::get_string_utf8::GetStringUTF8Input { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - let bytes = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), |b| *b); - Some(String::from_utf8(bytes).unwrap()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string_utf8::GetStringUTF8Input { value } + crate::operation::get_string_utf8::GetStringUTF8Input::builder() + .set_value(match dafny_value.value().as_ref() { + crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&dafny_value.value().Extract(), |b| *b)).unwrap()), + _ => ::std::option::Option::None, +}) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_output.rs index 1ceb81a53a..be225b6181 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_output.rs @@ -1,39 +1,30 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_string_utf8::GetStringUTF8Output, ) -> ::std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, +>{ + ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output::GetStringUTF8Output { + value: ::std::rc::Rc::new(match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) }, + None => crate::_Wrappers_Compile::Option::None {}, +}), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( - dafny_value: ::std::rc::Rc, + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, + >, ) -> crate::operation::get_string_utf8::GetStringUTF8Output { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - let bytes = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), |b| *b); - Some(String::from_utf8(bytes).unwrap()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string_utf8::GetStringUTF8Output { value } + crate::operation::get_string_utf8::GetStringUTF8Output::builder() + .set_value(match dafny_value.value().as_ref() { + crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&dafny_value.value().Extract(), |b| *b)).unwrap()), + _ => ::std::option::Option::None, +}) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value.rs index f942e0b21e..25e02541ce 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value.rs @@ -1,12 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError, -) -> ::std::rc::Rc -{ +) -> ::std::rc::Rc { match value { crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs index 97719cd80e..233ffd0804 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs @@ -1,43 +1,30 @@ -use core::str; - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput, + value: crate::operation::get_string_utf8_known_value::GetStringUTF8Input, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input::GetStringUTF8Input { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) }, + None => crate::_Wrappers_Compile::Option::None {}, +}), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, >, -) -> crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - let bytes = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), |b| *b); - Some(String::from_utf8(bytes).unwrap()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput { value } +) -> crate::operation::get_string_utf8_known_value::GetStringUTF8Input { + crate::operation::get_string_utf8_known_value::GetStringUTF8Input::builder() + .set_value(match dafny_value.value().as_ref() { + crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&dafny_value.value().Extract(), |b| *b)).unwrap()), + _ => ::std::option::Option::None, +}) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs index 2f0ea07136..2aa9d94c0f 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs @@ -1,39 +1,30 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, + value: crate::operation::get_string_utf8_known_value::GetStringUTF8Output, ) -> ::std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, +>{ + ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output::GetStringUTF8Output { + value: ::std::rc::Rc::new(match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) }, + None => crate::_Wrappers_Compile::Option::None {}, +}), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( - dafny_value: ::std::rc::Rc, -) -> crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - let bytes = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), |b| *b); - Some(String::from_utf8(bytes).unwrap()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput { value } + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, + >, +) -> crate::operation::get_string_utf8_known_value::GetStringUTF8Output { + crate::operation::get_string_utf8_known_value::GetStringUTF8Output::builder() + .set_value(match dafny_value.value().as_ref() { + crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&dafny_value.value().Extract(), |b| *b)).unwrap()), + _ => ::std::option::Option::None, +}) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config.rs index 286313ae8b..d8734a9d1d 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_string_config; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config/_simple_string_config.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config/_simple_string_config.rs index 95d7da8d43..71f90a271c 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config/_simple_string_config.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config/_simple_string_config.rs @@ -1,10 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_string_config::SimpleStringConfig, ) -> ::std::rc::Rc< - crate::simple::types::smithystring::internaldafny::types::SimpleStringConfig, + crate::r#simple::types::smithystring::internaldafny::types::SimpleStringConfig, > { ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::SimpleStringConfig::SimpleStringConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/implementation_from_dafny.rs-e b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/implementation_from_dafny.rs-e deleted file mode 100644 index 0c57116297..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/implementation_from_dafny.rs-e +++ /dev/null @@ -1,1880 +0,0 @@ -#![allow(warnings, unconditional_panic)] -#![allow(nonstandard_style)] - -pub mod _module { - -} -pub mod simple { - pub mod types { - pub mod smithystring { - pub mod internaldafny { - pub use ::dafny_runtime::UpcastObject; - pub use ::std::any::Any; - pub use crate::simple::types::smithystring::internaldafny::types::ISimpleTypesStringClient; - - pub struct _default {} - - impl _default { - pub fn DefaultSimpleStringConfig() -> ::std::rc::Rc { - ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::SimpleStringConfig::SimpleStringConfig {}) - } - pub fn SimpleString(config: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut res = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut client = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object>::new(); - let mut _nw0: ::dafny_runtime::Object = crate::simple::types::smithystring::internaldafny::SimpleStringClient::_allocate_object(); - crate::simple::types::smithystring::internaldafny::SimpleStringClient::_ctor(&_nw0, &::std::rc::Rc::new(crate::r#_SimpleStringImpl_Compile::Config::Config {})); - client = ::dafny_runtime::MaybePlacebo::from(_nw0.clone()); - res = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Success { - value: client.read() - })); - return res.read(); - } - pub fn CreateSuccessOfClient(client: &::dafny_runtime::Object) -> ::std::rc::Rc, ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Success { - value: client.clone() - }) - } - pub fn CreateFailureOfError(error: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Failure { - error: error.clone() - }) - } - } - - pub struct SimpleStringClient { - pub r#__i_config: ::std::rc::Rc - } - - impl SimpleStringClient { - pub fn _allocate_object() -> ::dafny_runtime::Object { - ::dafny_runtime::allocate_object::() - } - pub fn _ctor(this: &::dafny_runtime::Object, config: &::std::rc::Rc) -> () { - let mut _set__i_config: bool = false; - ::dafny_runtime::update_field_uninit_object!(this.clone(), r#__i_config, _set__i_config, config.clone()); - return (); - } - pub fn config(&self) -> ::std::rc::Rc { - self.r#__i_config.clone() - } - } - - impl UpcastObject - for crate::simple::types::smithystring::internaldafny::SimpleStringClient { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); - } - - impl ISimpleTypesStringClient - for crate::simple::types::smithystring::internaldafny::SimpleStringClient { - fn GetString(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut _out0 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - _out0 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleStringImpl_Compile::_default::GetString(&self.config().clone(), input)); - output = ::dafny_runtime::MaybePlacebo::from(_out0.read()); - return output.read(); - } - fn GetStringKnownValue(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut _out1 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - _out1 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleStringImpl_Compile::_default::GetStringKnownValue(&self.config().clone(), input)); - output = ::dafny_runtime::MaybePlacebo::from(_out1.read()); - return output.read(); - } - fn GetStringUTF8(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut _out2 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - _out2 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleStringImpl_Compile::_default::GetStringUTF8(&self.config().clone(), input)); - output = ::dafny_runtime::MaybePlacebo::from(_out2.read()); - return output.read(); - } - fn GetStringUTF8KnownValue(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut _out3 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - _out3 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleStringImpl_Compile::_default::GetStringUTF8KnownValue(&self.config().clone(), input)); - output = ::dafny_runtime::MaybePlacebo::from(_out3.read()); - return output.read(); - } - } - - impl UpcastObject - for crate::simple::types::smithystring::internaldafny::SimpleStringClient { - ::dafny_runtime::UpcastObjectFn!(dyn crate::simple::types::smithystring::internaldafny::types::ISimpleTypesStringClient); - } - - pub mod types { - pub use ::std::fmt::Debug; - pub use ::dafny_runtime::DafnyPrint; - pub use ::std::cmp::Eq; - pub use ::std::hash::Hash; - pub use ::std::default::Default; - pub use ::std::convert::AsRef; - pub use ::dafny_runtime::UpcastObject; - pub use ::std::any::Any; - - #[derive(PartialEq, Clone)] - pub enum DafnyCallEvent { - DafnyCallEvent { - input: I, - output: O - } - } - - impl DafnyCallEvent { - pub fn input(&self) -> &I { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => input, - } - } - pub fn output(&self) -> &O { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => output, - } - } - } - - impl Debug - for DafnyCallEvent { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for DafnyCallEvent { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.DafnyCallEvent.DafnyCallEvent(")?; - ::dafny_runtime::DafnyPrint::fmt_print(input, _formatter, false)?; - write!(_formatter, ", ")?; - ::dafny_runtime::DafnyPrint::fmt_print(output, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for DafnyCallEvent {} - - impl Hash - for DafnyCallEvent { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => { - ::std::hash::Hash::hash(input, _state); - ::std::hash::Hash::hash(output, _state) - }, - } - } - } - - impl Default - for DafnyCallEvent { - fn default() -> DafnyCallEvent { - DafnyCallEvent::DafnyCallEvent { - input: ::std::default::Default::default(), - output: ::std::default::Default::default() - } - } - } - - impl AsRef> - for &DafnyCallEvent { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum GetStringInput { - GetStringInput { - value: ::std::rc::Rc>> - } - } - - impl GetStringInput { - pub fn value(&self) -> &::std::rc::Rc>> { - match self { - GetStringInput::GetStringInput{value, } => value, - } - } - } - - impl Debug - for GetStringInput { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for GetStringInput { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - GetStringInput::GetStringInput{value, } => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.GetStringInput.GetStringInput(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for GetStringInput {} - - impl Hash - for GetStringInput { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - GetStringInput::GetStringInput{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for GetStringInput { - fn default() -> GetStringInput { - GetStringInput::GetStringInput { - value: ::std::default::Default::default() - } - } - } - - impl AsRef - for &GetStringInput { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum GetStringOutput { - GetStringOutput { - value: ::std::rc::Rc>> - } - } - - impl GetStringOutput { - pub fn value(&self) -> &::std::rc::Rc>> { - match self { - GetStringOutput::GetStringOutput{value, } => value, - } - } - } - - impl Debug - for GetStringOutput { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for GetStringOutput { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - GetStringOutput::GetStringOutput{value, } => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.GetStringOutput.GetStringOutput(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for GetStringOutput {} - - impl Hash - for GetStringOutput { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - GetStringOutput::GetStringOutput{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for GetStringOutput { - fn default() -> GetStringOutput { - GetStringOutput::GetStringOutput { - value: ::std::default::Default::default() - } - } - } - - impl AsRef - for &GetStringOutput { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum GetStringUTF8Input { - GetStringUTF8Input { - value: ::std::rc::Rc> - } - } - - impl GetStringUTF8Input { - pub fn value(&self) -> &::std::rc::Rc> { - match self { - GetStringUTF8Input::GetStringUTF8Input{value, } => value, - } - } - } - - impl Debug - for GetStringUTF8Input { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for GetStringUTF8Input { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - GetStringUTF8Input::GetStringUTF8Input{value, } => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.GetStringUTF8Input.GetStringUTF8Input(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for GetStringUTF8Input {} - - impl Hash - for GetStringUTF8Input { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - GetStringUTF8Input::GetStringUTF8Input{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for GetStringUTF8Input { - fn default() -> GetStringUTF8Input { - GetStringUTF8Input::GetStringUTF8Input { - value: ::std::default::Default::default() - } - } - } - - impl AsRef - for &GetStringUTF8Input { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum GetStringUTF8Output { - GetStringUTF8Output { - value: ::std::rc::Rc> - } - } - - impl GetStringUTF8Output { - pub fn value(&self) -> &::std::rc::Rc> { - match self { - GetStringUTF8Output::GetStringUTF8Output{value, } => value, - } - } - } - - impl Debug - for GetStringUTF8Output { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for GetStringUTF8Output { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - GetStringUTF8Output::GetStringUTF8Output{value, } => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.GetStringUTF8Output.GetStringUTF8Output(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for GetStringUTF8Output {} - - impl Hash - for GetStringUTF8Output { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - GetStringUTF8Output::GetStringUTF8Output{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for GetStringUTF8Output { - fn default() -> GetStringUTF8Output { - GetStringUTF8Output::GetStringUTF8Output { - value: ::std::default::Default::default() - } - } - } - - impl AsRef - for &GetStringUTF8Output { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum SimpleStringConfig { - SimpleStringConfig {} - } - - impl SimpleStringConfig {} - - impl Debug - for SimpleStringConfig { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for SimpleStringConfig { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - SimpleStringConfig::SimpleStringConfig{} => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.SimpleStringConfig.SimpleStringConfig")?; - Ok(()) - }, - } - } - } - - impl SimpleStringConfig { - pub fn _AllSingletonConstructors() -> ::dafny_runtime::SequenceIter<::std::rc::Rc> { - ::dafny_runtime::seq![::std::rc::Rc::new(SimpleStringConfig::SimpleStringConfig {})].iter() - } - } - - impl Eq - for SimpleStringConfig {} - - impl Hash - for SimpleStringConfig { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - SimpleStringConfig::SimpleStringConfig{} => { - - }, - } - } - } - - impl Default - for SimpleStringConfig { - fn default() -> SimpleStringConfig { - SimpleStringConfig::SimpleStringConfig {} - } - } - - impl AsRef - for &SimpleStringConfig { - fn as_ref(&self) -> Self { - self - } - } - - pub struct ISimpleTypesStringClientCallHistory {} - - impl ISimpleTypesStringClientCallHistory { - pub fn _allocate_object() -> ::dafny_runtime::Object { - ::dafny_runtime::allocate_object::() - } - } - - impl UpcastObject - for crate::simple::types::smithystring::internaldafny::types::ISimpleTypesStringClientCallHistory { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); - } - - pub trait ISimpleTypesStringClient: ::std::any::Any + ::dafny_runtime::UpcastObject { - fn GetString(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; - fn GetStringKnownValue(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; - fn GetStringUTF8(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; - fn GetStringUTF8KnownValue(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; - } - - #[derive(PartialEq, Clone)] - pub enum Error { - CollectionOfErrors { - list: ::dafny_runtime::Sequence<::std::rc::Rc>, - message: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> - }, - Opaque { - obj: ::dafny_runtime::Object - } - } - - impl Error { - pub fn list(&self) -> &::dafny_runtime::Sequence<::std::rc::Rc> { - match self { - Error::CollectionOfErrors{list, message, } => list, - Error::Opaque{obj, } => panic!("field does not exist on this variant"), - } - } - pub fn message(&self) -> &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - match self { - Error::CollectionOfErrors{list, message, } => message, - Error::Opaque{obj, } => panic!("field does not exist on this variant"), - } - } - pub fn obj(&self) -> &::dafny_runtime::Object { - match self { - Error::CollectionOfErrors{list, message, } => panic!("field does not exist on this variant"), - Error::Opaque{obj, } => obj, - } - } - } - - impl Debug - for Error { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Error { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Error::CollectionOfErrors{list, message, } => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.Error.CollectionOfErrors(")?; - ::dafny_runtime::DafnyPrint::fmt_print(list, _formatter, false)?; - write!(_formatter, ", ")?; - ::dafny_runtime::DafnyPrint::fmt_print(message, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - Error::Opaque{obj, } => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.Error.Opaque(")?; - ::dafny_runtime::DafnyPrint::fmt_print(obj, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for Error {} - - impl Hash - for Error { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Error::CollectionOfErrors{list, message, } => { - ::std::hash::Hash::hash(list, _state); - ::std::hash::Hash::hash(message, _state) - }, - Error::Opaque{obj, } => { - ::std::hash::Hash::hash(obj, _state) - }, - } - } - } - - impl Default - for Error { - fn default() -> Error { - Error::CollectionOfErrors { - list: ::std::default::Default::default(), - message: ::std::default::Default::default() - } - } - } - - impl AsRef - for &Error { - fn as_ref(&self) -> Self { - self - } - } - - pub type OpaqueError = ::std::rc::Rc; - } - } - } - } -} -pub mod r#_SimpleStringImpl_Compile { - pub use ::std::fmt::Debug; - pub use ::dafny_runtime::DafnyPrint; - pub use ::std::cmp::Eq; - pub use ::std::hash::Hash; - pub use ::std::default::Default; - pub use ::std::convert::AsRef; - - pub struct _default {} - - impl _default { - pub fn GetString(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { - value: input.value().clone() - }); - output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Success { - value: res.clone() - })); - return output.read(); - } - pub fn GetStringKnownValue(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { - panic!("Halt") - }; - let mut _e00: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> = input.value().value().clone(); - let mut _e10: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> = ::dafny_runtime::string_utf16_of("TEST_SIMPLE_STRING_KNOWN_VALUE"); - if !(_e00.clone() == _e10.clone()) { - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&::dafny_runtime::string_utf16_of("Left:\n"))); - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&_e00)); - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&::dafny_runtime::string_utf16_of("Right:\n"))); - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&_e10)); - panic!("Halt") - }; - let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { - value: input.value().clone() - }); - output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Success { - value: res.clone() - })); - return output.read(); - } - pub fn GetStringUTF8(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { - panic!("Halt") - }; - let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::GetStringUTF8Output::GetStringUTF8Output { - value: input.value().clone() - }); - output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Success { - value: res.clone() - })); - return output.read(); - } - pub fn GetStringUTF8KnownValue(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { - panic!("Halt") - }; - let mut expected: ::dafny_runtime::Sequence = ::dafny_runtime::seq![72, 101, 108, 108, 111]; - let mut _e01: crate::UTF8::ValidUTF8Bytes = input.value().value().clone(); - let mut _e11: ::dafny_runtime::Sequence = expected.clone(); - if !(_e01.clone() == _e11.clone()) { - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&::dafny_runtime::string_utf16_of("Left:\n"))); - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&_e01)); - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&::dafny_runtime::string_utf16_of("Right:\n"))); - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&_e11)); - panic!("Halt") - }; - let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::GetStringUTF8Output::GetStringUTF8Output { - value: input.value().clone() - }); - output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Success { - value: res.clone() - })); - return output.read(); - } - } - - #[derive(PartialEq, Clone)] - pub enum Config { - Config {} - } - - impl Config {} - - impl Debug - for Config { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Config { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Config::Config{} => { - write!(_formatter, "SimpleStringImpl_Compile.Config.Config")?; - Ok(()) - }, - } - } - } - - impl Config { - pub fn _AllSingletonConstructors() -> ::dafny_runtime::SequenceIter<::std::rc::Rc> { - ::dafny_runtime::seq![::std::rc::Rc::new(Config::Config {})].iter() - } - } - - impl Eq - for Config {} - - impl Hash - for Config { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Config::Config{} => { - - }, - } - } - } - - impl Default - for Config { - fn default() -> Config { - Config::Config {} - } - } - - impl AsRef - for &Config { - fn as_ref(&self) -> Self { - self - } - } -} -pub mod r#_StandardLibrary_Compile { - pub struct _default {} - - impl _default { - pub fn Join<_T: ::dafny_runtime::DafnyType>(ss: &::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>, joiner: &::dafny_runtime::Sequence<_T>) -> ::dafny_runtime::Sequence<_T> { - let mut _accumulator: ::dafny_runtime::Sequence<_T> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>; - let mut _r0 = ss.clone(); - let mut _r1 = joiner.clone(); - 'TAIL_CALL_START: loop { - let ss = _r0; - let joiner = _r1; - if ss.cardinality() == ::dafny_runtime::int!(1) { - return _accumulator.concat(&ss.get(&::dafny_runtime::int!(0))); - } else { - _accumulator = _accumulator.concat(&ss.get(&::dafny_runtime::int!(0)).concat(&joiner)); - let mut _in0: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ss.drop(&::dafny_runtime::int!(1)); - let mut _in1: ::dafny_runtime::Sequence<_T> = joiner.clone(); - _r0 = _in0.clone(); - _r1 = _in1.clone(); - continue 'TAIL_CALL_START; - } - } - } - pub fn Split<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> { - let mut _accumulator: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>; - let mut _r0 = s.clone(); - let mut _r1 = delim.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let delim = _r1; - let mut i: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(&s, &delim, &::dafny_runtime::int!(0)); - if matches!((&i).as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { - _accumulator = _accumulator.concat(&::dafny_runtime::seq![s.take(i.value())]); - let mut _in2: ::dafny_runtime::Sequence<_T> = s.drop(&(i.value().clone() + ::dafny_runtime::int!(1))); - let mut _in3: _T = delim.clone(); - _r0 = _in2.clone(); - _r1 = _in3.clone(); - continue 'TAIL_CALL_START; - } else { - return _accumulator.concat(&::dafny_runtime::seq![s.clone()]); - } - } - } - pub fn SplitOnce<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> (::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>) { - let mut i: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(s, delim, &::dafny_runtime::int!(0)); - ( - s.take(i.value()), - s.drop(&(i.value().clone() + ::dafny_runtime::int!(1))) - ) - } - pub fn r#_SplitOnce_q<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> ::std::rc::Rc, ::dafny_runtime::Sequence<_T>)>> { - let mut valueOrError0: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(s, delim, &::dafny_runtime::int!(0)); - if valueOrError0.IsFailure() { - valueOrError0.PropagateFailure::<(::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>)>() - } else { - let mut i: ::dafny_runtime::_System::nat = valueOrError0.Extract(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<(::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>)>::Some { - value: ( - s.take(&i), - s.drop(&(i.clone() + ::dafny_runtime::int!(1))) - ) - }) - } - } - pub fn FindIndexMatching<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, c: &_T, i: &::dafny_runtime::_System::nat) -> ::std::rc::Rc> { - crate::r#_StandardLibrary_Compile::_default::FindIndex::<_T>(s, { - let c: _T = c.clone(); - &({ - let mut c = c.clone(); - ::std::rc::Rc::new(move |x: &_T| -> bool{ - x.clone() == c.clone() - }) - }) - }, i) - } - pub fn FindIndex<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>, f: &::std::rc::Rc bool>, i: &::dafny_runtime::_System::nat) -> ::std::rc::Rc> { - let mut _r0 = s.clone(); - let mut _r1 = f.clone(); - let mut _r2 = i.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let f = _r1; - let i = _r2; - if i.clone() == s.cardinality() { - return ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::_System::nat>::None {}); - } else { - if (&f)(&s.get(&i)) { - return ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::_System::nat>::Some { - value: i.clone() - }); - } else { - let mut _in4: ::dafny_runtime::Sequence<_T> = s.clone(); - let mut _in5: ::std::rc::Rc bool> = f.clone(); - let mut _in6: ::dafny_runtime::DafnyInt = i.clone() + ::dafny_runtime::int!(1); - _r0 = _in4.clone(); - _r1 = _in5.clone(); - _r2 = _in6.clone(); - continue 'TAIL_CALL_START; - } - } - } - } - pub fn Filter<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>, f: &::std::rc::Rc bool>) -> ::dafny_runtime::Sequence<_T> { - let mut _accumulator: ::dafny_runtime::Sequence<_T> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>; - let mut _r0 = s.clone(); - let mut _r1 = f.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let f = _r1; - if s.cardinality() == ::dafny_runtime::int!(0) { - return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>)); - } else { - if (&f)(&s.get(&::dafny_runtime::int!(0))) { - _accumulator = _accumulator.concat(&::dafny_runtime::seq![s.get(&::dafny_runtime::int!(0))]); - let mut _in7: ::dafny_runtime::Sequence<_T> = s.drop(&::dafny_runtime::int!(1)); - let mut _in8: ::std::rc::Rc bool> = f.clone(); - _r0 = _in7.clone(); - _r1 = _in8.clone(); - continue 'TAIL_CALL_START; - } else { - let mut _in9: ::dafny_runtime::Sequence<_T> = s.drop(&::dafny_runtime::int!(1)); - let mut _in10: ::std::rc::Rc bool> = f.clone(); - _r0 = _in9.clone(); - _r1 = _in10.clone(); - continue 'TAIL_CALL_START; - } - } - } - } - pub fn Min(a: &::dafny_runtime::DafnyInt, b: &::dafny_runtime::DafnyInt) -> ::dafny_runtime::DafnyInt { - if a.clone() < b.clone() { - a.clone() - } else { - b.clone() - } - } - pub fn Fill<_T: ::dafny_runtime::DafnyType>(value: &_T, n: &::dafny_runtime::_System::nat) -> ::dafny_runtime::Sequence<_T> { - { - let _initializer = { - let value: _T = value.clone(); - { - let mut value = value.clone(); - ::std::rc::Rc::new(move |_v0: &::dafny_runtime::DafnyInt| -> _T{ - value.clone() - }) - } - }; - ::dafny_runtime::integer_range(::dafny_runtime::Zero::zero(), n.clone()).map(|i| _initializer(&i)).collect::<::dafny_runtime::Sequence<_>>() - } - } - pub fn SeqToArray<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> ::dafny_runtime::Object<[_T]> { - let mut a = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object<[_T]>>::new(); - let mut _init0: ::std::rc::Rc _T> = { - let s: ::dafny_runtime::Sequence<_T> = s.clone(); - { - let mut s = s.clone(); - ::std::rc::Rc::new(move |i: &::dafny_runtime::DafnyInt| -> _T{ - s.get(i) - }) - } - }; - let mut _nw1: ::dafny_runtime::Object<[::std::mem::MaybeUninit<_T>]> = ::dafny_runtime::array::placebos_usize_object::<_T>(::dafny_runtime::DafnyUsize::into_usize(s.cardinality())); - for r#__i0_0 in ::dafny_runtime::integer_range(0, ::dafny_runtime::rd!(_nw1.clone()).len()) { - { - let __idx0 = ::dafny_runtime::DafnyUsize::into_usize(r#__i0_0.clone()); - ::dafny_runtime::md!(_nw1)[__idx0] = ::std::mem::MaybeUninit::new((&_init0)(&::dafny_runtime::int!(r#__i0_0.clone()))); - } - } - a = ::dafny_runtime::MaybePlacebo::from(::dafny_runtime::array::construct_object(_nw1.clone())); - return a.read(); - } - pub fn LexicographicLessOrEqual<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, b: &::dafny_runtime::Sequence<_T>, less: &::std::rc::Rc bool>) -> bool { - ::dafny_runtime::integer_range(::dafny_runtime::int!(0), a.cardinality() + ::dafny_runtime::int!(1)).any(({ - let mut a = a.clone(); - let mut b = b.clone(); - let mut less = less.clone(); - ::std::rc::Rc::new(move |r#__exists_var_0: ::dafny_runtime::DafnyInt| -> bool{ - let mut k: ::dafny_runtime::DafnyInt = r#__exists_var_0.clone(); - ::dafny_runtime::int!(0) <= k.clone() && k.clone() <= a.cardinality() && crate::r#_StandardLibrary_Compile::_default::LexicographicLessOrEqualAux::<_T>(&a, &b, &less, &k) - }) - }).as_ref()) - } - pub fn LexicographicLessOrEqualAux<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, b: &::dafny_runtime::Sequence<_T>, less: &::std::rc::Rc bool>, lengthOfCommonPrefix: &::dafny_runtime::_System::nat) -> bool { - lengthOfCommonPrefix.clone() <= b.cardinality() && ::dafny_runtime::integer_range(::dafny_runtime::int!(0), lengthOfCommonPrefix.clone()).all(({ - let mut lengthOfCommonPrefix = lengthOfCommonPrefix.clone(); - let mut a = a.clone(); - let mut b = b.clone(); - ::std::rc::Rc::new(move |r#__forall_var_0: ::dafny_runtime::DafnyInt| -> bool{ - let mut i: ::dafny_runtime::DafnyInt = r#__forall_var_0.clone(); - !(::dafny_runtime::int!(0) <= i.clone() && i.clone() < lengthOfCommonPrefix.clone()) || a.get(&i) == b.get(&i) - }) - }).as_ref()) && (lengthOfCommonPrefix.clone() == a.cardinality() || lengthOfCommonPrefix.clone() < b.cardinality() && less(&a.get(lengthOfCommonPrefix), &b.get(lengthOfCommonPrefix))) - } - pub fn SetToOrderedSequence<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Set<::dafny_runtime::Sequence<_T>>, less: &::std::rc::Rc bool>) -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> { - let mut _accumulator: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>; - let mut _r0 = s.clone(); - let mut _r1 = less.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let less = _r1; - if s.clone() == ::dafny_runtime::set!{} { - return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>)); - } else { - return (&({ - let mut s = s.clone(); - let mut less = less.clone(); - ::std::rc::Rc::new(move |r#__let_dummy_0: &::dafny_runtime::DafnyInt| -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>{ - let mut a = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Sequence<_T>>::new(); - 'label_goto__ASSIGN_SUCH_THAT_0: loop { - for r#__assign_such_that_0 in (&s).iter().cloned() { - a = ::dafny_runtime::MaybePlacebo::from(r#__assign_such_that_0.clone()); - if s.contains(&a.read()) && crate::r#_StandardLibrary_Compile::_default::IsMinimum::<_T>(&a.read(), &s, &less) { - break 'label_goto__ASSIGN_SUCH_THAT_0; - } - } - panic!("Halt"); - break; - }; - ::dafny_runtime::seq![a.read()].concat(&crate::r#_StandardLibrary_Compile::_default::SetToOrderedSequence::<_T>(&s.subtract(&::dafny_runtime::set!{a.read()}), &less)) - }) - }))(&::dafny_runtime::int!(0)); - } - } - } - pub fn IsMinimum<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, s: &::dafny_runtime::Set<::dafny_runtime::Sequence<_T>>, less: &::std::rc::Rc bool>) -> bool { - s.contains(a) && s.iter().all(({ - let mut a = a.clone(); - let mut s = s.clone(); - let mut less = less.clone(); - ::std::rc::Rc::new(move |r#__forall_var_1: &::dafny_runtime::Sequence<_T>| -> bool{ - let mut z: ::dafny_runtime::Sequence<_T> = r#__forall_var_1.clone(); - !s.contains(&z) || crate::r#_StandardLibrary_Compile::_default::LexicographicLessOrEqual::<_T>(&a, &z, &less) - }) - }).as_ref()) - } - } - - pub mod r#_UInt_Compile { - pub use ::std::default::Default; - pub use ::dafny_runtime::DafnyPrint; - - pub struct _default {} - - impl _default { - pub fn UInt8Less(a: u8, b: u8) -> bool { - a < b - } - pub fn HasUint16Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { - s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT16_LIMIT() - } - pub fn HasUint32Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { - s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT32_LIMIT() - } - pub fn HasUint64Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { - s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT64_LIMIT() - } - pub fn UInt16ToSeq(x: u16) -> ::dafny_runtime::Sequence { - let mut b0: u8 = (x / 256) as u8; - let mut b1: u8 = (x % 256) as u8; - ::dafny_runtime::seq![b0, b1] - } - pub fn SeqToUInt16(s: &::dafny_runtime::Sequence) -> u16 { - let mut x0: u16 = s.get(&::dafny_runtime::int!(0)) as u16 * 256; - x0 + s.get(&::dafny_runtime::int!(1)) as u16 - } - pub fn UInt32ToSeq(x: u32) -> ::dafny_runtime::Sequence { - let mut b0: u8 = (x / 16777216) as u8; - let mut x0: u32 = x - b0 as u32 * 16777216; - let mut b1: u8 = (x0 / 65536) as u8; - let mut x1: u32 = x0 - b1 as u32 * 65536; - let mut b2: u8 = (x1 / 256) as u8; - let mut b3: u8 = (x1 % 256) as u8; - ::dafny_runtime::seq![b0, b1, b2, b3] - } - pub fn SeqToUInt32(s: &::dafny_runtime::Sequence) -> u32 { - let mut x0: u32 = s.get(&::dafny_runtime::int!(0)) as u32 * 16777216; - let mut x1: u32 = x0 + s.get(&::dafny_runtime::int!(1)) as u32 * 65536; - let mut x2: u32 = x1 + s.get(&::dafny_runtime::int!(2)) as u32 * 256; - x2 + s.get(&::dafny_runtime::int!(3)) as u32 - } - pub fn UInt64ToSeq(x: u64) -> ::dafny_runtime::Sequence { - let mut b0: u8 = (x / 72057594037927936) as u8; - let mut x0: u64 = x - b0 as u64 * 72057594037927936; - let mut b1: u8 = (x0 / 281474976710656) as u8; - let mut x1: u64 = x0 - b1 as u64 * 281474976710656; - let mut b2: u8 = (x1 / 1099511627776) as u8; - let mut x2: u64 = x1 - b2 as u64 * 1099511627776; - let mut b3: u8 = (x2 / 4294967296) as u8; - let mut x3: u64 = x2 - b3 as u64 * 4294967296; - let mut b4: u8 = (x3 / 16777216) as u8; - let mut x4: u64 = x3 - b4 as u64 * 16777216; - let mut b5: u8 = (x4 / 65536) as u8; - let mut x5: u64 = x4 - b5 as u64 * 65536; - let mut b6: u8 = (x5 / 256) as u8; - let mut b7: u8 = (x5 % 256) as u8; - ::dafny_runtime::seq![b0, b1, b2, b3, b4, b5, b6, b7] - } - pub fn SeqToUInt64(s: &::dafny_runtime::Sequence) -> u64 { - let mut x0: u64 = s.get(&::dafny_runtime::int!(0)) as u64 * 72057594037927936; - let mut x1: u64 = x0 + s.get(&::dafny_runtime::int!(1)) as u64 * 281474976710656; - let mut x2: u64 = x1 + s.get(&::dafny_runtime::int!(2)) as u64 * 1099511627776; - let mut x3: u64 = x2 + s.get(&::dafny_runtime::int!(3)) as u64 * 4294967296; - let mut x4: u64 = x3 + s.get(&::dafny_runtime::int!(4)) as u64 * 16777216; - let mut x5: u64 = x4 + s.get(&::dafny_runtime::int!(5)) as u64 * 65536; - let mut x6: u64 = x5 + s.get(&::dafny_runtime::int!(6)) as u64 * 256; - let mut x: u64 = x6 + s.get(&::dafny_runtime::int!(7)) as u64; - x - } - pub fn UINT16_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"65536") - } - pub fn UINT32_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"4294967296") - } - pub fn UINT64_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"18446744073709551616") - } - pub fn INT32_MAX_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"2147483648") - } - pub fn INT64_MAX_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"9223372036854775808") - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint8(pub u8); - - impl uint8 { - pub fn is(_source: u8) -> bool { - return true; - } - } - - impl Default - for uint8 { - fn default() -> Self { - uint8(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint8 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint8 { - type Target = u8; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint16(pub u16); - - impl uint16 { - pub fn is(_source: u16) -> bool { - return true; - } - } - - impl Default - for uint16 { - fn default() -> Self { - uint16(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint16 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint16 { - type Target = u16; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint32(pub u32); - - impl uint32 { - pub fn is(_source: u32) -> bool { - return true; - } - } - - impl Default - for uint32 { - fn default() -> Self { - uint32(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint32 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint32 { - type Target = u32; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint64(pub u64); - - impl uint64 { - pub fn is(_source: u64) -> bool { - return true; - } - } - - impl Default - for uint64 { - fn default() -> Self { - uint64(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint64 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint64 { - type Target = u64; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct int32(pub i32); - - impl int32 { - pub fn is(_source: i32) -> bool { - return true; - } - } - - impl Default - for int32 { - fn default() -> Self { - int32(::std::default::Default::default()) - } - } - - impl DafnyPrint - for int32 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for int32 { - type Target = i32; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct int64(pub i64); - - impl int64 { - pub fn is(_source: i64) -> bool { - return true; - } - } - - impl Default - for int64 { - fn default() -> Self { - int64(::std::default::Default::default()) - } - } - - impl DafnyPrint - for int64 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for int64 { - type Target = i64; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct posInt64(pub u64); - - impl posInt64 { - pub fn is(_source: u64) -> bool { - let mut x: ::dafny_runtime::DafnyInt = ::std::convert::Into::<::dafny_runtime::DafnyInt>::into(_source.clone()); - return ::dafny_runtime::int!(0) < x.clone() && x.clone() < ::dafny_runtime::int!(b"9223372036854775808"); - } - } - - impl Default - for posInt64 { - fn default() -> Self { - posInt64(1) - } - } - - impl DafnyPrint - for posInt64 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for posInt64 { - type Target = u64; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - pub type seq16 = ::dafny_runtime::Sequence; - - pub type seq32 = ::dafny_runtime::Sequence; - - pub type seq64 = ::dafny_runtime::Sequence; - } -} -pub mod r#_StandardLibraryInterop_Compile { - pub use ::dafny_runtime::UpcastObject; - pub use ::std::any::Any; - - pub struct WrappersInterop {} - - impl WrappersInterop { - pub fn _allocate_object() -> ::dafny_runtime::Object { - ::dafny_runtime::allocate_object::() - } - pub fn CreateStringSome(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Some { - value: s.clone() - }) - } - pub fn CreateStringNone() -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::None {}) - } - pub fn CreateBooleanSome(b: bool) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::Some { - value: b - }) - } - pub fn CreateBooleanNone() -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::None {}) - } - } - - impl UpcastObject - for WrappersInterop { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); - } -} -pub mod UTF8 { - pub struct _default {} - - impl _default { - pub fn CreateEncodeSuccess(bytes: &crate::UTF8::ValidUTF8Bytes) -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Success { - value: bytes.clone() - }) - } - pub fn CreateEncodeFailure(error: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Failure { - error: error.clone() - }) - } - pub fn CreateDecodeSuccess(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: s.clone() - }) - } - pub fn CreateDecodeFailure(error: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: error.clone() - }) - } - pub fn IsASCIIString(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> bool { - let mut _hresult: bool = ::default(); - let mut _hi0: ::dafny_runtime::DafnyInt = s.cardinality(); - for i in ::dafny_runtime::integer_range(::dafny_runtime::int!(0), _hi0.clone()) { - if !(::dafny_runtime::int!(s.get(&i).0) < ::dafny_runtime::int!(128)) { - _hresult = false; - return _hresult; - } - } - _hresult = true; - return _hresult; - } - pub fn EncodeAscii(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> crate::UTF8::ValidUTF8Bytes { - let mut _accumulator: crate::UTF8::ValidUTF8Bytes = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence; - let mut _r0 = s.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - if s.cardinality() == ::dafny_runtime::int!(0) { - return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence)); - } else { - let mut x: ::dafny_runtime::Sequence = ::dafny_runtime::seq![s.get(&::dafny_runtime::int!(0)).0 as u8]; - _accumulator = _accumulator.concat(&x); - let mut _in11: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> = s.drop(&::dafny_runtime::int!(1)); - _r0 = _in11.clone(); - continue 'TAIL_CALL_START; - } - } - } - pub fn Uses1Byte(s: &::dafny_runtime::Sequence) -> bool { - 0 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 127 - } - pub fn Uses2Bytes(s: &::dafny_runtime::Sequence) -> bool { - 194 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 223 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) - } - pub fn Uses3Bytes(s: &::dafny_runtime::Sequence) -> bool { - s.get(&::dafny_runtime::int!(0)) == 224 && (160 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || 225 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 236 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || s.get(&::dafny_runtime::int!(0)) == 237 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 159) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || 238 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 239 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) - } - pub fn Uses4Bytes(s: &::dafny_runtime::Sequence) -> bool { - s.get(&::dafny_runtime::int!(0)) == 240 && (144 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) || 241 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 243 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) || s.get(&::dafny_runtime::int!(0)) == 244 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 143) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) - } - pub fn ValidUTF8Range(a: &::dafny_runtime::Sequence, lo: &::dafny_runtime::_System::nat, hi: &::dafny_runtime::_System::nat) -> bool { - let mut _r0 = a.clone(); - let mut _r1 = lo.clone(); - let mut _r2 = hi.clone(); - 'TAIL_CALL_START: loop { - let a = _r0; - let lo = _r1; - let hi = _r2; - if lo.clone() == hi.clone() { - return true; - } else { - let mut r: ::dafny_runtime::Sequence = a.slice(&lo, &hi); - if crate::UTF8::_default::Uses1Byte(&r) { - let mut _in12: ::dafny_runtime::Sequence = a.clone(); - let mut _in13: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(1); - let mut _in14: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in12.clone(); - _r1 = _in13.clone(); - _r2 = _in14.clone(); - continue 'TAIL_CALL_START; - } else { - if ::dafny_runtime::int!(2) <= r.cardinality() && crate::UTF8::_default::Uses2Bytes(&r) { - let mut _in15: ::dafny_runtime::Sequence = a.clone(); - let mut _in16: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(2); - let mut _in17: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in15.clone(); - _r1 = _in16.clone(); - _r2 = _in17.clone(); - continue 'TAIL_CALL_START; - } else { - if ::dafny_runtime::int!(3) <= r.cardinality() && crate::UTF8::_default::Uses3Bytes(&r) { - let mut _in18: ::dafny_runtime::Sequence = a.clone(); - let mut _in19: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(3); - let mut _in20: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in18.clone(); - _r1 = _in19.clone(); - _r2 = _in20.clone(); - continue 'TAIL_CALL_START; - } else { - if ::dafny_runtime::int!(4) <= r.cardinality() && crate::UTF8::_default::Uses4Bytes(&r) { - let mut _in21: ::dafny_runtime::Sequence = a.clone(); - let mut _in22: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(4); - let mut _in23: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in21.clone(); - _r1 = _in22.clone(); - _r2 = _in23.clone(); - continue 'TAIL_CALL_START; - } else { - return false; - } - } - } - } - } - } - } - pub fn ValidUTF8Seq(s: &::dafny_runtime::Sequence) -> bool { - crate::UTF8::_default::ValidUTF8Range(s, &::dafny_runtime::int!(0), &s.cardinality()) - } - } - - pub type ValidUTF8Bytes = ::dafny_runtime::Sequence; - - pub fn r#__init_ValidUTF8Bytes() -> ::dafny_runtime::Sequence { - ::dafny_runtime::seq![] as ::dafny_runtime::Sequence - } -} -pub mod r#_Wrappers_Compile { - pub use ::std::fmt::Debug; - pub use ::dafny_runtime::DafnyPrint; - pub use ::std::cmp::Eq; - pub use ::std::hash::Hash; - pub use ::std::default::Default; - pub use ::std::convert::AsRef; - - pub struct _default {} - - impl _default { - pub fn Need<_E: ::dafny_runtime::DafnyType>(condition: bool, error: &_E) -> ::std::rc::Rc> { - if condition { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Outcome::<_E>::Pass {}) - } else { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Outcome::<_E>::Fail { - error: error.clone() - }) - } - } - } - - #[derive(PartialEq, Clone)] - pub enum Option { - None {}, - Some { - value: T - } - } - - impl Option { - pub fn ToResult(self: &::std::rc::Rc) -> ::std::rc::Rc>> { - let mut _source0: ::std::rc::Rc> = self.clone(); - if matches!((&_source0).as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::string_utf16_of("Option is None") - }) - } else { - let mut r#___mcc_h0: T = _source0.value().clone(); - let mut v: T = r#___mcc_h0.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Success { - value: v.clone() - }) - } - } - pub fn UnwrapOr(self: &::std::rc::Rc, default: &T) -> T { - let mut _source1: ::std::rc::Rc> = self.clone(); - if matches!((&_source1).as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) { - default.clone() - } else { - let mut r#___mcc_h0: T = _source1.value().clone(); - let mut v: T = r#___mcc_h0.clone(); - v.clone() - } - } - pub fn IsFailure(self: &::std::rc::Rc) -> bool { - matches!(self.as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) - } - pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<_U>::None {}) - } - pub fn Extract(self: &::std::rc::Rc) -> T { - self.value().clone() - } - pub fn value(&self) -> &T { - match self { - Option::None{} => panic!("field does not exist on this variant"), - Option::Some{value, } => value, - } - } - } - - impl Debug - for Option { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Option { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Option::None{} => { - write!(_formatter, "Wrappers_Compile.Option.None")?; - Ok(()) - }, - Option::Some{value, } => { - write!(_formatter, "Wrappers_Compile.Option.Some(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Option { - pub fn coerce(f_0: ::std::rc::Rc r#__T0 + 'static>) -> ::std::rc::Rc) -> Option> { - ::std::rc::Rc::new(move |this: Self| -> Option{ - match this { - Option::None{} => { - Option::None {} - }, - Option::Some{value, } => { - Option::Some { - value: f_0.clone()(value) - } - }, - } - }) - } - } - - impl Eq - for Option {} - - impl Hash - for Option { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Option::None{} => { - - }, - Option::Some{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for Option { - fn default() -> Option { - Option::None {} - } - } - - impl AsRef> - for &Option { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum Result { - Success { - value: T - }, - Failure { - error: R - } - } - - impl Result { - pub fn ToOption(self: &::std::rc::Rc) -> ::std::rc::Rc> { - let mut _source2: ::std::rc::Rc> = self.clone(); - if matches!((&_source2).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { - let mut r#___mcc_h0: T = _source2.value().clone(); - let mut s: T = r#___mcc_h0.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::Some { - value: s.clone() - }) - } else { - let mut r#___mcc_h1: R = _source2.error().clone(); - let mut e: R = r#___mcc_h1.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::None {}) - } - } - pub fn UnwrapOr(self: &::std::rc::Rc, default: &T) -> T { - let mut _source3: ::std::rc::Rc> = self.clone(); - if matches!((&_source3).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { - let mut r#___mcc_h0: T = _source3.value().clone(); - let mut s: T = r#___mcc_h0.clone(); - s.clone() - } else { - let mut r#___mcc_h1: R = _source3.error().clone(); - let mut e: R = r#___mcc_h1.clone(); - default.clone() - } - } - pub fn IsFailure(self: &::std::rc::Rc) -> bool { - matches!(self.as_ref(), crate::r#_Wrappers_Compile::Result::Failure{ .. }) - } - pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<_U, R>::Failure { - error: self.error().clone() - }) - } - pub fn MapFailure<_NewR: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc, reWrap: &::std::rc::Rc _NewR>) -> ::std::rc::Rc> { - let mut _source4: ::std::rc::Rc> = self.clone(); - if matches!((&_source4).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { - let mut r#___mcc_h0: T = _source4.value().clone(); - let mut s: T = r#___mcc_h0.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::::Success { - value: s.clone() - }) - } else { - let mut r#___mcc_h1: R = _source4.error().clone(); - let mut e: R = r#___mcc_h1.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::::Failure { - error: reWrap(&e) - }) - } - } - pub fn Extract(self: &::std::rc::Rc) -> T { - self.value().clone() - } - pub fn value(&self) -> &T { - match self { - Result::Success{value, } => value, - Result::Failure{error, } => panic!("field does not exist on this variant"), - } - } - pub fn error(&self) -> &R { - match self { - Result::Success{value, } => panic!("field does not exist on this variant"), - Result::Failure{error, } => error, - } - } - } - - impl Debug - for Result { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Result { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Result::Success{value, } => { - write!(_formatter, "Wrappers_Compile.Result.Success(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - Result::Failure{error, } => { - write!(_formatter, "Wrappers_Compile.Result.Failure(")?; - ::dafny_runtime::DafnyPrint::fmt_print(error, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Result { - pub fn coerce(f_0: ::std::rc::Rc r#__T0 + 'static>, f_1: ::std::rc::Rc r#__T1 + 'static>) -> ::std::rc::Rc) -> Result> { - ::std::rc::Rc::new(move |this: Self| -> Result{ - match this { - Result::Success{value, } => { - Result::Success { - value: f_0.clone()(value) - } - }, - Result::Failure{error, } => { - Result::Failure { - error: f_1.clone()(error) - } - }, - } - }) - } - } - - impl Eq - for Result {} - - impl Hash - for Result { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Result::Success{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - Result::Failure{error, } => { - ::std::hash::Hash::hash(error, _state) - }, - } - } - } - - impl Default - for Result { - fn default() -> Result { - Result::Success { - value: ::std::default::Default::default() - } - } - } - - impl AsRef> - for &Result { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum Outcome { - Pass {}, - Fail { - error: E - } - } - - impl Outcome { - pub fn IsFailure(self: &::std::rc::Rc) -> bool { - matches!(self.as_ref(), crate::r#_Wrappers_Compile::Outcome::Fail{ .. }) - } - pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<_U, E>::Failure { - error: self.error().clone() - }) - } - pub fn error(&self) -> &E { - match self { - Outcome::Pass{} => panic!("field does not exist on this variant"), - Outcome::Fail{error, } => error, - } - } - } - - impl Debug - for Outcome { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Outcome { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Outcome::Pass{} => { - write!(_formatter, "Wrappers_Compile.Outcome.Pass")?; - Ok(()) - }, - Outcome::Fail{error, } => { - write!(_formatter, "Wrappers_Compile.Outcome.Fail(")?; - ::dafny_runtime::DafnyPrint::fmt_print(error, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for Outcome {} - - impl Hash - for Outcome { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Outcome::Pass{} => { - - }, - Outcome::Fail{error, } => { - ::std::hash::Hash::hash(error, _state) - }, - } - } - } - - impl Default - for Outcome { - fn default() -> Outcome { - Outcome::Pass {} - } - } - - impl AsRef> - for &Outcome { - fn as_ref(&self) -> Self { - self - } - } -} \ No newline at end of file diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/lib.rs deleted file mode 100644 index 4315dacf41..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,17 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub use client::Client; -pub use types::simple_string_config::SimpleStringConfig; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation.rs index 11a6156789..1220a72598 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetString` operation. pub mod get_string; @@ -11,4 +12,3 @@ pub mod get_string_utf8; /// Types for the `GetStringUTF8KnownValue` operation. pub mod get_string_utf8_known_value; - diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string.rs index 813f2280e3..2ac87c12d5 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetString`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -137,9 +139,9 @@ pub use crate::operation::get_string::_get_string_output::GetStringOutput; pub use crate::operation::get_string::_get_string_input::GetStringInput; -mod _get_string_input; +pub(crate) mod _get_string_output; -mod _get_string_output; +pub(crate) mod _get_string_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_input.rs index 9c0d47f5f2..b775cb1bfa 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_input.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetStringInput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, +pub value: ::std::option::Option<::std::string::String>, } impl GetStringInput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} } impl GetStringInput { /// Creates a new builder-style object to manufacture [`GetStringInput`](crate::operation::operation::GetStringInput). @@ -29,19 +31,19 @@ pub struct GetStringInputBuilder { } impl GetStringInputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} /// Consumes the builder and constructs a [`GetStringInput`](crate::operation::operation::GetStringInput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_output.rs index ab6b1fa3cd..0f89443a9b 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_output.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetStringOutput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, +pub value: ::std::option::Option<::std::string::String>, } impl GetStringOutput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} } impl GetStringOutput { /// Creates a new builder-style object to manufacture [`GetStringOutput`](crate::operation::operation::GetStringOutput). @@ -29,19 +31,19 @@ pub struct GetStringOutputBuilder { } impl GetStringOutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} /// Consumes the builder and constructs a [`GetStringOutput`](crate::operation::operation::GetStringOutput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/builders.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/builders.rs index ec32b2e2ce..e0c6cd015e 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/builders.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/builders.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_string::_get_string_output::GetStringOutputBuilder; pub use crate::operation::get_string::_get_string_input::GetStringInputBuilder; @@ -21,12 +23,12 @@ impl GetStringInputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetStringFluentBuilder { - client: crate::Client, - inner: crate::operation::get_string::builders::GetStringInputBuilder, + client: crate::client::Client, + pub(crate) inner: crate::operation::get_string::builders::GetStringInputBuilder, } impl GetStringFluentBuilder { /// Creates a new `GetString`. - pub(crate) fn new(client: crate::Client) -> Self { + pub(crate) fn new(client: crate::client::Client) -> Self { Self { client, inner: ::std::default::Default::default(), @@ -56,17 +58,17 @@ impl GetStringFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.inner = self.inner.value(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value.rs index d6abc77c74..0d9960be0e 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetStringKnownValue`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,28 +12,27 @@ impl GetStringKnownValue { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_string_known_value::GetStringKnownValueInput, + input: crate::operation::get_string_known_value::GetStringInput, ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringKnownValueOutput, + crate::operation::get_string_known_value::GetStringOutput, crate::operation::get_string_known_value::GetStringKnownValueError, > { - let inner_input = - crate::conversions::get_string_known_value::_get_string_known_value_input::to_dafny( - input, - ); + let inner_input = crate::conversions::get_string_known_value::_get_string_known_value_input::to_dafny(input); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetString(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetStringKnownValue(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - Ok(crate::conversions::get_string_known_value::_get_string_known_value_output::from_dafny(inner_result.value().clone())) - } else { - Err( - crate::conversions::get_string_known_value::from_dafny_error( - inner_result.error().clone(), + Ok( + crate::conversions::get_string_known_value::_get_string_known_value_output::from_dafny( + inner_result.value().clone(), ), ) + } else { + Err(crate::conversions::get_string_known_value::from_dafny_error( + inner_result.error().clone(), + )) } } } @@ -134,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetStrin } } -pub use crate::operation::get_string_known_value::_get_string_known_value_output::GetStringKnownValueOutput; +pub use crate::operation::get_string_known_value::_get_string_output::GetStringOutput; -pub use crate::operation::get_string_known_value::_get_string_known_value_input::GetStringKnownValueInput; +pub use crate::operation::get_string_known_value::_get_string_input::GetStringInput; -mod _get_string_known_value_input; +pub(crate) mod _get_string_output; -mod _get_string_known_value_output; +pub(crate) mod _get_string_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_input.rs new file mode 100644 index 0000000000..2eedc4c6b9 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetStringInput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::string::String>, +} +impl GetStringInput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} +} +impl GetStringInput { + /// Creates a new builder-style object to manufacture [`GetStringInput`](crate::operation::operation::GetStringInput). + pub fn builder() -> crate::operation::get_string_known_value::builders::GetStringInputBuilder { + crate::operation::get_string_known_value::builders::GetStringInputBuilder::default() + } +} + +/// A builder for [`GetStringInput`](crate::operation::operation::GetStringInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetStringInputBuilder { + pub(crate) value: ::std::option::Option<::std::string::String>, +} +impl GetStringInputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} + /// Consumes the builder and constructs a [`GetStringInput`](crate::operation::operation::GetStringInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_string_known_value::GetStringInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_string_known_value::GetStringInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_input.rs deleted file mode 100644 index b67c3effad..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_input.rs +++ /dev/null @@ -1,60 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetStringKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, -} -impl GetStringKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } -} -impl GetStringKnownValueInput { - /// Creates a new builder-style object to manufacture [`GetStringKnownValueInput`](crate::operation::operation::GetStringKnownValueInput). - pub fn builder( - ) -> crate::operation::get_string_known_value::builders::GetStringKnownValueInputBuilder { - crate::operation::get_string_known_value::builders::GetStringKnownValueInputBuilder::default( - ) - } -} - -/// A builder for [`GetStringKnownValueInput`](crate::operation::operation::GetStringKnownValueInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetStringKnownValueInputBuilder { - pub(crate) value: ::std::option::Option<::std::string::String>, -} -impl GetStringKnownValueInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } - /// Consumes the builder and constructs a [`GetStringKnownValueInput`](crate::operation::operation::GetStringKnownValueInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringKnownValueInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_string_known_value::GetStringKnownValueInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_output.rs deleted file mode 100644 index 291e692c5a..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_output.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetStringKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, -} -impl GetStringKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } -} -impl GetStringKnownValueOutput { - /// Creates a new builder-style object to manufacture [`GetStringKnownValueOutput`](crate::operation::operation::GetStringKnownValueOutput). - pub fn builder( - ) -> crate::operation::get_string_known_value::builders::GetStringKnownValueOutputBuilder { - crate::operation::get_string_known_value::builders::GetStringKnownValueOutputBuilder::default() - } -} - -/// A builder for [`GetStringKnownValueOutput`](crate::operation::operation::GetStringKnownValueOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetStringKnownValueOutputBuilder { - pub(crate) value: ::std::option::Option<::std::string::String>, -} -impl GetStringKnownValueOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } - /// Consumes the builder and constructs a [`GetStringKnownValueOutput`](crate::operation::operation::GetStringKnownValueOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringKnownValueOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_string_known_value::GetStringKnownValueOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_output.rs new file mode 100644 index 0000000000..dd7b2a2ebc --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetStringOutput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::string::String>, +} +impl GetStringOutput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} +} +impl GetStringOutput { + /// Creates a new builder-style object to manufacture [`GetStringOutput`](crate::operation::operation::GetStringOutput). + pub fn builder() -> crate::operation::get_string_known_value::builders::GetStringOutputBuilder { + crate::operation::get_string_known_value::builders::GetStringOutputBuilder::default() + } +} + +/// A builder for [`GetStringOutput`](crate::operation::operation::GetStringOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetStringOutputBuilder { + pub(crate) value: ::std::option::Option<::std::string::String>, +} +impl GetStringOutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} + /// Consumes the builder and constructs a [`GetStringOutput`](crate::operation::operation::GetStringOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_string_known_value::GetStringOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_string_known_value::GetStringOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/builders.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/builders.rs index 82b4c7fb37..0d379f9cad 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/builders.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/builders.rs @@ -1,15 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_string_known_value::_get_string_known_value_output::GetStringKnownValueOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_string_known_value::_get_string_output::GetStringOutputBuilder; -pub use crate::operation::get_string_known_value::_get_string_known_value_input::GetStringKnownValueInputBuilder; +pub use crate::operation::get_string_known_value::_get_string_input::GetStringInputBuilder; -impl GetStringKnownValueInputBuilder { +impl GetStringInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringKnownValueOutput, + crate::operation::get_string_known_value::GetStringOutput, crate::operation::get_string_known_value::GetStringKnownValueError, > { let mut fluent_builder = client.get_string_known_value(); @@ -21,57 +23,52 @@ impl GetStringKnownValueInputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetStringKnownValueFluentBuilder { - client: crate::Client, - inner: crate::operation::get_string_known_value::builders::GetStringKnownValueInputBuilder, + client: crate::client::Client, + pub(crate) inner: crate::operation::get_string_known_value::builders::GetStringInputBuilder, } impl GetStringKnownValueFluentBuilder { /// Creates a new `GetStringKnownValue`. - pub(crate) fn new(client: crate::Client) -> Self { + pub(crate) fn new(client: crate::client::Client) -> Self { Self { client, inner: ::std::default::Default::default(), } } /// Access the GetStringKnownValue as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_string_known_value::builders::GetStringKnownValueInputBuilder { + pub fn as_input(&self) -> &crate::operation::get_string_known_value::builders::GetStringInputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringKnownValueOutput, + crate::operation::get_string_known_value::GetStringOutput, crate::operation::get_string_known_value::GetStringKnownValueError, > { let input = self .inner .build() - // Using unhandled since GetString doesn't declare any validation, + // Using unhandled since GetStringKnownValue doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. - .map_err( - crate::operation::get_string_known_value::GetStringKnownValueError::unhandled, - )?; - crate::operation::get_string_known_value::GetStringKnownValue::send(&self.client, input) - .await + .map_err(crate::operation::get_string_known_value::GetStringKnownValueError::unhandled)?; + crate::operation::get_string_known_value::GetStringKnownValue::send(&self.client, input).await } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.inner = self.inner.value(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8.rs index 966f215250..d27e047855 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetStringUTF8`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -15,8 +17,7 @@ impl GetStringUTF8 { crate::operation::get_string_utf8::GetStringUTF8Output, crate::operation::get_string_utf8::GetStringUTF8Error, > { - let inner_input = - crate::conversions::get_string_utf8::_get_string_utf8_input::to_dafny(input); + let inner_input = crate::conversions::get_string_utf8::_get_string_utf8_input::to_dafny(input); let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetStringUTF8(&inner_input); if matches!( @@ -138,9 +139,9 @@ pub use crate::operation::get_string_utf8::_get_string_utf8_output::GetStringUTF pub use crate::operation::get_string_utf8::_get_string_utf8_input::GetStringUTF8Input; -mod _get_string_utf8_input; +pub(crate) mod _get_string_utf8_output; -mod _get_string_utf8_output; +pub(crate) mod _get_string_utf8_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_input.rs index a448688ed3..8950b2a8c0 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_input.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetStringUTF8Input { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, +pub value: ::std::option::Option<::std::string::String>, } impl GetStringUTF8Input { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} } impl GetStringUTF8Input { /// Creates a new builder-style object to manufacture [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). @@ -29,19 +31,19 @@ pub struct GetStringUTF8InputBuilder { } impl GetStringUTF8InputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} /// Consumes the builder and constructs a [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_output.rs index 2c8dca6a85..bb7220129d 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_output.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetStringUTF8Output { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, +pub value: ::std::option::Option<::std::string::String>, } impl GetStringUTF8Output { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} } impl GetStringUTF8Output { /// Creates a new builder-style object to manufacture [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). @@ -29,19 +31,19 @@ pub struct GetStringUTF8OutputBuilder { } impl GetStringUTF8OutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} /// Consumes the builder and constructs a [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/builders.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/builders.rs index 26bf3d9e26..2291919ec3 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/builders.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/builders.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_string_utf8::_get_string_utf8_output::GetStringUTF8OutputBuilder; pub use crate::operation::get_string_utf8::_get_string_utf8_input::GetStringUTF8InputBuilder; @@ -21,21 +23,19 @@ impl GetStringUTF8InputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetStringUTF8FluentBuilder { - client: crate::Client, - inner: crate::operation::get_string_utf8::builders::GetStringUTF8InputBuilder, + client: crate::client::Client, + pub(crate) inner: crate::operation::get_string_utf8::builders::GetStringUTF8InputBuilder, } impl GetStringUTF8FluentBuilder { /// Creates a new `GetStringUTF8`. - pub(crate) fn new(client: crate::Client) -> Self { + pub(crate) fn new(client: crate::client::Client) -> Self { Self { client, inner: ::std::default::Default::default(), } } /// Access the GetStringUTF8 as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_string_utf8::builders::GetStringUTF8InputBuilder { + pub fn as_input(&self) -> &crate::operation::get_string_utf8::builders::GetStringUTF8InputBuilder { &self.inner } /// Sends the request and returns the response. @@ -48,7 +48,7 @@ impl GetStringUTF8FluentBuilder { let input = self .inner .build() - // Using unhandled since GetString doesn't declare any validation, + // Using unhandled since GetStringUTF8 doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, @@ -58,17 +58,17 @@ impl GetStringUTF8FluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.inner = self.inner.value(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value.rs index 16b06252a3..47bb6d9ea5 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetStringUTF8KnownValue`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,13 +12,12 @@ impl GetStringUTF8KnownValue { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput, + input: crate::operation::get_string_utf8_known_value::GetStringUTF8Input, ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, + crate::operation::get_string_utf8_known_value::GetStringUTF8Output, crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError, > { - let inner_input = - crate::conversions::get_string_utf8_known_value::_get_string_utf8_known_value_input::to_dafny(input); + let inner_input = crate::conversions::get_string_utf8_known_value::_get_string_utf8_known_value_input::to_dafny(input); let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetStringUTF8KnownValue(&inner_input); if matches!( @@ -134,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetStrin } } -pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_known_value_output::GetStringUTF8KnownValueOutput; +pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_output::GetStringUTF8Output; -pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_known_value_input::GetStringUTF8KnownValueInput; +pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_input::GetStringUTF8Input; -mod _get_string_utf8_known_value_input; +pub(crate) mod _get_string_utf8_output; -mod _get_string_utf8_known_value_output; +pub(crate) mod _get_string_utf8_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_input.rs new file mode 100644 index 0000000000..6e21c111bd --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetStringUTF8Input { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::string::String>, +} +impl GetStringUTF8Input { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} +} +impl GetStringUTF8Input { + /// Creates a new builder-style object to manufacture [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). + pub fn builder() -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8InputBuilder { + crate::operation::get_string_utf8_known_value::builders::GetStringUTF8InputBuilder::default() + } +} + +/// A builder for [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetStringUTF8InputBuilder { + pub(crate) value: ::std::option::Option<::std::string::String>, +} +impl GetStringUTF8InputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} + /// Consumes the builder and constructs a [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_string_utf8_known_value::GetStringUTF8Input, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_string_utf8_known_value::GetStringUTF8Input { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs deleted file mode 100644 index 6b73af0d8f..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetStringUTF8KnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, -} -impl GetStringUTF8KnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } -} -impl GetStringUTF8KnownValueInput { - /// Creates a new builder-style object to manufacture [`GetStringUTF8KnownValueInput`](crate::operation::operation::GetStringUTF8KnownValueInput). - pub fn builder() -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueInputBuilder { - crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueInputBuilder::default() - } -} - -/// A builder for [`GetStringUTF8KnownValueInput`](crate::operation::operation::GetStringUTF8KnownValueInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetStringUTF8KnownValueInputBuilder { - pub(crate) value: ::std::option::Option<::std::string::String>, -} -impl GetStringUTF8KnownValueInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } - /// Consumes the builder and constructs a [`GetStringUTF8KnownValueInput`](crate::operation::operation::GetStringUTF8KnownValueInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs deleted file mode 100644 index 8c77126081..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetStringUTF8KnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, -} -impl GetStringUTF8KnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } -} -impl GetStringUTF8KnownValueOutput { - /// Creates a new builder-style object to manufacture [`GetStringUTF8KnownValueOutput`](crate::operation::operation::GetStringUTF8KnownValueOutput). - pub fn builder() -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueOutputBuilder { - crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueOutputBuilder::default() - } -} - -/// A builder for [`GetStringUTF8KnownValueOutput`](crate::operation::operation::GetStringUTF8KnownValueOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetStringUTF8KnownValueOutputBuilder { - pub(crate) value: ::std::option::Option<::std::string::String>, -} -impl GetStringUTF8KnownValueOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } - /// Consumes the builder and constructs a [`GetStringUTF8KnownValueOutput`](crate::operation::operation::GetStringUTF8KnownValueOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_output.rs new file mode 100644 index 0000000000..f1dfb24b67 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetStringUTF8Output { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::string::String>, +} +impl GetStringUTF8Output { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} +} +impl GetStringUTF8Output { + /// Creates a new builder-style object to manufacture [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). + pub fn builder() -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8OutputBuilder { + crate::operation::get_string_utf8_known_value::builders::GetStringUTF8OutputBuilder::default() + } +} + +/// A builder for [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetStringUTF8OutputBuilder { + pub(crate) value: ::std::option::Option<::std::string::String>, +} +impl GetStringUTF8OutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} + /// Consumes the builder and constructs a [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_string_utf8_known_value::GetStringUTF8Output, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_string_utf8_known_value::GetStringUTF8Output { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/builders.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/builders.rs index 0b29a00e10..c6e957eee6 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/builders.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/builders.rs @@ -1,15 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_known_value_output::GetStringUTF8KnownValueOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_output::GetStringUTF8OutputBuilder; -pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_known_value_input::GetStringUTF8KnownValueInputBuilder; +pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_input::GetStringUTF8InputBuilder; -impl GetStringUTF8KnownValueInputBuilder { +impl GetStringUTF8InputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, + crate::operation::get_string_utf8_known_value::GetStringUTF8Output, crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError, > { let mut fluent_builder = client.get_string_utf8_known_value(); @@ -21,34 +23,32 @@ impl GetStringUTF8KnownValueInputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetStringUTF8KnownValueFluentBuilder { - client: crate::Client, - inner: crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueInputBuilder, + client: crate::client::Client, + pub(crate) inner: crate::operation::get_string_utf8_known_value::builders::GetStringUTF8InputBuilder, } impl GetStringUTF8KnownValueFluentBuilder { /// Creates a new `GetStringUTF8KnownValue`. - pub(crate) fn new(client: crate::Client) -> Self { + pub(crate) fn new(client: crate::client::Client) -> Self { Self { client, inner: ::std::default::Default::default(), } } /// Access the GetStringUTF8KnownValue as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueInputBuilder { + pub fn as_input(&self) -> &crate::operation::get_string_utf8_known_value::builders::GetStringUTF8InputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, + crate::operation::get_string_utf8_known_value::GetStringUTF8Output, crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError, > { let input = self .inner .build() - // Using unhandled since GetString doesn't declare any validation, + // Using unhandled since GetStringUTF8KnownValue doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, @@ -58,17 +58,17 @@ impl GetStringUTF8KnownValueFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.inner = self.inner.value(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types.rs index 7ec7460923..9e117395c3 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `SimpleStringConfig` pub mod simple_string_config; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types/simple_string_config.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types/simple_string_config.rs index 6b9ec61a06..94d186d226 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types/simple_string_config.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types/simple_string_config.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleStringConfig {} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..4f32d02ae7 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::smithystring::internaldafny::wrapped::_default { + pub fn WrappedSimpleString(config: &::std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::SimpleStringConfig, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..f89535dd13 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,179 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::smithystring::internaldafny::types::ISimpleTypesStringClient); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::SimpleStringConfig, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_string_config::_simple_string_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::smithystring::internaldafny::types::ISimpleTypesStringClient for Client { + fn GetString( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_string::_get_string_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_string::GetString::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_string::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_string::_get_string_output::to_dafny(client), + }, + ), + } + } + + fn GetStringKnownValue( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_string_known_value::_get_string_known_value_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_string_known_value::GetStringKnownValue::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_string_known_value::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_string_known_value::_get_string_known_value_output::to_dafny(client), + }, + ), + } + } + + fn GetStringUTF8( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_string_utf8::_get_string_utf8_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_string_utf8::GetStringUTF8::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_string_utf8::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_string_utf8::_get_string_utf8_output::to_dafny(client), + }, + ), + } + } + + fn GetStringUTF8KnownValue( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_string_utf8_known_value::_get_string_utf8_known_value_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValue::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_string_utf8_known_value::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_string_utf8_known_value::_get_string_utf8_known_value_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/Makefile b/TestModels/SimpleTypes/SimpleTimestamp/Makefile index 6575072c56..55d0f10c8b 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/Makefile +++ b/TestModels/SimpleTypes/SimpleTimestamp/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk @@ -22,10 +23,8 @@ SMITHY_DEPS=dafny-dependencies/Model/traits.smithy # This project has no dependencies # DEPENDENT-MODELS:= - POLYMORPH_OPTIONS=--generate client-constructors,project-files - # Constants for languages that drop extern names (Python, Go) TYPES_FILE_PATH=Model/SimpleTypesTimestampTypes.dfy diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/Cargo.toml index 94927ac487..de5d419467 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/Cargo.toml @@ -5,14 +5,21 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] -dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} aws-smithy-runtime = { version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = { version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" +dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} [dev-dependencies] -tokio = { version = "1.26.0", features = ["full"] } +simple_timestamp = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] +version = "1.26.0" +features = ["full"] [lib] path = "src/implementation_from_dafny.rs" diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client.rs index 1691812f17..c87832fe22 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -29,7 +30,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client/get_timestamp.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client/get_timestamp.rs index 9004f4f30c..e272f76759 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client/get_timestamp.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client/get_timestamp.rs @@ -1,15 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetTimestamp`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(DateTime)`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::set_value):
required: **false**
(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::value) / [`set_value(Option<::aws_smithy_types::DateTime>)`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetTimestampOutput`](crate::operation::get_timestamp::GetTimestampOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_timestamp::GetTimestampOutput::value): (undocumented) + /// - [`value(Option<::aws_smithy_types::DateTime>)`](crate::operation::get_timestamp::GetTimestampOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_timestamp::GetTimestampError) - pub fn get_timestamp( - &self, - ) -> crate::operation::get_timestamp::builders::GetTimestampFluentBuilder { + pub fn get_timestamp(&self) -> crate::operation::get_timestamp::builders::GetTimestampFluentBuilder { crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions.rs index 6c19c684d4..85c9ba3aa5 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions.rs @@ -1,4 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_timestamp; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod simple_timestamp_config; + pub mod get_timestamp; + + pub mod simple_timestamp_config; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..255fc97000 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::timestamp::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp.rs index 64d9cf3a17..e96799af63 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp.rs @@ -1,12 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_timestamp::GetTimestampError, -) -> ::std::rc::Rc -{ +) -> ::std::rc::Rc { match value { crate::operation::get_timestamp::GetTimestampError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::timestamp::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_input.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_input.rs index ec1fde893a..b42a091567 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_input.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_input.rs @@ -1,39 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_timestamp::GetTimestampInput, ) -> ::std::rc::Rc< crate::r#simple::types::timestamp::internaldafny::types::GetTimestampInput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s.to_string()) }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::timestamp::internaldafny::types::GetTimestampInput::GetTimestampInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::otimestamp_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::timestamp::internaldafny::types::GetTimestampInput, >, -) -> Result< - crate::operation::get_timestamp::GetTimestampInput, - aws_smithy_types::date_time::DateTimeParseError, -> { - let value = match dafny_value.value().as_ref() { - crate::_Wrappers_Compile::Option::None {} => None, - crate::_Wrappers_Compile::Option::Some { value } => { - let value = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&value); - let value = ::aws_smithy_types::DateTime::from_str( - &value, - aws_smithy_types::date_time::Format::DateTime, - )?; - Some(value) - } - }; - - Ok(crate::operation::get_timestamp::GetTimestampInput { value }) +) -> crate::operation::get_timestamp::GetTimestampInput { + crate::operation::get_timestamp::GetTimestampInput::builder() + .set_value(crate::standard_library_conversions::otimestamp_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_output.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_output.rs index 958069da06..09e9489bd3 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_output.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_output.rs @@ -1,39 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_timestamp::GetTimestampOutput, ) -> ::std::rc::Rc< crate::r#simple::types::timestamp::internaldafny::types::GetTimestampOutput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s.to_string()) }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::timestamp::internaldafny::types::GetTimestampOutput::GetTimestampOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::otimestamp_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::timestamp::internaldafny::types::GetTimestampOutput, >, -) -> Result< - crate::operation::get_timestamp::GetTimestampOutput, - aws_smithy_types::date_time::DateTimeParseError, -> { - let value = match dafny_value.value().as_ref() { - crate::_Wrappers_Compile::Option::None {} => None, - crate::_Wrappers_Compile::Option::Some { value } => { - let value = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&value); - let value = ::aws_smithy_types::DateTime::from_str( - &value, - aws_smithy_types::date_time::Format::DateTime, - )?; - Some(value) - } - }; - - Ok(crate::operation::get_timestamp::GetTimestampOutput { value }) +) -> crate::operation::get_timestamp::GetTimestampOutput { + crate::operation::get_timestamp::GetTimestampOutput::builder() + .set_value(crate::standard_library_conversions::otimestamp_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config.rs index 3ab1449023..f4c49447c2 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_timestamp_config; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config/_simple_timestamp_config.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config/_simple_timestamp_config.rs index 7a6ad17f9b..65be65a356 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config/_simple_timestamp_config.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config/_simple_timestamp_config.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_timestamp_config::SimpleTimestampConfig, ) -> ::std::rc::Rc< - crate::simple::types::timestamp::internaldafny::types::SimpleTimestampConfig, ->{ + crate::r#simple::types::timestamp::internaldafny::types::SimpleTimestampConfig, +> { ::std::rc::Rc::new(crate::r#simple::types::timestamp::internaldafny::types::SimpleTimestampConfig::SimpleTimestampConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/lib.rs deleted file mode 100644 index 4e55b724cc..0000000000 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub mod implementation_from_dafny; - -pub use client::Client; -pub use types::simple_timestamp_config::SimpleTimestampConfig; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation.rs index 14ae6ca55a..e1bae12748 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetTimestamp` operation. pub mod get_timestamp; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp.rs index 27f406c721..a393c9880c 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetTimestamp`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -22,10 +24,11 @@ impl GetTimestamp { inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - crate::conversions::get_timestamp::_get_timestamp_output::from_dafny( - inner_result.value().clone(), + Ok( + crate::conversions::get_timestamp::_get_timestamp_output::from_dafny( + inner_result.value().clone(), + ), ) - .map_err(crate::operation::get_timestamp::GetTimestampError::unhandled) } else { Err(crate::conversions::get_timestamp::from_dafny_error( inner_result.error().clone(), @@ -136,9 +139,9 @@ pub use crate::operation::get_timestamp::_get_timestamp_output::GetTimestampOutp pub use crate::operation::get_timestamp::_get_timestamp_input::GetTimestampInput; -mod _get_timestamp_input; +pub(crate) mod _get_timestamp_output; -mod _get_timestamp_output; +pub(crate) mod _get_timestamp_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_input.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_input.rs index acf259d313..1155b34c91 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_input.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_input.rs @@ -1,25 +1,27 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetTimestampInput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::aws_smithy_types::DateTime>, +pub value: ::std::option::Option<::aws_smithy_types::DateTime>, } impl GetTimestampInput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&::aws_smithy_types::DateTime> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::DateTime> { + self.value +} } impl GetTimestampInput { - /// Creates a new builder-style object to manufacture [`GetTimestampInput`](crate::operation::get_timestamp::GetTimestampInput). + /// Creates a new builder-style object to manufacture [`GetTimestampInput`](crate::operation::operation::GetTimestampInput). pub fn builder() -> crate::operation::get_timestamp::builders::GetTimestampInputBuilder { crate::operation::get_timestamp::builders::GetTimestampInputBuilder::default() } } -/// A builder for [`GetTimestampInput`](crate::operation::get_timestamp::GetTimestampInput). +/// A builder for [`GetTimestampInput`](crate::operation::operation::GetTimestampInput). #[non_exhaustive] #[derive( ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, @@ -29,20 +31,20 @@ pub struct GetTimestampInputBuilder { } impl GetTimestampInputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: ::aws_smithy_types::DateTime) -> Self { - self.value = ::std::option::Option::Some(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { - &self.value - } - /// Consumes the builder and constructs a [`GetTimestampInput`](crate::operation::get_timestamp::GetTimestampInput). +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::DateTime>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { + &self.value +} + /// Consumes the builder and constructs a [`GetTimestampInput`](crate::operation::operation::GetTimestampInput). pub fn build( self, ) -> ::std::result::Result< diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_output.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_output.rs index 711324b3a8..c4f3ab84e0 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_output.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_output.rs @@ -1,25 +1,27 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetTimestampOutput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::aws_smithy_types::DateTime>, +pub value: ::std::option::Option<::aws_smithy_types::DateTime>, } impl GetTimestampOutput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&::aws_smithy_types::DateTime> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::DateTime> { + self.value +} } impl GetTimestampOutput { - /// Creates a new builder-style object to manufacture [`GetTimestampOutput`](crate::operation::get_timestamp::GetTimestampOutput). + /// Creates a new builder-style object to manufacture [`GetTimestampOutput`](crate::operation::operation::GetTimestampOutput). pub fn builder() -> crate::operation::get_timestamp::builders::GetTimestampOutputBuilder { crate::operation::get_timestamp::builders::GetTimestampOutputBuilder::default() } } -/// A builder for [`GetTimestampOutput`](crate::operation::get_timestamp::GetTimestampOutput). +/// A builder for [`GetTimestampOutput`](crate::operation::operation::GetTimestampOutput). #[non_exhaustive] #[derive( ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, @@ -29,21 +31,28 @@ pub struct GetTimestampOutputBuilder { } impl GetTimestampOutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: ::aws_smithy_types::DateTime) -> Self { - self.value = ::std::option::Option::Some(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { - &self.value - } - /// Consumes the builder and constructs a [`GetTimestampOutput`](crate::operation::get_timestamp::GetTimestampOutput). - pub fn build(self) -> crate::operation::get_timestamp::GetTimestampOutput { - crate::operation::get_timestamp::GetTimestampOutput { value: self.value } +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::DateTime>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { + &self.value +} + /// Consumes the builder and constructs a [`GetTimestampOutput`](crate::operation::operation::GetTimestampOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_timestamp::GetTimestampOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_timestamp::GetTimestampOutput { + value: self.value, + }) } } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/builders.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/builders.rs index 6097f5dc0d..4f9282db2a 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/builders.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/builders.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_timestamp::_get_timestamp_output::GetTimestampOutputBuilder; pub use crate::operation::get_timestamp::_get_timestamp_input::GetTimestampInputBuilder; @@ -22,7 +24,7 @@ impl GetTimestampInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetTimestampFluentBuilder { client: crate::client::Client, - inner: crate::operation::get_timestamp::builders::GetTimestampInputBuilder, + pub(crate) inner: crate::operation::get_timestamp::builders::GetTimestampInputBuilder, } impl GetTimestampFluentBuilder { /// Creates a new `GetTimestamp`. @@ -56,17 +58,17 @@ impl GetTimestampFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::DateTime>) -> Self { - self.inner = self.inner.value(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::DateTime>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types.rs index b22d67ccbb..7eff17a000 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `SimpleTimestampConfig` pub mod simple_timestamp_config; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types/simple_timestamp_config.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types/simple_timestamp_config.rs index 611191c990..678b4ac557 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types/simple_timestamp_config.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types/simple_timestamp_config.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleTimestampConfig {} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..cefeb4517d --- /dev/null +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::timestamp::internaldafny::wrapped::_default { + pub fn WrappedSimpleTimestamp(config: &::std::rc::Rc< + crate::r#simple::types::timestamp::internaldafny::types::SimpleTimestampConfig, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..c33b27e948 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,89 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::timestamp::internaldafny::types::ISimpleTypesTimestampClient); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::timestamp::internaldafny::types::SimpleTimestampConfig, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_timestamp_config::_simple_timestamp_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::timestamp::internaldafny::types::ISimpleTypesTimestampClient for Client { + fn GetTimestamp( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::timestamp::internaldafny::types::GetTimestampInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::timestamp::internaldafny::types::GetTimestampOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_timestamp::_get_timestamp_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_timestamp::GetTimestamp::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_timestamp::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_timestamp::_get_timestamp_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/tests/simple_timestamp_test.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/tests/simple_timestamp_test.rs index b6b60a0483..f45eb0c6ee 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/tests/simple_timestamp_test.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/tests/simple_timestamp_test.rs @@ -28,7 +28,7 @@ async fn test_get_timestamp() { .unwrap(); let result = client().get_timestamp().value(ts).send().await.unwrap(); let value = result.value().unwrap(); - assert_eq!(value, &ts); + assert_eq!(value, ts); } pub fn client() -> Client { diff --git a/TestModels/SimpleTypes/SimpleTimestamp/src/WrappedSimpleTypesTimestampImpl.dfy b/TestModels/SimpleTypes/SimpleTimestamp/src/WrappedSimpleTypesTimestampImpl.dfy new file mode 100644 index 0000000000..ce9fc36dbc --- /dev/null +++ b/TestModels/SimpleTypes/SimpleTimestamp/src/WrappedSimpleTypesTimestampImpl.dfy @@ -0,0 +1,10 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/SimpleTypesTimestampTypesWrapped.dfy" + +module {:options "--function-syntax:4"} {:extern "simple.types.timestamp.internaldafny.wrapped"} WrappedSimpleTypesTimestampService refines WrappedAbstractSimpleTypesTimestampService { + import WrappedService = SimpleTimestamp + function WrappedDefaultSimpleTimestampConfig(): SimpleTimestampConfig { + SimpleTimestampConfig + } +} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/test/SimpleTimestampImplTest.dfy b/TestModels/SimpleTypes/SimpleTimestamp/test/SimpleTimestampImplTest.dfy index 7cd928417e..a30f145cd2 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/test/SimpleTimestampImplTest.dfy +++ b/TestModels/SimpleTypes/SimpleTimestamp/test/SimpleTimestampImplTest.dfy @@ -12,6 +12,7 @@ module SimpleTimestampImplTest { var client :- expect SimpleTimestamp.SimpleTimestamp(); TestGetTimestamp(client); + TestGetTimestampNoMs(client); } method TestGetTimestamp(client: ISimpleTypesTimestampClient) @@ -19,9 +20,26 @@ module SimpleTimestampImplTest { modifies client.Modifies ensures client.ValidState() { - var dafnyTimestamp := "2024-06-11T12:34:56"; - var ret :- expect client.GetTimestamp(SimpleTimestamp.Types.GetTimestampInput(value:= Some(dafnyTimestamp))); + var dafnyTimestamp := "2024-06-11T12:34:56.789Z"; + var ret :- expect client.GetTimestamp(SimpleTimestamp.Types.GetTimestampInput(value := Some(dafnyTimestamp))); expect ret.value == Some(dafnyTimestamp); print ret; } + + method TestGetTimestampNoMs(client: ISimpleTypesTimestampClient) + requires client.ValidState() + modifies client.Modifies + ensures client.ValidState() + { + var dafnyTimestamp := "2024-06-11T12:34:56Z"; + var ret :- expect client.GetTimestamp(SimpleTimestamp.Types.GetTimestampInput(value := Some(dafnyTimestamp))); + expect ret.value.Some?; + var retTimestamp := ret.value.value; + + // It's okay if milliseconds are serialized, so only check for prefix + expect |retTimestamp| > 0; + expect retTimestamp[|retTimestamp| - 1] == 'Z'; + expect dafnyTimestamp[|dafnyTimestamp| - 1] <= retTimestamp[|retTimestamp| - 1]; + print ret; + } } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/test/WrappedSimpleTimestampTest.dfy b/TestModels/SimpleTypes/SimpleTimestamp/test/WrappedSimpleTimestampTest.dfy index 3e741368ff..d51eb599bc 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/test/WrappedSimpleTimestampTest.dfy +++ b/TestModels/SimpleTypes/SimpleTimestamp/test/WrappedSimpleTimestampTest.dfy @@ -11,5 +11,6 @@ module WrappedSimpleTypesTimestampTest { var client :- expect WrappedSimpleTypesTimestampService.WrappedSimpleTimestamp(); SimpleTimestampImplTest.TestGetTimestamp(client); + SimpleTimestampImplTest.TestGetTimestampNoMs(client); } } diff --git a/TestModels/Union/runtimes/rust/src/standard_library_externs.rs b/TestModels/Union/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/Union/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/attribute_action.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/attribute_action.rs index 3b4bb95a5e..86959a17b6 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/attribute_action.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/attribute_action.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::AttributeAction, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::AttributeAction::Add => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::ADD {}, - aws_sdk_dynamodb::types::AttributeAction::Put => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::PUT {}, - aws_sdk_dynamodb::types::AttributeAction::Delete => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::DELETE {}, + aws_sdk_dynamodb::types::AttributeAction::Add => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::ADD {}, +aws_sdk_dynamodb::types::AttributeAction::Put => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::PUT {}, +aws_sdk_dynamodb::types::AttributeAction::Delete => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::DELETE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction, ) -> aws_sdk_dynamodb::types::AttributeAction { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::ADD {} => aws_sdk_dynamodb::types::AttributeAction::Add, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::PUT {} => aws_sdk_dynamodb::types::AttributeAction::Put, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::DELETE {} => aws_sdk_dynamodb::types::AttributeAction::Delete, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::ADD {} => aws_sdk_dynamodb::types::AttributeAction::Add, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::PUT {} => aws_sdk_dynamodb::types::AttributeAction::Put, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::DELETE {} => aws_sdk_dynamodb::types::AttributeAction::Delete, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/batch_statement_error_code_enum.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/batch_statement_error_code_enum.rs index 93746fece8..fd53a818a3 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/batch_statement_error_code_enum.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/batch_statement_error_code_enum.rs @@ -7,17 +7,17 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::RequestLimitExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::RequestLimitExceeded {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ValidationError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ValidationError {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::TransactionConflict => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::TransactionConflict {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ThrottlingError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ThrottlingError {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::InternalServerError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::InternalServerError {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ResourceNotFound => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ResourceNotFound {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::AccessDenied => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::AccessDenied {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::DuplicateItem => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::DuplicateItem {}, + aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::RequestLimitExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::RequestLimitExceeded {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ValidationError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ValidationError {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::TransactionConflict => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::TransactionConflict {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ThrottlingError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ThrottlingError {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::InternalServerError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::InternalServerError {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ResourceNotFound => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ResourceNotFound {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::AccessDenied => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::AccessDenied {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::DuplicateItem => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::DuplicateItem {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -26,16 +26,16 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum, ) -> aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::RequestLimitExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::RequestLimitExceeded, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ValidationError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ValidationError, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::TransactionConflict {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::TransactionConflict, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ThrottlingError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ThrottlingError, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::InternalServerError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::InternalServerError, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ResourceNotFound {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ResourceNotFound, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::AccessDenied {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::AccessDenied, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::DuplicateItem {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::DuplicateItem, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::RequestLimitExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::RequestLimitExceeded, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ValidationError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ValidationError, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::TransactionConflict {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::TransactionConflict, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ThrottlingError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ThrottlingError, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::InternalServerError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::InternalServerError, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ResourceNotFound {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ResourceNotFound, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::AccessDenied {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::AccessDenied, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::DuplicateItem {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::DuplicateItem, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/billing_mode.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/billing_mode.rs index 5304c2abc0..a29d5b3565 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/billing_mode.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/billing_mode.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::BillingMode, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::BillingMode::Provisioned => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PROVISIONED {}, - aws_sdk_dynamodb::types::BillingMode::PayPerRequest => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PAY_PER_REQUEST {}, + aws_sdk_dynamodb::types::BillingMode::Provisioned => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PROVISIONED {}, +aws_sdk_dynamodb::types::BillingMode::PayPerRequest => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PAY_PER_REQUEST {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode, ) -> aws_sdk_dynamodb::types::BillingMode { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PROVISIONED {} => aws_sdk_dynamodb::types::BillingMode::Provisioned, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PAY_PER_REQUEST {} => aws_sdk_dynamodb::types::BillingMode::PayPerRequest, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PROVISIONED {} => aws_sdk_dynamodb::types::BillingMode::Provisioned, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PAY_PER_REQUEST {} => aws_sdk_dynamodb::types::BillingMode::PayPerRequest, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/comparison_operator.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/comparison_operator.rs index 0c75159bda..a18dec568f 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/comparison_operator.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/comparison_operator.rs @@ -7,19 +7,19 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ComparisonOperator, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ComparisonOperator::Eq => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::EQ {}, - aws_sdk_dynamodb::types::ComparisonOperator::Ne => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NE {}, - aws_sdk_dynamodb::types::ComparisonOperator::In => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::IN {}, - aws_sdk_dynamodb::types::ComparisonOperator::Le => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LE {}, - aws_sdk_dynamodb::types::ComparisonOperator::Lt => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LT {}, - aws_sdk_dynamodb::types::ComparisonOperator::Ge => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GE {}, - aws_sdk_dynamodb::types::ComparisonOperator::Gt => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GT {}, - aws_sdk_dynamodb::types::ComparisonOperator::Between => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BETWEEN {}, - aws_sdk_dynamodb::types::ComparisonOperator::NotNull => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_NULL {}, - aws_sdk_dynamodb::types::ComparisonOperator::Null => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NULL {}, - aws_sdk_dynamodb::types::ComparisonOperator::Contains => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::CONTAINS {}, - aws_sdk_dynamodb::types::ComparisonOperator::NotContains => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_CONTAINS {}, - aws_sdk_dynamodb::types::ComparisonOperator::BeginsWith => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BEGINS_WITH {}, + aws_sdk_dynamodb::types::ComparisonOperator::Eq => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::EQ {}, +aws_sdk_dynamodb::types::ComparisonOperator::Ne => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NE {}, +aws_sdk_dynamodb::types::ComparisonOperator::In => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::IN {}, +aws_sdk_dynamodb::types::ComparisonOperator::Le => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LE {}, +aws_sdk_dynamodb::types::ComparisonOperator::Lt => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LT {}, +aws_sdk_dynamodb::types::ComparisonOperator::Ge => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GE {}, +aws_sdk_dynamodb::types::ComparisonOperator::Gt => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GT {}, +aws_sdk_dynamodb::types::ComparisonOperator::Between => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BETWEEN {}, +aws_sdk_dynamodb::types::ComparisonOperator::NotNull => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_NULL {}, +aws_sdk_dynamodb::types::ComparisonOperator::Null => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NULL {}, +aws_sdk_dynamodb::types::ComparisonOperator::Contains => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::CONTAINS {}, +aws_sdk_dynamodb::types::ComparisonOperator::NotContains => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_CONTAINS {}, +aws_sdk_dynamodb::types::ComparisonOperator::BeginsWith => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BEGINS_WITH {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -28,18 +28,18 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator, ) -> aws_sdk_dynamodb::types::ComparisonOperator { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::EQ {} => aws_sdk_dynamodb::types::ComparisonOperator::Eq, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NE {} => aws_sdk_dynamodb::types::ComparisonOperator::Ne, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::IN {} => aws_sdk_dynamodb::types::ComparisonOperator::In, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LE {} => aws_sdk_dynamodb::types::ComparisonOperator::Le, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LT {} => aws_sdk_dynamodb::types::ComparisonOperator::Lt, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GE {} => aws_sdk_dynamodb::types::ComparisonOperator::Ge, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GT {} => aws_sdk_dynamodb::types::ComparisonOperator::Gt, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BETWEEN {} => aws_sdk_dynamodb::types::ComparisonOperator::Between, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_NULL {} => aws_sdk_dynamodb::types::ComparisonOperator::NotNull, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NULL {} => aws_sdk_dynamodb::types::ComparisonOperator::Null, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::CONTAINS {} => aws_sdk_dynamodb::types::ComparisonOperator::Contains, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_CONTAINS {} => aws_sdk_dynamodb::types::ComparisonOperator::NotContains, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BEGINS_WITH {} => aws_sdk_dynamodb::types::ComparisonOperator::BeginsWith, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::EQ {} => aws_sdk_dynamodb::types::ComparisonOperator::Eq, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NE {} => aws_sdk_dynamodb::types::ComparisonOperator::Ne, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::IN {} => aws_sdk_dynamodb::types::ComparisonOperator::In, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LE {} => aws_sdk_dynamodb::types::ComparisonOperator::Le, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LT {} => aws_sdk_dynamodb::types::ComparisonOperator::Lt, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GE {} => aws_sdk_dynamodb::types::ComparisonOperator::Ge, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GT {} => aws_sdk_dynamodb::types::ComparisonOperator::Gt, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BETWEEN {} => aws_sdk_dynamodb::types::ComparisonOperator::Between, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_NULL {} => aws_sdk_dynamodb::types::ComparisonOperator::NotNull, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NULL {} => aws_sdk_dynamodb::types::ComparisonOperator::Null, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::CONTAINS {} => aws_sdk_dynamodb::types::ComparisonOperator::Contains, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_CONTAINS {} => aws_sdk_dynamodb::types::ComparisonOperator::NotContains, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BEGINS_WITH {} => aws_sdk_dynamodb::types::ComparisonOperator::BeginsWith, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/conditional_operator.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/conditional_operator.rs index 64208da483..216ac006fb 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/conditional_operator.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/conditional_operator.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ConditionalOperator, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ConditionalOperator::And => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::AND {}, - aws_sdk_dynamodb::types::ConditionalOperator::Or => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::OR {}, + aws_sdk_dynamodb::types::ConditionalOperator::And => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::AND {}, +aws_sdk_dynamodb::types::ConditionalOperator::Or => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::OR {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator, ) -> aws_sdk_dynamodb::types::ConditionalOperator { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::AND {} => aws_sdk_dynamodb::types::ConditionalOperator::And, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::OR {} => aws_sdk_dynamodb::types::ConditionalOperator::Or, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::AND {} => aws_sdk_dynamodb::types::ConditionalOperator::And, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::OR {} => aws_sdk_dynamodb::types::ConditionalOperator::Or, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/index_status.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/index_status.rs index cd99dab3d6..df88cdcb2c 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/index_status.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/index_status.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::IndexStatus, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::IndexStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::CREATING {}, - aws_sdk_dynamodb::types::IndexStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::UPDATING {}, - aws_sdk_dynamodb::types::IndexStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::DELETING {}, - aws_sdk_dynamodb::types::IndexStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::ACTIVE {}, + aws_sdk_dynamodb::types::IndexStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::CREATING {}, +aws_sdk_dynamodb::types::IndexStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::UPDATING {}, +aws_sdk_dynamodb::types::IndexStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::DELETING {}, +aws_sdk_dynamodb::types::IndexStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::ACTIVE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus, ) -> aws_sdk_dynamodb::types::IndexStatus { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::CREATING {} => aws_sdk_dynamodb::types::IndexStatus::Creating, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::UPDATING {} => aws_sdk_dynamodb::types::IndexStatus::Updating, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::DELETING {} => aws_sdk_dynamodb::types::IndexStatus::Deleting, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::ACTIVE {} => aws_sdk_dynamodb::types::IndexStatus::Active, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::CREATING {} => aws_sdk_dynamodb::types::IndexStatus::Creating, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::UPDATING {} => aws_sdk_dynamodb::types::IndexStatus::Updating, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::DELETING {} => aws_sdk_dynamodb::types::IndexStatus::Deleting, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::ACTIVE {} => aws_sdk_dynamodb::types::IndexStatus::Active, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/key_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/key_type.rs index 0d5d59c569..ea86df5b0e 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/key_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/key_type.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::KeyType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::KeyType::Hash => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::HASH {}, - aws_sdk_dynamodb::types::KeyType::Range => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::RANGE {}, + aws_sdk_dynamodb::types::KeyType::Hash => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::HASH {}, +aws_sdk_dynamodb::types::KeyType::Range => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::RANGE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType, ) -> aws_sdk_dynamodb::types::KeyType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::HASH {} => aws_sdk_dynamodb::types::KeyType::Hash, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::RANGE {} => aws_sdk_dynamodb::types::KeyType::Range, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::HASH {} => aws_sdk_dynamodb::types::KeyType::Hash, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::RANGE {} => aws_sdk_dynamodb::types::KeyType::Range, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/projection_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/projection_type.rs index d242c07d48..28b89124fa 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/projection_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/projection_type.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ProjectionType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ProjectionType::All => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::ALL {}, - aws_sdk_dynamodb::types::ProjectionType::KeysOnly => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::KEYS_ONLY {}, - aws_sdk_dynamodb::types::ProjectionType::Include => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::INCLUDE {}, + aws_sdk_dynamodb::types::ProjectionType::All => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::ALL {}, +aws_sdk_dynamodb::types::ProjectionType::KeysOnly => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::KEYS_ONLY {}, +aws_sdk_dynamodb::types::ProjectionType::Include => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::INCLUDE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType, ) -> aws_sdk_dynamodb::types::ProjectionType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::ALL {} => aws_sdk_dynamodb::types::ProjectionType::All, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::KEYS_ONLY {} => aws_sdk_dynamodb::types::ProjectionType::KeysOnly, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::INCLUDE {} => aws_sdk_dynamodb::types::ProjectionType::Include, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::ALL {} => aws_sdk_dynamodb::types::ProjectionType::All, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::KEYS_ONLY {} => aws_sdk_dynamodb::types::ProjectionType::KeysOnly, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::INCLUDE {} => aws_sdk_dynamodb::types::ProjectionType::Include, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/replica_status.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/replica_status.rs index 11e2638d48..fd626473a6 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/replica_status.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/replica_status.rs @@ -7,13 +7,13 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReplicaStatus, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReplicaStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATING {}, - aws_sdk_dynamodb::types::ReplicaStatus::CreationFailed => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATION_FAILED {}, - aws_sdk_dynamodb::types::ReplicaStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::UPDATING {}, - aws_sdk_dynamodb::types::ReplicaStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::DELETING {}, - aws_sdk_dynamodb::types::ReplicaStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::ACTIVE {}, - aws_sdk_dynamodb::types::ReplicaStatus::RegionDisabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::REGION_DISABLED {}, - aws_sdk_dynamodb::types::ReplicaStatus::InaccessibleEncryptionCredentials => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {}, + aws_sdk_dynamodb::types::ReplicaStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATING {}, +aws_sdk_dynamodb::types::ReplicaStatus::CreationFailed => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATION_FAILED {}, +aws_sdk_dynamodb::types::ReplicaStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::UPDATING {}, +aws_sdk_dynamodb::types::ReplicaStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::DELETING {}, +aws_sdk_dynamodb::types::ReplicaStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::ACTIVE {}, +aws_sdk_dynamodb::types::ReplicaStatus::RegionDisabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::REGION_DISABLED {}, +aws_sdk_dynamodb::types::ReplicaStatus::InaccessibleEncryptionCredentials => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -22,12 +22,12 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus, ) -> aws_sdk_dynamodb::types::ReplicaStatus { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATING {} => aws_sdk_dynamodb::types::ReplicaStatus::Creating, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATION_FAILED {} => aws_sdk_dynamodb::types::ReplicaStatus::CreationFailed, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::UPDATING {} => aws_sdk_dynamodb::types::ReplicaStatus::Updating, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::DELETING {} => aws_sdk_dynamodb::types::ReplicaStatus::Deleting, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::ACTIVE {} => aws_sdk_dynamodb::types::ReplicaStatus::Active, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::REGION_DISABLED {} => aws_sdk_dynamodb::types::ReplicaStatus::RegionDisabled, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {} => aws_sdk_dynamodb::types::ReplicaStatus::InaccessibleEncryptionCredentials, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATING {} => aws_sdk_dynamodb::types::ReplicaStatus::Creating, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATION_FAILED {} => aws_sdk_dynamodb::types::ReplicaStatus::CreationFailed, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::UPDATING {} => aws_sdk_dynamodb::types::ReplicaStatus::Updating, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::DELETING {} => aws_sdk_dynamodb::types::ReplicaStatus::Deleting, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::ACTIVE {} => aws_sdk_dynamodb::types::ReplicaStatus::Active, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::REGION_DISABLED {} => aws_sdk_dynamodb::types::ReplicaStatus::RegionDisabled, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {} => aws_sdk_dynamodb::types::ReplicaStatus::InaccessibleEncryptionCredentials, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_consumed_capacity.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_consumed_capacity.rs index fbfeeb4e61..b2526611f3 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_consumed_capacity.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_consumed_capacity.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReturnConsumedCapacity, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReturnConsumedCapacity::Indexes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::INDEXES {}, - aws_sdk_dynamodb::types::ReturnConsumedCapacity::Total => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::TOTAL {}, - aws_sdk_dynamodb::types::ReturnConsumedCapacity::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::NONE {}, + aws_sdk_dynamodb::types::ReturnConsumedCapacity::Indexes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::INDEXES {}, +aws_sdk_dynamodb::types::ReturnConsumedCapacity::Total => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::TOTAL {}, +aws_sdk_dynamodb::types::ReturnConsumedCapacity::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::NONE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity, ) -> aws_sdk_dynamodb::types::ReturnConsumedCapacity { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::INDEXES {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::Indexes, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::TOTAL {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::Total, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::NONE {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::None, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::INDEXES {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::Indexes, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::TOTAL {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::Total, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::NONE {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::None, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_item_collection_metrics.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_item_collection_metrics.rs index 0896dc4cd3..6857387303 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_item_collection_metrics.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_item_collection_metrics.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReturnItemCollectionMetrics, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::Size => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::SIZE {}, - aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::NONE {}, + aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::Size => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::SIZE {}, +aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::NONE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics, ) -> aws_sdk_dynamodb::types::ReturnItemCollectionMetrics { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::SIZE {} => aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::Size, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::NONE {} => aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::None, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::SIZE {} => aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::Size, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::NONE {} => aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::None, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_value.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_value.rs index 21983ab80f..df8085df33 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_value.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_value.rs @@ -7,11 +7,11 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReturnValue, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReturnValue::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::NONE {}, - aws_sdk_dynamodb::types::ReturnValue::AllOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_OLD {}, - aws_sdk_dynamodb::types::ReturnValue::UpdatedOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_OLD {}, - aws_sdk_dynamodb::types::ReturnValue::AllNew => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_NEW {}, - aws_sdk_dynamodb::types::ReturnValue::UpdatedNew => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_NEW {}, + aws_sdk_dynamodb::types::ReturnValue::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::NONE {}, +aws_sdk_dynamodb::types::ReturnValue::AllOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_OLD {}, +aws_sdk_dynamodb::types::ReturnValue::UpdatedOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_OLD {}, +aws_sdk_dynamodb::types::ReturnValue::AllNew => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_NEW {}, +aws_sdk_dynamodb::types::ReturnValue::UpdatedNew => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_NEW {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -20,10 +20,10 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue, ) -> aws_sdk_dynamodb::types::ReturnValue { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::NONE {} => aws_sdk_dynamodb::types::ReturnValue::None, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_OLD {} => aws_sdk_dynamodb::types::ReturnValue::AllOld, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_OLD {} => aws_sdk_dynamodb::types::ReturnValue::UpdatedOld, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_NEW {} => aws_sdk_dynamodb::types::ReturnValue::AllNew, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_NEW {} => aws_sdk_dynamodb::types::ReturnValue::UpdatedNew, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::NONE {} => aws_sdk_dynamodb::types::ReturnValue::None, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_OLD {} => aws_sdk_dynamodb::types::ReturnValue::AllOld, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_OLD {} => aws_sdk_dynamodb::types::ReturnValue::UpdatedOld, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_NEW {} => aws_sdk_dynamodb::types::ReturnValue::AllNew, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_NEW {} => aws_sdk_dynamodb::types::ReturnValue::UpdatedNew, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_values_on_condition_check_failure.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_values_on_condition_check_failure.rs index b185462326..7d3380d942 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_values_on_condition_check_failure.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_values_on_condition_check_failure.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::AllOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::ALL_OLD {}, - aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::NONE {}, + aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::AllOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::ALL_OLD {}, +aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::NONE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure, ) -> aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::ALL_OLD {} => aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::AllOld, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::NONE {} => aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::None, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::ALL_OLD {} => aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::AllOld, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::NONE {} => aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::None, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/scalar_attribute_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/scalar_attribute_type.rs index 7a16ac8159..f921f603f0 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/scalar_attribute_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/scalar_attribute_type.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ScalarAttributeType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ScalarAttributeType::S => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::S {}, - aws_sdk_dynamodb::types::ScalarAttributeType::N => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::N {}, - aws_sdk_dynamodb::types::ScalarAttributeType::B => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::B {}, + aws_sdk_dynamodb::types::ScalarAttributeType::S => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::S {}, +aws_sdk_dynamodb::types::ScalarAttributeType::N => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::N {}, +aws_sdk_dynamodb::types::ScalarAttributeType::B => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::B {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType, ) -> aws_sdk_dynamodb::types::ScalarAttributeType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::S {} => aws_sdk_dynamodb::types::ScalarAttributeType::S, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::N {} => aws_sdk_dynamodb::types::ScalarAttributeType::N, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::B {} => aws_sdk_dynamodb::types::ScalarAttributeType::B, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::S {} => aws_sdk_dynamodb::types::ScalarAttributeType::S, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::N {} => aws_sdk_dynamodb::types::ScalarAttributeType::N, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::B {} => aws_sdk_dynamodb::types::ScalarAttributeType::B, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/select.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/select.rs index 52afedb1c3..c52b7a634b 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/select.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/select.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::Select, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::Select::AllAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_ATTRIBUTES {}, - aws_sdk_dynamodb::types::Select::AllProjectedAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_PROJECTED_ATTRIBUTES {}, - aws_sdk_dynamodb::types::Select::SpecificAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::SPECIFIC_ATTRIBUTES {}, - aws_sdk_dynamodb::types::Select::Count => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::COUNT {}, + aws_sdk_dynamodb::types::Select::AllAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_ATTRIBUTES {}, +aws_sdk_dynamodb::types::Select::AllProjectedAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_PROJECTED_ATTRIBUTES {}, +aws_sdk_dynamodb::types::Select::SpecificAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::SPECIFIC_ATTRIBUTES {}, +aws_sdk_dynamodb::types::Select::Count => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::COUNT {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select, ) -> aws_sdk_dynamodb::types::Select { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::AllAttributes, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_PROJECTED_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::AllProjectedAttributes, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::SPECIFIC_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::SpecificAttributes, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::COUNT {} => aws_sdk_dynamodb::types::Select::Count, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::AllAttributes, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_PROJECTED_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::AllProjectedAttributes, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::SPECIFIC_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::SpecificAttributes, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::COUNT {} => aws_sdk_dynamodb::types::Select::Count, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_status.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_status.rs index fd0a2e7a4b..a4f20bf1cf 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_status.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_status.rs @@ -7,11 +7,11 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::SseStatus, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::SseStatus::Enabling => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLING {}, - aws_sdk_dynamodb::types::SseStatus::Enabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLED {}, - aws_sdk_dynamodb::types::SseStatus::Disabling => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLING {}, - aws_sdk_dynamodb::types::SseStatus::Disabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLED {}, - aws_sdk_dynamodb::types::SseStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::UPDATING {}, + aws_sdk_dynamodb::types::SseStatus::Enabling => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLING {}, +aws_sdk_dynamodb::types::SseStatus::Enabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLED {}, +aws_sdk_dynamodb::types::SseStatus::Disabling => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLING {}, +aws_sdk_dynamodb::types::SseStatus::Disabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLED {}, +aws_sdk_dynamodb::types::SseStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::UPDATING {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -20,10 +20,10 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus, ) -> aws_sdk_dynamodb::types::SseStatus { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLING {} => aws_sdk_dynamodb::types::SseStatus::Enabling, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLED {} => aws_sdk_dynamodb::types::SseStatus::Enabled, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLING {} => aws_sdk_dynamodb::types::SseStatus::Disabling, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLED {} => aws_sdk_dynamodb::types::SseStatus::Disabled, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::UPDATING {} => aws_sdk_dynamodb::types::SseStatus::Updating, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLING {} => aws_sdk_dynamodb::types::SseStatus::Enabling, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLED {} => aws_sdk_dynamodb::types::SseStatus::Enabled, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLING {} => aws_sdk_dynamodb::types::SseStatus::Disabling, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLED {} => aws_sdk_dynamodb::types::SseStatus::Disabled, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::UPDATING {} => aws_sdk_dynamodb::types::SseStatus::Updating, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_type.rs index 6a6dfd122e..56f69062bc 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_type.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::SseType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::SseType::Aes256 => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::AES256 {}, - aws_sdk_dynamodb::types::SseType::Kms => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::KMS {}, + aws_sdk_dynamodb::types::SseType::Aes256 => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::AES256 {}, +aws_sdk_dynamodb::types::SseType::Kms => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::KMS {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType, ) -> aws_sdk_dynamodb::types::SseType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::AES256 {} => aws_sdk_dynamodb::types::SseType::Aes256, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::KMS {} => aws_sdk_dynamodb::types::SseType::Kms, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::AES256 {} => aws_sdk_dynamodb::types::SseType::Aes256, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::KMS {} => aws_sdk_dynamodb::types::SseType::Kms, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/stream_view_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/stream_view_type.rs index df3a0c2b7b..718b38e764 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/stream_view_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/stream_view_type.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::StreamViewType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::StreamViewType::NewImage => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_IMAGE {}, - aws_sdk_dynamodb::types::StreamViewType::OldImage => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::OLD_IMAGE {}, - aws_sdk_dynamodb::types::StreamViewType::NewAndOldImages => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_AND_OLD_IMAGES {}, - aws_sdk_dynamodb::types::StreamViewType::KeysOnly => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::KEYS_ONLY {}, + aws_sdk_dynamodb::types::StreamViewType::NewImage => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_IMAGE {}, +aws_sdk_dynamodb::types::StreamViewType::OldImage => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::OLD_IMAGE {}, +aws_sdk_dynamodb::types::StreamViewType::NewAndOldImages => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_AND_OLD_IMAGES {}, +aws_sdk_dynamodb::types::StreamViewType::KeysOnly => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::KEYS_ONLY {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType, ) -> aws_sdk_dynamodb::types::StreamViewType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_IMAGE {} => aws_sdk_dynamodb::types::StreamViewType::NewImage, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::OLD_IMAGE {} => aws_sdk_dynamodb::types::StreamViewType::OldImage, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_AND_OLD_IMAGES {} => aws_sdk_dynamodb::types::StreamViewType::NewAndOldImages, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::KEYS_ONLY {} => aws_sdk_dynamodb::types::StreamViewType::KeysOnly, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_IMAGE {} => aws_sdk_dynamodb::types::StreamViewType::NewImage, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::OLD_IMAGE {} => aws_sdk_dynamodb::types::StreamViewType::OldImage, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_AND_OLD_IMAGES {} => aws_sdk_dynamodb::types::StreamViewType::NewAndOldImages, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::KEYS_ONLY {} => aws_sdk_dynamodb::types::StreamViewType::KeysOnly, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_class.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_class.rs index dba3a71daa..f0a717fc91 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_class.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_class.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::TableClass, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::TableClass::Standard => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD {}, - aws_sdk_dynamodb::types::TableClass::StandardInfrequentAccess => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD_INFREQUENT_ACCESS {}, + aws_sdk_dynamodb::types::TableClass::Standard => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD {}, +aws_sdk_dynamodb::types::TableClass::StandardInfrequentAccess => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD_INFREQUENT_ACCESS {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass, ) -> aws_sdk_dynamodb::types::TableClass { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD {} => aws_sdk_dynamodb::types::TableClass::Standard, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD_INFREQUENT_ACCESS {} => aws_sdk_dynamodb::types::TableClass::StandardInfrequentAccess, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD {} => aws_sdk_dynamodb::types::TableClass::Standard, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD_INFREQUENT_ACCESS {} => aws_sdk_dynamodb::types::TableClass::StandardInfrequentAccess, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_status.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_status.rs index 444e0c5411..e996bc8805 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_status.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_status.rs @@ -7,13 +7,13 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::TableStatus, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::TableStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::CREATING {}, - aws_sdk_dynamodb::types::TableStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::UPDATING {}, - aws_sdk_dynamodb::types::TableStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::DELETING {}, - aws_sdk_dynamodb::types::TableStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ACTIVE {}, - aws_sdk_dynamodb::types::TableStatus::InaccessibleEncryptionCredentials => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {}, - aws_sdk_dynamodb::types::TableStatus::Archiving => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVING {}, - aws_sdk_dynamodb::types::TableStatus::Archived => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVED {}, + aws_sdk_dynamodb::types::TableStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::CREATING {}, +aws_sdk_dynamodb::types::TableStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::UPDATING {}, +aws_sdk_dynamodb::types::TableStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::DELETING {}, +aws_sdk_dynamodb::types::TableStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ACTIVE {}, +aws_sdk_dynamodb::types::TableStatus::InaccessibleEncryptionCredentials => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {}, +aws_sdk_dynamodb::types::TableStatus::Archiving => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVING {}, +aws_sdk_dynamodb::types::TableStatus::Archived => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVED {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -22,12 +22,12 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus, ) -> aws_sdk_dynamodb::types::TableStatus { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::CREATING {} => aws_sdk_dynamodb::types::TableStatus::Creating, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::UPDATING {} => aws_sdk_dynamodb::types::TableStatus::Updating, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::DELETING {} => aws_sdk_dynamodb::types::TableStatus::Deleting, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ACTIVE {} => aws_sdk_dynamodb::types::TableStatus::Active, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {} => aws_sdk_dynamodb::types::TableStatus::InaccessibleEncryptionCredentials, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVING {} => aws_sdk_dynamodb::types::TableStatus::Archiving, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVED {} => aws_sdk_dynamodb::types::TableStatus::Archived, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::CREATING {} => aws_sdk_dynamodb::types::TableStatus::Creating, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::UPDATING {} => aws_sdk_dynamodb::types::TableStatus::Updating, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::DELETING {} => aws_sdk_dynamodb::types::TableStatus::Deleting, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ACTIVE {} => aws_sdk_dynamodb::types::TableStatus::Active, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {} => aws_sdk_dynamodb::types::TableStatus::InaccessibleEncryptionCredentials, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVING {} => aws_sdk_dynamodb::types::TableStatus::Archiving, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVED {} => aws_sdk_dynamodb::types::TableStatus::Archived, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/standard_library_externs.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/customer_master_key_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/customer_master_key_spec.rs index 3115f64a3a..d00e07390b 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/customer_master_key_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/customer_master_key_spec.rs @@ -7,19 +7,19 @@ pub fn to_dafny( value: aws_sdk_kms::types::CustomerMasterKeySpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::CustomerMasterKeySpec::Rsa2048 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_2048 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::Rsa3072 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_3072 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::Rsa4096 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_4096 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P256 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P384 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP521 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P521 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::EccSecgP256K1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_SECG_P256K1 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SYMMETRIC_DEFAULT {}, - aws_sdk_kms::types::CustomerMasterKeySpec::Hmac224 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_224 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::Hmac256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_256 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::Hmac384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_384 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::Hmac512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_512 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::Sm2 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SM2 {}, + aws_sdk_kms::types::CustomerMasterKeySpec::Rsa2048 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_2048 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::Rsa3072 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_3072 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::Rsa4096 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_4096 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P256 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P384 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP521 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P521 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::EccSecgP256K1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_SECG_P256K1 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SYMMETRIC_DEFAULT {}, +aws_sdk_kms::types::CustomerMasterKeySpec::Hmac224 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_224 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::Hmac256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_256 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::Hmac384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_384 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::Hmac512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_512 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::Sm2 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SM2 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -28,18 +28,18 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec, ) -> aws_sdk_kms::types::CustomerMasterKeySpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_2048 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa2048, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_3072 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa3072, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_4096 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa4096, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P256 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P384 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP384, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P521 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP521, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_SECG_P256K1 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccSecgP256K1, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::CustomerMasterKeySpec::SymmetricDefault, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_224 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac224, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_256 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_384 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac384, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_512 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac512, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SM2 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Sm2, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_2048 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa2048, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_3072 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa3072, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_4096 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa4096, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P256 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P384 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP384, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P521 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP521, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_SECG_P256K1 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccSecgP256K1, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::CustomerMasterKeySpec::SymmetricDefault, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_224 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac224, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_256 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_384 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac384, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_512 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac512, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SM2 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Sm2, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/data_key_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/data_key_spec.rs index aa96da51cb..f26b83c132 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/data_key_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/data_key_spec.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_kms::types::DataKeySpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::DataKeySpec::Aes256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_256 {}, - aws_sdk_kms::types::DataKeySpec::Aes128 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_128 {}, + aws_sdk_kms::types::DataKeySpec::Aes256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_256 {}, +aws_sdk_kms::types::DataKeySpec::Aes128 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_128 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec, ) -> aws_sdk_kms::types::DataKeySpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_256 {} => aws_sdk_kms::types::DataKeySpec::Aes256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_128 {} => aws_sdk_kms::types::DataKeySpec::Aes128, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_256 {} => aws_sdk_kms::types::DataKeySpec::Aes256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_128 {} => aws_sdk_kms::types::DataKeySpec::Aes128, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/encryption_algorithm_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/encryption_algorithm_spec.rs index 8cc859bad9..af802a8f42 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/encryption_algorithm_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/encryption_algorithm_spec.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_kms::types::EncryptionAlgorithmSpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::EncryptionAlgorithmSpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::SYMMETRIC_DEFAULT {}, - aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_1 {}, - aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_256 {}, + aws_sdk_kms::types::EncryptionAlgorithmSpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::SYMMETRIC_DEFAULT {}, +aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_1 {}, +aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_256 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec, ) -> aws_sdk_kms::types::EncryptionAlgorithmSpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::SymmetricDefault, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_1 {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha1, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_256 {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::SymmetricDefault, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_1 {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha1, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_256 {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_agreement_algorithm_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_agreement_algorithm_spec.rs index ab964fd2f7..1693266fff 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_agreement_algorithm_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_agreement_algorithm_spec.rs @@ -7,7 +7,7 @@ pub fn to_dafny( value: aws_sdk_kms::types::KeyAgreementAlgorithmSpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::KeyAgreementAlgorithmSpec::Ecdh => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec::ECDH {}, + aws_sdk_kms::types::KeyAgreementAlgorithmSpec::Ecdh => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec::ECDH {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -16,6 +16,6 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec, ) -> aws_sdk_kms::types::KeyAgreementAlgorithmSpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec::ECDH {} => aws_sdk_kms::types::KeyAgreementAlgorithmSpec::Ecdh, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec::ECDH {} => aws_sdk_kms::types::KeyAgreementAlgorithmSpec::Ecdh, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_encryption_mechanism.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_encryption_mechanism.rs index 1dd9d0e9d8..80c4b4d9b9 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_encryption_mechanism.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_encryption_mechanism.rs @@ -7,7 +7,7 @@ pub fn to_dafny( value: aws_sdk_kms::types::KeyEncryptionMechanism, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::KeyEncryptionMechanism::RsaesOaepSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism::RSAES_OAEP_SHA_256 {}, + aws_sdk_kms::types::KeyEncryptionMechanism::RsaesOaepSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism::RSAES_OAEP_SHA_256 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -16,6 +16,6 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism, ) -> aws_sdk_kms::types::KeyEncryptionMechanism { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism::RSAES_OAEP_SHA_256 {} => aws_sdk_kms::types::KeyEncryptionMechanism::RsaesOaepSha256, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism::RSAES_OAEP_SHA_256 {} => aws_sdk_kms::types::KeyEncryptionMechanism::RsaesOaepSha256, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_spec.rs index 66ae3f0dc7..14c6136fc9 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_spec.rs @@ -7,19 +7,19 @@ pub fn to_dafny( value: aws_sdk_kms::types::KeySpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::KeySpec::Rsa2048 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_2048 {}, - aws_sdk_kms::types::KeySpec::Rsa3072 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_3072 {}, - aws_sdk_kms::types::KeySpec::Rsa4096 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_4096 {}, - aws_sdk_kms::types::KeySpec::EccNistP256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P256 {}, - aws_sdk_kms::types::KeySpec::EccNistP384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P384 {}, - aws_sdk_kms::types::KeySpec::EccNistP521 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P521 {}, - aws_sdk_kms::types::KeySpec::EccSecgP256K1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_SECG_P256K1 {}, - aws_sdk_kms::types::KeySpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SYMMETRIC_DEFAULT {}, - aws_sdk_kms::types::KeySpec::Hmac224 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_224 {}, - aws_sdk_kms::types::KeySpec::Hmac256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_256 {}, - aws_sdk_kms::types::KeySpec::Hmac384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_384 {}, - aws_sdk_kms::types::KeySpec::Hmac512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_512 {}, - aws_sdk_kms::types::KeySpec::Sm2 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SM2 {}, + aws_sdk_kms::types::KeySpec::Rsa2048 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_2048 {}, +aws_sdk_kms::types::KeySpec::Rsa3072 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_3072 {}, +aws_sdk_kms::types::KeySpec::Rsa4096 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_4096 {}, +aws_sdk_kms::types::KeySpec::EccNistP256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P256 {}, +aws_sdk_kms::types::KeySpec::EccNistP384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P384 {}, +aws_sdk_kms::types::KeySpec::EccNistP521 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P521 {}, +aws_sdk_kms::types::KeySpec::EccSecgP256K1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_SECG_P256K1 {}, +aws_sdk_kms::types::KeySpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SYMMETRIC_DEFAULT {}, +aws_sdk_kms::types::KeySpec::Hmac224 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_224 {}, +aws_sdk_kms::types::KeySpec::Hmac256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_256 {}, +aws_sdk_kms::types::KeySpec::Hmac384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_384 {}, +aws_sdk_kms::types::KeySpec::Hmac512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_512 {}, +aws_sdk_kms::types::KeySpec::Sm2 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SM2 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -28,18 +28,18 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec, ) -> aws_sdk_kms::types::KeySpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_2048 {} => aws_sdk_kms::types::KeySpec::Rsa2048, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_3072 {} => aws_sdk_kms::types::KeySpec::Rsa3072, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_4096 {} => aws_sdk_kms::types::KeySpec::Rsa4096, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P256 {} => aws_sdk_kms::types::KeySpec::EccNistP256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P384 {} => aws_sdk_kms::types::KeySpec::EccNistP384, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P521 {} => aws_sdk_kms::types::KeySpec::EccNistP521, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_SECG_P256K1 {} => aws_sdk_kms::types::KeySpec::EccSecgP256K1, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::KeySpec::SymmetricDefault, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_224 {} => aws_sdk_kms::types::KeySpec::Hmac224, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_256 {} => aws_sdk_kms::types::KeySpec::Hmac256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_384 {} => aws_sdk_kms::types::KeySpec::Hmac384, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_512 {} => aws_sdk_kms::types::KeySpec::Hmac512, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SM2 {} => aws_sdk_kms::types::KeySpec::Sm2, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_2048 {} => aws_sdk_kms::types::KeySpec::Rsa2048, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_3072 {} => aws_sdk_kms::types::KeySpec::Rsa3072, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_4096 {} => aws_sdk_kms::types::KeySpec::Rsa4096, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P256 {} => aws_sdk_kms::types::KeySpec::EccNistP256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P384 {} => aws_sdk_kms::types::KeySpec::EccNistP384, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P521 {} => aws_sdk_kms::types::KeySpec::EccNistP521, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_SECG_P256K1 {} => aws_sdk_kms::types::KeySpec::EccSecgP256K1, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::KeySpec::SymmetricDefault, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_224 {} => aws_sdk_kms::types::KeySpec::Hmac224, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_256 {} => aws_sdk_kms::types::KeySpec::Hmac256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_384 {} => aws_sdk_kms::types::KeySpec::Hmac384, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_512 {} => aws_sdk_kms::types::KeySpec::Hmac512, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SM2 {} => aws_sdk_kms::types::KeySpec::Sm2, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_usage_type.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_usage_type.rs index fdf182c6dd..8d2db6b3ca 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_usage_type.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_usage_type.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_kms::types::KeyUsageType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::KeyUsageType::SignVerify => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::SIGN_VERIFY {}, - aws_sdk_kms::types::KeyUsageType::EncryptDecrypt => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::ENCRYPT_DECRYPT {}, - aws_sdk_kms::types::KeyUsageType::GenerateVerifyMac => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::GENERATE_VERIFY_MAC {}, - aws_sdk_kms::types::KeyUsageType::KeyAgreement => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::KEY_AGREEMENT {}, + aws_sdk_kms::types::KeyUsageType::SignVerify => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::SIGN_VERIFY {}, +aws_sdk_kms::types::KeyUsageType::EncryptDecrypt => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::ENCRYPT_DECRYPT {}, +aws_sdk_kms::types::KeyUsageType::GenerateVerifyMac => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::GENERATE_VERIFY_MAC {}, +aws_sdk_kms::types::KeyUsageType::KeyAgreement => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::KEY_AGREEMENT {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType, ) -> aws_sdk_kms::types::KeyUsageType { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::SIGN_VERIFY {} => aws_sdk_kms::types::KeyUsageType::SignVerify, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::ENCRYPT_DECRYPT {} => aws_sdk_kms::types::KeyUsageType::EncryptDecrypt, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::GENERATE_VERIFY_MAC {} => aws_sdk_kms::types::KeyUsageType::GenerateVerifyMac, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::KEY_AGREEMENT {} => aws_sdk_kms::types::KeyUsageType::KeyAgreement, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::SIGN_VERIFY {} => aws_sdk_kms::types::KeyUsageType::SignVerify, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::ENCRYPT_DECRYPT {} => aws_sdk_kms::types::KeyUsageType::EncryptDecrypt, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::GENERATE_VERIFY_MAC {} => aws_sdk_kms::types::KeyUsageType::GenerateVerifyMac, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::KEY_AGREEMENT {} => aws_sdk_kms::types::KeyUsageType::KeyAgreement, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/origin_type.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/origin_type.rs index 79b60c37bd..8878e10fa2 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/origin_type.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/origin_type.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_kms::types::OriginType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::OriginType::AwsKms => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_KMS {}, - aws_sdk_kms::types::OriginType::External => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL {}, - aws_sdk_kms::types::OriginType::AwsCloudhsm => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_CLOUDHSM {}, - aws_sdk_kms::types::OriginType::ExternalKeyStore => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL_KEY_STORE {}, + aws_sdk_kms::types::OriginType::AwsKms => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_KMS {}, +aws_sdk_kms::types::OriginType::External => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL {}, +aws_sdk_kms::types::OriginType::AwsCloudhsm => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_CLOUDHSM {}, +aws_sdk_kms::types::OriginType::ExternalKeyStore => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL_KEY_STORE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType, ) -> aws_sdk_kms::types::OriginType { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_KMS {} => aws_sdk_kms::types::OriginType::AwsKms, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL {} => aws_sdk_kms::types::OriginType::External, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_CLOUDHSM {} => aws_sdk_kms::types::OriginType::AwsCloudhsm, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL_KEY_STORE {} => aws_sdk_kms::types::OriginType::ExternalKeyStore, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_KMS {} => aws_sdk_kms::types::OriginType::AwsKms, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL {} => aws_sdk_kms::types::OriginType::External, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_CLOUDHSM {} => aws_sdk_kms::types::OriginType::AwsCloudhsm, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL_KEY_STORE {} => aws_sdk_kms::types::OriginType::ExternalKeyStore, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/signing_algorithm_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/signing_algorithm_spec.rs index bc9cbeb90b..4fcc04f841 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/signing_algorithm_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/signing_algorithm_spec.rs @@ -7,16 +7,16 @@ pub fn to_dafny( value: aws_sdk_kms::types::SigningAlgorithmSpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_256 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_384 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_512 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_256 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_384 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_512 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_256 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_384 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_512 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::Sm2Dsa => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::SM2DSA {}, + aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_256 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_384 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_512 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_256 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_384 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_512 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_256 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_384 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_512 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::Sm2Dsa => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::SM2DSA {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -25,15 +25,15 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec, ) -> aws_sdk_kms::types::SigningAlgorithmSpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha384, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha512, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha384, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha512, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha384, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha512, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::SM2DSA {} => aws_sdk_kms::types::SigningAlgorithmSpec::Sm2Dsa, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha384, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha512, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha384, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha512, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha384, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha512, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::SM2DSA {} => aws_sdk_kms::types::SigningAlgorithmSpec::Sm2Dsa, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/standard_library_externs.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java index b94c917561..e064c19942 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java @@ -243,15 +243,7 @@ private void generateDafny(final Path outputDir) { dafnyOtherGeneratedAspects(outputDir); - LOGGER.info("Formatting Dafny code in {}", outputDir); - runCommand( - outputDir, - "dafny", - "format", - "--function-syntax:3", - "--unicode-char:false", - "." - ); + formatDafnyCode(outputDir); handlePatching(TargetLanguage.DAFNY, outputDir); } @@ -312,16 +304,29 @@ private void dafnyOtherGeneratedAspects(final Path outputDir) { // Perhaps we can make a `smithy init` template for that instead? if (!generationAspects.isEmpty()) { - Path srcDir = outputDir.resolve("../src"); - LOGGER.info("Formatting Dafny code in {}", srcDir); - runCommand( - srcDir, - "dafny", - "format", - "--function-syntax:3", - "--unicode-char:false", - "." - ); + formatDafnyCode(outputDir.resolve("../src")); + } + } + + /** + * Formats the Dafny code in the given path using {@code dafny format}, + * but does not throw an exception if the command fails. + *

+ * This enables generating interdependent Dafny files + * across multiple smithy-dafny-codegen invocations. + */ + private void formatDafnyCode(final Path path) { + LOGGER.info("Formatting Dafny code in {}", path); + final CommandResult formatResult = runCommand( + path, + "dafny", + "format", + "--function-syntax:3", + "--unicode-char:false", + "." + ); + if (formatResult.exitCode != 0) { + LOGGER.warn("Formatting failed:\n{}", formatResult.output); } } @@ -357,7 +362,7 @@ private void generateJava(final Path outputDir, final Path testOutputDir) { javaOtherGeneratedAspects(); LOGGER.info("Formatting Java code in {}", outputDir); - runCommand( + runCommandOrThrow( outputDir, "npm", "i", @@ -365,7 +370,7 @@ private void generateJava(final Path outputDir, final Path testOutputDir) { "prettier@3", "prettier-plugin-java@2.5" ); - runCommand( + runCommandOrThrow( outputDir, "npx", "prettier@3", @@ -541,7 +546,7 @@ private void generateDotnet(final Path outputDir) { .filter(path -> path.toFile().getName().endsWith(".csproj")) .map(Path::toString) ); - runCommand(dotnetRoot, args.toArray(String[]::new)); + runCommandOrThrow(dotnetRoot, args.toArray(String[]::new)); } catch (IOException e) { throw new RuntimeException(e); } @@ -718,13 +723,17 @@ private void generateRust(final Path outputDir) { generator.generate(outputDir); } - // TODO: This should be part of the StandardLibrary instead, + // TODO: These should be part of the StandardLibrary instead, // but since the Dafny Rust code generator doesn't yet support multiple crates, // we have to inline it instead. writeTemplatedFile( "runtimes/rust/src/standard_library_conversions.rs", Map.of() ); + writeTemplatedFile( + "runtimes/rust/src/standard_library_externs.rs", + Map.of() + ); handlePatching(TargetLanguage.RUST, outputDir); } @@ -762,13 +771,14 @@ private void handlePatching(TargetLanguage targetLanguage, Path outputDir) { ); Path outputDirRelative = libraryRoot.relativize(outputDir); // Need to ignore the exit code because diff will return 1 if there is a diff - String patchContent = runCommandIgnoringExitCode( + String patchContent = runCommand( libraryRoot, "git", "diff", "-R", outputDirRelative.toString() - ); + ) + .output; if (!patchContent.isBlank()) { IOUtils.writeToFile(patchContent, patchFile.toFile()); } @@ -784,7 +794,13 @@ private void handlePatching(TargetLanguage targetLanguage, Path outputDir) { if (dafnyVersion.compareTo(patchFilePair.getKey()) >= 0) { Path patchFile = patchFilePair.getValue(); LOGGER.info("Applying patch file {}", patchFile); - runCommand(libraryRoot, "git", "apply", "-v", patchFile.toString()); + runCommandOrThrow( + libraryRoot, + "git", + "apply", + "-v", + patchFile.toString() + ); return; } } @@ -914,7 +930,10 @@ private String extraDeclarationsForLocalService() { pub mod operation; mod conversions; + + /// Copied from StandardLibrary mod standard_library_conversions; + mod standard_library_externs; #[cfg(feature = "wrapped-client")] pub mod wrapped; @@ -932,26 +951,34 @@ private String extraDeclarationsForLocalService() { ); } - private String runCommand(Path workingDir, String... args) { - List argsList = List.of(args); - StringBuilder output = new StringBuilder(); - int exitCode = IoUtils.runCommand( + private record CommandResult(int exitCode, String output) {} + + /** + * Runs the given command and throws an exception if the exit code is nonzero. + */ + private String runCommandOrThrow(Path workingDir, String... args) { + final CommandResult result = runCommand(workingDir, args); + if (result.exitCode != 0) { + throw new RuntimeException( + "Command failed: " + List.of(args) + "\n" + result.output + ); + } + return result.output; + } + + /** + * Runs the given command. + */ + private CommandResult runCommand(Path workingDir, String... args) { + final List argsList = List.of(args); + final StringBuilder output = new StringBuilder(); + final int exitCode = IoUtils.runCommand( argsList, workingDir, output, Collections.emptyMap() ); - if (exitCode != 0) { - throw new RuntimeException("Command failed: " + argsList + "\n" + output); - } - return output.toString(); - } - - private String runCommandIgnoringExitCode(Path workingDir, String... args) { - List argsList = List.of(args); - StringBuilder output = new StringBuilder(); - IoUtils.runCommand(argsList, workingDir, output, Collections.emptyMap()); - return output.toString(); + return new CommandResult(exitCode, output.toString()); } private Path standardLibraryPath() { diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithydotnet/TypeConversionCodegen.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithydotnet/TypeConversionCodegen.java index c955b48e2f..05494838e1 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithydotnet/TypeConversionCodegen.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithydotnet/TypeConversionCodegen.java @@ -114,6 +114,7 @@ public Map generate() { Stream.of(typeConverter.fromDafny, typeConverter.toDafny) ) ) + .prepend(conversionConstants()) .lineSeparated() .braced(); final TokenTree conversionClass = conversionClassBody @@ -122,6 +123,16 @@ public Map generate() { return Map.of(TYPE_CONVERSION_CLASS_PATH, conversionClass.prepend(prelude)); } + private static TokenTree conversionConstants() { + return TokenTree.of( + """ + private const string ISO8601DateFormat = "yyyy-MM-dd\\\\THH:mm:ss.fff\\\\Z"; + + private const string ISO8601DateFormatNoMS = "yyyy-MM-dd\\\\THH:mm:ss\\\\Z"; + """ + ); + } + /** * Returns a stream of type converters for synthetic types (types that aren't defined in the model). */ @@ -383,15 +394,13 @@ public TypeConverter generateTimestampConverter( ) { final TokenTree fromDafnyBody = Token.of( """ - System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(""); string timestampString = new string(value.Elements); - return System.DateTime.ParseExact(timestampString, "s", culture); + return System.DateTime.ParseExact(timestampString, new[] {ISO8601DateFormat, ISO8601DateFormatNoMS}, System.Globalization.CultureInfo.InvariantCulture); """ ); final TokenTree toDafnyBody = Token.of( """ - System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(""); - string timestampString = value.ToString("s", culture); + string timestampString = value.ToString(ISO8601DateFormat, System.Globalization.CultureInfo.InvariantCulture); return Dafny.Sequence.FromString(timestampString); """ ); diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/AbstractRustShimGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/AbstractRustShimGenerator.java index 7a67e71036..5319e4a0db 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/AbstractRustShimGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/AbstractRustShimGenerator.java @@ -8,15 +8,19 @@ import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; +import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; import software.amazon.polymorph.utils.IOUtils; +import software.amazon.polymorph.utils.MapUtils; +import software.amazon.polymorph.utils.ModelUtils; import software.amazon.polymorph.utils.TokenTree; -import software.amazon.smithy.aws.traits.ServiceTrait; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.OperationIndex; +import software.amazon.smithy.model.shapes.EnumShape; import software.amazon.smithy.model.shapes.ListShape; import software.amazon.smithy.model.shapes.MapShape; import software.amazon.smithy.model.shapes.MemberShape; @@ -26,7 +30,6 @@ import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.UnionShape; -import software.amazon.smithy.model.traits.EnumDefinition; import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.RequiredTrait; @@ -103,7 +106,7 @@ protected RustFile conversionsErrorModule() { evalTemplate( getClass(), "runtimes/rust/conversions/error.rs", - dafnyModuleVariables() + serviceVariables() ) ); return new RustFile( @@ -122,17 +125,6 @@ protected TokenTree declarePubModules(Stream moduleNames) { .lineSeparated(); } - protected Map dafnyModuleVariables() { - final Map stringStringMap = new HashMap<>(); - stringStringMap.put("dafnyModuleName", getDafnyModuleName()); - stringStringMap.put( - "dafnyInternalModuleName", - getDafnyInternalModuleName() - ); - stringStringMap.put("dafnyTypesModuleName", getDafnyTypesModuleName()); - return stringStringMap; - } - protected RustFile conversionsModule() { Stream operationModules = model .getOperationShapes() @@ -153,9 +145,8 @@ protected RustFile conversionsModule() { .filter(this::shouldGenerateEnumForUnion) .map(structureShape -> toSnakeCase(structureShape.getId().getName())); - Stream enumModules = model - .getStringShapesWithTrait(EnumTrait.class) - .stream() + Stream enumModules = ModelUtils + .streamEnumShapes(model, service.getId().getNamespace()) .map(structureShape -> toSnakeCase(structureShape.getId().getName())); TokenTree content = declarePubModules( @@ -301,8 +292,8 @@ private TokenTree fromDafny( boolean isDafnyOption ) { return switch (shape.getType()) { - case STRING -> { - if (shape.hasTrait(EnumTrait.class)) { + case STRING, ENUM -> { + if (shape.hasTrait(EnumTrait.class) || shape.isEnumShape()) { var enumShapeName = toSnakeCase(shape.toShapeId().getName()); if (isDafnyOption) { yield TokenTree.of( @@ -328,6 +319,30 @@ private TokenTree fromDafny( } yield result; } + } else if (shape.hasTrait(DafnyUtf8BytesTrait.class)) { + final String dafnyToRust = + "::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&%s, |b| *b)).unwrap()"; + String valueToRust; + if (isDafnyOption) { + valueToRust = + """ + match %s.as_ref() { + crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(%s), + _ => ::std::option::Option::None, + }""".formatted( + dafnyValue, + dafnyToRust.formatted(dafnyValue + ".Extract()") + ); + if (!isRustOption) { + valueToRust = "(%s).unwrap()".formatted(valueToRust); + } + } else { + valueToRust = dafnyToRust.formatted(dafnyValue + ".as_ref()"); + if (isRustOption) { + valueToRust = "Some(%s)".formatted(valueToRust); + } + } + yield TokenTree.of(valueToRust); } else { if (isDafnyOption) { yield TokenTree.of( @@ -571,21 +586,30 @@ private TokenTree toDafnyVariantMemberForOperationRequest( ) { Shape targetShape = model.expectShape(member.getTarget()); String snakeCaseMemberName = toSnakeCase(member.getMemberName()); - boolean isRequired = member.hasTrait(RequiredTrait.class); - // These rules were mostly reverse-engineered from inspection of Rust SDKs, - // and may not be complete! - boolean isRustRequired = - (isRequired && - !operationIndex.isOutputStructure(parent) && - !operationIndex.isInputStructure(parent) && - !targetShape.isStructureShape()) || - (operationIndex.isOutputStructure(parent) && - targetShape.isIntegerShape()); return toDafny( targetShape, "value." + snakeCaseMemberName, - !isRustRequired, - !isRequired + !isRustFieldRequired(parent, member), + !hasRequiredTrait(member) + ); + } + + protected final boolean hasRequiredTrait(final MemberShape member) { + return member.hasTrait(RequiredTrait.class); + } + + protected boolean isRustFieldRequired( + final Shape parent, + final MemberShape member + ) { + // These rules were mostly reverse-engineered from inspection of Rust SDKs, + // and may not be complete! + final Shape targetShape = model.expectShape(member.getTarget()); + return ( + hasRequiredTrait(member) && + !operationIndex.isOutputStructure(parent) && + !operationIndex.isInputStructure(parent) && + !targetShape.isStructureShape() ); } @@ -604,8 +628,8 @@ private TokenTree toDafny( boolean isDafnyOption ) { return switch (shape.getType()) { - case STRING -> { - if (shape.hasTrait(EnumTrait.class)) { + case STRING, ENUM -> { + if (shape.hasTrait(EnumTrait.class) || shape.isEnumShape()) { var enumShapeName = toSnakeCase(shape.toShapeId().getName()); if (isDafnyOption) { yield TokenTree.of( @@ -631,6 +655,24 @@ private TokenTree toDafny( ) ); } + } else if (shape.hasTrait(DafnyUtf8BytesTrait.class)) { + final String rustToDafny = + "dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&%s.as_bytes().to_vec(), |b| *b)"; + String valueToDafny; + if (isRustOption) { + valueToDafny = + """ + match %s { + Some(s) => crate::_Wrappers_Compile::Option::Some { value: %s }, + None => crate::_Wrappers_Compile::Option::None {}, + }""".formatted(rustValue, rustToDafny.formatted("s")); + if (!isDafnyOption) { + valueToDafny = "(%s).Extract()".formatted(valueToDafny); + } + } else { + valueToDafny = rustToDafny.formatted(rustValue); + } + yield TokenTree.of("::std::rc::Rc::new(%s)".formatted(valueToDafny)); } else { if (isRustOption) { var result = TokenTree.of( @@ -867,154 +909,82 @@ private TokenTree toDafny( }; } - protected TokenTree enumToDafnyFunction(final Shape enumShape) { - String enumName = enumShape.getId().getName(); - String rustEnumName = toPascalCase(enumName); - String sdkId = service - .expectTrait(ServiceTrait.class) - .getSdkId() - .toLowerCase(); - String dafnyTypesModuleName = getDafnyTypesModuleName(); - Map variables = Map.of( - "sdkCrate", - "aws_sdk_" + sdkId, - "enumName", - enumName, - "rustEnumName", - rustEnumName, - "dafnyTypesModuleName", - dafnyTypesModuleName - ); - - String sdkTypeName = evalTemplate( - "$sdkCrate:L::types::$rustEnumName:L", - variables + protected TokenTree enumToDafnyFunction(final EnumShape enumShape) { + final Map variables = MapUtils.merge( + serviceVariables(), + enumVariables(enumShape) ); + var branches = enumShape + .getEnumValues() + .keySet() + .stream() + .map(memberName -> + evalTemplate( + "$rustTypesModuleName:L::$rustEnumName:L::$rustEnumMemberName:L => crate::r#$dafnyTypesModuleName:L::$enumName:L::$dafnyEnumMemberName:L {},", + MapUtils.merge(variables, enumMemberVariables(memberName)) + ) + ) + .collect(Collectors.joining("\n")); + variables.put("branches", branches); - var prelude = TokenTree.of( + // TODO: This should not be a panic, but the Dafny image of the enum shape doesn't have an Unknown variant of any kind, + // so there's no way to succeed. + // See https://github.com/smithy-lang/smithy-dafny/issues/476. + // This could be handled more cleanly if conversion functions returned Results, + // but that would be a large and disruptive change to the overall code flow. + return TokenTree.of( evalTemplate( """ #[allow(dead_code)] pub fn to_dafny( - value: $sdkCrate:L::types::$rustEnumName:L, + value: $rustTypesModuleName:L::$rustEnumName:L, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - + $branches:L + _ => panic!("Unknown enum variant: {}", value), + }) + } """, variables ) ); - - var branches = TokenTree - .of( - enumShape - .expectTrait(EnumTrait.class) - .getValues() - .stream() - .map(e -> - TokenTree.of( - sdkTypeName + - "::" + - rustEnumName(e) + - " => crate::r#" + - dafnyTypesModuleName + - "::" + - enumName + - "::" + - dafnyEnumName(e) + - " {}," - ) - ) - ) - .lineSeparated(); - // TODO: This should not be a panic, but the Dafny image of the enum shape doesn't have an Unknown variant of any kind, - // so there's no way to succeed. - // See https://github.com/smithy-lang/smithy-dafny/issues/476. - // This could be handled more cleanly if conversion functions returned Results, - // but that would be a large and disruptive change to the overall code flow. - final var postlude = TokenTree.of( - """ - - _ => panic!("Unknown enum variant: {}", value), - }) - } - """ - ); - - return TokenTree.of(prelude, branches, postlude); } - protected TokenTree enumFromDafnyFunction(final Shape enumShape) { - String enumName = enumShape.getId().getName(); - String rustEnumName = toPascalCase(enumName); - String sdkId = service - .expectTrait(ServiceTrait.class) - .getSdkId() - .toLowerCase(); - String dafnyTypesModuleName = getDafnyTypesModuleName(); - Map variables = Map.of( - "sdkCrate", - "aws_sdk_" + sdkId, - "enumName", - enumName, - "rustEnumName", - rustEnumName, - "dafnyTypesModuleName", - dafnyTypesModuleName + protected TokenTree enumFromDafnyFunction(final EnumShape enumShape) { + final Map variables = MapUtils.merge( + serviceVariables(), + enumVariables(enumShape) ); - String sdkTypeName = evalTemplate( - "$sdkCrate:L::types::$rustEnumName:L", - variables - ); + var branches = enumShape + .getEnumValues() + .keySet() + .stream() + .map(memberName -> + evalTemplate( + "crate::r#$dafnyTypesModuleName:L::$enumName:L::$dafnyEnumMemberName:L {} => $rustTypesModuleName:L::$rustEnumName:L::$rustEnumMemberName:L,", + MapUtils.merge(variables, enumMemberVariables(memberName)) + ) + ) + .collect(Collectors.joining("\n")); + variables.put("branches", branches); - var prelude = TokenTree.of( + return TokenTree.of( evalTemplate( """ #[allow(dead_code)] pub fn from_dafny( dafny_value: &crate::r#$dafnyTypesModuleName:L::$enumName:L, - ) -> $sdkCrate:L::types::$rustEnumName:L { + ) -> $rustTypesModuleName:L::$rustEnumName:L { match dafny_value { - + $branches:L + } + } """, variables ) ); - - var branches = TokenTree - .of( - enumShape - .expectTrait(EnumTrait.class) - .getValues() - .stream() - .map(e -> - TokenTree.of( - "crate::r#" + - dafnyTypesModuleName + - "::" + - enumName + - "::" + - dafnyEnumName(e) + - " {} => " + - sdkTypeName + - "::" + - rustEnumName(e) + - "," - ) - ) - ) - .lineSeparated(); - final var postlude = TokenTree.of( - """ - - } - } - """ - ); - - return TokenTree.of(prelude, branches, postlude); } protected Set allOperationConversionModules() { @@ -1028,16 +998,40 @@ protected abstract Set operationConversionModules( final OperationShape operationShape ); - private String rustEnumName(EnumDefinition ed) { - return toPascalCase(ed.getValue()); + protected RustFile enumConversionModule(final EnumShape enumShape) { + Path path = Path.of( + "src", + "conversions", + toSnakeCase(enumName(enumShape)) + ".rs" + ); + + return new RustFile( + path, + TokenTree + .of(enumToDafnyFunction(enumShape), enumFromDafnyFunction(enumShape)) + .lineSeparated() + ); } - private String dafnyEnumName(EnumDefinition ed) { - return ed.getValue(); + /** + * Generates values for variables commonly used in service-specific templates. + */ + protected HashMap serviceVariables() { + final HashMap variables = new HashMap<>(); + variables.put("serviceName", service.getId().getName(service)); + variables.put("dafnyModuleName", getDafnyModuleName()); + variables.put("dafnyInternalModuleName", getDafnyInternalModuleName()); + variables.put("dafnyTypesModuleName", getDafnyTypesModuleName()); + variables.put("rustTypesModuleName", getRustTypesModuleName()); + return variables; } protected String getDafnyModuleName() { - return service.getId().getNamespace().replace(".", "::"); + return service + .getId() + .getNamespace() + .replace(".", "::") + .toLowerCase(Locale.ROOT); } protected String getDafnyInternalModuleName() { @@ -1048,14 +1042,7 @@ protected String getDafnyTypesModuleName() { return "%s::types".formatted(getDafnyInternalModuleName()); } - /** - * Generates values for variables commonly used in service-specific templates. - */ - protected HashMap serviceVariables() { - final HashMap variables = new HashMap<>(); - variables.put("serviceName", service.getId().getName(service)); - return variables; - } + protected abstract String getRustTypesModuleName(); /** * Generates values for variables commonly used in operation-specific templates. @@ -1066,6 +1053,8 @@ protected HashMap operationVariables( final String opName = operationName(operationShape); final String opInputName = operationInputName(operationShape); final String opOutputName = operationOutputName(operationShape); + final String synOpInputName = syntheticOperationInputName(operationShape); + final String synOpOutputName = syntheticOperationOutputName(operationShape); final String snakeCaseOpName = toSnakeCase(opName); final HashMap variables = new HashMap<>(); @@ -1073,16 +1062,18 @@ protected HashMap operationVariables( variables.put("operationInputName", opInputName); variables.put("operationOutputName", opOutputName); variables.put("operationErrorName", operationErrorTypeName(operationShape)); + variables.put("syntheticOperationInputName", synOpInputName); + variables.put("syntheticOperationOutputName", synOpOutputName); variables.put("snakeCaseOperationName", snakeCaseOpName); variables.put("snakeCaseOperationInputName", toSnakeCase(opInputName)); variables.put("snakeCaseOperationOutputName", toSnakeCase(opOutputName)); variables.put( - "syntheticOperationInputName", - syntheticOperationInputName(operationShape) + "snakeCaseSyntheticOperationInputName", + toSnakeCase(synOpInputName) ); variables.put( - "syntheticOperationOutputName", - syntheticOperationOutputName(operationShape) + "snakeCaseSyntheticOperationOutputName", + toSnakeCase(synOpOutputName) ); return variables; } @@ -1111,43 +1102,46 @@ protected String operationErrorTypeName(final OperationShape operationShape) { return "%sError".formatted(operationName(operationShape)); } - /** - * Generates values for variables commonly used in structure-member-specific templates. - */ - protected HashMap memberVariables( - final MemberShape memberShape - ) { + protected String enumName(final EnumShape enumShape) { + return enumShape.getId().getName(service); + } + + protected String rustEnumName(final EnumShape enumShape) { + return toPascalCase(enumName(enumShape)); + } + + protected String qualifiedRustEnumType(final EnumShape enumShape) { + return "%s::%s".formatted( + getRustTypesModuleName(), + rustEnumName(enumShape) + ); + } + + protected HashMap enumVariables(final EnumShape enumShape) { final HashMap variables = new HashMap<>(); - variables.put("fieldName", toSnakeCase(memberShape.getMemberName())); - variables.put( - "fieldType", - rustTypeForShape(model.expectShape(memberShape.getTarget())) - ); + final String enumName = enumName(enumShape); + variables.put("enumName", enumName); + variables.put("snakeCaseEnumName", toSnakeCase(enumName)); + variables.put("rustEnumName", rustEnumName(enumShape)); + variables.put("qualifiedRustEnumType", qualifiedRustEnumType(enumShape)); return variables; } - // Currently only handles simple types, and doesn't account for any traits - protected String rustTypeForShape(final Shape shape) { - return switch (shape.getType()) { - case BOOLEAN -> "::std::primitive::bool"; - // integral - case BYTE -> "::std::primitive::i8"; - case SHORT -> "::std::primitive::i16"; - case INTEGER -> "::std::primitive::i32"; - case LONG -> "::std::primitive::i64"; - // floats - case FLOAT -> "::std::primitive::f32"; - case DOUBLE -> "::std::primitive::f64"; - // special numerics - case BIG_INTEGER -> "::num::bigint::BigInt"; - case BIG_DECIMAL -> "::num::rational::BigRational"; - // special collections - case BLOB -> "::std::vec::Vec<::std::primitive::u8>"; - case STRING -> "::std::string::String"; - // TODO: enum, list, map, structure, union - default -> throw new UnsupportedOperationException( - "Unsupported shape type: " + shape.getType() - ); - }; + protected String rustEnumMemberName(final String memberName) { + return toPascalCase(memberName); + } + + protected String dafnyEnumMemberName(final String memberName) { + return memberName; + } + + protected HashMap enumMemberVariables( + final String memberName + ) { + final HashMap variables = new HashMap<>(); + variables.put("enumMemberName", memberName); + variables.put("dafnyEnumMemberName", dafnyEnumMemberName(memberName)); + variables.put("rustEnumMemberName", rustEnumMemberName(memberName)); + return variables; } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustAwsSdkShimGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustAwsSdkShimGenerator.java index 3c08de804c..ca2ecf80e9 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustAwsSdkShimGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustAwsSdkShimGenerator.java @@ -13,15 +13,16 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.polymorph.utils.MapUtils; +import software.amazon.polymorph.utils.ModelUtils; import software.amazon.polymorph.utils.TokenTree; import software.amazon.smithy.aws.traits.ServiceTrait; import software.amazon.smithy.model.Model; +import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.StructureShape; -import software.amazon.smithy.model.traits.EnumTrait; /** * Generates all Rust modules needed to wrap @@ -47,11 +48,10 @@ protected Set rustFiles() { ); result.addAll( - model - .getStringShapesWithTrait(EnumTrait.class) - .stream() + ModelUtils + .streamEnumShapes(model, service.getId().getNamespace()) .map(this::enumConversionModule) - .collect(Collectors.toSet()) + .toList() ); result.add(conversionsModule()); @@ -64,12 +64,7 @@ protected Set rustFiles() { } private RustFile clientModule() { - final Map variables = MapUtils.merge( - serviceVariables(), - dafnyModuleVariables() - ); - variables.put("clientName", "%sClient".formatted(getSdkId())); - + final Map variables = serviceVariables(); var preamble = TokenTree.of( evalTemplate( """ @@ -152,10 +147,8 @@ private TokenTree operationClientFunction( ) { final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); - variables.put("clientName", "%sClient".formatted(getSdkId())); final ShapeId outputShapeId = operationShape.getOutputShape(); final String outputType = outputShapeId.equals( @@ -221,7 +214,7 @@ private TokenTree structureToDafnyFunction( """ #[allow(dead_code)] pub fn to_dafny( - value: &$sdkCrate:L::types::$rustStructureName:L, + value: &$rustTypesModuleName:L::$rustStructureName:L, ) -> ::std::rc::Rc{ ::std::rc::Rc::new( crate::r#$dafnyTypesModuleName:L::$structureName:L::$structureName:L { @@ -230,10 +223,7 @@ pub fn to_dafny( ) } """; - final Map variables = MapUtils.merge( - serviceVariables(), - dafnyModuleVariables() - ); + final Map variables = serviceVariables(); variables.put("structureName", structureName); variables.put("rustStructureName", toPascalCase(structureName)); variables.put( @@ -259,10 +249,7 @@ private TokenTree structureFromDafnyFunction( ) ? ".unwrap()" : ""; - final Map variables = MapUtils.merge( - serviceVariables(), - dafnyModuleVariables() - ); + final Map variables = serviceVariables(); variables.put("structureName", structureName); variables.put("rustStructureName", toPascalCase(structureName)); variables.put("snakeCaseStructureName", toSnakeCase(structureName)); @@ -280,8 +267,8 @@ pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#$dafnyTypesModuleName:L::$structureName:L, >, - ) -> $sdkCrate:L::types::$rustStructureName:L { - $sdkCrate:L::types::$rustStructureName:L::builder() + ) -> $rustTypesModuleName:L::$rustStructureName:L { + $rustTypesModuleName:L::$rustStructureName:L::builder() $fluentMemberSetters:L .build() $unwrapIfNeeded:L @@ -298,7 +285,6 @@ protected TokenTree operationRequestToDafnyFunction( ) { final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); StructureShape inputShape = model.expectShape( @@ -329,13 +315,23 @@ pub fn to_dafny( ); } + @Override + protected boolean isRustFieldRequired(Shape parent, MemberShape member) { + // These rules were mostly reverse-engineered from inspection of Rust SDKs, + // and may not be complete! + final Shape targetShape = model.expectShape(member.getTarget()); + return ( + super.isRustFieldRequired(parent, member) || + (operationIndex.isOutputStructure(parent) && targetShape.isIntegerShape()) + ); + } + @Override protected TokenTree operationRequestFromDafnyFunction( final OperationShape operationShape ) { final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); StructureShape inputShape = model.expectShape( @@ -372,7 +368,6 @@ protected TokenTree operationResponseToDafnyFunction( ) { final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); StructureShape outputShape = model.expectShape( @@ -473,7 +468,6 @@ protected TokenTree operationErrorToDafnyFunction( final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); variables.put("errorCases", errorCases.toString()); @@ -511,7 +505,6 @@ protected TokenTree errorVariantToDafny( ) { final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); String errorName = toPascalCase(errorShape.getId().getName()); @@ -538,7 +531,7 @@ private RustFile errorConversionModule(final Shape errorStructure) { """ #[allow(dead_code)] pub fn to_dafny( - value: $sdkCrate:L::types::error::$pascalCaseName:L, + value: $rustTypesModuleName:L::error::$pascalCaseName:L, ) -> ::std::rc::Rc{ ::std::rc::Rc::new( crate::r#$dafnyTypesModuleName:L::Error::$structureName:L { @@ -547,34 +540,14 @@ pub fn to_dafny( ) } """; - final Map variables = MapUtils.merge( - serviceVariables(), - dafnyModuleVariables() - ); + final Map variables = serviceVariables(); variables.put("structureName", structureName); variables.put("pascalCaseName", pascalCaseName); variables.put( "variants", toDafnyVariantsForStructure(errorStructure).toString() ); - String evaluated = evalTemplate(template, variables); - return new RustFile(path, TokenTree.of(evaluated)); - } - - private RustFile enumConversionModule(final Shape enumShape) { - Path path = Path.of( - "src", - "conversions", - toSnakeCase(enumShape.getId().getName()) + ".rs" - ); - - return new RustFile( - path, - TokenTree.of( - enumToDafnyFunction(enumShape), - enumFromDafnyFunction(enumShape) - ) - ); + return new RustFile(path, TokenTree.of(evalTemplate(template, variables))); } @Override @@ -584,6 +557,11 @@ protected String getDafnyModuleName() { ); } + @Override + protected String getRustTypesModuleName() { + return "%s::types".formatted(getSdkCrate()); + } + private String getSdkId() { return service.expectTrait(ServiceTrait.class).getSdkId(); } @@ -595,8 +573,10 @@ private String getSdkCrate() { @Override protected HashMap serviceVariables() { final HashMap variables = super.serviceVariables(); - variables.put("sdkId", getSdkId()); + final String sdkId = getSdkId(); + variables.put("sdkId", sdkId); variables.put("sdkCrate", getSdkCrate()); + variables.put("clientName", "%sClient".formatted(sdkId)); return variables; } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustLibraryShimGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustLibraryShimGenerator.java index dbf694082e..180fd1b8dd 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustLibraryShimGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustLibraryShimGenerator.java @@ -1,6 +1,7 @@ package software.amazon.polymorph.smithyrust.generator; import static software.amazon.polymorph.utils.IOUtils.evalTemplate; +import static software.amazon.smithy.rust.codegen.core.util.StringsKt.toPascalCase; import static software.amazon.smithy.rust.codegen.core.util.StringsKt.toSnakeCase; import java.nio.file.Path; @@ -17,12 +18,14 @@ import software.amazon.polymorph.utils.ModelUtils; import software.amazon.polymorph.utils.TokenTree; import software.amazon.smithy.model.Model; +import software.amazon.smithy.model.shapes.EnumShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.StructureShape; +import software.amazon.smithy.model.traits.EnumTrait; /** * Generates all Rust modules needed to wrap a Dafny library as a Rust library. @@ -62,6 +65,12 @@ protected Set rustFiles() { // types result.add(typesModule()); result.add(typesConfigModule()); + result.addAll( + ModelUtils + .streamEnumShapes(model, service.getId().getNamespace()) + .map(this::enumTypeModule) + .toList() + ); // errors result.add(errorModule()); @@ -81,8 +90,13 @@ protected Set rustFiles() { result.add(conversionsErrorModule()); result.addAll(configConversionModules()); result.addAll(allOperationConversionModules()); + result.addAll( + ModelUtils + .streamEnumShapes(model, service.getId().getNamespace()) + .map(this::enumConversionModule) + .toList() + ); // TODO structure conversion modules - // TODO enum conversion modules // TODO union conversion modules // wrapped client @@ -93,10 +107,7 @@ protected Set rustFiles() { } private RustFile clientModule() { - final Map variables = MapUtils.merge( - dafnyModuleVariables(), - serviceVariables() - ); + final Map variables = serviceVariables(); variables.put( "operationModules", serviceOperationShapes() @@ -191,10 +202,26 @@ private String operationClientOutputDoc(final OperationShape operationShape) { } private RustFile typesModule() { + final Map variables = serviceVariables(); + + final String enumModules = ModelUtils + .streamEnumShapes(model, service.getId().getNamespace()) + .map(enumShape -> + IOUtils.evalTemplate( + """ + mod _$snakeCaseEnumName:L; + pub use crate::types::_$snakeCaseEnumName:L::$rustEnumName:L; + """, + enumVariables(enumShape) + ) + ) + .collect(Collectors.joining("\n")); + variables.put("enumModules", enumModules); + final String content = IOUtils.evalTemplate( getClass(), "runtimes/rust/types.rs", - serviceVariables() + variables ); return new RustFile(Path.of("src", "types.rs"), TokenTree.of(content)); } @@ -214,6 +241,46 @@ private RustFile typesConfigModule() { return new RustFile(path, TokenTree.of(content)); } + private RustFile enumTypeModule(final EnumShape enumShape) { + final Map variables = MapUtils.merge( + serviceVariables(), + enumVariables(enumShape) + ); + + final Set memberNames = enumShape.getEnumValues().keySet(); + + final String variants = memberNames + .stream() + .map(this::rustEnumMemberName) + .map("%s,"::formatted) + .collect(Collectors.joining("\n")); + variables.put("variants", variants); + + final String displayVariants = memberNames + .stream() + .map(memberName -> + IOUtils.evalTemplate( + "$rustEnumName:L::$rustEnumMemberName:L => write!(f, \"$enumMemberName:L\"),", + MapUtils.merge(variables, enumMemberVariables(memberName)) + ) + ) + .collect(Collectors.joining("\n")); + variables.put("displayVariants", displayVariants); + + final String content = IOUtils.evalTemplate( + getClass(), + "runtimes/rust/types/enum.rs", + variables + ); + + final Path path = Path.of( + "src", + "types", + "_%s.rs".formatted(toSnakeCase(enumName(enumShape))) + ); + return new RustFile(path, TokenTree.of(content)); + } + private RustFile operationModule() { final String opTemplate = """ @@ -319,14 +386,22 @@ private String operationStructureField(final MemberShape memberShape) { } private String operationStructureGetter(final MemberShape memberShape) { + final Map variables = memberVariables(memberShape); + + // for some simple shapes, the Rust runtime types are not Copy + final Shape targetShape = model.expectShape(memberShape.getTarget()); + final boolean needsClone = + targetShape.isBlobShape() || targetShape.isStringShape(); + variables.put("fieldClone", needsClone ? ".clone()" : ""); + final String template = """ #[allow(missing_docs)] // documentation missing in model pub fn $fieldName:L(&self) -> ::std::option::Option<$fieldType:L> { - self.$fieldName:L + self.$fieldName:L$fieldClone:L } """; - return IOUtils.evalTemplate(template, memberVariables(memberShape)); + return IOUtils.evalTemplate(template, variables); } private String operationStructureBuilderField(final MemberShape memberShape) { @@ -440,10 +515,7 @@ private RustFile errorConversionModule( } private Set configConversionModules() { - final Map variables = MapUtils.merge( - serviceVariables(), - dafnyModuleVariables() - ); + final Map variables = serviceVariables(); final String snakeCaseConfigName = variables.get("snakeCaseConfigName"); final String outerContent = IOUtils.evalTemplate( @@ -486,7 +558,6 @@ protected Set operationConversionModules( ) { final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); @@ -543,7 +614,6 @@ private TokenTree operationStructureToDafnyFunction( ); final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); variables.put("structureName", structureId.getName(service)); @@ -601,7 +671,6 @@ private TokenTree operationStructureFromDafnyFunction( ); final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); variables.put("structureName", structureId.getName(service)); @@ -635,16 +704,13 @@ private RustFile wrappedModule() { final String content = IOUtils.evalTemplate( getClass(), "runtimes/rust/wrapped.rs", - MapUtils.merge(serviceVariables(), dafnyModuleVariables()) + serviceVariables() ); return new RustFile(Path.of("src", "wrapped.rs"), TokenTree.of(content)); } private RustFile wrappedClientModule() { - final Map variables = MapUtils.merge( - serviceVariables(), - dafnyModuleVariables() - ); + final Map variables = serviceVariables(); variables.put( "operationImpls", serviceOperationShapes() @@ -667,7 +733,6 @@ private String wrappedClientOperationImpl( ) { final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); return IOUtils.evalTemplate( @@ -704,6 +769,11 @@ protected HashMap serviceVariables() { return variables; } + @Override + protected String getRustTypesModuleName() { + return "crate::types"; + } + @Override protected String syntheticOperationInputName(OperationShape operationShape) { return operationName(operationShape) + "Input"; @@ -713,4 +783,55 @@ protected String syntheticOperationInputName(OperationShape operationShape) { protected String syntheticOperationOutputName(OperationShape operationShape) { return operationName(operationShape) + "Output"; } + + /** + * Generates values for variables commonly used in structure-member-specific templates. + */ + private HashMap memberVariables( + final MemberShape memberShape + ) { + final HashMap variables = new HashMap<>(); + variables.put("fieldName", toSnakeCase(memberShape.getMemberName())); + variables.put( + "fieldType", + rustTypeForShape(model.expectShape(memberShape.getTarget())) + ); + return variables; + } + + // Currently only handles simple types and enums, and doesn't account for any traits + private String rustTypeForShape(final Shape shape) { + return switch (shape.getType()) { + case BOOLEAN -> "::std::primitive::bool"; + // integral + case BYTE -> "::std::primitive::i8"; + case SHORT -> "::std::primitive::i16"; + case INTEGER -> "::std::primitive::i32"; + case LONG -> "::std::primitive::i64"; + // floats + case FLOAT -> "::std::primitive::f32"; + case DOUBLE -> "::std::primitive::f64"; + // special numerics + case BIG_INTEGER -> "::num::bigint::BigInt"; + case BIG_DECIMAL -> "::num::rational::BigRational"; + // special collections + case BLOB -> "::aws_smithy_types::Blob"; + case STRING -> { + //noinspection deprecation + if (shape.hasTrait(EnumTrait.class)) { + yield qualifiedRustEnumType( + ModelUtils.stringToEnumShape(shape.asStringShape().orElseThrow()) + ); + } + yield "::std::string::String"; + } + case ENUM -> qualifiedRustEnumType(shape.asEnumShape().orElseThrow()); + // everything else + case TIMESTAMP -> "::aws_smithy_types::DateTime"; + // TODO: list, map, structure, union + default -> throw new UnsupportedOperationException( + "Unsupported shape type: " + shape.getType() + ); + }; + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/utils/ModelUtils.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/utils/ModelUtils.java index 47e50c7340..0795b6a8c8 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/utils/ModelUtils.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/utils/ModelUtils.java @@ -110,6 +110,36 @@ public static Stream streamNamespaceErrors( ); } + /** + * Returns a stream of enum shapes in the given namespace. + * These include both Smithy v2 enums, + * and Smithy v1 @enum strings converted to {@link EnumShape}s. + */ + public static Stream streamEnumShapes( + final Model model, + final String namespace + ) { + @SuppressWarnings("deprecation") + final Stream v1Enums = model + .getStringShapesWithTrait(EnumTrait.class) + .stream() + .map(ModelUtils::stringToEnumShape); + final Stream v2Enums = model.getEnumShapes().stream(); + return Stream + .concat(v1Enums, v2Enums) + .filter(shape -> shape.getId().getNamespace().equals(namespace)); + } + + public static EnumShape stringToEnumShape(final StringShape stringShape) { + return EnumShape + .fromStringShape(stringShape) + .orElseThrow(() -> + new UnsupportedOperationException( + "Could not convert %s to an enum".formatted(stringShape.getId()) + ) + ); + } + /** * @return true if the given shape ID is in the given service's namespace */ diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/conversions/operation.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/conversions/operation.rs index 874db88a83..9919295c45 100644 --- a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/conversions/operation.rs +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/conversions/operation.rs @@ -25,6 +25,6 @@ pub fn from_dafny_error( } } -pub mod _$snakeCaseOperationInputName:L; +pub mod _$snakeCaseSyntheticOperationInputName:L; -pub mod _$snakeCaseOperationOutputName:L; \ No newline at end of file +pub mod _$snakeCaseSyntheticOperationOutputName:L; \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/operation/outer.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/operation/outer.rs index 5d5817d737..0aea337ee7 100644 --- a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/operation/outer.rs +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/operation/outer.rs @@ -14,7 +14,7 @@ impl $operationName:L { crate::operation::$snakeCaseOperationName:L::$operationOutputName:L, crate::operation::$snakeCaseOperationName:L::$operationErrorName:L, > { - let inner_input = crate::conversions::$snakeCaseOperationName:L::_$snakeCaseOperationInputName:L::to_dafny(input); + let inner_input = crate::conversions::$snakeCaseOperationName:L::_$snakeCaseSyntheticOperationInputName:L::to_dafny(input); let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).$operationName:L(&inner_input); if matches!( @@ -22,7 +22,7 @@ impl $operationName:L { crate::r#_Wrappers_Compile::Result::Success { .. } ) { Ok( - crate::conversions::$snakeCaseOperationName:L::_$snakeCaseOperationOutputName:L::from_dafny( + crate::conversions::$snakeCaseOperationName:L::_$snakeCaseSyntheticOperationOutputName:L::from_dafny( inner_result.value().clone(), ), ) diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/src/standard_library_externs.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types.rs index 2627a01b4a..94630df9d1 100644 --- a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types.rs +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types.rs @@ -1,2 +1,4 @@ /// Types for the `$configName:L` -pub mod $snakeCaseConfigName:L; \ No newline at end of file +pub mod $snakeCaseConfigName:L; + +$enumModules:L \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types/enum.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types/enum.rs new file mode 100644 index 0000000000..0c74b9c52d --- /dev/null +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types/enum.rs @@ -0,0 +1,12 @@ +#[derive(Debug, PartialEq, Copy, Clone)] +pub enum $rustEnumName:L { + $variants:L +} + +impl ::std::fmt::Display for $rustEnumName:L { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match self { + $displayVariants:L + } + } +} \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/wrapped/client_operation_impl.part.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/wrapped/client_operation_impl.part.rs index ce6976a530..ad3ac5afc9 100644 --- a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/wrapped/client_operation_impl.part.rs +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/wrapped/client_operation_impl.part.rs @@ -12,7 +12,7 @@ >, >{ let inner_input = - crate::conversions::$snakeCaseOperationName:L::_$snakeCaseOperationInputName:L::from_dafny(input.clone()); + crate::conversions::$snakeCaseOperationName:L::_$snakeCaseSyntheticOperationInputName:L::from_dafny(input.clone()); let result = self.rt.block_on(crate::operation::$snakeCaseOperationName:L::$operationName:L::send(&self.wrapped, inner_input)); match result { Err(error) => ::std::rc::Rc::new( @@ -22,7 +22,7 @@ ), Ok(client) => ::std::rc::Rc::new( crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::$snakeCaseOperationName:L::_$snakeCaseOperationOutputName:L::to_dafny(client), + value: crate::conversions::$snakeCaseOperationName:L::_$snakeCaseSyntheticOperationOutputName:L::to_dafny(client), }, ), } From dfca8d9d318114fa7ad43b383e223c682dd49200 Mon Sep 17 00:00:00 2001 From: Andrew Jewell <107044381+ajewellamz@users.noreply.github.com> Date: Tue, 3 Sep 2024 12:08:39 -0400 Subject: [PATCH 32/44] fix: bump Rust version to 1.80 (#553) * fix: bump Rust version to 1.80 --- .github/workflows/test_models_rust_tests.yml | 2 +- TestModels/Errors/runtimes/rust/Cargo.toml | 8 +++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/.github/workflows/test_models_rust_tests.yml b/.github/workflows/test_models_rust_tests.yml index 5d0175142e..7833df745f 100644 --- a/.github/workflows/test_models_rust_tests.yml +++ b/.github/workflows/test_models_rust_tests.yml @@ -59,7 +59,7 @@ jobs: - name: Set up Rust uses: actions-rust-lang/setup-rust-toolchain@v1 with: - toolchain: "1.76.0" + toolchain: "1.80.0" rustflags: "" components: rustfmt diff --git a/TestModels/Errors/runtimes/rust/Cargo.toml b/TestModels/Errors/runtimes/rust/Cargo.toml index 9434c16e44..b14b9e9ec0 100644 --- a/TestModels/Errors/runtimes/rust/Cargo.toml +++ b/TestModels/Errors/runtimes/rust/Cargo.toml @@ -6,12 +6,10 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +aws-smithy-runtime = {version = "1.7.1", features=["client"]} +aws-smithy-runtime-api = {version = "1.7.2", features=["client"]} +aws-smithy-types = "1.2.4" dafny_runtime = { path = "../../../dafny-dependencies/dafny_runtime_rust"} -[dependencies.aws-smithy-runtime] -features = ["client"] -[dependencies.aws-smithy-runtime-api] -features = ["client"] -[dependencies.aws-smithy-types] [dev-dependencies.tokio] version = "1.26.0" From 0a707a2e66fc492740d6a2c9b5b83eb0b569eca8 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Tue, 3 Sep 2024 10:57:19 -0700 Subject: [PATCH 33/44] Remove unwanted whitespace --- .../polymorph/smithygo/codegen/knowledge/GoPointableIndex.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java index 2925b7d232..0a7e5834f4 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java @@ -15,7 +15,7 @@ * */ - package software.amazon.polymorph.smithygo.codegen.knowledge; +package software.amazon.polymorph.smithygo.codegen.knowledge; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.KnowledgeIndex; From 17425b1564466c58eda085e9e91399a6bdeced34 Mon Sep 17 00:00:00 2001 From: Robin Salkeld Date: Tue, 3 Sep 2024 13:56:49 -0700 Subject: [PATCH 34/44] chore(ci): make all pull.yml jobs required in branch protection automatically (#554) As is the case for many suites of GitHub actions, it's a huge pain to manually maintain the list of required checks in the branch protection. This change leverages https://github.com/re-actors/alls-green to add a single capstone action that only passes if all dependent jobs pass (see repo README for details on why the naive approach doesn't work). Once this is approved I'll update the required checks before merging. Also adding Python tests to the list of triggers in the nightly build since I noticed it was missing. --- .github/workflows/nightly_dafny.yml | 1 + .github/workflows/pull.yml | 15 +++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/.github/workflows/nightly_dafny.yml b/.github/workflows/nightly_dafny.yml index 4edb7ab15f..20b5baa2b4 100644 --- a/.github/workflows/nightly_dafny.yml +++ b/.github/workflows/nightly_dafny.yml @@ -50,6 +50,7 @@ jobs: dafny-nightly-java, dafny-nightly-net, dafny-nightly-rust, + dafny-nightly-python, ] if: ${{ always() && contains(needs.*.result, 'failure') }} env: diff --git a/.github/workflows/pull.yml b/.github/workflows/pull.yml index 7ee82eede0..31e2db4dbe 100644 --- a/.github/workflows/pull.yml +++ b/.github/workflows/pull.yml @@ -66,3 +66,18 @@ jobs: uses: ./.github/workflows/test_models_python_tests.yml with: dafny: ${{ matrix.dafny-version }} + + pr-ci-all-required: + if: always() + needs: + - pr-ci-verification + - pr-ci-java + - pr-ci-net + - pr-ci-rust + - pr-ci-python + runs-on: ubuntu-latest + steps: + - name: Verify all required jobs passed + uses: re-actors/alls-green@release/v1 + with: + jobs: ${{ toJSON(needs) }} From 3c0a1ce5736fb4de5faf0d8067e8dc7cf93839fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Corella?= <39066999+josecorella@users.noreply.github.com> Date: Tue, 3 Sep 2024 17:12:08 -0700 Subject: [PATCH 35/44] chore: add Dafny 4.8.0 (#522) --- .github/workflows/pull.yml | 4 ++-- .github/workflows/push.yml | 4 ++-- .../amazon/polymorph/smithyjava/ForEachDafnyTest.java | 1 + 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/pull.yml b/.github/workflows/pull.yml index 31e2db4dbe..eabedfa742 100644 --- a/.github/workflows/pull.yml +++ b/.github/workflows/pull.yml @@ -10,10 +10,10 @@ jobs: steps: - name: Populate Dafny versions list id: populate-dafny-versions-list - run: echo "dafny-versions-list=['4.2.0', '4.4.0']" >> $GITHUB_OUTPUT + run: echo "dafny-versions-list=['4.2.0', '4.4.0', '4.8.0']" >> $GITHUB_OUTPUT - name: Populate Dafny versions list for "only new versions" languages (Python) id: populate-only-new-dafny-versions-list - run: echo "only-new-dafny-versions-list=['4.7.0']" >> $GITHUB_OUTPUT + run: echo "only-new-dafny-versions-list=['4.8.0']" >> $GITHUB_OUTPUT outputs: dafny-version-list: ${{ steps.populate-dafny-versions-list.outputs.dafny-versions-list }} only-new-dafny-version-list: ${{ steps.populate-only-new-dafny-versions-list.outputs.only-new-dafny-versions-list }} diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml index 43c1298b78..e3d69c219c 100644 --- a/.github/workflows/push.yml +++ b/.github/workflows/push.yml @@ -12,10 +12,10 @@ jobs: steps: - name: Populate Dafny versions list id: populate-dafny-versions-list - run: echo "dafny-versions-list=['4.2.0', '4.4.0']" >> $GITHUB_OUTPUT + run: echo "dafny-versions-list=['4.2.0', '4.4.0', '4.8.0']" >> $GITHUB_OUTPUT - name: Populate Dafny versions list for "only new versions" languages (Python) id: populate-only-new-dafny-versions-list - run: echo "only-new-dafny-versions-list=['4.7.0']" >> $GITHUB_OUTPUT + run: echo "only-new-dafny-versions-list=['4.8.0']" >> $GITHUB_OUTPUT outputs: dafny-version-list: ${{ steps.populate-dafny-versions-list.outputs.dafny-versions-list }} only-new-dafny-version-list: ${{ steps.populate-only-new-dafny-versions-list.outputs.only-new-dafny-versions-list }} diff --git a/codegen/smithy-dafny-codegen/src/test/java/software/amazon/polymorph/smithyjava/ForEachDafnyTest.java b/codegen/smithy-dafny-codegen/src/test/java/software/amazon/polymorph/smithyjava/ForEachDafnyTest.java index 20ace96be3..61f032a862 100644 --- a/codegen/smithy-dafny-codegen/src/test/java/software/amazon/polymorph/smithyjava/ForEachDafnyTest.java +++ b/codegen/smithy-dafny-codegen/src/test/java/software/amazon/polymorph/smithyjava/ForEachDafnyTest.java @@ -17,6 +17,7 @@ public static Collection dafnies() { new Object[][] { { new DafnyVersion(4, 1, 0) }, { new DafnyVersion(4, 3, 0) }, + { new DafnyVersion(4, 8, 0) }, } ); } From 4a80456153cd34089ca9b5422eee3b4548ec9354 Mon Sep 17 00:00:00 2001 From: Shubham Chaturvedi Date: Tue, 3 Sep 2024 22:25:22 -0700 Subject: [PATCH 36/44] fix: CI --- .github/workflows/test_models_go_tests.yml | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/.github/workflows/test_models_go_tests.yml b/.github/workflows/test_models_go_tests.yml index eb781ab665..7715afa52b 100644 --- a/.github/workflows/test_models_go_tests.yml +++ b/.github/workflows/test_models_go_tests.yml @@ -85,7 +85,28 @@ jobs: run: | go mod init github.com/dafny-lang/DafnyRuntimeGo go mod tidy + + - name: Setup Java 17 for codegen + uses: actions/setup-java@v3 + with: + distribution: "corretto" + java-version: 17 + + - name: Setup smithy-dafny-conversion + uses: gradle/gradle-build-action@v2 + with: + arguments: publishToMavenLocal + build-root-directory: smithy-dafny-conversion + - name: Install Smithy-Dafny codegen dependencies + uses: ./.github/actions/install_smithy_dafny_codegen_dependencies + + - name: Install smithy-dafny-codegen locally + uses: gradle/gradle-build-action@v2 + with: + arguments: :smithy-dafny-codegen:pTML + build-root-directory: codegen + - name: polymorph dafny dependencies shell: bash working-directory: ./TestModels/dafny-dependencies/StandardLibrary From 2cf84b39ce16ed5bd6e38d8b67e80474a0ce3a0a Mon Sep 17 00:00:00 2001 From: Shubham Chaturvedi Date: Tue, 3 Sep 2024 22:59:45 -0700 Subject: [PATCH 37/44] fix: use gradle for CI --- .github/workflows/manual.yml | 4 + .github/workflows/pull.yml | 10 ++ .github/workflows/push.yml | 9 ++ .github/workflows/test_models_go_tests.yml | 139 ++++++++------------- SmithyDafnyMakefile.mk | 4 + 5 files changed, 80 insertions(+), 86 deletions(-) diff --git a/.github/workflows/manual.yml b/.github/workflows/manual.yml index de51a9e953..d8af636504 100644 --- a/.github/workflows/manual.yml +++ b/.github/workflows/manual.yml @@ -32,3 +32,7 @@ jobs: uses: ./.github/workflows/test_models_python_tests.yml with: dafny: ${{ inputs.dafny }} + manual-ci-go: + uses: ./.github/workflows/test_models_go_tests.yml + with: + dafny: ${{ inputs.dafny }} \ No newline at end of file diff --git a/.github/workflows/pull.yml b/.github/workflows/pull.yml index eabedfa742..c1954ad279 100644 --- a/.github/workflows/pull.yml +++ b/.github/workflows/pull.yml @@ -66,6 +66,15 @@ jobs: uses: ./.github/workflows/test_models_python_tests.yml with: dafny: ${{ matrix.dafny-version }} + pr-ci-go: + needs: pr-populate-dafny-versions + strategy: + fail-fast: false + matrix: + dafny-version: ${{ fromJson(needs.pr-populate-dafny-versions.outputs.only-new-dafny-version-list) }} + uses: ./.github/workflows/test_models_go_tests.yml + with: + dafny: ${{ matrix.dafny-version }} pr-ci-all-required: if: always() @@ -75,6 +84,7 @@ jobs: - pr-ci-net - pr-ci-rust - pr-ci-python + - pr-ci-go runs-on: ubuntu-latest steps: - name: Verify all required jobs passed diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml index e3d69c219c..f2d599274d 100644 --- a/.github/workflows/push.yml +++ b/.github/workflows/push.yml @@ -68,3 +68,12 @@ jobs: uses: ./.github/workflows/test_models_python_tests.yml with: dafny: ${{ matrix.dafny-version }} + push-ci-go: + needs: pr-populate-dafny-versions + strategy: + fail-fast: false + matrix: + dafny-version: ${{ fromJson(needs.pr-populate-dafny-versions.outputs.only-new-dafny-version-list) }} + uses: ./.github/workflows/test_models_go_tests.yml + with: + dafny: ${{ matrix.dafny-version }} \ No newline at end of file diff --git a/.github/workflows/test_models_go_tests.yml b/.github/workflows/test_models_go_tests.yml index 7715afa52b..bccce7d1df 100644 --- a/.github/workflows/test_models_go_tests.yml +++ b/.github/workflows/test_models_go_tests.yml @@ -1,74 +1,59 @@ name: Library Go tests -on: ["pull_request", "push"] +on: + workflow_call: + inputs: + dafny: + description: "The Dafny version to run" + required: true + type: string + num_shards: + required: false + type: number + default: 5 jobs: - test_go: + populate-matrix-dimensions: + runs-on: ubuntu-latest + steps: + - name: Populate shard list + id: populate-shard-list + run: echo "shard-list=[`seq -s , 1 ${{ inputs.num_shards }}`]" >> $GITHUB_OUTPUT + outputs: + shard-list: ${{ steps.populate-shard-list.outputs.shard-list }} + testGo: + needs: populate-matrix-dimensions strategy: - fail-fast: false + fail-fast: false # at least for development; see all errors matrix: - library: [ - # TestModels/dafny-dependencies/StandardLibrary, # This stores current Polymorph dependencies that all TestModels depend on - TestModels/Aggregate, - # TestModels/AggregateReferences, - TestModels/CodegenPatches, - TestModels/Constraints, - TestModels/Constructor, - TestModels/Dependencies, - TestModels/Errors, - TestModels/Extendable, - TestModels/Extern, - # TestModels/LanguageSpecificLogic, - # TestModels/LocalService, - # TestModels/MultipleModels, - TestModels/Refinement, - TestModels/Resource, - # TestModels/SimpleTypes/BigDecimal, - # TestModels/SimpleTypes/BigInteger, - TestModels/SimpleTypes/SimpleBlob, - TestModels/SimpleTypes/SimpleBoolean, - # TestModels/SimpleTypes/SimpleByte, - TestModels/SimpleTypes/SimpleDouble, - TestModels/SimpleTypes/SimpleEnum, - # TestModels/SimpleTypes/SimpleEnumV2, - # TestModels/SimpleTypes/SimpleFloat, - TestModels/SimpleTypes/SimpleInteger, - TestModels/SimpleTypes/SimpleLong, - # TestModels/SimpleTypes/SimpleShort, - TestModels/SimpleTypes/SimpleString, - # TestModels/SimpleTypes/SimpleTimestamp, - TestModels/Union, - # TestModels/aws-sdks/ddb, - TestModels/aws-sdks/kms - ] - runs-on: "macos-12" + shard: ${{ fromJson(needs.populate-matrix-dimensions.outputs.shard-list) }} + runs-on: "ubuntu-latest" + permissions: + id-token: write + contents: read + env: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 steps: - - uses: actions/checkout@v2 + - name: Support longpaths on Git checkout + run: | + git config --global core.longpaths true - # - name: Setup Dafny 4.5.0 - # uses: dafny-lang/setup-dafny-action@v1.7.0 - # with: - # dafny-version: 4.5.0 - # TODO: Setup Dafny once its released - - name: Setup dotnet - uses: actions/setup-dotnet@v4 + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@v1 with: - dotnet-version: 6.0.x + aws-region: us-west-2 + role-to-assume: arn:aws:iam::370957321024:role/GitHub-CI-PolymorphTestModels-Role-us-west-2 + role-session-name: PythonTests - - name: Build Dafny from source - run: | - git clone https://github.com/dafny-lang/dafny.git --recurse-submodules - cd dafny - make exe - - - name: Install Z3 version 4.12.1 - run: | - cd $GITHUB_WORKSPACE/dafny - make z3-mac + - uses: actions/checkout@v3 + with: + submodules: recursive - - name: Add Dafny to PATH - run: | - echo "$GITHUB_WORKSPACE/dafny/Scripts" >> $GITHUB_PATH + - name: Setup Dafny + uses: dafny-lang/setup-dafny-action@v1.7.0 + with: + dafny-version: ${{ inputs.dafny }} - name: Install Go uses: actions/setup-go@v2 @@ -107,29 +92,11 @@ jobs: arguments: :smithy-dafny-codegen:pTML build-root-directory: codegen - - name: polymorph dafny dependencies - shell: bash - working-directory: ./TestModels/dafny-dependencies/StandardLibrary - run: | - export DAFNY_VERSION=4.6 - make polymorph_dafny - make transpile_go - make polymorph_go - cd ./runtimes/go/ImplementationFromDafny-go/ - go mod init github.com/dafny-lang/DafnyStandardLibGo - # TODO: This should handwritten (in the makefile or something) - echo "replace github.com/dafny-lang/DafnyRuntimeGo => ../../../../../DafnyRuntimeGo/" >> go.mod; - - - name: Generate Polymorph Dafny and Go code - shell: bash - working-directory: ./${{ matrix.library }} - run: | - export DAFNY_VERSION=4.6 - make polymorph_dafny - sh ./removeDotFromExtern.sh - make transpile_go - make polymorph_go - - goimports -w runtimes/go/ - cd runtimes/go/TestsFromDafny-go/ - go run TestsFromDafny.go \ No newline at end of file + - name: Execute smithy-dafny-codegen-test tests + uses: gradle/gradle-build-action@v2 + env: + JUNIT_SHARD: ${{ matrix.shard }} + JUNIT_SHARD_COUNT: ${{ inputs.num_shards }} + with: + arguments: :smithy-dafny-codegen-test:test --tests '*smithygo*' --info + build-root-directory: codegen \ No newline at end of file diff --git a/SmithyDafnyMakefile.mk b/SmithyDafnyMakefile.mk index 766df9d585..b1797549b4 100644 --- a/SmithyDafnyMakefile.mk +++ b/SmithyDafnyMakefile.mk @@ -767,6 +767,10 @@ clean_go: rm -rf $(LIBRARY_ROOT)/runtimes/go/ImplementationFromDafny-go rm -rf $(LIBRARY_ROOT)/runtimes/go/TestsFromDafny-go +test_go: + cd runtimes/go/TestFromDafny-go + go run TestsFromDafny.go + ########################## Python targets # Python MUST transpile dependencies first to generate .dtr files From f1504b560de9d9ce30035aa9574f4bd1257f326e Mon Sep 17 00:00:00 2001 From: Shubham Chaturvedi Date: Tue, 3 Sep 2024 23:05:24 -0700 Subject: [PATCH 38/44] fix: Add CI Tests --- .../polymorph/smithygo/GoTestModels.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 codegen/smithy-dafny-codegen-test/src/test/java/software/amazon/polymorph/smithygo/GoTestModels.java diff --git a/codegen/smithy-dafny-codegen-test/src/test/java/software/amazon/polymorph/smithygo/GoTestModels.java b/codegen/smithy-dafny-codegen-test/src/test/java/software/amazon/polymorph/smithygo/GoTestModels.java new file mode 100644 index 0000000000..07bf4bce64 --- /dev/null +++ b/codegen/smithy-dafny-codegen-test/src/test/java/software/amazon/polymorph/smithygo/GoTestModels.java @@ -0,0 +1,47 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package software.amazon.polymorph.smithygo; + +import java.nio.file.Path; +import java.util.HashSet; +import java.util.Set; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import software.amazon.polymorph.TestModelTest; + +class GoTestModels extends TestModelTest { + + private static final Set DISABLED_TESTS = new HashSet<>(); + + static { + DISABLED_TESTS.add("AggregateReferences"); + DISABLED_TESTS.add("LanguageSpecificLogic"); + DISABLED_TESTS.add("SimpleTypes/BigDecimal"); + DISABLED_TESTS.add("SimpleTypes/BigInteger"); + DISABLED_TESTS.add("SimpleTypes/SimpleByte"); + DISABLED_TESTS.add("SimpleTypes/SimpleFloat"); + DISABLED_TESTS.add("SimpleTypes/SimpleShort"); + DISABLED_TESTS.add("SimpleTypes/SimpleTimestamp"); + DISABLED_TESTS.add("aws-sdks/ddb-lite"); + DISABLED_TESTS.add("aws-sdks/glue"); + DISABLED_TESTS.add("aws-sdks/lakeformation"); + DISABLED_TESTS.add("aws-sdks/kms-lite"); + DISABLED_TESTS.add("aws-sdks/sqs"); + DISABLED_TESTS.add("aws-sdks/sqs-via-cli"); + } + + @ParameterizedTest + @MethodSource("discoverTestModels") + void testModelsForJava(String relativeTestModelPath) { + Assumptions.assumeFalse(DISABLED_TESTS.contains(relativeTestModelPath)); + + Path testModelPath = getTestModelPath(relativeTestModelPath); + make(testModelPath, "setup_prettier"); + make(testModelPath, "polymorph_dafny"); + make(testModelPath, "polymorph_go"); + make(testModelPath, "transpile_go"); + make(testModelPath, "test_go"); + } +} From 61cc56482e92f37a878da605d22ed912f494bad7 Mon Sep 17 00:00:00 2001 From: Shubham Chaturvedi Date: Tue, 3 Sep 2024 23:20:07 -0700 Subject: [PATCH 39/44] fix: Drop the removeDots script --- SmithyDafnyMakefile.mk | 8 +----- TestModels/Constraints/removeDotFromExtern.sh | 27 ------------------- 2 files changed, 1 insertion(+), 34 deletions(-) delete mode 100644 TestModels/Constraints/removeDotFromExtern.sh diff --git a/SmithyDafnyMakefile.mk b/SmithyDafnyMakefile.mk index b1797549b4..6f598e4f7b 100644 --- a/SmithyDafnyMakefile.mk +++ b/SmithyDafnyMakefile.mk @@ -434,7 +434,7 @@ _polymorph_dafny: OUTPUT_DAFNY=\ --output-dafny $(if $(DIR_STRUCTURE_V2), $(LIBRARY_ROOT)/dafny/$(SERVICE)/Model, $(LIBRARY_ROOT)/Model) _polymorph_dafny: INPUT_DAFNY=\ --include-dafny $(PROJECT_ROOT)/$(STD_LIBRARY)/src/Index.dfy -_polymorph_dafny: _polymorph removeDots +_polymorph_dafny: _polymorph # Generates dotnet code for all namespaces in this project .PHONY: polymorph_dotnet @@ -866,9 +866,3 @@ local_transpile_test_single: TRANSPILE_DEPENDENCIES= \ $(patsubst %, -library:$(PROJECT_ROOT)/%, $(PROJECT_INDEX)) \ -library:$(PROJECT_ROOT)/$(STD_LIBRARY)/src/Index.dfy local_transpile_test_single: transpile_test - -removeDots: - chmod +x ./removeDotFromExtern.sh - ./removeDotFromExtern.sh - -transpile_implementation_go: removeDots \ No newline at end of file diff --git a/TestModels/Constraints/removeDotFromExtern.sh b/TestModels/Constraints/removeDotFromExtern.sh deleted file mode 100644 index 410b6a0fe9..0000000000 --- a/TestModels/Constraints/removeDotFromExtern.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash -# TODO: remove this file if codegen is not generating extern with "." in go - -removeDotFromExtern() { - local directory="$1" - # Recursively search for all files in the current directory and subdirectories - for file in $(find "$directory" -type f); do - # Check if the file contains the pattern "{:extern "XYZ" }" - if grep -q '{:extern ".*"' "$file"; then - # Extract the "XYZ" part from the pattern - xyz=$(grep -o '{:extern "\([^"]*\)"' "$file" | sed 's/{:extern "\([^"]*\)"/\1/') - # Check if the "XYZ" part contains a dot - if [[ "$xyz" == *"."* ]]; then - # Remove the dot from "XYZ" - new_xyz=$(echo "$xyz" | sed 's/\.//g') - # Update the file with the new pattern - sed "s/{:extern \"$xyz\"/{:extern \"$new_xyz\"/g" $file > $file.tmp - cat $file.tmp > $file - rm $file.tmp - fi - fi - done -} - -removeDotFromExtern "Model" -removeDotFromExtern "src" - From ac8a6a47c9e3b7272a90129bc4133ed97e4fac94 Mon Sep 17 00:00:00 2001 From: Shubham Chaturvedi Date: Tue, 3 Sep 2024 23:29:19 -0700 Subject: [PATCH 40/44] fix: prettify --- .github/workflows/manual.yml | 2 +- .github/workflows/push.yml | 2 +- .github/workflows/test_models_go_tests.yml | 10 +- .../software/amazon/polymorph/CodegenCli.java | 25 +- .../amazon/polymorph/CodegenEngine.java | 39 +- .../awssdk/AwsSdkGoPointableIndex.java | 418 ++-- .../DafnyAwsSdkClientShimGenerator.java | 233 ++- ...fnyAwsSdkClientTypeConversionProtocol.java | 1070 ++++++---- .../DafnyGoAwsSdkClientCodegenPlugin.java | 76 +- .../awssdk/DafnyGoAwsSdkDirectedCodegen.java | 134 +- .../AwsSdkToDafnyShapeVisitor.java | 870 ++++---- .../DafnyToAwsSdkShapeVisitor.java | 830 +++++--- .../smithygo/codegen/AddOperationShapes.java | 191 +- .../smithygo/codegen/ApplicationProtocol.java | 8 +- .../smithygo/codegen/CodegenUtils.java | 751 +++---- .../smithygo/codegen/EnumGenerator.java | 142 +- .../smithygo/codegen/GenerationContext.java | 264 +-- .../smithygo/codegen/GoDelegator.java | 7 +- .../smithygo/codegen/GoDependency.java | 604 +++--- .../smithygo/codegen/GoSettings.java | 346 ++-- .../polymorph/smithygo/codegen/GoWriter.java | 1480 +++++++------- .../smithygo/codegen/ImportDeclarations.java | 93 +- .../smithygo/codegen/IntEnumGenerator.java | 119 +- .../smithygo/codegen/SmithyGoDependency.java | 261 ++- .../smithygo/codegen/StructureGenerator.java | 325 +-- .../smithygo/codegen/SymbolUtils.java | 382 ++-- .../smithygo/codegen/SymbolVisitor.java | 1039 +++++----- .../polymorph/smithygo/codegen/Synthetic.java | 168 +- .../smithygo/codegen/UnionGenerator.java | 185 +- .../smithygo/codegen/ValidationGenerator.java | 623 +++--- .../codegen/integration/GoIntegration.java | 4 +- .../integration/ProtocolGenerator.java | 78 +- .../codegen/knowledge/GoPointableIndex.java | 438 ++-- .../codegen/knowledge/GoUsageIndex.java | 119 +- .../codegen/knowledge/GoValidationIndex.java | 346 ++-- .../localservice/DafnyGoPointableIndex.java | 9 +- .../DafnyLocalServiceCodegenPlugin.java | 78 +- .../DafnyLocalServiceDirectedCodegen.java | 272 ++- .../DafnyLocalServiceGenerator.java | 1344 ++++++++----- ...fnyLocalServiceTypeConversionProtocol.java | 1762 +++++++++++------ .../localservice/nameresolver/Constants.java | 9 +- .../nameresolver/DafnyNameResolver.java | 324 +-- .../nameresolver/SmithyNameResolver.java | 244 ++- .../DafnyToSmithyShapeVisitor.java | 972 +++++---- .../SmithyToDafnyShapeVisitor.java | 1092 +++++----- .../smithygo/utils/GoCodegenUtils.java | 68 +- 46 files changed, 10640 insertions(+), 7216 deletions(-) diff --git a/.github/workflows/manual.yml b/.github/workflows/manual.yml index d8af636504..fc44ba70e6 100644 --- a/.github/workflows/manual.yml +++ b/.github/workflows/manual.yml @@ -35,4 +35,4 @@ jobs: manual-ci-go: uses: ./.github/workflows/test_models_go_tests.yml with: - dafny: ${{ inputs.dafny }} \ No newline at end of file + dafny: ${{ inputs.dafny }} diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml index f2d599274d..2f164cb8c2 100644 --- a/.github/workflows/push.yml +++ b/.github/workflows/push.yml @@ -76,4 +76,4 @@ jobs: dafny-version: ${{ fromJson(needs.pr-populate-dafny-versions.outputs.only-new-dafny-version-list) }} uses: ./.github/workflows/test_models_go_tests.yml with: - dafny: ${{ matrix.dafny-version }} \ No newline at end of file + dafny: ${{ matrix.dafny-version }} diff --git a/.github/workflows/test_models_go_tests.yml b/.github/workflows/test_models_go_tests.yml index bccce7d1df..946630e1a9 100644 --- a/.github/workflows/test_models_go_tests.yml +++ b/.github/workflows/test_models_go_tests.yml @@ -58,7 +58,7 @@ jobs: - name: Install Go uses: actions/setup-go@v2 with: - go-version: '1.21' + go-version: "1.21" - name: Install Go imports run: | @@ -67,10 +67,10 @@ jobs: - name: Add go mod to Dafny Runtime Go shell: bash working-directory: ./DafnyRuntimeGo - run: | + run: | go mod init github.com/dafny-lang/DafnyRuntimeGo go mod tidy - + - name: Setup Java 17 for codegen uses: actions/setup-java@v3 with: @@ -91,7 +91,7 @@ jobs: with: arguments: :smithy-dafny-codegen:pTML build-root-directory: codegen - + - name: Execute smithy-dafny-codegen-test tests uses: gradle/gradle-build-action@v2 env: @@ -99,4 +99,4 @@ jobs: JUNIT_SHARD_COUNT: ${{ inputs.num_shards }} with: arguments: :smithy-dafny-codegen-test:test --tests '*smithygo*' --info - build-root-directory: codegen \ No newline at end of file + build-root-directory: codegen diff --git a/codegen/smithy-dafny-codegen-cli/src/main/java/software/amazon/polymorph/CodegenCli.java b/codegen/smithy-dafny-codegen-cli/src/main/java/software/amazon/polymorph/CodegenCli.java index 253f589759..4e12ab1308 100644 --- a/codegen/smithy-dafny-codegen-cli/src/main/java/software/amazon/polymorph/CodegenCli.java +++ b/codegen/smithy-dafny-codegen-cli/src/main/java/software/amazon/polymorph/CodegenCli.java @@ -21,13 +21,11 @@ import org.apache.commons.cli.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - -import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.loader.ModelAssembler; - import software.amazon.polymorph.CodegenEngine.TargetLanguage; import software.amazon.polymorph.smithydafny.DafnyVersion; import software.amazon.polymorph.smithyjava.generator.CodegenSubject.AwsSdkVersion; +import software.amazon.smithy.model.Model; +import software.amazon.smithy.model.loader.ModelAssembler; import software.amazon.smithy.model.validation.ValidatedResult; import software.amazon.smithy.model.validation.ValidationEvent; @@ -235,12 +233,12 @@ private static Options getCliOptionsForBuild() { .build() ) .addOption( - Option - .builder() - .longOpt("output-go") - .desc(" output directory for generated Go files") - .hasArg() - .build() + Option + .builder() + .longOpt("output-go") + .desc(" output directory for generated Go files") + .hasArg() + .build() ) .addOption( Option @@ -354,8 +352,7 @@ private static Options getCliOptionsForBuild() { .valueSeparator(',') .build() ); - } - + } private static Options getCliOptionsForPatchAfterTranspile() { return new Options() @@ -557,8 +554,8 @@ static Optional parse(String[] args) throws ParseException { .ofNullable(commandLine.getOptionValue("output-dotnet")) .map(Paths::get); final Optional outputGoDir = Optional - .ofNullable(commandLine.getOptionValue("output-go")) - .map(Paths::get); + .ofNullable(commandLine.getOptionValue("output-go")) + .map(Paths::get); final Optional outputRustDir = Optional .ofNullable(commandLine.getOptionValue("output-rust")) .map(Paths::get); diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java index 3d02397833..e3a234f9f3 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java @@ -43,6 +43,7 @@ import software.amazon.polymorph.smithydotnet.localServiceWrapper.LocalServiceWrappedConversionCodegen; import software.amazon.polymorph.smithydotnet.localServiceWrapper.LocalServiceWrappedShimCodegen; import software.amazon.polymorph.smithygo.awssdk.DafnyGoAwsSdkClientCodegenPlugin; +import software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceCodegenPlugin; import software.amazon.polymorph.smithyjava.generator.CodegenSubject.AwsSdkVersion; import software.amazon.polymorph.smithyjava.generator.awssdk.v1.JavaAwsSdkV1; import software.amazon.polymorph.smithyjava.generator.awssdk.v2.JavaAwsSdkV2; @@ -66,7 +67,6 @@ import software.amazon.smithy.model.node.ObjectNode; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.utils.IoUtils; -import software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceCodegenPlugin; import software.amazon.smithy.utils.Pair; public class CodegenEngine { @@ -815,25 +815,36 @@ private void handlePatching(TargetLanguage targetLanguage, Path outputDir) { private void generateGo() { if (libraryName.isEmpty()) { - throw new IllegalArgumentException("Python codegen requires a module name"); + throw new IllegalArgumentException("Go codegen requires a library name"); } - ObjectNode.Builder goSettingsBuilder = ObjectNode.builder() - .withMember("service", serviceShape.getId().toString()) - .withMember("moduleName", libraryName.get()); + ObjectNode.Builder goSettingsBuilder = ObjectNode + .builder() + .withMember("service", serviceShape.getId().toString()) + .withMember("moduleName", libraryName.get()); - final PluginContext pluginContext = PluginContext.builder() - .model(model) - .fileManifest(FileManifest.create(targetLangOutputDirs.get(TargetLanguage.GO))) - .settings(goSettingsBuilder.build()) - .build(); + final PluginContext pluginContext = PluginContext + .builder() + .model(model) + .fileManifest( + FileManifest.create(targetLangOutputDirs.get(TargetLanguage.GO)) + ) + .settings(goSettingsBuilder.build()) + .build(); - final Map smithyNamespaceToGoModuleNameMap = new HashMap<>(dependencyLibraryNames); - smithyNamespaceToGoModuleNameMap.put(serviceShape.getId().getNamespace(), libraryName.get()); + final Map smithyNamespaceToGoModuleNameMap = new HashMap<>( + dependencyLibraryNames + ); + smithyNamespaceToGoModuleNameMap.put( + serviceShape.getId().getNamespace(), + libraryName.get() + ); if (this.awsSdkStyle) { - new DafnyGoAwsSdkClientCodegenPlugin(smithyNamespaceToGoModuleNameMap).run(pluginContext); + new DafnyGoAwsSdkClientCodegenPlugin(smithyNamespaceToGoModuleNameMap) + .run(pluginContext); } else { - new DafnyLocalServiceCodegenPlugin(smithyNamespaceToGoModuleNameMap).run(pluginContext); + new DafnyLocalServiceCodegenPlugin(smithyNamespaceToGoModuleNameMap) + .run(pluginContext); } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/AwsSdkGoPointableIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/AwsSdkGoPointableIndex.java index c57767d9c8..a6524a8a24 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/AwsSdkGoPointableIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/AwsSdkGoPointableIndex.java @@ -20,226 +20,262 @@ import software.amazon.smithy.utils.SetUtils; public class AwsSdkGoPointableIndex implements KnowledgeIndex { - public static final NullableIndex.CheckMode DEFAULT_CHECKMODE = - NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1_NO_INPUT; - - private static final Logger LOGGER = Logger.getLogger(AwsSdkGoPointableIndex.class.getName()); - - // All types that are Go value types - private static final Set INHERENTLY_VALUE = SetUtils.of( - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - ShapeType.UNION, - ShapeType.DOCUMENT - ); - - // All types that are Go pointer types - private static final Set INHERENTLY_POINTABLE = SetUtils.of( - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - // All types that cannot be dereferenced - private static final Set INHERENTLY_NONDEREFERENCABLE = SetUtils.of( - // built in slice/map - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - - // Interfaces - ShapeType.UNION, - ShapeType.DOCUMENT, - - // known pointer types. - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER + public static final NullableIndex.CheckMode DEFAULT_CHECKMODE = + NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1_NO_INPUT; + + private static final Logger LOGGER = Logger.getLogger( + AwsSdkGoPointableIndex.class.getName() + ); + + // All types that are Go value types + private static final Set INHERENTLY_VALUE = SetUtils.of( + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + ShapeType.UNION, + ShapeType.DOCUMENT + ); + + // All types that are Go pointer types + private static final Set INHERENTLY_POINTABLE = SetUtils.of( + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + // All types that cannot be dereferenced + private static final Set INHERENTLY_NONDEREFERENCABLE = + SetUtils.of( + // built in slice/map + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + // Interfaces + ShapeType.UNION, + ShapeType.DOCUMENT, + // known pointer types. + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER ); - // All types types that are comparable to nil - private static final Set INHERENTLY_NILLABLE = SetUtils.of( - // built in slice/map - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - - // Interfaces - ShapeType.UNION, - ShapeType.DOCUMENT, - - // known pointer types. - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - - - - private final Model model; - private final NullableIndex nullableIndex; - private final NullableIndex.CheckMode checkMode; - private final Set pointableShapes = new HashSet<>(); - private final Set nillableShapes = new HashSet<>(); - private final Set dereferencableShapes = new HashSet<>(); - - public AwsSdkGoPointableIndex(Model model, NullableIndex.CheckMode checkMode) { - this.model = model; - this.nullableIndex = NullableIndex.of(model); - this.checkMode = checkMode; - - for (Shape shape : model.toSet()) { - if (shape.asMemberShape().isPresent()) { - MemberShape member = shape.asMemberShape().get(); - Shape targetShape = model.expectShape(member.getTarget()); - - if (isMemberPointable(member, targetShape)) { - pointableShapes.add(shape.getId()); - } - if (isMemberNillable(member, targetShape)) { - nillableShapes.add(shape.getId()); - } - if (isMemberDereferencable(member, targetShape)) { - dereferencableShapes.add(shape.getId()); - } - } else { - if (isShapePointable(shape)) { - pointableShapes.add(shape.getId()); - nillableShapes.add(shape.getId()); - } - if (isShapeNillable(shape)) { - nillableShapes.add(shape.getId()); - } - if (isShapeDereferencable(shape)) { - dereferencableShapes.add(shape.getId()); - } - } + // All types types that are comparable to nil + private static final Set INHERENTLY_NILLABLE = SetUtils.of( + // built in slice/map + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + // Interfaces + ShapeType.UNION, + ShapeType.DOCUMENT, + // known pointer types. + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + private final Model model; + private final NullableIndex nullableIndex; + private final NullableIndex.CheckMode checkMode; + private final Set pointableShapes = new HashSet<>(); + private final Set nillableShapes = new HashSet<>(); + private final Set dereferencableShapes = new HashSet<>(); + + public AwsSdkGoPointableIndex( + Model model, + NullableIndex.CheckMode checkMode + ) { + this.model = model; + this.nullableIndex = NullableIndex.of(model); + this.checkMode = checkMode; + + for (Shape shape : model.toSet()) { + if (shape.asMemberShape().isPresent()) { + MemberShape member = shape.asMemberShape().get(); + Shape targetShape = model.expectShape(member.getTarget()); + + if (isMemberPointable(member, targetShape)) { + pointableShapes.add(shape.getId()); + } + if (isMemberNillable(member, targetShape)) { + nillableShapes.add(shape.getId()); + } + if (isMemberDereferencable(member, targetShape)) { + dereferencableShapes.add(shape.getId()); + } + } else { + if (isShapePointable(shape)) { + pointableShapes.add(shape.getId()); + nillableShapes.add(shape.getId()); + } + if (isShapeNillable(shape)) { + nillableShapes.add(shape.getId()); } + if (isShapeDereferencable(shape)) { + dereferencableShapes.add(shape.getId()); + } + } } + } - public AwsSdkGoPointableIndex(Model model) { - this(model, DEFAULT_CHECKMODE); - } + public AwsSdkGoPointableIndex(Model model) { + this(model, DEFAULT_CHECKMODE); + } - public static AwsSdkGoPointableIndex of(Model model) { - return model.getKnowledge(AwsSdkGoPointableIndex.class, AwsSdkGoPointableIndex::new); - } + public static AwsSdkGoPointableIndex of(Model model) { + return model.getKnowledge( + AwsSdkGoPointableIndex.class, + AwsSdkGoPointableIndex::new + ); + } + + public static AwsSdkGoPointableIndex of( + Model model, + NullableIndex.CheckMode checkMode + ) { + return model.getKnowledge( + AwsSdkGoPointableIndex.class, + model1 -> new AwsSdkGoPointableIndex(model1, checkMode) + ); + } + + private boolean isMemberDereferencable( + MemberShape member, + Shape targetShape + ) { + return ( + !INHERENTLY_NONDEREFERENCABLE.contains(targetShape.getType()) && + isMemberPointable(member, targetShape) + ); + } - public static AwsSdkGoPointableIndex of(Model model, NullableIndex.CheckMode checkMode) { - return model.getKnowledge(AwsSdkGoPointableIndex.class, (model1) -> new AwsSdkGoPointableIndex(model1, checkMode)); - } + private boolean isMemberNillable(MemberShape member, Shape targetShape) { + return ( + INHERENTLY_NILLABLE.contains(targetShape.getType()) || + isMemberPointable(member, targetShape) + ); + } - private boolean isMemberDereferencable(MemberShape member, Shape targetShape) { - return !INHERENTLY_NONDEREFERENCABLE.contains(targetShape.getType()) && isMemberPointable(member, targetShape); + private boolean isMemberPointable(MemberShape member, Shape targetShape) { + // Streamed blob shapes are never pointers because they are interfaces + if (isBlobStream(targetShape)) { + return false; } - private boolean isMemberNillable(MemberShape member, Shape targetShape) { - return INHERENTLY_NILLABLE.contains(targetShape.getType()) || isMemberPointable(member, targetShape); + if ( + INHERENTLY_VALUE.contains(targetShape.getType()) || + isShapeEnum(targetShape) + ) { + return false; } - private boolean isMemberPointable(MemberShape member, Shape targetShape) { + return nullableIndex.isMemberNullable(member, checkMode); + } - // Streamed blob shapes are never pointers because they are interfaces - if (isBlobStream(targetShape)) { - return false; - } + private boolean isShapeDereferencable(Shape shape) { + return ( + !INHERENTLY_NONDEREFERENCABLE.contains(shape.getType()) && + isShapePointable(shape) + ); + } - if (INHERENTLY_VALUE.contains(targetShape.getType()) || isShapeEnum(targetShape)) { - return false; - } + private boolean isShapeNillable(Shape shape) { + return ( + INHERENTLY_NILLABLE.contains(shape.getType()) || isShapePointable(shape) + ); + } - return nullableIndex.isMemberNullable(member, checkMode); + private boolean isShapePointable(Shape shape) { + // All operation input and output shapes are pointable. + if (isOperationStruct(shape)) { + return true; } - private boolean isShapeDereferencable(Shape shape) { - return !INHERENTLY_NONDEREFERENCABLE.contains(shape.getType()) && isShapePointable(shape); + // Streamed blob shapes are never pointers because they are interfaces + if (isBlobStream(shape)) { + return false; } - private boolean isShapeNillable(Shape shape) { - return INHERENTLY_NILLABLE.contains(shape.getType()) || isShapePointable(shape); + if (shape.isServiceShape()) { + return true; } - private boolean isShapePointable(Shape shape) { - // All operation input and output shapes are pointable. - if (isOperationStruct(shape)) { - return true; - } - - // Streamed blob shapes are never pointers because they are interfaces - if (isBlobStream(shape)) { - return false; - } - - if (shape.isServiceShape()) { - return true; - } - - // This is odd because its not a go type but a function with receiver - if (shape.isOperationShape()) { - return false; - } - - if (INHERENTLY_POINTABLE.contains(shape.getType())) { - return true; - } - - if (INHERENTLY_VALUE.contains(shape.getType()) || isShapeEnum(shape)) { - return false; - } - - return nullableIndex.isNullable(shape); + // This is odd because its not a go type but a function with receiver + if (shape.isOperationShape()) { + return false; } - private boolean isShapeEnum(Shape shape) { - return shape.getType() == ShapeType.STRING && shape.hasTrait(EnumTrait.class) - || shape.getType() == ShapeType.ENUM - || shape.getType() == ShapeType.INT_ENUM; + if (INHERENTLY_POINTABLE.contains(shape.getType())) { + return true; } - private boolean isBlobStream(Shape shape) { - return shape.getType() == ShapeType.BLOB && shape.hasTrait(StreamingTrait.ID); + if (INHERENTLY_VALUE.contains(shape.getType()) || isShapeEnum(shape)) { + return false; } - public boolean isOperationStruct(Shape shape) { - NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); - for (Relationship relationship : provider.getNeighbors(shape)) { - RelationshipType relationshipType = relationship.getRelationshipType(); - if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { - return true; - } - } - - return false; - } + return nullableIndex.isNullable(shape); + } - /** - * Returns if the shape should be generated as a Go pointer type or not. - * - * @param shape the shape to check if should be pointable type. - * @return if the shape is should be a Go pointer type. - */ - public final boolean isPointable(ToShapeId shape) { - return pointableShapes.contains(shape.toShapeId()); - } + private boolean isShapeEnum(Shape shape) { + return ( + (shape.getType() == ShapeType.STRING && + shape.hasTrait(EnumTrait.class)) || + shape.getType() == ShapeType.ENUM || + shape.getType() == ShapeType.INT_ENUM + ); + } - /** - * Returns if the Go type generated for the shape is comparable to nil. - * - * @param shape the shape to check - * @return if the shape's go type is comparable to nil - */ - public final boolean isNillable(ToShapeId shape) { - return nillableShapes.contains(shape.toShapeId()); + private boolean isBlobStream(Shape shape) { + return ( + shape.getType() == ShapeType.BLOB && shape.hasTrait(StreamingTrait.ID) + ); + } + + public boolean isOperationStruct(Shape shape) { + NeighborProvider provider = NeighborProviderIndex + .of(model) + .getReverseProvider(); + for (Relationship relationship : provider.getNeighbors(shape)) { + RelationshipType relationshipType = relationship.getRelationshipType(); + if ( + relationshipType == RelationshipType.INPUT || + relationshipType == RelationshipType.OUTPUT + ) { + return true; + } } - /** - * Returns if the Go type generated for the shape can be dereferenced. - * - * @param shape the shape to check - * @return if the shape's go type is dereferencable - */ - public final boolean isDereferencable(ToShapeId shape) { - return dereferencableShapes.contains(shape.toShapeId()); - } -} \ No newline at end of file + return false; + } + + /** + * Returns if the shape should be generated as a Go pointer type or not. + * + * @param shape the shape to check if should be pointable type. + * @return if the shape is should be a Go pointer type. + */ + public final boolean isPointable(ToShapeId shape) { + return pointableShapes.contains(shape.toShapeId()); + } + + /** + * Returns if the Go type generated for the shape is comparable to nil. + * + * @param shape the shape to check + * @return if the shape's go type is comparable to nil + */ + public final boolean isNillable(ToShapeId shape) { + return nillableShapes.contains(shape.toShapeId()); + } + + /** + * Returns if the Go type generated for the shape can be dereferenced. + * + * @param shape the shape to check + * @return if the shape's go type is dereferencable + */ + public final boolean isDereferencable(ToShapeId shape) { + return dereferencableShapes.contains(shape.toShapeId()); + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientShimGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientShimGenerator.java index f0116ce4fc..a9835297ae 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientShimGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientShimGenerator.java @@ -15,91 +15,174 @@ public class DafnyAwsSdkClientShimGenerator implements Runnable { - private final GenerationContext context; - private final ServiceShape service; - private final GoDelegator writerDelegator; - private final Model dafnyNonNormalizedModel; - private final Model awsNormalizedModel; - private final SymbolProvider symbolProvider; + private final GenerationContext context; + private final ServiceShape service; + private final GoDelegator writerDelegator; + private final Model dafnyNonNormalizedModel; + private final Model awsNormalizedModel; + private final SymbolProvider symbolProvider; - public DafnyAwsSdkClientShimGenerator(GenerationContext context, ServiceShape service) { - this.context = context; - this.service = service; - dafnyNonNormalizedModel = context.model(); - awsNormalizedModel = AddOperationShapes.execute(context.model(), service.toShapeId()); - writerDelegator = context.writerDelegator(); - symbolProvider = context.symbolProvider(); - } + public DafnyAwsSdkClientShimGenerator( + GenerationContext context, + ServiceShape service + ) { + this.context = context; + this.service = service; + dafnyNonNormalizedModel = context.model(); + awsNormalizedModel = + AddOperationShapes.execute(context.model(), service.toShapeId()); + writerDelegator = context.writerDelegator(); + symbolProvider = context.symbolProvider(); + } - @Override - public void run() { - generateShim(); - } + @Override + public void run() { + generateShim(); + } - void generateShim() { - final var namespace = "%swrapped".formatted(DafnyNameResolver.dafnyNamespace(service)); + void generateShim() { + final var namespace = + "%swrapped".formatted(DafnyNameResolver.dafnyNamespace(service)); - writerDelegator.useFileWriter("%s/shim.go".formatted(namespace), namespace, writer -> { + writerDelegator.useFileWriter( + "%s/shim.go".formatted(namespace), + namespace, + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(service) + ); + writer.addImport( + SmithyNameResolver.getGoModuleNameForSdkNamespace( + awsNormalizedModel + .expectShape(service.toShapeId(), ServiceShape.class) + .toShapeId() + .getNamespace() + ) + ); + writer.addImportFromModule( + "github.com/dafny-lang/DafnyStandardLibGo", + "Wrappers" + ); + writer.addUseImports(SmithyGoDependency.CONTEXT); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + SmithyNameResolver.shapeNamespace(service) + ); + writer.write( + """ + type Shim struct { + $L + Client *$L + } + """, + DafnyNameResolver.getDafnyInterfaceClient( + service, + service.expectTrait(ServiceTrait.class) + ), + SmithyNameResolver.getAwsServiceClient( + service.expectTrait(ServiceTrait.class) + ) + ); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(service)); - writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedModel.expectShape(service.toShapeId(), ServiceShape.class).toShapeId().getNamespace())); - writer.addImportFromModule("github.com/dafny-lang/DafnyStandardLibGo", "Wrappers"); - writer.addUseImports(SmithyGoDependency.CONTEXT); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.shapeNamespace(service)); - writer.write(""" - type Shim struct { - $L - Client *$L - } - """, - DafnyNameResolver.getDafnyInterfaceClient(service, service.expectTrait(ServiceTrait.class)), - SmithyNameResolver.getAwsServiceClient(service.expectTrait(ServiceTrait.class)) + service + .getOperations() + .forEach(operation -> { + final var awsNormalizedOperation = awsNormalizedModel.expectShape( + operation, + OperationShape.class + ); + final var awsNormalizedInputShape = awsNormalizedModel.expectShape( + awsNormalizedOperation.getInputShape() + ); + final var awsNormalizedOutputShape = awsNormalizedModel.expectShape( + awsNormalizedOperation.getOutputShape() ); + final var operationShape = dafnyNonNormalizedModel.expectShape( + operation, + OperationShape.class + ); + final var inputShape = dafnyNonNormalizedModel.expectShape( + operationShape.getInputShape() + ); + final var outputShape = dafnyNonNormalizedModel.expectShape( + operationShape.getOutputShape() + ); + final var inputType = awsNormalizedInputShape.hasTrait( + UnitTypeTrait.class + ) + ? "" + : "input %s".formatted( + DafnyNameResolver.getDafnyType( + inputShape, + symbolProvider.toSymbol(inputShape) + ) + ); - service.getOperations().forEach(operation -> { - final var awsNormalizedOperation = awsNormalizedModel.expectShape(operation, OperationShape.class); - final var awsNormalizedInputShape = awsNormalizedModel.expectShape(awsNormalizedOperation.getInputShape()); - final var awsNormalizedOutputShape = awsNormalizedModel.expectShape(awsNormalizedOperation.getOutputShape()); - - final var operationShape = dafnyNonNormalizedModel.expectShape(operation, OperationShape.class); - final var inputShape = dafnyNonNormalizedModel.expectShape(operationShape.getInputShape()); - final var outputShape = dafnyNonNormalizedModel.expectShape(operationShape.getOutputShape()); - final var inputType = awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) ? "" - : "input %s".formatted(DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(inputShape))); + final var typeConversion = awsNormalizedInputShape.hasTrait( + UnitTypeTrait.class + ) + ? "" + : "var native_request = %s(input)".formatted( + SmithyNameResolver.getFromDafnyMethodName( + awsNormalizedInputShape, + "" + ) + ); - final var typeConversion = awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) ? "" - : "var native_request = %s(input)".formatted(SmithyNameResolver.getFromDafnyMethodName(awsNormalizedInputShape, "")); + final var clientCall = + "shim.Client.%s(context.Background() %s)".formatted( + operationShape.getId().getName(), + awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) + ? "" + : ", &native_request" + ); - final var clientCall = "shim.Client.%s(context.Background() %s)".formatted(operationShape.getId().getName(), - awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) ? "" : ", &native_request"); + String clientResponse, returnResponse; + if (awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class)) { + clientResponse = "var _, native_error"; + returnResponse = "dafny.TupleOf()"; + writer.addImportFromModule( + "github.com/dafny-lang/DafnyRuntimeGo", + "dafny" + ); + } else { + clientResponse = "var native_response, native_error"; + returnResponse = + "%s(*native_response)".formatted( + SmithyNameResolver.getToDafnyMethodName( + awsNormalizedOutputShape, + "" + ) + ); + } - String clientResponse, returnResponse; - if (awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class)) { - clientResponse = "var _, native_error"; - returnResponse = "dafny.TupleOf()"; - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - } else { - clientResponse = "var native_response, native_error"; - returnResponse = "%s(*native_response)".formatted(SmithyNameResolver.getToDafnyMethodName(awsNormalizedOutputShape, "")); + writer.write( + """ + func (shim *Shim) $L($L) Wrappers.Result { + $L + $L = $L + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_($L.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_($L) } - - writer.write(""" - func (shim *Shim) $L($L) Wrappers.Result { - $L - $L = $L - if native_error != nil { - return Wrappers.Companion_Result_.Create_Failure_($L.Error_ToDafny(native_error)) - } - return Wrappers.Companion_Result_.Create_Success_($L) - } - """, - operationShape.getId().getName(), - inputType, typeConversion, clientResponse, clientCall, - SmithyNameResolver.shapeNamespace(service), - returnResponse - ); - }); - }); - } + """, + operationShape.getId().getName(), + inputType, + typeConversion, + clientResponse, + clientCall, + SmithyNameResolver.shapeNamespace(service), + returnResponse + ); + }); + } + ); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientTypeConversionProtocol.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientTypeConversionProtocol.java index 0b50402b28..3a82903637 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientTypeConversionProtocol.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientTypeConversionProtocol.java @@ -1,5 +1,10 @@ package software.amazon.polymorph.smithygo.awssdk; +import static software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceTypeConversionProtocol.TO_DAFNY; +import static software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceTypeConversionProtocol.TO_NATIVE; + +import java.util.HashSet; +import java.util.Set; import software.amazon.polymorph.smithygo.awssdk.shapevisitor.AwsSdkToDafnyShapeVisitor; import software.amazon.polymorph.smithygo.awssdk.shapevisitor.DafnyToAwsSdkShapeVisitor; import software.amazon.polymorph.smithygo.codegen.AddOperationShapes; @@ -18,359 +23,744 @@ import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.UnitTypeTrait; -import java.util.HashSet; -import java.util.Set; - -import static software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceTypeConversionProtocol.TO_DAFNY; -import static software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceTypeConversionProtocol.TO_NATIVE; - -public class DafnyAwsSdkClientTypeConversionProtocol implements ProtocolGenerator { - final Model dafnyNonNormalizedModel; - final Model awsNormalizedModel; - final ServiceShape serviceShape; - public DafnyAwsSdkClientTypeConversionProtocol(Model model, ServiceShape serviceShape) { - dafnyNonNormalizedModel = model; - awsNormalizedModel = AddOperationShapes.execute(model, serviceShape.toShapeId()); - - this.serviceShape = serviceShape; - } +public class DafnyAwsSdkClientTypeConversionProtocol + implements ProtocolGenerator { + + final Model dafnyNonNormalizedModel; + final Model awsNormalizedModel; + final ServiceShape serviceShape; + + public DafnyAwsSdkClientTypeConversionProtocol( + Model model, + ServiceShape serviceShape + ) { + dafnyNonNormalizedModel = model; + awsNormalizedModel = + AddOperationShapes.execute(model, serviceShape.toShapeId()); + + this.serviceShape = serviceShape; + } + + @Override + public ShapeId getProtocol() { + return null; + } + + @Override + public ApplicationProtocol getApplicationProtocol() { + return null; + } + + @Override + public void generateSerializers(GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var symbolProvider = context.symbolProvider(); + final var writerDelegator = context.writerDelegator(); + serviceShape + .getOperations() + .forEach(eachOperation -> { + final var awsNormalizedOperation = awsNormalizedModel.expectShape( + eachOperation, + OperationShape.class + ); + final var awsNormalizedInputShape = awsNormalizedModel.expectShape( + awsNormalizedOperation.getInputShape() + ); + if (!alreadyVisited.contains(awsNormalizedInputShape.toShapeId())) { + alreadyVisited.add(awsNormalizedInputShape.toShapeId()); + if ( + !awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) && + awsNormalizedInputShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var awsNormalizedInputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName( + serviceShape, + awsNormalizedInputShape, + "" + ); + final var awsNormalizedInputSymbol = symbolProvider.toSymbol( + awsNormalizedInputShape + ); + final var dafnyInput = dafnyNonNormalizedModel + .expectShape(eachOperation, OperationShape.class) + .getInputShape(); + final var dafnyInputSymbol = symbolProvider.toSymbol( + dafnyNonNormalizedModel.expectShape(dafnyInput) + ); + writerDelegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImport( + SmithyNameResolver.getGoModuleNameForSdkNamespace( + awsNormalizedInputShape.toShapeId().getNamespace() + ) + ); + writer.write( + """ + func $L(nativeInput $L)($L) { + ${C|} + }""", + awsNormalizedInputToDafnyMethodName, + SmithyNameResolver.getSmithyTypeAws( + serviceShape.expectTrait(ServiceTrait.class), + awsNormalizedInputSymbol, + false + ), + DafnyNameResolver.getDafnyType( + dafnyNonNormalizedModel.expectShape(dafnyInput), + dafnyInputSymbol + ), + writer.consumer(w -> + generateRequestSerializer( + context, + awsNormalizedOperation, + context.writerDelegator() + ) + ) + ); + } + ); + } + } - @Override - public ShapeId getProtocol() { - return null; - } + final var awsNormalizedOutputShape = awsNormalizedModel.expectShape( + awsNormalizedOperation.getOutputShape() + ); + if (!alreadyVisited.contains(awsNormalizedOutputShape.toShapeId())) { + alreadyVisited.add(awsNormalizedOutputShape.toShapeId()); + if ( + !awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class) && + awsNormalizedOutputShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var awsNormalizedOutputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName( + serviceShape, + awsNormalizedOutputShape, + "" + ); + final var awsNormalizedOutputSymbol = symbolProvider.toSymbol( + awsNormalizedOutputShape + ); + final var dafnyOutput = dafnyNonNormalizedModel + .expectShape(eachOperation, OperationShape.class) + .getOutputShape(); + final var dafnyOutputSymbol = symbolProvider.toSymbol( + dafnyNonNormalizedModel.expectShape(dafnyOutput) + ); + writerDelegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImport( + SmithyNameResolver.getGoModuleNameForSdkNamespace( + awsNormalizedInputShape.toShapeId().getNamespace() + ) + ); + writer.write( + """ + func $L(nativeOutput $L)($L) { + ${C|} + }""", + awsNormalizedOutputToDafnyMethodName, + SmithyNameResolver.getSmithyTypeAws( + serviceShape.expectTrait(ServiceTrait.class), + awsNormalizedOutputSymbol, + false + ), + DafnyNameResolver.getDafnyType( + dafnyNonNormalizedModel.expectShape(dafnyOutput), + dafnyOutputSymbol + ), + writer.consumer(w -> + generateResponseSerializer( + context, + awsNormalizedOperation, + context.writerDelegator() + ) + ) + ); + } + ); + } + } + }); + generateErrorSerializer(context); + } + + @Override + public void generateDeserializers(GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var symbolProvider = context.symbolProvider(); + final var delegator = context.writerDelegator(); + + serviceShape + .getOperations() + .forEach(eachOperation -> { + final var awsNormalizedOperationShape = awsNormalizedModel.expectShape( + eachOperation, + OperationShape.class + ); + final var awsNormalizedInputShape = awsNormalizedModel.expectShape( + awsNormalizedOperationShape.getInputShape() + ); + if (!alreadyVisited.contains(awsNormalizedInputShape.toShapeId())) { + alreadyVisited.add(awsNormalizedInputShape.toShapeId()); + if ( + !awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) && + awsNormalizedInputShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var awsNormalizedInputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + awsNormalizedInputShape, + "" + ); + final var awsNormalizedInputSymbol = symbolProvider.toSymbol( + awsNormalizedInputShape + ); + final var dafnyInput = dafnyNonNormalizedModel + .expectShape(eachOperation, OperationShape.class) + .getInputShape(); + final var dafnyInputSymbol = symbolProvider.toSymbol( + dafnyNonNormalizedModel.expectShape(dafnyInput) + ); + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImport( + SmithyNameResolver.getGoModuleNameForSdkNamespace( + awsNormalizedInputShape.toShapeId().getNamespace() + ) + ); + writer.write( + """ + func $L(dafnyInput $L)($L) { + ${C|} + }""", + awsNormalizedInputFromDafnyMethodName, + DafnyNameResolver.getDafnyType( + dafnyNonNormalizedModel.expectShape(dafnyInput), + dafnyInputSymbol + ), + SmithyNameResolver.getSmithyTypeAws( + serviceShape.expectTrait(ServiceTrait.class), + awsNormalizedInputSymbol, + false + ), + writer.consumer(w -> + generateRequestDeserializer( + context, + awsNormalizedOperationShape, + context.writerDelegator() + ) + ) + ); + } + ); + } + } - @Override - public ApplicationProtocol getApplicationProtocol() { - return null; - } + final var awsNormalizedOutputShape = awsNormalizedModel.expectShape( + awsNormalizedOperationShape.getOutputShape() + ); + if (!alreadyVisited.contains(awsNormalizedOutputShape.toShapeId())) { + alreadyVisited.add(awsNormalizedOutputShape.toShapeId()); + if ( + !awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class) && + awsNormalizedOutputShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var awsNormalizedOutputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + awsNormalizedOutputShape, + "" + ); + final var awsNormalizedOutputSymbol = context + .symbolProvider() + .toSymbol(awsNormalizedOutputShape); + final var dafnyOutput = dafnyNonNormalizedModel + .expectShape(eachOperation, OperationShape.class) + .getOutputShape(); + final var dafnyOutputSymbol = symbolProvider.toSymbol( + dafnyNonNormalizedModel.expectShape(dafnyOutput) + ); + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImport( + SmithyNameResolver.getGoModuleNameForSdkNamespace( + awsNormalizedInputShape.toShapeId().getNamespace() + ) + ); + writer.write( + """ + func $L(dafnyOutput $L)($L) { + ${C|} + }""", + awsNormalizedOutputFromDafnyMethodName, + DafnyNameResolver.getDafnyType( + dafnyNonNormalizedModel.expectShape(dafnyOutput), + dafnyOutputSymbol + ), + SmithyNameResolver.getSmithyTypeAws( + serviceShape.expectTrait(ServiceTrait.class), + awsNormalizedOutputSymbol, + false + ), + writer.consumer(w -> + generateResponseDeserializer( + context, + awsNormalizedOperationShape, + context.writerDelegator() + ) + ) + ); + } + ); + } + } + }); + + generateErrorDeserializer(context); + } + + private void generateRequestSerializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + final var nonNormalizedOperation = dafnyNonNormalizedModel.expectShape( + operation.toShapeId(), + OperationShape.class + ); + final var targetShape = dafnyNonNormalizedModel.expectShape( + nonNormalizedOperation.getInputShape() + ); + delegator.useFileWriter( + "%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var input = targetShape.accept( + new AwsSdkToDafnyShapeVisitor( + context, + "nativeInput", + writer, + false, + false, + false + ) + ); + writer.write( + """ + return $L + """, + input + ); + } + ); + } + + private void generateResponseSerializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + final var nonNormalizedOperation = dafnyNonNormalizedModel.expectShape( + operation.toShapeId(), + OperationShape.class + ); + final var targetShape = dafnyNonNormalizedModel.expectShape( + nonNormalizedOperation.getOutputShape() + ); + delegator.useFileWriter( + "%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var input = targetShape.accept( + new AwsSdkToDafnyShapeVisitor( + context, + "nativeOutput", + writer, + false, + false, + false + ) + ); + writer.write( + """ + return $L + """, + input + ); + } + ); + } + + private void generateRequestDeserializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(operation), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var inputShape = operation.getInputShape(); + + final var targetShape = awsNormalizedModel.expectShape(inputShape); + final var input = targetShape.accept( + new DafnyToAwsSdkShapeVisitor(context, "dafnyInput", writer) + ); - @Override - public void generateSerializers(GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var symbolProvider = context.symbolProvider(); - final var writerDelegator = context.writerDelegator(); - serviceShape.getOperations().forEach(eachOperation -> { - final var awsNormalizedOperation = awsNormalizedModel.expectShape(eachOperation, OperationShape.class); - final var awsNormalizedInputShape = awsNormalizedModel.expectShape(awsNormalizedOperation.getInputShape()); - if (!alreadyVisited.contains(awsNormalizedInputShape.toShapeId())) { - alreadyVisited.add(awsNormalizedInputShape.toShapeId()); - if (!awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) && awsNormalizedInputShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var awsNormalizedInputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, awsNormalizedInputShape, ""); - final var awsNormalizedInputSymbol = symbolProvider.toSymbol(awsNormalizedInputShape); - final var dafnyInput = dafnyNonNormalizedModel.expectShape(eachOperation, OperationShape.class).getInputShape(); - final var dafnyInputSymbol = symbolProvider.toSymbol(dafnyNonNormalizedModel.expectShape(dafnyInput)); - writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedInputShape.toShapeId().getNamespace())); - writer.write(""" - func $L(nativeInput $L)($L) { - ${C|} - }""", awsNormalizedInputToDafnyMethodName, SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), awsNormalizedInputSymbol, false), - DafnyNameResolver.getDafnyType(dafnyNonNormalizedModel.expectShape(dafnyInput), dafnyInputSymbol), - writer.consumer(w -> generateRequestSerializer(context, awsNormalizedOperation, context.writerDelegator()))); - }); - } - } + writer.write( + """ + return $L + """, + input + ); + } + ); + } + + private void generateResponseDeserializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(operation), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var outputShape = operation.getOutputShape(); + + final var targetShape = awsNormalizedModel.expectShape(outputShape); + final var output = targetShape.accept( + new DafnyToAwsSdkShapeVisitor(context, "dafnyOutput", writer) + ); - final var awsNormalizedOutputShape = awsNormalizedModel.expectShape(awsNormalizedOperation.getOutputShape()); - if (!alreadyVisited.contains(awsNormalizedOutputShape.toShapeId())) { - alreadyVisited.add(awsNormalizedOutputShape.toShapeId()); - if (!awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class) && awsNormalizedOutputShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var awsNormalizedOutputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, awsNormalizedOutputShape, ""); - final var awsNormalizedOutputSymbol = symbolProvider.toSymbol(awsNormalizedOutputShape); - final var dafnyOutput = dafnyNonNormalizedModel.expectShape(eachOperation, OperationShape.class).getOutputShape(); - final var dafnyOutputSymbol = symbolProvider.toSymbol(dafnyNonNormalizedModel.expectShape(dafnyOutput)); - writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedInputShape.toShapeId().getNamespace())); - writer.write(""" - func $L(nativeOutput $L)($L) { - ${C|} - }""", awsNormalizedOutputToDafnyMethodName, - SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), awsNormalizedOutputSymbol, false), - DafnyNameResolver.getDafnyType(dafnyNonNormalizedModel.expectShape(dafnyOutput), dafnyOutputSymbol), - writer.consumer(w -> generateResponseSerializer(context, awsNormalizedOperation, context.writerDelegator()))); - }); - } + writer.write( + """ + return $L + """, + output + ); + } + ); + } + + private void generateErrorSerializer(final GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var errorShapes = awsNormalizedModel.getShapesWithTrait( + ErrorTrait.class + ); + + for (final var errorShape : errorShapes) { + if ( + !errorShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + continue; + } + if (!alreadyVisited.contains(errorShape.toShapeId())) { + alreadyVisited.add(errorShape.toShapeId()); + final var getInputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName(serviceShape, errorShape, ""); + + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(errorShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(errorShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSdkNamespace( + errorShape.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespaceAws( + serviceShape.expectTrait(ServiceTrait.class), + true + ) + ); + writer.write( + """ + func $L(nativeInput types.$L)($L) { + ${C|} + }""", + getInputToDafnyMethodName, + context.symbolProvider().toSymbol(errorShape).getName(), + DafnyNameResolver.getDafnyBaseErrorType(errorShape), + writer.consumer(w -> { + String output = errorShape.accept( + new AwsSdkToDafnyShapeVisitor( + context, + "nativeInput", + writer, + false, + false, + false + ) + ); + writer.write( + """ + return $L + """, + output + ); + }) + ); } - }); - generateErrorSerializer(context); + ); + } } - @Override - public void generateDeserializers(GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var symbolProvider = context.symbolProvider(); - final var delegator = context.writerDelegator(); - - serviceShape.getOperations().forEach(eachOperation -> { - final var awsNormalizedOperationShape = awsNormalizedModel.expectShape(eachOperation, OperationShape.class); - final var awsNormalizedInputShape = awsNormalizedModel.expectShape(awsNormalizedOperationShape.getInputShape()); - if (!alreadyVisited.contains(awsNormalizedInputShape.toShapeId())) { - alreadyVisited.add(awsNormalizedInputShape.toShapeId()); - if (!awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) && awsNormalizedInputShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var awsNormalizedInputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, awsNormalizedInputShape, ""); - final var awsNormalizedInputSymbol = symbolProvider.toSymbol(awsNormalizedInputShape); - final var dafnyInput = dafnyNonNormalizedModel.expectShape(eachOperation, OperationShape.class).getInputShape(); - final var dafnyInputSymbol = symbolProvider.toSymbol(dafnyNonNormalizedModel.expectShape(dafnyInput)); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedInputShape.toShapeId().getNamespace())); - writer.write(""" - func $L(dafnyInput $L)($L) { - ${C|} - }""", awsNormalizedInputFromDafnyMethodName, DafnyNameResolver.getDafnyType(dafnyNonNormalizedModel.expectShape(dafnyInput), dafnyInputSymbol), - SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), awsNormalizedInputSymbol, false), - writer.consumer(w -> generateRequestDeserializer(context, awsNormalizedOperationShape, context.writerDelegator()))); - }); + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.write( + """ + func OpaqueError_Input_ToDafny(nativeInput error)($L.Error) { + return $L.Companion_Error_.Create_Opaque_(nativeInput) + }""", + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape) + ); + } + ); + + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.write( + """ + func Error_ToDafny(err error)($L.Error) { + switch err.(type) { + // Service Errors + ${C|} + + default: + return OpaqueError_Input_ToDafny(err) } } - - final var awsNormalizedOutputShape = awsNormalizedModel.expectShape(awsNormalizedOperationShape.getOutputShape()); - if (!alreadyVisited.contains(awsNormalizedOutputShape.toShapeId())) { - alreadyVisited.add(awsNormalizedOutputShape.toShapeId()); - if (!awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class) && awsNormalizedOutputShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var awsNormalizedOutputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, awsNormalizedOutputShape, ""); - final var awsNormalizedOutputSymbol = context.symbolProvider().toSymbol(awsNormalizedOutputShape); - final var dafnyOutput = dafnyNonNormalizedModel.expectShape(eachOperation, OperationShape.class).getOutputShape(); - final var dafnyOutputSymbol = symbolProvider.toSymbol(dafnyNonNormalizedModel.expectShape(dafnyOutput)); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedInputShape.toShapeId().getNamespace())); - writer.write(""" - func $L(dafnyOutput $L)($L) { - ${C|} - }""", awsNormalizedOutputFromDafnyMethodName, DafnyNameResolver.getDafnyType(dafnyNonNormalizedModel.expectShape(dafnyOutput), dafnyOutputSymbol), - SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), awsNormalizedOutputSymbol, false), - writer.consumer(w -> generateResponseDeserializer(context, awsNormalizedOperationShape, context.writerDelegator()))); - }); - } + """, + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + writer.consumer(w -> { + for (var error : errorShapes) { + w.write( + """ + case *$L: + return $L(*err.(*$L)) + """, + SmithyNameResolver.getSmithyTypeAws( + serviceShape.expectTrait(ServiceTrait.class), + context + .symbolProvider() + .toSymbol( + awsNormalizedModel.expectShape(error.toShapeId()) + ), + true + ), + SmithyNameResolver.getToDafnyMethodName( + serviceShape, + awsNormalizedModel.expectShape(error.toShapeId()), + "" + ), + SmithyNameResolver.getSmithyTypeAws( + serviceShape.expectTrait(ServiceTrait.class), + context + .symbolProvider() + .toSymbol( + awsNormalizedModel.expectShape(error.toShapeId()) + ), + true + ) + ); + } + }) + ); + } + ); + } + + private void generateErrorDeserializer(final GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var errorShapes = awsNormalizedModel.getShapesWithTrait( + ErrorTrait.class + ); + for (final var errorShape : errorShapes) { + if ( + !errorShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + continue; + } + if (!alreadyVisited.contains(errorShape.toShapeId())) { + alreadyVisited.add(errorShape.toShapeId()); + final var getOutputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + errorShape, + "" + ); + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(errorShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(errorShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSdkNamespace( + errorShape.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespaceAws( + serviceShape.expectTrait(ServiceTrait.class), + true + ) + ); + writer.write( + """ + func $L(dafnyOutput $L)(types.$L) { + ${C|} + }""", + getOutputFromDafnyMethodName, + DafnyNameResolver.getDafnyBaseErrorType(errorShape), + context.symbolProvider().toSymbol(errorShape).getName(), + writer.consumer(w -> { + String output = errorShape.accept( + new DafnyToAwsSdkShapeVisitor( + context, + "dafnyOutput", + writer + ) + ); + writer.write( + """ + return $L + """, + output + ); + }) + ); } - }); - - generateErrorDeserializer(context); - - } - - private void generateRequestSerializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - final var nonNormalizedOperation = dafnyNonNormalizedModel.expectShape(operation.toShapeId(), OperationShape.class); - final var targetShape = dafnyNonNormalizedModel.expectShape(nonNormalizedOperation.getInputShape()); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), SmithyNameResolver.shapeNamespace(operation), writer -> { - final var input = targetShape.accept(new AwsSdkToDafnyShapeVisitor( - context, - "nativeInput", - writer, - false, false, false - )); - writer.write(""" - return $L - """, - input); - } - ); - } - - private void generateResponseSerializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - final var nonNormalizedOperation = dafnyNonNormalizedModel.expectShape(operation.toShapeId(), OperationShape.class); - final var targetShape = dafnyNonNormalizedModel.expectShape(nonNormalizedOperation.getOutputShape()); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), SmithyNameResolver.shapeNamespace(operation), writer -> { - final var input = targetShape.accept(new AwsSdkToDafnyShapeVisitor( - context, - "nativeOutput", - writer, - false, false, false - )); - writer.write(""" - return $L - """, - input); - } - ); - } - - private void generateRequestDeserializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_NATIVE), SmithyNameResolver.shapeNamespace(operation), writer -> { - - final var inputShape = operation.getInputShape(); - - final var targetShape = awsNormalizedModel.expectShape(inputShape); - final var input = targetShape.accept(new DafnyToAwsSdkShapeVisitor( - context, - "dafnyInput", - writer - )); - - writer.write(""" - return $L - """, input); - }); + ); + } } - private void generateResponseDeserializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_NATIVE), SmithyNameResolver.shapeNamespace(operation), writer -> { - - final var outputShape = operation.getOutputShape(); - - final var targetShape = awsNormalizedModel.expectShape(outputShape); - final var output = targetShape.accept(new DafnyToAwsSdkShapeVisitor( - context, - "dafnyOutput", - writer - )); - - writer.write(""" - return $L - """, output); - }); - } - - private void generateErrorSerializer(final GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var errorShapes = awsNormalizedModel.getShapesWithTrait(ErrorTrait.class); - - for (final var errorShape : - errorShapes) { - if (!errorShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - continue; - } - if (!alreadyVisited.contains(errorShape.toShapeId())) { - alreadyVisited.add(errorShape.toShapeId()); - final var getInputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, errorShape, ""); - - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(errorShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(errorShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSdkNamespace(errorShape.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespaceAws(serviceShape.expectTrait(ServiceTrait.class), true)); - writer.write(""" - func $L(nativeInput types.$L)($L) { - ${C|} - }""", - getInputToDafnyMethodName, context.symbolProvider().toSymbol(errorShape).getName(), DafnyNameResolver.getDafnyBaseErrorType(errorShape), - writer.consumer(w -> { - String output = errorShape.accept(new AwsSdkToDafnyShapeVisitor( - context, - "nativeInput", - writer, - false, false, false - )); - writer.write(""" - return $L - """, output); - })); - }); - } + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addUseImports(SmithyGoDependency.FMT); + writer.write( + """ + func OpaqueError_Output_FromDafny(dafnyOutput $L.Error)(error) { + return fmt.Errorf(fmt.Sprintf("%v", dafnyOutput.Dtor_obj())) + }""", + DafnyNameResolver.dafnyTypesNamespace(serviceShape) + ); } - - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.write(""" - func OpaqueError_Input_ToDafny(nativeInput error)($L.Error) { - return $L.Companion_Error_.Create_Opaque_(nativeInput) - }""", DafnyNameResolver.dafnyTypesNamespace(serviceShape), DafnyNameResolver.dafnyTypesNamespace(serviceShape)); - }); - - - context.writerDelegator() - .useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), - SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.write(""" - func Error_ToDafny(err error)($L.Error) { - switch err.(type) { - // Service Errors - ${C|} - - default: - return OpaqueError_Input_ToDafny(err) - } - } - """, DafnyNameResolver.dafnyTypesNamespace(serviceShape), - writer.consumer(w -> { - for (var error : errorShapes) { - w.write(""" - case *$L: - return $L(*err.(*$L)) - """, SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), context.symbolProvider().toSymbol(awsNormalizedModel.expectShape(error.toShapeId())), true), - SmithyNameResolver.getToDafnyMethodName(serviceShape, awsNormalizedModel.expectShape(error.toShapeId()), ""), - SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), context.symbolProvider().toSymbol(awsNormalizedModel.expectShape(error.toShapeId())), true)); - } - }) - ); - }); - } - - private void generateErrorDeserializer(final GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var errorShapes = awsNormalizedModel.getShapesWithTrait(ErrorTrait.class); - for (final var errorShape : - errorShapes) { - if (!errorShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - continue; - } - if (!alreadyVisited.contains(errorShape.toShapeId())) { - alreadyVisited.add(errorShape.toShapeId()); - final var getOutputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, errorShape, ""); - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(errorShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(errorShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSdkNamespace(errorShape.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespaceAws(serviceShape.expectTrait(ServiceTrait.class), true)); - writer.write(""" - func $L(dafnyOutput $L)(types.$L) { - ${C|} - }""", - getOutputFromDafnyMethodName, DafnyNameResolver.getDafnyBaseErrorType(errorShape), context.symbolProvider().toSymbol(errorShape).getName(), - writer.consumer(w -> { - String output = errorShape.accept(new DafnyToAwsSdkShapeVisitor( - context, - "dafnyOutput", - writer - )); - writer.write(""" - return $L - """, output); - })); - }); + ); + + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.write( + """ + func Error_FromDafny(err $L.Error)(error) { + // Service Errors + ${C|} + + return OpaqueError_Output_FromDafny(err) } + """, + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + writer.consumer(w -> { + for (var error : awsNormalizedModel.getShapesWithTrait( + ErrorTrait.class + )) { + w.write( + """ + if err.Is_$L() { + e := $L(err) + return &e + } + """, + error.toShapeId().getName(), + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + awsNormalizedModel.expectShape(error.toShapeId()), + "" + ) + ); + } + }) + ); } - - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addUseImports(SmithyGoDependency.FMT); - writer.write(""" - func OpaqueError_Output_FromDafny(dafnyOutput $L.Error)(error) { - return fmt.Errorf(fmt.Sprintf("%v", dafnyOutput.Dtor_obj())) - }""", - DafnyNameResolver.dafnyTypesNamespace(serviceShape)); - }); - - context.writerDelegator() - .useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), - SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.write(""" - func Error_FromDafny(err $L.Error)(error) { - // Service Errors - ${C|} - - return OpaqueError_Output_FromDafny(err) - } - """, DafnyNameResolver.dafnyTypesNamespace(serviceShape), - writer.consumer(w -> { - for (var error : awsNormalizedModel.getShapesWithTrait(ErrorTrait.class)) { - w.write(""" - if err.Is_$L() { - e := $L(err) - return &e - } - """, error.toShapeId().getName(), SmithyNameResolver.getFromDafnyMethodName(serviceShape, awsNormalizedModel.expectShape(error.toShapeId()), "")); - } - }) - ); - }); - } + ); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkClientCodegenPlugin.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkClientCodegenPlugin.java index a8ef0ae239..1398a55c1c 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkClientCodegenPlugin.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkClientCodegenPlugin.java @@ -1,5 +1,6 @@ package software.amazon.polymorph.smithygo.awssdk; +import java.util.Map; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoSettings; import software.amazon.polymorph.smithygo.codegen.GoWriter; @@ -9,52 +10,59 @@ import software.amazon.smithy.build.SmithyBuildPlugin; import software.amazon.smithy.codegen.core.directed.CodegenDirector; -import java.util.Map; - public class DafnyGoAwsSdkClientCodegenPlugin implements SmithyBuildPlugin { - public DafnyGoAwsSdkClientCodegenPlugin(final Map smithyNamespaceToPythonModuleNameMap) { - super(); - SmithyNameResolver.setSmithyNamespaceToGoModuleNameMap(smithyNamespaceToPythonModuleNameMap); - } + public DafnyGoAwsSdkClientCodegenPlugin( + final Map smithyNamespaceToPythonModuleNameMap + ) { + super(); + SmithyNameResolver.setSmithyNamespaceToGoModuleNameMap( + smithyNamespaceToPythonModuleNameMap + ); + } - @Override - public String getName() { - return "dafny-go-aws-sdk-client-codegen"; } + @Override + public String getName() { + return "dafny-go-aws-sdk-client-codegen"; + } - public void run(PluginContext context) { - CodegenDirector runner - = new CodegenDirector<>(); + public void run(PluginContext context) { + CodegenDirector< + GoWriter, + GoIntegration, + GenerationContext, + GoSettings + > runner = new CodegenDirector<>(); - runner.directedCodegen(new DafnyGoAwsSdkDirectedCodegen()); + runner.directedCodegen(new DafnyGoAwsSdkDirectedCodegen()); - // Set the SmithyIntegration class to look for and apply using SPI. - runner.integrationClass(GoIntegration.class); + // Set the SmithyIntegration class to look for and apply using SPI. + runner.integrationClass(GoIntegration.class); - // Set the FileManifest and Model from the plugin. - runner.fileManifest(context.getFileManifest()); + // Set the FileManifest and Model from the plugin. + runner.fileManifest(context.getFileManifest()); - // Create the GoSettings object from the plugin settings. - GoSettings settings = GoSettings.from(context.getSettings()); - runner.settings(settings); + // Create the GoSettings object from the plugin settings. + GoSettings settings = GoSettings.from(context.getSettings()); + runner.settings(settings); - runner.model(context.getModel()); + runner.model(context.getModel()); - runner.service(settings.getService()); + runner.service(settings.getService()); - // Configure the director to perform some common model transforms. - runner.performDefaultCodegenTransforms(); + // Configure the director to perform some common model transforms. + runner.performDefaultCodegenTransforms(); - // TODO: Not using below because it would break existing AWS SDKs. Maybe it should be configurable - // so generic SDKs call this by default, but AWS SDKs can opt-out of it via a setting. - // runner.createDedicatedInputsAndOutputs(); + // TODO: Not using below because it would break existing AWS SDKs. Maybe it should be configurable + // so generic SDKs call this by default, but AWS SDKs can opt-out of it via a setting. + // runner.createDedicatedInputsAndOutputs(); - // Run it! - runner.run(); - } + // Run it! + runner.run(); + } - @Override - public void execute(PluginContext context) { - this.run(context); - } + @Override + public void execute(PluginContext context) { + this.run(context); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkDirectedCodegen.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkDirectedCodegen.java index 16798586aa..ddbccecbe4 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkDirectedCodegen.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkDirectedCodegen.java @@ -16,62 +16,84 @@ import software.amazon.smithy.codegen.core.directed.GenerateStructureDirective; import software.amazon.smithy.codegen.core.directed.GenerateUnionDirective; -public class DafnyGoAwsSdkDirectedCodegen implements DirectedCodegen { - @Override - public SymbolProvider createSymbolProvider(CreateSymbolProviderDirective directive) { - return new SymbolVisitor(directive.model(), directive.settings()); +public class DafnyGoAwsSdkDirectedCodegen + implements DirectedCodegen { + + @Override + public SymbolProvider createSymbolProvider( + CreateSymbolProviderDirective directive + ) { + return new SymbolVisitor(directive.model(), directive.settings()); + } + + @Override + public GenerationContext createContext( + CreateContextDirective directive + ) { + return GenerationContext + .builder() + .model(directive.model()) + .settings(directive.settings()) + .symbolProvider(directive.symbolProvider()) + .fileManifest(directive.fileManifest()) + .integrations(directive.integrations()) + .writerDelegator( + new GoDelegator(directive.fileManifest(), directive.symbolProvider()) + ) + .protocolGenerator( + new DafnyAwsSdkClientTypeConversionProtocol( + directive.model(), + directive.service() + ) + ) + .build(); + } + + @Override + public void generateService( + GenerateServiceDirective directive + ) { + new DafnyAwsSdkClientShimGenerator(directive.context(), directive.service()) + .run(); + + var protocolGenerator = directive.context().protocolGenerator(); + if (protocolGenerator == null) { + return; } - @Override - public GenerationContext createContext(CreateContextDirective directive) { - return GenerationContext.builder() - .model(directive.model()) - .settings(directive.settings()) - .symbolProvider(directive.symbolProvider()) - .fileManifest(directive.fileManifest()) - .integrations(directive.integrations()) - .writerDelegator(new GoDelegator(directive.fileManifest(), directive.symbolProvider())) - .protocolGenerator(new DafnyAwsSdkClientTypeConversionProtocol(directive.model(), directive.service())) - .build(); - } - - @Override - public void generateService(GenerateServiceDirective directive) { - new DafnyAwsSdkClientShimGenerator(directive.context(), directive.service()).run(); - - var protocolGenerator = directive.context().protocolGenerator(); - if (protocolGenerator == null) { - return; - } - - protocolGenerator.generateSerializers(directive.context()); - - protocolGenerator.generateDeserializers(directive.context()); - - } - - @Override - public void generateStructure(GenerateStructureDirective generateStructureDirective) { - - } - - @Override - public void generateError(GenerateErrorDirective generateErrorDirective) { - - } - - @Override - public void generateUnion(GenerateUnionDirective generateUnionDirective) { - - } - - @Override - public void generateEnumShape(GenerateEnumDirective generateEnumDirective) { - - } - - @Override - public void generateIntEnumShape(GenerateIntEnumDirective generateIntEnumDirective) { - - } + protocolGenerator.generateSerializers(directive.context()); + + protocolGenerator.generateDeserializers(directive.context()); + } + + @Override + public void generateStructure( + GenerateStructureDirective< + GenerationContext, + GoSettings + > generateStructureDirective + ) {} + + @Override + public void generateError( + GenerateErrorDirective generateErrorDirective + ) {} + + @Override + public void generateUnion( + GenerateUnionDirective generateUnionDirective + ) {} + + @Override + public void generateEnumShape( + GenerateEnumDirective generateEnumDirective + ) {} + + @Override + public void generateIntEnumShape( + GenerateIntEnumDirective< + GenerationContext, + GoSettings + > generateIntEnumDirective + ) {} } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/AwsSdkToDafnyShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/AwsSdkToDafnyShapeVisitor.java index 62d13f66b3..d89e542548 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/AwsSdkToDafnyShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/AwsSdkToDafnyShapeVisitor.java @@ -1,5 +1,7 @@ package software.amazon.polymorph.smithygo.awssdk.shapevisitor; +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + import software.amazon.polymorph.smithygo.awssdk.AwsSdkGoPointableIndex; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoWriter; @@ -26,394 +28,538 @@ import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.utils.StringUtils; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - public class AwsSdkToDafnyShapeVisitor extends ShapeVisitor.Default { - private final GenerationContext context; - private final String dataSource; - private final GoWriter writer; - private final boolean isConfigShape; - private final boolean isOptional; - protected boolean isPointerType; - - public void setPointerType() { - this.isPointerType = false; + private final GenerationContext context; + private final String dataSource; + private final GoWriter writer; + private final boolean isConfigShape; + + private final boolean isOptional; + protected boolean isPointerType; + + public void setPointerType() { + this.isPointerType = false; + } + + public AwsSdkToDafnyShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isConfigShape, + final boolean isOptional, + final boolean isPointerType + ) { + this.context = context; + this.dataSource = dataSource; + this.writer = writer; + this.isConfigShape = isConfigShape; + this.isOptional = isOptional; + this.isPointerType = isPointerType; + } + + @Override + protected String getDefault(Shape shape) { + throw new CodegenException( + String.format( + "Unsupported conversion of %s to %s using the %s protocol", + shape, + shape.getType(), + context.protocolGenerator().getName() + ) + ); + } + + @Override + public String blobShape(BlobShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - - public AwsSdkToDafnyShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isConfigShape, - final boolean isOptional, - final boolean isPointerType - ) { - this.context = context; - this.dataSource = dataSource; - this.writer = writer; - this.isConfigShape = isConfigShape; - this.isOptional = isOptional; - this.isPointerType = isPointerType; + return """ + func () %s { + var v []interface{} + if %s == nil {return %s} + for _, e := range %s { + v = append(v, e) + } + return %s; + }()""".formatted( + returnType, + dataSource, + nilWrapIfRequired, + dataSource, + someWrapIfRequired.formatted("dafny.SeqOf(v...)") + ); + } + + @Override + public String structureShape(final StructureShape shape) { + final var builder = new StringBuilder(); + writer.addImportFromModule( + "github.com/dafny-lang/DafnyStandardLibGo", + "Wrappers" + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + shape.toShapeId().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(shape) + ); + + String someWrapIfRequired = "%s"; + + String companionStruct; + String returnType; + if (shape.hasTrait(ErrorTrait.class)) { + companionStruct = + DafnyNameResolver.getDafnyErrorCompanionCreate( + shape, + context.symbolProvider().toSymbol(shape) + ); + returnType = DafnyNameResolver.getDafnyBaseErrorType(shape); + } else { + companionStruct = + DafnyNameResolver.getDafnyCompanionTypeCreate( + shape, + context.symbolProvider().toSymbol(shape) + ); + returnType = + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ); } + String nilWrapIfRequired = returnType.concat("{}"); - @Override - protected String getDefault(Shape shape) { - throw new CodegenException(String.format( - "Unsupported conversion of %s to %s using the %s protocol", - shape, shape.getType(), context.protocolGenerator().getName())); + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - @Override - public String blobShape(BlobShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - return """ - func () %s { - var v []interface{} - if %s == nil {return %s} - for _, e := range %s { - v = append(v, e) - } - return %s; - }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, someWrapIfRequired.formatted("dafny.SeqOf(v...)")); + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); } - - @Override - public String structureShape(final StructureShape shape) { - final var builder = new StringBuilder(); - writer.addImportFromModule("github.com/dafny-lang/DafnyStandardLibGo", "Wrappers"); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(shape.toShapeId().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(shape)); - - String someWrapIfRequired = "%s"; - - String companionStruct; - String returnType; - if (shape.hasTrait(ErrorTrait.class)) { - companionStruct = DafnyNameResolver.getDafnyErrorCompanionCreate(shape, context.symbolProvider().toSymbol(shape)); - returnType = DafnyNameResolver.getDafnyBaseErrorType(shape); - } else { - companionStruct = DafnyNameResolver.getDafnyCompanionTypeCreate(shape, context.symbolProvider().toSymbol(shape)); - returnType = DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)); - } - String nilWrapIfRequired = returnType.concat("{}"); - - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - var goCodeBlock = """ - func () %s { - %s - return %s - }()"""; - - - builder.append("%1$s(".formatted(companionStruct)); - String fieldSeparator = ","; - for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { - final var memberName = memberShapeEntry.getKey(); - final var memberShape = memberShapeEntry.getValue(); - final var targetShape = context.model().expectShape(memberShape.getTarget()); - builder.append("%1$s%2$s".formatted( - targetShape.accept( - new AwsSdkToDafnyShapeVisitor(context, dataSource + "." + StringUtils.capitalize(memberName), - writer, isConfigShape, memberShape.isOptional(), AwsSdkGoPointableIndex.of(context.model()).isPointable(memberShape) - )), fieldSeparator - )); - } - - - return goCodeBlock.formatted(returnType, nilCheck, someWrapIfRequired.formatted(builder.append(")").toString())); + var goCodeBlock = + """ + func () %s { + %s + return %s + }()"""; + + builder.append("%1$s(".formatted(companionStruct)); + String fieldSeparator = ","; + for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { + final var memberName = memberShapeEntry.getKey(); + final var memberShape = memberShapeEntry.getValue(); + final var targetShape = context + .model() + .expectShape(memberShape.getTarget()); + builder.append( + "%1$s%2$s".formatted( + targetShape.accept( + new AwsSdkToDafnyShapeVisitor( + context, + dataSource + "." + StringUtils.capitalize(memberName), + writer, + isConfigShape, + memberShape.isOptional(), + AwsSdkGoPointableIndex + .of(context.model()) + .isPointable(memberShape) + ) + ), + fieldSeparator + ) + ); } - @Override - public String mapShape(MapShape shape) { - StringBuilder builder = new StringBuilder(); - - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - MemberShape keyMemberShape = shape.getKey(); - final Shape keyTargetShape = context.model().expectShape(keyMemberShape.getTarget()); - MemberShape valueMemberShape = shape.getValue(); - final Shape valueTargetShape = context.model().expectShape(valueMemberShape.getTarget()); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Map"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - builder.append(""" - func () %s { - %s - fieldValue := dafny.NewMapBuilder() - for key, val := range %s { - fieldValue.Add(%s, %s) - } - return %s - }()""".formatted(returnType, nilCheck, dataSource, - keyTargetShape.accept( - new AwsSdkToDafnyShapeVisitor(context, "key", writer, isConfigShape, false, false)), - valueTargetShape.accept( - new AwsSdkToDafnyShapeVisitor(context, "val", writer, isConfigShape, false, false)), - someWrapIfRequired.formatted("fieldValue.ToMap()") - ) - ); - - // Close structure - return builder.toString(); - + return goCodeBlock.formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(builder.append(")").toString()) + ); + } + + @Override + public String mapShape(MapShape shape) { + StringBuilder builder = new StringBuilder(); + + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + MemberShape keyMemberShape = shape.getKey(); + final Shape keyTargetShape = context + .model() + .expectShape(keyMemberShape.getTarget()); + MemberShape valueMemberShape = shape.getValue(); + final Shape valueTargetShape = context + .model() + .expectShape(valueMemberShape.getTarget()); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Map"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - - @Override - public String listShape(ListShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - StringBuilder builder = new StringBuilder(); - - MemberShape memberShape = shape.getMember(); - final Shape targetShape = context.model().expectShape(memberShape.getTarget()); - - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - - builder.append(""" - func () %s { - if %s == nil { return %s } - var fieldValue []interface{} = make([]interface{}, 0) - for _, val := range %s { - element := %s - fieldValue = append(fieldValue, element) - } - return %s - }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, - targetShape.accept( - new AwsSdkToDafnyShapeVisitor(context, "val", writer, isConfigShape, false, false) - ), someWrapIfRequired.formatted("dafny.SeqOf(fieldValue...)"))); - - // Close structure - return builder.toString(); + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); } - - @Override - public String booleanShape(BooleanShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "false"; - String someWrapIfRequired = "%s%s"; - String returnType = "bool"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; - } - - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); + builder.append( + """ + func () %s { + %s + fieldValue := dafny.NewMapBuilder() + for key, val := range %s { + fieldValue.Add(%s, %s) + } + return %s + }()""".formatted( + returnType, + nilCheck, + dataSource, + keyTargetShape.accept( + new AwsSdkToDafnyShapeVisitor( + context, + "key", + writer, + isConfigShape, + false, + false + ) + ), + valueTargetShape.accept( + new AwsSdkToDafnyShapeVisitor( + context, + "val", + writer, + isConfigShape, + false, + false + ) + ), + someWrapIfRequired.formatted("fieldValue.ToMap()") + ) + ); + + // Close structure + return builder.toString(); + } + + @Override + public String listShape(ListShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + StringBuilder builder = new StringBuilder(); + + MemberShape memberShape = shape.getMember(); + final Shape targetShape = context + .model() + .expectShape(memberShape.getTarget()); + + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - @Override - public String stringShape(StringShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (shape.hasTrait(EnumTrait.class)) { - String someWrapIfRequired = "%s"; - String returnType = DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)); - if (this.isOptional) { - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } + builder.append( + """ + func () %s { + if %s == nil { return %s } + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range %s { + element := %s + fieldValue = append(fieldValue, element) + } + return %s + }()""".formatted( + returnType, + dataSource, + nilWrapIfRequired, + dataSource, + targetShape.accept( + new AwsSdkToDafnyShapeVisitor( + context, + "val", + writer, + isConfigShape, + false, + false + ) + ), + someWrapIfRequired.formatted("dafny.SeqOf(fieldValue...)") + ) + ); + + // Close structure + return builder.toString(); + } + + @Override + public String booleanShape(BooleanShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "false"; + String someWrapIfRequired = "%s%s"; + String returnType = "bool"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; + } - return """ - func () %s { - var index int - for _, enumVal := range %s.Values() { - index++ - if enumVal == %s{ - break; - } - } - var enum interface{} - for allEnums, i := dafny.Iterate(%s{}.AllSingletonConstructors()), 0; i < index; i++ { - var ok bool - enum, ok = allEnums() - if !ok { - break; - } - } - return %s - }()""".formatted(returnType, dataSource, dataSource, DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), someWrapIfRequired.formatted("enum.(%s)".formatted(DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))))); - } else { - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } - var nilCheck = ""; - var dereferenceIfRequired = isPointerType ? "*" : ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) + ); + } + + @Override + public String stringShape(StringShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (shape.hasTrait(EnumTrait.class)) { + String someWrapIfRequired = "%s"; + String returnType = DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ); + if (this.isOptional) { + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + return """ + func () %s { + var index int + for _, enumVal := range %s.Values() { + index++ + if enumVal == %s{ + break; + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(%s{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break; + } + } + return %s + }()""".formatted( + returnType, + dataSource, + dataSource, + DafnyNameResolver.getDafnyCompanionStructType( + shape, + context.symbolProvider().toSymbol(shape) + ), + someWrapIfRequired.formatted( + "enum.(%s)".formatted( + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ) + ) + ) + ); + } else { + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + var nilCheck = ""; + var dereferenceIfRequired = isPointerType ? "*" : ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + + if (shape.hasTrait(DafnyUtf8BytesTrait.class)) writer.addUseImports( + SmithyGoDependency.stdlib("unicode/utf8") + ); + + var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) + ? """ + dafny.SeqOf(func () []interface{} { + utf8.ValidString(%s%s) + b := []byte(%s%s) + f := make([]interface{}, len(b)) + for i, v := range b { + f[i] = v } - - if (shape.hasTrait(DafnyUtf8BytesTrait.class)) - writer.addUseImports(SmithyGoDependency.stdlib("unicode/utf8")); - - var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) ? """ - dafny.SeqOf(func () []interface{} { - utf8.ValidString(%s%s) - b := []byte(%s%s) - f := make([]interface{}, len(b)) - for i, v := range b { - f[i] = v - } - return f - }()...)""".formatted(dereferenceIfRequired, dataSource, dereferenceIfRequired, dataSource) : "dafny.SeqOfChars([]dafny.Char(%s%s)...)".formatted(dereferenceIfRequired, dataSource); - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(underlyingType)); - } + return f + }()...)""".formatted( + dereferenceIfRequired, + dataSource, + dereferenceIfRequired, + dataSource + ) + : "dafny.SeqOfChars([]dafny.Char(%s%s)...)".formatted( + dereferenceIfRequired, + dataSource + ); + + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(underlyingType) + ); } - - @Override - public String integerShape(IntegerShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "0"; - String someWrapIfRequired = "%s%s"; - String returnType = "int"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; - } - - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); - + } + + @Override + public String integerShape(IntegerShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "0"; + String someWrapIfRequired = "%s%s"; + String returnType = "int"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; } - @Override - public String longShape(LongShape shape) { - String nilWrapIfRequired = "0"; - String someWrapIfRequired = "%s%s"; - String returnType = "int64"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; - } - - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); } - @Override - public String doubleShape(DoubleShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); - writer.addUseImports(SmithyGoDependency.MATH); - - String nilWrapIfRequired = "dafny.SeqOf()"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) + ); + } + + @Override + public String longShape(LongShape shape) { + String nilWrapIfRequired = "0"; + String someWrapIfRequired = "%s%s"; + String returnType = "int64"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; + } - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } - return """ - func () %s { - %s - var bits = math.Float64bits(%s%s) - var bytes = make([]byte, 8) - binary.LittleEndian.PutUint64(bytes, bits) - var v []interface{} - for _, e := range bytes { - v = append(v, e) - } - return %s; - }()""".formatted(returnType, nilCheck, dereferenceIfRequired, dataSource, someWrapIfRequired.formatted("dafny.SeqOf(v...)")); + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) + ); + } + + @Override + public String doubleShape(DoubleShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); + writer.addUseImports(SmithyGoDependency.MATH); + + String nilWrapIfRequired = "dafny.SeqOf()"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - @Override - public String unionShape(UnionShape shape) { - return """ - func () Wrappers.Option { - _ = val - return Wrappers.Companion_Option_.Create_None_() - }()"""; + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); } - @Override - public String timestampShape(TimestampShape shape) { - if (this.isOptional) { - return "Wrappers.Companion_Option_.Create_None_()"; - } - return "dafny.SeqOf()"; + return """ + func () %s { + %s + var bits = math.Float64bits(%s%s) + var bytes = make([]byte, 8) + binary.LittleEndian.PutUint64(bytes, bits) + var v []interface{} + for _, e := range bytes { + v = append(v, e) + } + return %s; + }()""".formatted( + returnType, + nilCheck, + dereferenceIfRequired, + dataSource, + someWrapIfRequired.formatted("dafny.SeqOf(v...)") + ); + } + + @Override + public String unionShape(UnionShape shape) { + return """ + func () Wrappers.Option { + _ = val + return Wrappers.Companion_Option_.Create_None_() + }()"""; + } + + @Override + public String timestampShape(TimestampShape shape) { + if (this.isOptional) { + return "Wrappers.Companion_Option_.Create_None_()"; } -} \ No newline at end of file + return "dafny.SeqOf()"; + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/DafnyToAwsSdkShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/DafnyToAwsSdkShapeVisitor.java index db3d54c719..a427578d93 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/DafnyToAwsSdkShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/DafnyToAwsSdkShapeVisitor.java @@ -1,9 +1,11 @@ package software.amazon.polymorph.smithygo.awssdk.shapevisitor; +import java.util.Arrays; +import java.util.List; +import software.amazon.polymorph.smithygo.awssdk.AwsSdkGoPointableIndex; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoWriter; import software.amazon.polymorph.smithygo.codegen.SmithyGoDependency; -import software.amazon.polymorph.smithygo.awssdk.AwsSdkGoPointableIndex; import software.amazon.polymorph.smithygo.codegen.SymbolUtils; import software.amazon.polymorph.smithygo.codegen.Synthetic; import software.amazon.polymorph.smithygo.codegen.knowledge.GoPointableIndex; @@ -33,363 +35,537 @@ import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.utils.StringUtils; -import java.util.Arrays; -import java.util.List; - public class DafnyToAwsSdkShapeVisitor extends ShapeVisitor.Default { - private static final List shapeName = Arrays.asList("IndexSizeBytes", "ItemCount", "ProcessedSizeBytes", "TableSizeBytes"); - private final AwsSdkGoPointableIndex awsSdkGoPointableIndex; - private final GenerationContext context; - private final String dataSource; - private final GoWriter writer; - private final ServiceTrait serviceTrait; - private final boolean isOptional; - private final boolean isPointable; - public DafnyToAwsSdkShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer - ) { - this(context, dataSource, writer, false, false); - } + private static final List shapeName = Arrays.asList( + "IndexSizeBytes", + "ItemCount", + "ProcessedSizeBytes", + "TableSizeBytes" + ); + private final AwsSdkGoPointableIndex awsSdkGoPointableIndex; + private final GenerationContext context; + private final String dataSource; + private final GoWriter writer; + private final ServiceTrait serviceTrait; + private final boolean isOptional; + private final boolean isPointable; - public DafnyToAwsSdkShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isOptional, - final boolean isPointable - ) { - this.context = context; - this.dataSource = dataSource; - this.writer = writer; - this.isOptional = isOptional; - this.isPointable = isPointable; - this.awsSdkGoPointableIndex = new AwsSdkGoPointableIndex(context.model()); - this.serviceTrait = context.model().expectShape(context.settings().getService(context.model()).toShapeId()).getTrait(ServiceTrait.class).get(); - } + public DafnyToAwsSdkShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer + ) { + this(context, dataSource, writer, false, false); + } - @Override - protected String getDefault(Shape shape) { - throw new CodegenException(String.format( - "Unsupported conversion of %s to %s using the %s protocol", - shape, shape.getType(), context.protocolGenerator().getName())); - } + public DafnyToAwsSdkShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isOptional, + final boolean isPointable + ) { + this.context = context; + this.dataSource = dataSource; + this.writer = writer; + this.isOptional = isOptional; + this.isPointable = isPointable; + this.awsSdkGoPointableIndex = new AwsSdkGoPointableIndex(context.model()); + this.serviceTrait = + context + .model() + .expectShape(context.settings().getService(context.model()).toShapeId()) + .getTrait(ServiceTrait.class) + .get(); + } - @Override - public String blobShape(BlobShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - return """ - func () []byte { - var b []byte - if %s == nil { - return nil - } - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return b - } else { - b = append(b, val.(byte)) - } - } - }()""".formatted(dataSource, dataSource); - } + @Override + protected String getDefault(Shape shape) { + throw new CodegenException( + String.format( + "Unsupported conversion of %s to %s using the %s protocol", + shape, + shape.getType(), + context.protocolGenerator().getName() + ) + ); + } - @Override - public String structureShape(final StructureShape shape) { - final var builder = new StringBuilder(); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(shape.toShapeId().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(shape)); - var subtype = !(awsSdkGoPointableIndex.isOperationStruct(shape) || shape.hasTrait(Synthetic.class)) - || shape.toShapeId().getName().contains("Exception"); - var nilcheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilcheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilcheck = ""; - } - } - builder.append(""" - func() %s%s { - %s - return %s%s { - """.formatted(this.isPointable ? "*" : "", SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, subtype).concat(".").concat(shape.getId().getName()), - nilcheck, - this.isPointable ? "&" : "", - SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, subtype).concat(".").concat(shape.getId().getName())) - ); - for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { - final var memberName = memberShapeEntry.getKey(); - final var memberShape = memberShapeEntry.getValue(); - final var targetShape = context.model().expectShape(memberShape.getTarget()); - //TODO: Is it ever possible for structure to be nil? - final var derivedDataSource = "%1$s%2$s%3$s%4$s".formatted(dataSource, this.isOptional ? ".(%s)".formatted(DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))) : "", - ".Dtor_%s()".formatted(memberName), - memberShape.isOptional() ? ".UnwrapOr(nil)" : ""); - builder.append("%1$s: %2$s,".formatted( - StringUtils.capitalize(memberName), - targetShape.accept( - new DafnyToAwsSdkShapeVisitor(context, derivedDataSource, writer, memberShape.isOptional(), shapeName.contains(memberName) || awsSdkGoPointableIndex.isPointable(targetShape)) - ) - )); + @Override + public String blobShape(BlobShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + return """ + func () []byte { + var b []byte + if %s == nil { + return nil + } + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) } + } + }()""".formatted(dataSource, dataSource); + } - return builder.append("}}()").toString(); + @Override + public String structureShape(final StructureShape shape) { + final var builder = new StringBuilder(); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + shape.toShapeId().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(shape) + ); + var subtype = + !(awsSdkGoPointableIndex.isOperationStruct(shape) || + shape.hasTrait(Synthetic.class)) || + shape.toShapeId().getName().contains("Exception"); + var nilcheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilcheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilcheck = ""; + } + } + builder.append( + """ + func() %s%s { + %s + return %s%s { + """.formatted( + this.isPointable ? "*" : "", + SmithyNameResolver + .smithyTypesNamespaceAws(serviceTrait, subtype) + .concat(".") + .concat(shape.getId().getName()), + nilcheck, + this.isPointable ? "&" : "", + SmithyNameResolver + .smithyTypesNamespaceAws(serviceTrait, subtype) + .concat(".") + .concat(shape.getId().getName()) + ) + ); + for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { + final var memberName = memberShapeEntry.getKey(); + final var memberShape = memberShapeEntry.getValue(); + final var targetShape = context + .model() + .expectShape(memberShape.getTarget()); + //TODO: Is it ever possible for structure to be nil? + final var derivedDataSource = + "%1$s%2$s%3$s%4$s".formatted( + dataSource, + this.isOptional + ? ".(%s)".formatted( + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ) + ) + : "", + ".Dtor_%s()".formatted(memberName), + memberShape.isOptional() ? ".UnwrapOr(nil)" : "" + ); + builder.append( + "%1$s: %2$s,".formatted( + StringUtils.capitalize(memberName), + targetShape.accept( + new DafnyToAwsSdkShapeVisitor( + context, + derivedDataSource, + writer, + memberShape.isOptional(), + shapeName.contains(memberName) || + awsSdkGoPointableIndex.isPointable(targetShape) + ) + ) + ) + ); } - // TODO: smithy-dafny-conversion library - @Override - public String listShape(ListShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - StringBuilder builder = new StringBuilder(); + return builder.append("}}()").toString(); + } - MemberShape memberShape = shape.getMember(); - final Shape targetShape = context.model().expectShape(memberShape.getTarget()); - var typeName = GoCodegenUtils.getType(context.symbolProvider().toSymbol(targetShape), serviceTrait); - builder.append(""" - func() []%s{ - var fieldValue []%s - %s - for i := dafny.Iterate(%s.(dafny.Sequence)); ; { - val, ok := i() - if !ok { - break - } - fieldValue = append(fieldValue, %s)} - """.formatted(typeName, typeName, this.isOptional ? """ - if %s == nil { - return nil - }""".formatted(dataSource) : "", dataSource, - targetShape.accept( - new DafnyToAwsSdkShapeVisitor(context, "val%s".formatted(memberShape.isOptional() ? ".(%s)".formatted(DafnyNameResolver.getDafnyType(targetShape, context.symbolProvider().toSymbol(targetShape))) : ""), writer, false, awsSdkGoPointableIndex.isPointable(memberShape)) - ))); + // TODO: smithy-dafny-conversion library + @Override + public String listShape(ListShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + StringBuilder builder = new StringBuilder(); - // Close structure - return builder.append("return fieldValue }()").toString(); - } + MemberShape memberShape = shape.getMember(); + final Shape targetShape = context + .model() + .expectShape(memberShape.getTarget()); + var typeName = GoCodegenUtils.getType( + context.symbolProvider().toSymbol(targetShape), + serviceTrait + ); + builder.append( + """ + func() []%s{ + var fieldValue []%s + %s + for i := dafny.Iterate(%s.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, %s)} + """.formatted( + typeName, + typeName, + this.isOptional + ? """ + if %s == nil { + return nil + }""".formatted(dataSource) + : "", + dataSource, + targetShape.accept( + new DafnyToAwsSdkShapeVisitor( + context, + "val%s".formatted( + memberShape.isOptional() + ? ".(%s)".formatted( + DafnyNameResolver.getDafnyType( + targetShape, + context.symbolProvider().toSymbol(targetShape) + ) + ) + : "" + ), + writer, + false, + awsSdkGoPointableIndex.isPointable(memberShape) + ) + ) + ) + ); - @Override - public String mapShape(MapShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - StringBuilder builder = new StringBuilder(); + // Close structure + return builder.append("return fieldValue }()").toString(); + } - MemberShape keyMemberShape = shape.getKey(); - final Shape keyTargetShape = context.model().expectShape(keyMemberShape.getTarget()); - MemberShape valueMemberShape = shape.getValue(); - final Shape valueTargetShape = context.model().expectShape(valueMemberShape.getTarget()); - var typeName = GoCodegenUtils.getType(context.symbolProvider().toSymbol(valueTargetShape), serviceTrait); + @Override + public String mapShape(MapShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + StringBuilder builder = new StringBuilder(); - var nilCheck = ""; - if (this.isOptional) { - nilCheck = """ - if %s == nil { - return nil - } - """.formatted(dataSource); - } - builder.append(""" - func() map[string]%s { - var m map[string]%s = make(map[string]%s) - %s - for i := dafny.Iterate(%s%s.Items());; { - val, ok := i() - if !ok { - break; - } - m[%s] = %s - } - return m - }()""".formatted(typeName, typeName, typeName, nilCheck, dataSource, this.isOptional ? ".(dafny.Map)" : "", - keyTargetShape.accept( - new DafnyToAwsSdkShapeVisitor(context, "(*val.(dafny.Tuple).IndexInt(0))", writer, keyMemberShape.isOptional(), awsSdkGoPointableIndex.isPointable(keyMemberShape))), - valueTargetShape.accept( - new DafnyToAwsSdkShapeVisitor(context, "(*val.(dafny.Tuple).IndexInt(1))%s".formatted(valueMemberShape.isOptional() ? ".(%s)".formatted(DafnyNameResolver.getDafnyType(valueTargetShape, context.symbolProvider().toSymbol(valueTargetShape))) : ""), writer, false, awsSdkGoPointableIndex.isPointable(valueMemberShape)) - ) - )); - return builder.toString(); - } + MemberShape keyMemberShape = shape.getKey(); + final Shape keyTargetShape = context + .model() + .expectShape(keyMemberShape.getTarget()); + MemberShape valueMemberShape = shape.getValue(); + final Shape valueTargetShape = context + .model() + .expectShape(valueMemberShape.getTarget()); + var typeName = GoCodegenUtils.getType( + context.symbolProvider().toSymbol(valueTargetShape), + serviceTrait + ); - @Override - public String booleanShape(BooleanShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - var nilCheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilCheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilCheck = "if %s == nil { return b }".formatted(dataSource); - } + var nilCheck = ""; + if (this.isOptional) { + nilCheck = + """ + if %s == nil { + return nil } - return """ - func() %sbool { - var b bool - %s - b = %s%s - return %sb - }()""".formatted(this.isPointable ? "*" : "", nilCheck, dataSource, this.isOptional ? ".(%s)".formatted(context.symbolProvider().toSymbol(shape).getName()) : "", - this.isPointable ? "&" : ""); + """.formatted(dataSource); } + builder.append( + """ + func() map[string]%s { + var m map[string]%s = make(map[string]%s) + %s + for i := dafny.Iterate(%s%s.Items());; { + val, ok := i() + if !ok { + break; + } + m[%s] = %s + } + return m + }()""".formatted( + typeName, + typeName, + typeName, + nilCheck, + dataSource, + this.isOptional ? ".(dafny.Map)" : "", + keyTargetShape.accept( + new DafnyToAwsSdkShapeVisitor( + context, + "(*val.(dafny.Tuple).IndexInt(0))", + writer, + keyMemberShape.isOptional(), + awsSdkGoPointableIndex.isPointable(keyMemberShape) + ) + ), + valueTargetShape.accept( + new DafnyToAwsSdkShapeVisitor( + context, + "(*val.(dafny.Tuple).IndexInt(1))%s".formatted( + valueMemberShape.isOptional() + ? ".(%s)".formatted( + DafnyNameResolver.getDafnyType( + valueTargetShape, + context.symbolProvider().toSymbol(valueTargetShape) + ) + ) + : "" + ), + writer, + false, + awsSdkGoPointableIndex.isPointable(valueMemberShape) + ) + ) + ) + ); + return builder.toString(); + } - @Override - public String stringShape(StringShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (shape.hasTrait(EnumTrait.class)) { - if (this.isOptional) { - return """ - func () %s.%s { - var u %s.%s - //TODO: What to do if nil - if %s == nil { - return u - } - inputEnum := %s.(%s) - index := -1; - for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { - enum, ok := allEnums() - if ok { - index++ - if enum.(%s).Equals(inputEnum) { - break; - } - } - } - return u.Values()[index] - }()""".formatted(SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), context.symbolProvider().toSymbol(shape).getName(), - SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), context.symbolProvider().toSymbol(shape).getName(), - dataSource, - dataSource, DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)), - DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), - DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))); - } else { - return """ - func () %s.%s { - var u %s.%s - - inputEnum := %s - index := -1; - for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { - enum, ok := allEnums() - if ok { - index++ - if enum.(%s).Equals(inputEnum) { - break; - } - } - } - return u.Values()[index] - }()""".formatted(SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), context.symbolProvider().toSymbol(shape).getName(), - SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), context.symbolProvider().toSymbol(shape).getName(), - dataSource, - DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), - DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))); - } - } + @Override + public String booleanShape(BooleanShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + var nilCheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilCheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilCheck = "if %s == nil { return b }".formatted(dataSource); + } + } + return """ + func() %sbool { + var b bool + %s + b = %s%s + return %sb + }()""".formatted( + this.isPointable ? "*" : "", + nilCheck, + dataSource, + this.isOptional + ? ".(%s)".formatted( + context.symbolProvider().toSymbol(shape).getName() + ) + : "", + this.isPointable ? "&" : "" + ); + } - var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) ? "uint8" : "dafny.Char"; - var nilCheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilCheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilCheck = "if %s == nil { return s }".formatted(dataSource); + @Override + public String stringShape(StringShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (shape.hasTrait(EnumTrait.class)) { + if (this.isOptional) { + return """ + func () %s.%s { + var u %s.%s + //TODO: What to do if nil + if %s == nil { + return u } - } + inputEnum := %s.(%s) + index := -1; + for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(%s).Equals(inputEnum) { + break; + } + } + } + return u.Values()[index] + }()""".formatted( + SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), + context.symbolProvider().toSymbol(shape).getName(), + SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), + context.symbolProvider().toSymbol(shape).getName(), + dataSource, + dataSource, + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ), + DafnyNameResolver.getDafnyCompanionStructType( + shape, + context.symbolProvider().toSymbol(shape) + ), + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ) + ); + } else { return """ - func() (%sstring) { - var s string - %s - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return %s[]string{s}[0] - } else { - s = s + string(val.(%s)) - } - } - }()""".formatted(this.isPointable ? "*" : "", nilCheck, dataSource, this.isPointable ? "&" : "", underlyingType); - } + func () %s.%s { + var u %s.%s - @Override - public String integerShape(IntegerShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (AwsSdkGoPointableIndex.of(context.model()).isPointable(shape)) { - return """ - func() *int32 { - var i int32 - if %s == nil { - return nil - } - i = %s.(int32) - return &i - }()""".formatted(dataSource, dataSource); - } else { - return "%s.(%s)".formatted(dataSource, context.symbolProvider().toSymbol(shape).getName()); - } + inputEnum := %s + index := -1; + for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(%s).Equals(inputEnum) { + break; + } + } + } + return u.Values()[index] + }()""".formatted( + SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), + context.symbolProvider().toSymbol(shape).getName(), + SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), + context.symbolProvider().toSymbol(shape).getName(), + dataSource, + DafnyNameResolver.getDafnyCompanionStructType( + shape, + context.symbolProvider().toSymbol(shape) + ), + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ) + ); + } } - @Override - public String longShape(LongShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - var nilCheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilCheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilCheck = "if %s == nil { return i}".formatted(dataSource); - } - } - return """ - func() %sint64 { - var i int64 - %s - i = %s%s - return %si - }()""".formatted(this.isPointable ? "*" : "", nilCheck, dataSource, this.isOptional ? ".(int64)" : "", this.isPointable ? "&" : ""); + var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) + ? "uint8" + : "dafny.Char"; + var nilCheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilCheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilCheck = "if %s == nil { return s }".formatted(dataSource); + } } - - @Override - public String doubleShape(DoubleShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - writer.addUseImports(SmithyGoDependency.MATH); - writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); - var nilCheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilCheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilCheck = "if %s == nil { var f float64; return f}".formatted(dataSource); - } + return """ + func() (%sstring) { + var s string + %s + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return %s[]string{s}[0] + } else { + s = s + string(val.(%s)) + } } - return """ - func () %sfloat64 { - var b []byte - %s - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return %s[]float64{math.Float64frombits(binary.LittleEndian.Uint64(b))}[0] - } else { - b = append(b, val.(byte)) - } - } - }()""".formatted(this.isPointable ? "*" : "", nilCheck, dataSource, this.isPointable ? "&" : ""); + }()""".formatted( + this.isPointable ? "*" : "", + nilCheck, + dataSource, + this.isPointable ? "&" : "", + underlyingType + ); + } + + @Override + public String integerShape(IntegerShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (AwsSdkGoPointableIndex.of(context.model()).isPointable(shape)) { + return """ + func() *int32 { + var i int32 + if %s == nil { + return nil + } + i = %s.(int32) + return &i + }()""".formatted(dataSource, dataSource); + } else { + return "%s.(%s)".formatted( + dataSource, + context.symbolProvider().toSymbol(shape).getName() + ); } + } - @Override - public String unionShape(UnionShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - return """ - func () types.%s { - _ = val - return nil - }()""".formatted(context.symbolProvider().toSymbol(shape).getName()); + @Override + public String longShape(LongShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + var nilCheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilCheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilCheck = "if %s == nil { return i}".formatted(dataSource); + } } + return """ + func() %sint64 { + var i int64 + %s + i = %s%s + return %si + }()""".formatted( + this.isPointable ? "*" : "", + nilCheck, + dataSource, + this.isOptional ? ".(int64)" : "", + this.isPointable ? "&" : "" + ); + } - @Override - public String timestampShape(TimestampShape shape) { - return "nil"; + @Override + public String doubleShape(DoubleShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + writer.addUseImports(SmithyGoDependency.MATH); + writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); + var nilCheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilCheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilCheck = + "if %s == nil { var f float64; return f}".formatted(dataSource); + } } + return """ + func () %sfloat64 { + var b []byte + %s + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return %s[]float64{math.Float64frombits(binary.LittleEndian.Uint64(b))}[0] + } else { + b = append(b, val.(byte)) + } + } + }()""".formatted( + this.isPointable ? "*" : "", + nilCheck, + dataSource, + this.isPointable ? "&" : "" + ); + } + + @Override + public String unionShape(UnionShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + return """ + func () types.%s { + _ = val + return nil + }()""".formatted(context.symbolProvider().toSymbol(shape).getName()); + } + @Override + public String timestampShape(TimestampShape shape) { + return "nil"; + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/AddOperationShapes.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/AddOperationShapes.java index 36a3d64526..bd63a39ed6 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/AddOperationShapes.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/AddOperationShapes.java @@ -17,7 +17,6 @@ import java.util.TreeSet; import java.util.logging.Logger; - import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.shapes.AbstractShapeBuilder; @@ -31,85 +30,117 @@ * Ensures that each operation has a unique input and output shape. */ public final class AddOperationShapes { - private static final Logger LOGGER = Logger.getLogger(AddOperationShapes.class.getName()); - - private AddOperationShapes() { - } - - /** - * Processes the given model and returns a new model ensuring service operation has an unique input and output - * synthesized shape. - * - * @param model the model - * @param serviceShapeId the service shape - * @return a model with unique operation input and output shapes - */ - public static Model execute(Model model, ShapeId serviceShapeId) { - TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - ServiceShape service = model.expectShape(serviceShapeId, ServiceShape.class); - TreeSet operations = new TreeSet<>(topDownIndex.getContainedOperations( - model.expectShape(serviceShapeId))); - - Model.Builder modelBuilder = model.toBuilder(); - for (OperationShape operation : operations) { - OperationShape.Builder operationBuilder = operation.toBuilder(); - ShapeId operationId = operation.getId(); - LOGGER.info(() -> "building unique input/output shapes for " + operationId); - if (operation.getInput().isPresent()) { - StructureShape newInputShape = operation.getInput() - .map(shapeId -> cloneOperationShape( - service, operationId, (StructureShape) model.expectShape(shapeId), "Input")).get(); - modelBuilder.addShape(newInputShape); - operationBuilder.input(newInputShape.toShapeId()); - } - - if (operation.getOutput().isPresent()) { - StructureShape newOutputShape = operation.getOutput() - .map(shapeId -> cloneOperationShape( - service, operationId, (StructureShape) model.expectShape(shapeId), "Output")).get(); - modelBuilder.addShape(newOutputShape); - operationBuilder.output(newOutputShape.toShapeId()); - } - - // Update operation model with the input/output shape ids - modelBuilder.addShape(operationBuilder.build()); - } - - return modelBuilder.build(); - } -// private static StructureShape emptyOperationStructure(ServiceShape service, ShapeId opShapeId, String suffix) { -// return StructureShape.builder() -// .id(ShapeId.fromParts(service.toShapeId().getNamespace(), opShapeId.getName(service) + suffix)) -// .addTrait(Synthetic.builder().build()) -// .build(); -// } - - private static StructureShape cloneOperationShape( - ServiceShape service, - ShapeId operationShapeId, - StructureShape structureShape, - String suffix - ) { - return (StructureShape) cloneShape(structureShape, operationShapeId.getName(service) + suffix); + private static final Logger LOGGER = Logger.getLogger( + AddOperationShapes.class.getName() + ); + + private AddOperationShapes() {} + + /** + * Processes the given model and returns a new model ensuring service operation has an unique input and output + * synthesized shape. + * + * @param model the model + * @param serviceShapeId the service shape + * @return a model with unique operation input and output shapes + */ + public static Model execute(Model model, ShapeId serviceShapeId) { + TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); + ServiceShape service = model.expectShape( + serviceShapeId, + ServiceShape.class + ); + TreeSet operations = new TreeSet<>( + topDownIndex.getContainedOperations(model.expectShape(serviceShapeId)) + ); + + Model.Builder modelBuilder = model.toBuilder(); + for (OperationShape operation : operations) { + OperationShape.Builder operationBuilder = operation.toBuilder(); + ShapeId operationId = operation.getId(); + LOGGER.info(() -> "building unique input/output shapes for " + operationId + ); + if (operation.getInput().isPresent()) { + StructureShape newInputShape = operation + .getInput() + .map(shapeId -> + cloneOperationShape( + service, + operationId, + (StructureShape) model.expectShape(shapeId), + "Input" + ) + ) + .get(); + modelBuilder.addShape(newInputShape); + operationBuilder.input(newInputShape.toShapeId()); + } + + if (operation.getOutput().isPresent()) { + StructureShape newOutputShape = operation + .getOutput() + .map(shapeId -> + cloneOperationShape( + service, + operationId, + (StructureShape) model.expectShape(shapeId), + "Output" + ) + ) + .get(); + modelBuilder.addShape(newOutputShape); + operationBuilder.output(newOutputShape.toShapeId()); + } + + // Update operation model with the input/output shape ids + modelBuilder.addShape(operationBuilder.build()); } - private static Shape cloneShape(Shape shape, String cloneShapeName) { - ShapeId cloneShapeId = ShapeId.fromParts(shape.toShapeId().getNamespace(), cloneShapeName); - - AbstractShapeBuilder builder = Shape.shapeToBuilder(shape) - .id(cloneShapeId) - .addTrait(Synthetic.builder() - .archetype(shape.getId()) - .build()); - - shape.members().forEach(memberShape -> { - builder.addMember(memberShape.toBuilder() - .id(cloneShapeId.withMember(memberShape.getMemberName())) - .build()); - }); - - - return (Shape) builder.build(); - } -} \ No newline at end of file + return modelBuilder.build(); + } + + // private static StructureShape emptyOperationStructure(ServiceShape service, ShapeId opShapeId, String suffix) { + // return StructureShape.builder() + // .id(ShapeId.fromParts(service.toShapeId().getNamespace(), opShapeId.getName(service) + suffix)) + // .addTrait(Synthetic.builder().build()) + // .build(); + // } + + private static StructureShape cloneOperationShape( + ServiceShape service, + ShapeId operationShapeId, + StructureShape structureShape, + String suffix + ) { + return (StructureShape) cloneShape( + structureShape, + operationShapeId.getName(service) + suffix + ); + } + + private static Shape cloneShape(Shape shape, String cloneShapeName) { + ShapeId cloneShapeId = ShapeId.fromParts( + shape.toShapeId().getNamespace(), + cloneShapeName + ); + + AbstractShapeBuilder builder = Shape + .shapeToBuilder(shape) + .id(cloneShapeId) + .addTrait(Synthetic.builder().archetype(shape.getId()).build()); + + shape + .members() + .forEach(memberShape -> { + builder.addMember( + memberShape + .toBuilder() + .id(cloneShapeId.withMember(memberShape.getMemberName())) + .build() + ); + }); + + return (Shape) builder.build(); + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ApplicationProtocol.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ApplicationProtocol.java index a436b7d90a..d66d096247 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ApplicationProtocol.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ApplicationProtocol.java @@ -2,10 +2,14 @@ import software.amazon.smithy.codegen.core.SymbolReference; import software.amazon.smithy.utils.SmithyUnstableApi; + /** * Represents the resolves {@link Symbol}s and references for an * application protocol (e.g., "http", "mqtt", etc). */ @SmithyUnstableApi -public record ApplicationProtocol(String name, SymbolReference requestType, SymbolReference responseType) { -} +public record ApplicationProtocol( + String name, + SymbolReference requestType, + SymbolReference responseType +) {} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/CodegenUtils.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/CodegenUtils.java index 9e4d363813..aef04700fa 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/CodegenUtils.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/CodegenUtils.java @@ -15,6 +15,17 @@ package software.amazon.polymorph.smithygo.codegen; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.logging.Logger; import software.amazon.polymorph.smithygo.codegen.knowledge.GoPointableIndex; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; @@ -31,402 +42,422 @@ import software.amazon.smithy.model.traits.TitleTrait; import software.amazon.smithy.utils.StringUtils; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Optional; -import java.util.function.Predicate; -import java.util.logging.Logger; - /** * Utility methods likely to be needed across packages. */ public final class CodegenUtils { - private static final Logger LOGGER = Logger.getLogger(CodegenUtils.class.getName()); - - private static final String SYNTHETIC_NAMESPACE = "smithy.go.synthetic"; - - private CodegenUtils() { - } - - /** - * Executes a given shell command in a given directory. - * - * @param command The string command to execute, e.g. "go fmt". - * @param directory The directory to run the command in. - * @return Returns the console output of the command. - */ - public static String runCommand(String command, Path directory) { - String[] finalizedCommand; - if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { - finalizedCommand = new String[]{"cmd.exe", "/c", command}; - } else { - finalizedCommand = new String[]{"sh", "-c", command}; - } - - ProcessBuilder processBuilder = new ProcessBuilder(finalizedCommand) - .redirectErrorStream(true) - .directory(directory.toFile()); - - try { - Process process = processBuilder.start(); - List output = new ArrayList<>(); - - // Capture output for reporting. - try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( - process.getInputStream(), Charset.defaultCharset()))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - LOGGER.finest(line); - output.add(line); - } - } - - process.waitFor(); - process.destroy(); - - String joinedOutput = String.join(System.lineSeparator(), output); - if (process.exitValue() != 0) { - throw new CodegenException(String.format( - "Command `%s` failed with output:%n%n%s", command, joinedOutput)); - } - return joinedOutput; - } catch (InterruptedException | IOException e) { - throw new CodegenException(e); - } + private static final Logger LOGGER = Logger.getLogger( + CodegenUtils.class.getName() + ); + + private static final String SYNTHETIC_NAMESPACE = "smithy.go.synthetic"; + + private CodegenUtils() {} + + /** + * Executes a given shell command in a given directory. + * + * @param command The string command to execute, e.g. "go fmt". + * @param directory The directory to run the command in. + * @return Returns the console output of the command. + */ + public static String runCommand(String command, Path directory) { + String[] finalizedCommand; + if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { + finalizedCommand = new String[] { "cmd.exe", "/c", command }; + } else { + finalizedCommand = new String[] { "sh", "-c", command }; } - /** - * Gets the name under which the given package will be exported by default. - * - * @param packageName The full package name of the exported package. - * @return The name a the package will be imported under by default. - */ - public static String getDefaultPackageImportName(String packageName) { - if (StringUtils.isBlank(packageName) || !packageName.contains("/")) { - return packageName; + ProcessBuilder processBuilder = new ProcessBuilder(finalizedCommand) + .redirectErrorStream(true) + .directory(directory.toFile()); + + try { + Process process = processBuilder.start(); + List output = new ArrayList<>(); + + // Capture output for reporting. + try ( + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader( + process.getInputStream(), + Charset.defaultCharset() + ) + ) + ) { + String line; + while ((line = bufferedReader.readLine()) != null) { + LOGGER.finest(line); + output.add(line); } - return packageName.substring(packageName.lastIndexOf('/') + 1); + } + + process.waitFor(); + process.destroy(); + + String joinedOutput = String.join(System.lineSeparator(), output); + if (process.exitValue() != 0) { + throw new CodegenException( + String.format( + "Command `%s` failed with output:%n%n%s", + command, + joinedOutput + ) + ); + } + return joinedOutput; + } catch (InterruptedException | IOException e) { + throw new CodegenException(e); } - - /** - * Gets the alias to use when referencing the given symbol outside of its namespace. - * - *

The default value is the last path component of the symbol's namespace. - * - * @param symbol The symbol whose whose namespace alias should be retrieved. - * @return The alias of the symbol's namespace. - */ - public static String getSymbolNamespaceAlias(Symbol symbol) { - return symbol.getProperty(SymbolUtils.NAMESPACE_ALIAS, String.class) - .filter(StringUtils::isNotBlank) - .orElse(CodegenUtils.getDefaultPackageImportName(symbol.getNamespace())); + } + + /** + * Gets the name under which the given package will be exported by default. + * + * @param packageName The full package name of the exported package. + * @return The name a the package will be imported under by default. + */ + public static String getDefaultPackageImportName(String packageName) { + if (StringUtils.isBlank(packageName) || !packageName.contains("/")) { + return packageName; } - - /** - * Detects if an annotated mediatype indicates JSON contents. - * - * @param mediaType The media type to inspect. - * @return If the media type indicates JSON contents. - */ - public static boolean isJsonMediaType(String mediaType) { - return mediaType.equals("application/json") || mediaType.endsWith("+json"); + return packageName.substring(packageName.lastIndexOf('/') + 1); + } + + /** + * Gets the alias to use when referencing the given symbol outside of its namespace. + * + *

The default value is the last path component of the symbol's namespace. + * + * @param symbol The symbol whose whose namespace alias should be retrieved. + * @return The alias of the symbol's namespace. + */ + public static String getSymbolNamespaceAlias(Symbol symbol) { + return symbol + .getProperty(SymbolUtils.NAMESPACE_ALIAS, String.class) + .filter(StringUtils::isNotBlank) + .orElse(CodegenUtils.getDefaultPackageImportName(symbol.getNamespace())); + } + + /** + * Detects if an annotated mediatype indicates JSON contents. + * + * @param mediaType The media type to inspect. + * @return If the media type indicates JSON contents. + */ + public static boolean isJsonMediaType(String mediaType) { + return mediaType.equals("application/json") || mediaType.endsWith("+json"); + } + + /** + * Get the namespace where synthetic types are generated at runtime. + * + * @return synthetic type namespace + */ + public static String getSyntheticTypeNamespace() { + return CodegenUtils.SYNTHETIC_NAMESPACE; + } + + /** + * Get if the passed in shape is decorated as a synthetic clone, but there is no other shape the clone is + * created from. + * + * @param shape the shape to check if its a stubbed synthetic clone without an archetype. + * @return if the shape is synthetic clone, but not based on a specific shape. + */ + public static boolean isStubSynthetic(Shape shape) { + Optional optional = shape.getTrait(Synthetic.class); + if (!optional.isPresent()) { + return false; } - /** - * Get the namespace where synthetic types are generated at runtime. - * - * @return synthetic type namespace - */ - public static String getSyntheticTypeNamespace() { - return CodegenUtils.SYNTHETIC_NAMESPACE; + Synthetic synth = optional.get(); + return !synth.getArchetype().isPresent(); + } + + /** + * Returns the operand decorated with an & if the address of the shape type can be taken. + * + * @param model API model reference + * @param pointableIndex pointable index + * @param shape shape to use + * @param operand value to decorate + * @return updated operand + */ + public static String asAddressIfAddressable( + Model model, + GoPointableIndex pointableIndex, + Shape shape, + String operand + ) { + boolean isStruct = shape.getType() == ShapeType.STRUCTURE; + if (shape.isMemberShape()) { + isStruct = + model.expectShape(shape.asMemberShape().get().getTarget()).getType() == + ShapeType.STRUCTURE; } - /** - * Get if the passed in shape is decorated as a synthetic clone, but there is no other shape the clone is - * created from. - * - * @param shape the shape to check if its a stubbed synthetic clone without an archetype. - * @return if the shape is synthetic clone, but not based on a specific shape. - */ - public static boolean isStubSynthetic(Shape shape) { - Optional optional = shape.getTrait(Synthetic.class); - if (!optional.isPresent()) { - return false; - } - - Synthetic synth = optional.get(); - return !synth.getArchetype().isPresent(); + boolean shouldAddress = pointableIndex.isPointable(shape) && isStruct; + return shouldAddress ? "&" + operand : operand; + } + + /** + * Returns the operand decorated with an "*" if the shape is dereferencable. + * + * @param pointableIndex knowledge index for if shape is pointable. + * @param shape The shape whose value needs to be read. + * @param operand The value to be read from. + * @return updated operand + */ + public static String getAsValueIfDereferencable( + GoPointableIndex pointableIndex, + Shape shape, + String operand + ) { + if (!pointableIndex.isDereferencable(shape)) { + return operand; } - /** - * Returns the operand decorated with an & if the address of the shape type can be taken. - * - * @param model API model reference - * @param pointableIndex pointable index - * @param shape shape to use - * @param operand value to decorate - * @return updated operand - */ - public static String asAddressIfAddressable( - Model model, - GoPointableIndex pointableIndex, - Shape shape, - String operand - ) { - boolean isStruct = shape.getType() == ShapeType.STRUCTURE; - if (shape.isMemberShape()) { - isStruct = model.expectShape(shape.asMemberShape().get().getTarget()).getType() == ShapeType.STRUCTURE; - } - - boolean shouldAddress = pointableIndex.isPointable(shape) && isStruct; - return shouldAddress ? "&" + operand : operand; + return '*' + operand; + } + + /** + * Returns the operand decorated as a pointer type, without creating double pointer. + * + * @param pointableIndex knowledge index for if shape is pointable. + * @param shape The shape whose value of the type. + * @param operand The value to read. + * @return updated operand + */ + public static String getTypeAsTypePointer( + GoPointableIndex pointableIndex, + Shape shape, + String operand + ) { + if (pointableIndex.isPointable(shape)) { + return operand; } - /** - * Returns the operand decorated with an "*" if the shape is dereferencable. - * - * @param pointableIndex knowledge index for if shape is pointable. - * @param shape The shape whose value needs to be read. - * @param operand The value to be read from. - * @return updated operand - */ - public static String getAsValueIfDereferencable( - GoPointableIndex pointableIndex, - Shape shape, - String operand - ) { - if (!pointableIndex.isDereferencable(shape)) { - return operand; - } - - return '*' + operand; + return '*' + operand; + } + + /** + * Get the pointer reference to operand , if symbol is pointable. + * This method can be used by deserializers to get pointer to + * operand. + * + * @param model model for api. + * @param writer The writer dependencies will be added to, if needed. + * @param pointableIndex knowledge index for if shape is pointable. + * @param shape The shape whose value needs to be assigned. + * @param operand The Operand is the value to be assigned to the symbol shape. + * @return The Operand, along with pointer reference if applicable + */ + public static String getAsPointerIfPointable( + Model model, + GoWriter writer, + GoPointableIndex pointableIndex, + Shape shape, + String operand + ) { + if (!pointableIndex.isPointable(shape)) { + return operand; } - /** - * Returns the operand decorated as a pointer type, without creating double pointer. - * - * @param pointableIndex knowledge index for if shape is pointable. - * @param shape The shape whose value of the type. - * @param operand The value to read. - * @return updated operand - */ - public static String getTypeAsTypePointer( - GoPointableIndex pointableIndex, - Shape shape, - String operand - ) { - if (pointableIndex.isPointable(shape)) { - return operand; - } - - return '*' + operand; + if (shape.isMemberShape()) { + shape = model.expectShape(shape.asMemberShape().get().getTarget()); } - /** - * Get the pointer reference to operand , if symbol is pointable. - * This method can be used by deserializers to get pointer to - * operand. - * - * @param model model for api. - * @param writer The writer dependencies will be added to, if needed. - * @param pointableIndex knowledge index for if shape is pointable. - * @param shape The shape whose value needs to be assigned. - * @param operand The Operand is the value to be assigned to the symbol shape. - * @return The Operand, along with pointer reference if applicable - */ - public static String getAsPointerIfPointable( - Model model, - GoWriter writer, - GoPointableIndex pointableIndex, - Shape shape, - String operand - ) { - if (!pointableIndex.isPointable(shape)) { - return operand; - } - - if (shape.isMemberShape()) { - shape = model.expectShape(shape.asMemberShape().get().getTarget()); - } - - String prefix = ""; - String suffix = ")"; - - switch (shape.getType()) { - case STRING: - prefix = "ptr.String("; - break; - - case BOOLEAN: - prefix = "ptr.Bool("; - break; - - case BYTE: - prefix = "ptr.Int8("; - break; - case SHORT: - prefix = "ptr.Int16("; - break; - case INTEGER: - prefix = "ptr.Int32("; - break; - case LONG: - prefix = "ptr.Int64("; - break; - - case FLOAT: - prefix = "ptr.Float32("; - break; - case DOUBLE: - prefix = "ptr.Float64("; - break; - - case TIMESTAMP: - prefix = "ptr.Time("; - break; - - default: - return '&' + operand; - } - - writer.addUseImports(SmithyGoDependency.SMITHY_PTR); - return prefix + operand + suffix; + String prefix = ""; + String suffix = ")"; + + switch (shape.getType()) { + case STRING: + prefix = "ptr.String("; + break; + case BOOLEAN: + prefix = "ptr.Bool("; + break; + case BYTE: + prefix = "ptr.Int8("; + break; + case SHORT: + prefix = "ptr.Int16("; + break; + case INTEGER: + prefix = "ptr.Int32("; + break; + case LONG: + prefix = "ptr.Int64("; + break; + case FLOAT: + prefix = "ptr.Float32("; + break; + case DOUBLE: + prefix = "ptr.Float64("; + break; + case TIMESTAMP: + prefix = "ptr.Time("; + break; + default: + return '&' + operand; } - /** - * Returns the shape unpacked as a CollectionShape. Throws an exception if the passed in - * shape is not a list or set. - * - * @param shape the list or set shape. - * @return The unpacked CollectionShape. - */ - public static CollectionShape expectCollectionShape(Shape shape) { - if (shape instanceof CollectionShape) { - return (CollectionShape) (shape); - } - - throw new CodegenException("expect shape " + shape.getId() + " to be Collection, was " + shape.getType()); + writer.addUseImports(SmithyGoDependency.SMITHY_PTR); + return prefix + operand + suffix; + } + + /** + * Returns the shape unpacked as a CollectionShape. Throws an exception if the passed in + * shape is not a list or set. + * + * @param shape the list or set shape. + * @return The unpacked CollectionShape. + */ + public static CollectionShape expectCollectionShape(Shape shape) { + if (shape instanceof CollectionShape) { + return (CollectionShape) (shape); } - /** - * Returns the shape unpacked as a MapShape. Throws an exception if the passed in - * shape is not a map. - * - * @param shape the map shape. - * @return The unpacked MapShape. - */ - public static MapShape expectMapShape(Shape shape) { - if (shape instanceof MapShape) { - return (MapShape) (shape); - } - - throw new CodegenException("expect shape " + shape.getId() + " to be Map, was " + shape.getType()); + throw new CodegenException( + "expect shape " + + shape.getId() + + " to be Collection, was " + + shape.getType() + ); + } + + /** + * Returns the shape unpacked as a MapShape. Throws an exception if the passed in + * shape is not a map. + * + * @param shape the map shape. + * @return The unpacked MapShape. + */ + public static MapShape expectMapShape(Shape shape) { + if (shape instanceof MapShape) { + return (MapShape) (shape); } - /** - * Comparator to sort ShapeMember lists alphabetically, with required members first followed by optional members. - */ - public static final class SortedMembers implements Comparator { - private final SymbolProvider symbolProvider; - - /** - * Initializes the SortedMembers. - * - * @param symbolProvider symbol provider used for codegen. - */ - public SortedMembers(SymbolProvider symbolProvider) { - this.symbolProvider = symbolProvider; - } + throw new CodegenException( + "expect shape " + shape.getId() + " to be Map, was " + shape.getType() + ); + } - @Override - public int compare(MemberShape a, MemberShape b) { - // first compare if the members are required or not, which ever member is required should win. If both - // members are required or not required, continue on to alphabetic search. - - // If a is required but b isn't return -1 so a is sorted before b - // If b is required but a isn't, return 1 so a is sorted after b - // If both a and b are required or optional, use alphabetic sorting of a and b's member name. - - int requiredMember = 0; - if (a.hasTrait(RequiredTrait.class)) { - requiredMember -= 1; - } - if (b.hasTrait(RequiredTrait.class)) { - requiredMember += 1; - } - if (requiredMember != 0) { - return requiredMember; - } - - return symbolProvider.toMemberName(a) - .compareTo(symbolProvider.toMemberName(b)); - } - } + /** + * Comparator to sort ShapeMember lists alphabetically, with required members first followed by optional members. + */ + public static final class SortedMembers implements Comparator { - /** - * Attempts to find the first member by exact name in the containing structure. If the member is not found an - * exception will be thrown. - * - * @param shape structure containing member - * @param name member name - * @return MemberShape if found - */ - public static MemberShape expectMember(StructureShape shape, String name) { - return expectMember(shape, name::equals); - } + private final SymbolProvider symbolProvider; /** - * Attempts to find the first member by name using a member name predicate in the containing structure. If the - * member is not found an exception will be thrown. + * Initializes the SortedMembers. * - * @param shape structure containing member - * @param memberNamePredicate member name to search for - * @return MemberShape if found + * @param symbolProvider symbol provider used for codegen. */ - public static MemberShape expectMember(StructureShape shape, Predicate memberNamePredicate) { - return shape.getAllMembers().values().stream() - .filter((p) -> memberNamePredicate.test(p.getMemberName())) - .findFirst() - .orElseThrow(() -> new CodegenException("did not find member in structure shape, " + shape.getId())); + public SortedMembers(SymbolProvider symbolProvider) { + this.symbolProvider = symbolProvider; } - /** - * Attempts to get the title of the API's service from the model. If unalbe to get the title the fallback value - * will be returned instead. - * - * @param shape service shape - * @param fallback string to return if service does not have a title - * @return title of service - */ - public static String getServiceTitle(ServiceShape shape, String fallback) { - return shape.getTrait(TitleTrait.class).map(TitleTrait::getValue).orElse(fallback); + @Override + public int compare(MemberShape a, MemberShape b) { + // first compare if the members are required or not, which ever member is required should win. If both + // members are required or not required, continue on to alphabetic search. + + // If a is required but b isn't return -1 so a is sorted before b + // If b is required but a isn't, return 1 so a is sorted after b + // If both a and b are required or optional, use alphabetic sorting of a and b's member name. + + int requiredMember = 0; + if (a.hasTrait(RequiredTrait.class)) { + requiredMember -= 1; + } + if (b.hasTrait(RequiredTrait.class)) { + requiredMember += 1; + } + if (requiredMember != 0) { + return requiredMember; + } + + return symbolProvider + .toMemberName(a) + .compareTo(symbolProvider.toMemberName(b)); } - - /** - * isNumber returns if the shape is a number shape. - * - * @param shape shape to check - * @return true if is a number shape. - */ - public static boolean isNumber(Shape shape) { - switch (shape.getType()) { - case BYTE: - case SHORT: - case INTEGER: - case INT_ENUM: - case LONG: - case FLOAT: - case DOUBLE: - return true; - default: - return false; - } + } + + /** + * Attempts to find the first member by exact name in the containing structure. If the member is not found an + * exception will be thrown. + * + * @param shape structure containing member + * @param name member name + * @return MemberShape if found + */ + public static MemberShape expectMember(StructureShape shape, String name) { + return expectMember(shape, name::equals); + } + + /** + * Attempts to find the first member by name using a member name predicate in the containing structure. If the + * member is not found an exception will be thrown. + * + * @param shape structure containing member + * @param memberNamePredicate member name to search for + * @return MemberShape if found + */ + public static MemberShape expectMember( + StructureShape shape, + Predicate memberNamePredicate + ) { + return shape + .getAllMembers() + .values() + .stream() + .filter(p -> memberNamePredicate.test(p.getMemberName())) + .findFirst() + .orElseThrow(() -> + new CodegenException( + "did not find member in structure shape, " + shape.getId() + ) + ); + } + + /** + * Attempts to get the title of the API's service from the model. If unalbe to get the title the fallback value + * will be returned instead. + * + * @param shape service shape + * @param fallback string to return if service does not have a title + * @return title of service + */ + public static String getServiceTitle(ServiceShape shape, String fallback) { + return shape + .getTrait(TitleTrait.class) + .map(TitleTrait::getValue) + .orElse(fallback); + } + + /** + * isNumber returns if the shape is a number shape. + * + * @param shape shape to check + * @return true if is a number shape. + */ + public static boolean isNumber(Shape shape) { + switch (shape.getType()) { + case BYTE: + case SHORT: + case INTEGER: + case INT_ENUM: + case LONG: + case FLOAT: + case DOUBLE: + return true; + default: + return false; } + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/EnumGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/EnumGenerator.java index 739c4ea685..f86ec20ccf 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/EnumGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/EnumGenerator.java @@ -19,7 +19,6 @@ import java.util.Locale; import java.util.Set; import java.util.logging.Logger; - import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.shapes.EnumShape; @@ -33,66 +32,101 @@ * Renders enums and their constants. */ public final class EnumGenerator implements Runnable { - private static final Logger LOGGER = Logger.getLogger(EnumGenerator.class.getName()); - - private final SymbolProvider symbolProvider; - private final GoWriter writer; - private final Shape shape; - public EnumGenerator(SymbolProvider symbolProvider, GoWriter writer, Shape shape) { - this.symbolProvider = symbolProvider; - this.writer = writer; - this.shape = shape; - } + private static final Logger LOGGER = Logger.getLogger( + EnumGenerator.class.getName() + ); - @Override - public void run() { - Symbol symbol = symbolProvider.toSymbol(shape); - EnumTrait enumTrait = shape.expectTrait(EnumTrait.class); + private final SymbolProvider symbolProvider; + private final GoWriter writer; + private final Shape shape; - writer.write("type $L string", symbol.getName()).write(""); + public EnumGenerator( + SymbolProvider symbolProvider, + GoWriter writer, + Shape shape + ) { + this.symbolProvider = symbolProvider; + this.writer = writer; + this.shape = shape; + } - // Don't generate constants if there are no explicitly modeled names. We only need to - // look at one, since Smithy validates that if one has a name then they must all have - // a name. - if (enumTrait.getValues().get(0).getName().isPresent()) { - Set constants = new LinkedHashSet<>(); - writer.openBlock("const (", ")", () -> { - for (EnumDefinition definition : enumTrait.getValues()) { - StringBuilder labelBuilder = new StringBuilder(symbol.getName()); - String name = definition.getName().get(); + @Override + public void run() { + Symbol symbol = symbolProvider.toSymbol(shape); + EnumTrait enumTrait = shape.expectTrait(EnumTrait.class); - for (String part : name.split("(?U)[\\W_]")) { - if (part.matches(".*[a-z].*") && part.matches(".*[A-Z].*")) { - // Mixed case names should not be changed other than first letter capitalized. - labelBuilder.append(StringUtils.capitalize(part)); - } else { - // For all non-mixed case parts title case first letter, followed by all other lower cased. - labelBuilder.append(StringUtils.capitalize(part.toLowerCase(Locale.US))); - } - } - String label = labelBuilder.toString(); + writer.write("type $L string", symbol.getName()).write(""); - // If camel-casing would cause a conflict, don't camel-case this enum value. - if (constants.contains(label)) { - LOGGER.warning(String.format( - "Multiple enums resolved to the same name, `%s`, using unaltered value for: %s", - label, name)); - label = name; - } - constants.add(label); + // Don't generate constants if there are no explicitly modeled names. We only need to + // look at one, since Smithy validates that if one has a name then they must all have + // a name. + if (enumTrait.getValues().get(0).getName().isPresent()) { + Set constants = new LinkedHashSet<>(); + writer + .openBlock( + "const (", + ")", + () -> { + for (EnumDefinition definition : enumTrait.getValues()) { + StringBuilder labelBuilder = new StringBuilder(symbol.getName()); + String name = definition.getName().get(); - writer.write("$L $L = $S", label, symbol.getName(), definition.getValue()); + for (String part : name.split("(?U)[\\W_]")) { + if (part.matches(".*[a-z].*") && part.matches(".*[A-Z].*")) { + // Mixed case names should not be changed other than first letter capitalized. + labelBuilder.append(StringUtils.capitalize(part)); + } else { + // For all non-mixed case parts title case first letter, followed by all other lower cased. + labelBuilder.append( + StringUtils.capitalize(part.toLowerCase(Locale.US)) + ); } - }).write(""); - } + } + String label = labelBuilder.toString(); - writer.openBlock("func ($L) Values() []$L {", "}", symbol.getName(), symbol.getName(), () -> { - writer.openBlock("return []$L{", "}", symbol.getName(), () -> { - for (EnumDefinition definition : enumTrait.getValues()) { - writer.write("$S,", definition.getValue()); - } - }); - }); + // If camel-casing would cause a conflict, don't camel-case this enum value. + if (constants.contains(label)) { + LOGGER.warning( + String.format( + "Multiple enums resolved to the same name, `%s`, using unaltered value for: %s", + label, + name + ) + ); + label = name; + } + constants.add(label); + + writer.write( + "$L $L = $S", + label, + symbol.getName(), + definition.getValue() + ); + } + } + ) + .write(""); } -} \ No newline at end of file + + writer.openBlock( + "func ($L) Values() []$L {", + "}", + symbol.getName(), + symbol.getName(), + () -> { + writer.openBlock( + "return []$L{", + "}", + symbol.getName(), + () -> { + for (EnumDefinition definition : enumTrait.getValues()) { + writer.write("$S,", definition.getValue()); + } + } + ); + } + ); + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GenerationContext.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GenerationContext.java index 7fb586c8a6..d14117be43 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GenerationContext.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GenerationContext.java @@ -1,5 +1,7 @@ package software.amazon.polymorph.smithygo.codegen; +import java.util.ArrayList; +import java.util.List; import software.amazon.polymorph.smithygo.codegen.integration.GoIntegration; import software.amazon.polymorph.smithygo.codegen.integration.ProtocolGenerator; import software.amazon.smithy.build.FileManifest; @@ -8,152 +10,160 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.utils.SmithyBuilder; -import java.util.ArrayList; -import java.util.List; - -public class GenerationContext implements CodegenContext { - private final Model model; - private final GoSettings settings; - private final SymbolProvider symbolProvider; - private final FileManifest fileManifest; - private final GoDelegator writerDelegator; - private final List integrations; - private final ProtocolGenerator protocolGenerator; - - /** - * @return Returns the protocol generator to use in code generation. - */ - public ProtocolGenerator protocolGenerator() { - return protocolGenerator; - } - - private GenerationContext(Builder builder) { - model = SmithyBuilder.requiredState("model", builder.model); - settings = SmithyBuilder.requiredState("settings", builder.settings); - symbolProvider = SmithyBuilder.requiredState("symbolProvider", builder.symbolProvider); - fileManifest = SmithyBuilder.requiredState("fileManifest", builder.fileManifest); - writerDelegator = SmithyBuilder.requiredState("writerDelegator", builder.writerDelegator); - integrations = SmithyBuilder.requiredState("integrations", builder.integrations); - protocolGenerator = SmithyBuilder.requiredState("protocolGenerator", builder.protocolGenerator); - } +public class GenerationContext + implements CodegenContext { + + private final Model model; + private final GoSettings settings; + private final SymbolProvider symbolProvider; + private final FileManifest fileManifest; + private final GoDelegator writerDelegator; + private final List integrations; + private final ProtocolGenerator protocolGenerator; + + /** + * @return Returns the protocol generator to use in code generation. + */ + public ProtocolGenerator protocolGenerator() { + return protocolGenerator; + } + + private GenerationContext(Builder builder) { + model = SmithyBuilder.requiredState("model", builder.model); + settings = SmithyBuilder.requiredState("settings", builder.settings); + symbolProvider = + SmithyBuilder.requiredState("symbolProvider", builder.symbolProvider); + fileManifest = + SmithyBuilder.requiredState("fileManifest", builder.fileManifest); + writerDelegator = + SmithyBuilder.requiredState("writerDelegator", builder.writerDelegator); + integrations = + SmithyBuilder.requiredState("integrations", builder.integrations); + protocolGenerator = + SmithyBuilder.requiredState( + "protocolGenerator", + builder.protocolGenerator + ); + } + + @Override + public Model model() { + return model; + } + + @Override + public GoSettings settings() { + return settings; + } + + @Override + public SymbolProvider symbolProvider() { + return symbolProvider; + } + + @Override + public FileManifest fileManifest() { + return fileManifest; + } + + @Override + public GoDelegator writerDelegator() { + return writerDelegator; + } + + @Override + public List integrations() { + return integrations; + } + + /** + * @return Returns a builder. + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Builds {@link GenerationContext}s. + */ + public static final class Builder + implements SmithyBuilder { + + private Model model; + private GoSettings settings; + private SymbolProvider symbolProvider; + private FileManifest fileManifest; + private GoDelegator writerDelegator; + private List integrations = new ArrayList<>(); + private ProtocolGenerator protocolGenerator; @Override - public Model model() { - return model; + public GenerationContext build() { + return new GenerationContext(this); } - @Override - public GoSettings settings() { - return settings; + /** + * @param model The model being generated. + * @return Returns the builder. + */ + public Builder model(Model model) { + this.model = model; + return this; } - @Override - public SymbolProvider symbolProvider() { - return symbolProvider; + /** + * @param settings The resolved settings for the generator. + * @return Returns the builder. + */ + public Builder settings(GoSettings settings) { + this.settings = settings; + return this; } - @Override - public FileManifest fileManifest() { - return fileManifest; + /** + * @param symbolProvider The finalized symbol provider for the generator. + * @return Returns the builder. + */ + public Builder symbolProvider(SymbolProvider symbolProvider) { + this.symbolProvider = symbolProvider; + return this; } - @Override - public GoDelegator writerDelegator() { - return writerDelegator; + /** + * @param fileManifest The file manifest being used in the generator. + * @return Returns the builder. + */ + public Builder fileManifest(FileManifest fileManifest) { + this.fileManifest = fileManifest; + return this; } - @Override - public List integrations() { - return integrations; + /** + * @param writerDelegator The writer delegator to use in the generator. + * @return Returns the builder. + */ + public Builder writerDelegator(GoDelegator writerDelegator) { + this.writerDelegator = writerDelegator; + return this; } /** - * @return Returns a builder. + * @param integrations The integrations to use in the generator. + * @return Returns the builder. */ - public static Builder builder() { - return new Builder(); + public Builder integrations(List integrations) { + this.integrations.clear(); + this.integrations.addAll(integrations); + return this; } /** - * Builds {@link GenerationContext}s. + * @param protocolGenerator The resolved protocol generator to use. + * @return Returns the builder. */ - public static final class Builder implements SmithyBuilder { - private Model model; - private GoSettings settings; - private SymbolProvider symbolProvider; - private FileManifest fileManifest; - private GoDelegator writerDelegator; - private List integrations = new ArrayList<>(); - private ProtocolGenerator protocolGenerator; - - @Override - public GenerationContext build() { - return new GenerationContext(this); - } - - /** - * @param model The model being generated. - * @return Returns the builder. - */ - public Builder model(Model model) { - this.model = model; - return this; - } - - /** - * @param settings The resolved settings for the generator. - * @return Returns the builder. - */ - public Builder settings(GoSettings settings) { - this.settings = settings; - return this; - } - - /** - * @param symbolProvider The finalized symbol provider for the generator. - * @return Returns the builder. - */ - public Builder symbolProvider(SymbolProvider symbolProvider) { - this.symbolProvider = symbolProvider; - return this; - } - - /** - * @param fileManifest The file manifest being used in the generator. - * @return Returns the builder. - */ - public Builder fileManifest(FileManifest fileManifest) { - this.fileManifest = fileManifest; - return this; - } - - /** - * @param writerDelegator The writer delegator to use in the generator. - * @return Returns the builder. - */ - public Builder writerDelegator(GoDelegator writerDelegator) { - this.writerDelegator = writerDelegator; - return this; - } - - /** - * @param integrations The integrations to use in the generator. - * @return Returns the builder. - */ - public Builder integrations(List integrations) { - this.integrations.clear(); - this.integrations.addAll(integrations); - return this; - } - - /** - * @param protocolGenerator The resolved protocol generator to use. - * @return Returns the builder. - */ - public Builder protocolGenerator(ProtocolGenerator protocolGenerator) { - this.protocolGenerator = protocolGenerator; - return this; - } - + public Builder protocolGenerator(ProtocolGenerator protocolGenerator) { + this.protocolGenerator = protocolGenerator; + return this; } + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDelegator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDelegator.java index c2d5956024..76503ca034 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDelegator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDelegator.java @@ -24,7 +24,8 @@ * for getting shape specific GoWriters. */ public final class GoDelegator extends WriterDelegator { - public GoDelegator(FileManifest fileManifest, SymbolProvider symbolProvider) { - super(fileManifest, symbolProvider, new GoWriter.GoWriterFactory()); - } + + public GoDelegator(FileManifest fileManifest, SymbolProvider symbolProvider) { + super(fileManifest, symbolProvider, new GoWriter.GoWriterFactory()); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDependency.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDependency.java index ef207ff401..1092553d69 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDependency.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDependency.java @@ -15,11 +15,6 @@ package software.amazon.polymorph.smithygo.codegen; -import software.amazon.smithy.codegen.core.SymbolDependency; -import software.amazon.smithy.codegen.core.SymbolDependencyContainer; -import software.amazon.smithy.utils.SetUtils; -import software.amazon.smithy.utils.SmithyBuilder; - import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -27,330 +22,377 @@ import java.util.Objects; import java.util.Set; import java.util.TreeSet; +import software.amazon.smithy.codegen.core.SymbolDependency; +import software.amazon.smithy.codegen.core.SymbolDependencyContainer; +import software.amazon.smithy.utils.SetUtils; +import software.amazon.smithy.utils.SmithyBuilder; public final class GoDependency implements SymbolDependencyContainer { - private final Type type; - private final String sourcePath; - private final String importPath; - private final String alias; - private final String version; - private final Set dependencies; - private final SymbolDependency symbolDependency; - - private GoDependency(Builder builder) { - this.type = SmithyBuilder.requiredState("type", builder.type); - this.sourcePath = !this.type.equals(Type.STANDARD_LIBRARY) - ? SmithyBuilder.requiredState("sourcePath", builder.sourcePath) : ""; - this.importPath = SmithyBuilder.requiredState("importPath", builder.importPath); - this.alias = builder.alias; - this.version = SmithyBuilder.requiredState("version", builder.version); - this.dependencies = builder.dependencies; - - this.symbolDependency = SymbolDependency.builder() - .dependencyType(this.type.toString()) - .packageName(this.sourcePath) - .version(this.version) - .build(); + + private final Type type; + private final String sourcePath; + private final String importPath; + private final String alias; + private final String version; + private final Set dependencies; + private final SymbolDependency symbolDependency; + + private GoDependency(Builder builder) { + this.type = SmithyBuilder.requiredState("type", builder.type); + this.sourcePath = + !this.type.equals(Type.STANDARD_LIBRARY) + ? SmithyBuilder.requiredState("sourcePath", builder.sourcePath) + : ""; + this.importPath = + SmithyBuilder.requiredState("importPath", builder.importPath); + this.alias = builder.alias; + this.version = SmithyBuilder.requiredState("version", builder.version); + this.dependencies = builder.dependencies; + + this.symbolDependency = + SymbolDependency + .builder() + .dependencyType(this.type.toString()) + .packageName(this.sourcePath) + .version(this.version) + .build(); + } + + /** + * Get the the set of {@link GoDependency} required by this dependency. + * + * @return the set of dependencies + */ + public Set getGoDependencies() { + return this.dependencies; + } + + /** + * Get the symbol dependency representing the dependency. + * + * @return the symbol dependency + */ + public SymbolDependency getSymbolDependency() { + return symbolDependency; + } + + /** + * Get the type of dependency. + * + * @return the dependency type + */ + public Type getType() { + return type; + } + + /** + * Get the source code path of the dependency. + * + * @return the dependency source code path + */ + public String getSourcePath() { + return sourcePath; + } + + /** + * Get the import path of the dependency. + * + * @return the import path of the dependency + */ + public String getImportPath() { + return importPath; + } + + /** + * Get the alias of the module to use. + * + * @return the alias + */ + public String getAlias() { + return alias; + } + + /** + * Get the version of the dependency. + * + * @return the version + */ + public String getVersion() { + return version; + } + + @Override + public List getDependencies() { + Set symbolDependencySet = new TreeSet<>( + SetUtils.of(getSymbolDependency()) + ); + + symbolDependencySet.addAll( + resolveDependencies(getGoDependencies(), new HashSet<>(SetUtils.of(this))) + ); + + return new ArrayList<>(symbolDependencySet); + } + + private Set resolveDependencies( + Set goDependencies, + Set processed + ) { + Set symbolDependencies = new TreeSet<>(); + if (goDependencies.size() == 0) { + return symbolDependencies; } - /** - * Get the the set of {@link GoDependency} required by this dependency. - * - * @return the set of dependencies - */ - public Set getGoDependencies() { - return this.dependencies; + Set dependenciesToResolve = new TreeSet<>(); + for (GoDependency dependency : goDependencies) { + if (processed.contains(dependency)) { + continue; + } + processed.add(dependency); + symbolDependencies.add(dependency.getSymbolDependency()); + dependenciesToResolve.addAll(dependency.getGoDependencies()); } - /** - * Get the symbol dependency representing the dependency. - * - * @return the symbol dependency - */ - public SymbolDependency getSymbolDependency() { - return symbolDependency; + symbolDependencies.addAll( + resolveDependencies(dependenciesToResolve, processed) + ); + + return symbolDependencies; + } + + public static Builder builder() { + return new Builder(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } else if (!(o instanceof GoDependency)) { + return false; } - /** - * Get the type of dependency. - * - * @return the dependency type - */ - public Type getType() { - return type; + GoDependency other = (GoDependency) o; + + return ( + this.type.equals(other.type) && + this.sourcePath.equals(other.sourcePath) && + this.importPath.equals(other.importPath) && + this.alias.equals(other.alias) && + this.version.equals(other.version) && + this.dependencies.equals(other.dependencies) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + type, + sourcePath, + importPath, + alias, + version, + dependencies + ); + } + + /** + * Represents a dependency type. + */ + public enum Type { + STANDARD_LIBRARY, + DEPENDENCY; + + @Override + public String toString() { + switch (this) { + case STANDARD_LIBRARY: + return "stdlib"; + case DEPENDENCY: + return "dependency"; + default: + return "unknown"; + } } + } + + /** + * Get {@link GoDependency} representing the provided module description. + * + * @param sourcePath the root source path for the given code + * @param importPath the import path of the package + * @param version the version of source module + * @param alias a default alias to use when importing the package, can be null + * @return the dependency + */ + public static GoDependency moduleDependency( + String sourcePath, + String importPath, + String version, + String alias + ) { + Builder builder = GoDependency + .builder() + .type(Type.DEPENDENCY) + .sourcePath(sourcePath) + .importPath(importPath) + .version(version); + if (alias != null) { + builder.alias(alias); + } + return builder.build(); + } + + /** + * Get {@link GoDependency} representing the standard library import description. + * + * @param importPath the import path of the package + * @param version the version of source module + * @return the dependency + */ + public static GoDependency standardLibraryDependency( + String importPath, + String version + ) { + return GoDependency + .builder() + .type(Type.STANDARD_LIBRARY) + .importPath(importPath) + .version(version) + .build(); + } + + /** + * Get {@link GoDependency} representing the standard library import description. + * + * @param importPath the import path of the package + * @param version the version of source module + * @param alias the alias for stdlib dependency + * @return the dependency + */ + public static GoDependency standardLibraryDependency( + String importPath, + String version, + String alias + ) { + Builder builder = GoDependency + .builder() + .type(Type.STANDARD_LIBRARY) + .importPath(importPath) + .version(version); + + if (alias != null) { + builder.alias(alias); + } + return builder.build(); + } + + /** + * Builder for {@link GoDependency}. + */ + public static final class Builder implements SmithyBuilder { + + private Type type; + private String sourcePath; + private String importPath; + private String alias; + private String version; + private final Set dependencies = new TreeSet<>(); + + private Builder() {} /** - * Get the source code path of the dependency. + * Set the dependency type. * - * @return the dependency source code path + * @param type dependency type + * @return the builder */ - public String getSourcePath() { - return sourcePath; + public Builder type(Type type) { + this.type = type; + return this; } /** - * Get the import path of the dependency. + * Set the source path. * - * @return the import path of the dependency + * @param sourcePath the source path root + * @return the builder */ - public String getImportPath() { - return importPath; + public Builder sourcePath(String sourcePath) { + this.sourcePath = sourcePath; + return this; } /** - * Get the alias of the module to use. + * Set the import path. * - * @return the alias + * @param importPath the import path + * @return the builder */ - public String getAlias() { - return alias; + public Builder importPath(String importPath) { + this.importPath = importPath; + return this; } /** - * Get the version of the dependency. + * Set the dependency alias. * - * @return the version + * @param alias the alias + * @return the builder */ - public String getVersion() { - return version; - } - - @Override - public List getDependencies() { - Set symbolDependencySet = new TreeSet<>(SetUtils.of(getSymbolDependency())); - - symbolDependencySet.addAll(resolveDependencies(getGoDependencies(), new HashSet<>(SetUtils.of(this)))); - - return new ArrayList<>(symbolDependencySet); - } - - private Set resolveDependencies(Set goDependencies, Set processed) { - Set symbolDependencies = new TreeSet<>(); - if (goDependencies.size() == 0) { - return symbolDependencies; - } - - Set dependenciesToResolve = new TreeSet<>(); - for (GoDependency dependency : goDependencies) { - if (processed.contains(dependency)) { - continue; - } - processed.add(dependency); - symbolDependencies.add(dependency.getSymbolDependency()); - dependenciesToResolve.addAll(dependency.getGoDependencies()); - } - - symbolDependencies.addAll(resolveDependencies(dependenciesToResolve, processed)); - - return symbolDependencies; - } - - public static Builder builder() { - return new Builder(); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } else if (!(o instanceof GoDependency)) { - return false; - } - - GoDependency other = (GoDependency) o; - - return this.type.equals(other.type) && this.sourcePath.equals(other.sourcePath) - && this.importPath.equals(other.importPath) && this.alias.equals(other.alias) - && this.version.equals(other.version) && this.dependencies.equals(other.dependencies); - } - - @Override - public int hashCode() { - return Objects.hash(type, sourcePath, importPath, alias, version, dependencies); + public Builder alias(String alias) { + this.alias = alias; + return this; } /** - * Represents a dependency type. + * Set the dependency version. + * + * @param version the version + * @return the builder */ - public enum Type { - STANDARD_LIBRARY, DEPENDENCY; - - @Override - public String toString() { - switch (this) { - case STANDARD_LIBRARY: - return "stdlib"; - case DEPENDENCY: - return "dependency"; - default: - return "unknown"; - } - } + public Builder version(String version) { + this.version = version; + return this; } /** - * Get {@link GoDependency} representing the provided module description. + * Set the collection of {@link GoDependency} required by this dependency. * - * @param sourcePath the root source path for the given code - * @param importPath the import path of the package - * @param version the version of source module - * @param alias a default alias to use when importing the package, can be null - * @return the dependency + * @param dependencies a collection of dependencies + * @return the builder */ - public static GoDependency moduleDependency(String sourcePath, String importPath, String version, String alias) { - Builder builder = GoDependency.builder() - .type(Type.DEPENDENCY) - .sourcePath(sourcePath) - .importPath(importPath) - .version(version); - if (alias != null) { - builder.alias(alias); - } - return builder.build(); + public Builder dependencies(Collection dependencies) { + this.dependencies.clear(); + this.dependencies.addAll(dependencies); + return this; } /** - * Get {@link GoDependency} representing the standard library import description. + * Add a dependency on another {@link GoDependency}. * - * @param importPath the import path of the package - * @param version the version of source module - * @return the dependency + * @param dependency the dependency + * @return the builder */ - public static GoDependency standardLibraryDependency(String importPath, String version) { - return GoDependency.builder() - .type(Type.STANDARD_LIBRARY) - .importPath(importPath) - .version(version) - .build(); + public Builder addDependency(GoDependency dependency) { + this.dependencies.add(dependency); + return this; } /** - * Get {@link GoDependency} representing the standard library import description. + * Remove a dependency on another {@link GoDependency}. * - * @param importPath the import path of the package - * @param version the version of source module - * @param alias the alias for stdlib dependency - * @return the dependency + * @param dependency the dependency + * @return the builder */ - public static GoDependency standardLibraryDependency(String importPath, String version, String alias) { - Builder builder = GoDependency.builder() - .type(Type.STANDARD_LIBRARY) - .importPath(importPath) - .version(version); - - if (alias != null) { - builder.alias(alias); - } - return builder.build(); + public Builder removeDependency(GoDependency dependency) { + this.dependencies.remove(dependency); + return this; } - /** - * Builder for {@link GoDependency}. - */ - public static final class Builder implements SmithyBuilder { - private Type type; - private String sourcePath; - private String importPath; - private String alias; - private String version; - private final Set dependencies = new TreeSet<>(); - - private Builder() { - } - - /** - * Set the dependency type. - * - * @param type dependency type - * @return the builder - */ - public Builder type(Type type) { - this.type = type; - return this; - } - - /** - * Set the source path. - * - * @param sourcePath the source path root - * @return the builder - */ - public Builder sourcePath(String sourcePath) { - this.sourcePath = sourcePath; - return this; - } - - /** - * Set the import path. - * - * @param importPath the import path - * @return the builder - */ - public Builder importPath(String importPath) { - this.importPath = importPath; - return this; - } - - /** - * Set the dependency alias. - * - * @param alias the alias - * @return the builder - */ - public Builder alias(String alias) { - this.alias = alias; - return this; - } - - /** - * Set the dependency version. - * - * @param version the version - * @return the builder - */ - public Builder version(String version) { - this.version = version; - return this; - } - - /** - * Set the collection of {@link GoDependency} required by this dependency. - * - * @param dependencies a collection of dependencies - * @return the builder - */ - public Builder dependencies(Collection dependencies) { - this.dependencies.clear(); - this.dependencies.addAll(dependencies); - return this; - } - - /** - * Add a dependency on another {@link GoDependency}. - * - * @param dependency the dependency - * @return the builder - */ - public Builder addDependency(GoDependency dependency) { - this.dependencies.add(dependency); - return this; - } - - /** - * Remove a dependency on another {@link GoDependency}. - * - * @param dependency the dependency - * @return the builder - */ - public Builder removeDependency(GoDependency dependency) { - this.dependencies.remove(dependency); - return this; - } - - @Override - public GoDependency build() { - return new GoDependency(this); - } + @Override + public GoDependency build() { + return new GoDependency(this); } + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoSettings.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoSettings.java index 0c079a9b3c..5d9871a06f 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoSettings.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoSettings.java @@ -1,175 +1,195 @@ package software.amazon.polymorph.smithygo.codegen; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.node.ObjectNode; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.ShapeId; -import java.util.Arrays; -import java.util.Objects; -import java.util.Optional; - public class GoSettings { - private static final String SERVICE = "service"; - private static final String MODULE_NAME = "module"; - private static final String MODULE_DESCRIPTION = "moduleDescription"; - private static final String MODULE_VERSION = "moduleVersion"; - private static final String GENERATE_GO_MOD = "generateGoMod"; - private static final String GO_DIRECTIVE = "goDirective"; - - private ShapeId service; - private String moduleName; - private String moduleDescription = ""; - private String moduleVersion; - private Boolean generateGoMod = false; - private ShapeId protocol; - - /** - * Create a settings object from a configuration object node. - * - * @param config Config object to load. - * @return Returns the extracted settings. - */ - public static GoSettings from(ObjectNode config) { - GoSettings settings = new GoSettings(); - config.warnIfAdditionalProperties( - Arrays.asList(SERVICE, MODULE_NAME, MODULE_DESCRIPTION, MODULE_VERSION, GENERATE_GO_MOD, GO_DIRECTIVE)); - - settings.setService(config.expectStringMember(SERVICE).expectShapeId()); - settings.setModuleName(config.expectStringMember("moduleName").getValue()); - settings.setModuleDescription(config.getStringMemberOrDefault( - MODULE_DESCRIPTION, settings.getModuleName() + " client")); - settings.setModuleVersion(config.getStringMemberOrDefault(MODULE_VERSION, null)); - settings.setGenerateGoMod(config.getBooleanMemberOrDefault(GENERATE_GO_MOD, false)); - return settings; - } - - /** - * Gets the id of the service that is being generated. - * - * @return Returns the service id. - * @throws NullPointerException if the service has not been set. - */ - public ShapeId getService() { - return Objects.requireNonNull(service, SERVICE + " not set"); - } - - /** - * Gets the corresponding {@link ServiceShape} from a model. - * - * @param model Model to search for the service shape by ID. - * @return Returns the found {@code Service}. - * @throws NullPointerException if the service has not been set. - * @throws CodegenException if the service is invalid or not found. - */ - public ServiceShape getService(Model model) { - return model - .getShape(getService()) - .orElseThrow(() -> new CodegenException("Service shape not found: " + getService())) - .asServiceShape() - .orElseThrow(() -> new CodegenException("Shape is not a Service: " + getService())); - } - - /** - * Sets the service to generate. - * - * @param service The service to generate. - */ - public void setService(ShapeId service) { - this.service = Objects.requireNonNull(service); - } - - /** - * Gets the required module name for the module that will be generated. - * - * @return Returns the module name. - * @throws NullPointerException if the module name has not been set. - */ - public String getModuleName() { - return Objects.requireNonNull(moduleName, MODULE_NAME + " not set"); - } - - /** - * Sets the name of the module to generate. - * - * @param moduleName The name of the module to generate. - */ - public void setModuleName(String moduleName) { - this.moduleName = Objects.requireNonNull(moduleName); - } - - /** - * Gets the optional module description for the module that will be generated. - * - * @return Returns the module description. - */ - public String getModuleDescription() { - return moduleDescription; - } - - /** - * Sets the description of the module to generate. - * - * @param moduleDescription The description of the module to generate. - */ - public void setModuleDescription(String moduleDescription) { - this.moduleDescription = Objects.requireNonNull(moduleDescription); - } - - /** - * Gets the optional module version for the module that will be generated. - * - * @return Returns the module version. - */ - public Optional getModuleVersion() { - return Optional.ofNullable(moduleVersion); - } - - /** - * Sets the version of the module to generate. - * - * @param moduleVersion The version of the module to generate. - */ - public void setModuleVersion(String moduleVersion) { - if (moduleVersion != null) { - this.moduleVersion = moduleVersion; - } - } - - /** - * Gets the flag for generating go.mod file. - * - * @return Returns if go.mod will be generated (true) or not (false) - */ - public Boolean getGenerateGoMod() { - return generateGoMod; - } - - /** - * Sets the flag for generating go.mod file. - * - * @param generateGoMod If go.mod will be generated (true) or not (false) - */ - public void setGenerateGoMod(Boolean generateGoMod) { - this.generateGoMod = Objects.requireNonNull(generateGoMod); - } - - /** - * Gets the configured protocol to generate. - * - * @return Returns the configured protocol. - */ - public ShapeId getProtocol() { - return protocol; - } - /** - * Sets the protocol to generate. - * - * @param protocol Protocols to generate. - */ - public void setProtocol(ShapeId protocol) { - this.protocol = Objects.requireNonNull(protocol); + private static final String SERVICE = "service"; + private static final String MODULE_NAME = "module"; + private static final String MODULE_DESCRIPTION = "moduleDescription"; + private static final String MODULE_VERSION = "moduleVersion"; + private static final String GENERATE_GO_MOD = "generateGoMod"; + private static final String GO_DIRECTIVE = "goDirective"; + + private ShapeId service; + private String moduleName; + private String moduleDescription = ""; + private String moduleVersion; + private Boolean generateGoMod = false; + private ShapeId protocol; + + /** + * Create a settings object from a configuration object node. + * + * @param config Config object to load. + * @return Returns the extracted settings. + */ + public static GoSettings from(ObjectNode config) { + GoSettings settings = new GoSettings(); + config.warnIfAdditionalProperties( + Arrays.asList( + SERVICE, + MODULE_NAME, + MODULE_DESCRIPTION, + MODULE_VERSION, + GENERATE_GO_MOD, + GO_DIRECTIVE + ) + ); + + settings.setService(config.expectStringMember(SERVICE).expectShapeId()); + settings.setModuleName(config.expectStringMember("moduleName").getValue()); + settings.setModuleDescription( + config.getStringMemberOrDefault( + MODULE_DESCRIPTION, + settings.getModuleName() + " client" + ) + ); + settings.setModuleVersion( + config.getStringMemberOrDefault(MODULE_VERSION, null) + ); + settings.setGenerateGoMod( + config.getBooleanMemberOrDefault(GENERATE_GO_MOD, false) + ); + return settings; + } + + /** + * Gets the id of the service that is being generated. + * + * @return Returns the service id. + * @throws NullPointerException if the service has not been set. + */ + public ShapeId getService() { + return Objects.requireNonNull(service, SERVICE + " not set"); + } + + /** + * Gets the corresponding {@link ServiceShape} from a model. + * + * @param model Model to search for the service shape by ID. + * @return Returns the found {@code Service}. + * @throws NullPointerException if the service has not been set. + * @throws CodegenException if the service is invalid or not found. + */ + public ServiceShape getService(Model model) { + return model + .getShape(getService()) + .orElseThrow(() -> + new CodegenException("Service shape not found: " + getService()) + ) + .asServiceShape() + .orElseThrow(() -> + new CodegenException("Shape is not a Service: " + getService()) + ); + } + + /** + * Sets the service to generate. + * + * @param service The service to generate. + */ + public void setService(ShapeId service) { + this.service = Objects.requireNonNull(service); + } + + /** + * Gets the required module name for the module that will be generated. + * + * @return Returns the module name. + * @throws NullPointerException if the module name has not been set. + */ + public String getModuleName() { + return Objects.requireNonNull(moduleName, MODULE_NAME + " not set"); + } + + /** + * Sets the name of the module to generate. + * + * @param moduleName The name of the module to generate. + */ + public void setModuleName(String moduleName) { + this.moduleName = Objects.requireNonNull(moduleName); + } + + /** + * Gets the optional module description for the module that will be generated. + * + * @return Returns the module description. + */ + public String getModuleDescription() { + return moduleDescription; + } + + /** + * Sets the description of the module to generate. + * + * @param moduleDescription The description of the module to generate. + */ + public void setModuleDescription(String moduleDescription) { + this.moduleDescription = Objects.requireNonNull(moduleDescription); + } + + /** + * Gets the optional module version for the module that will be generated. + * + * @return Returns the module version. + */ + public Optional getModuleVersion() { + return Optional.ofNullable(moduleVersion); + } + + /** + * Sets the version of the module to generate. + * + * @param moduleVersion The version of the module to generate. + */ + public void setModuleVersion(String moduleVersion) { + if (moduleVersion != null) { + this.moduleVersion = moduleVersion; } + } + + /** + * Gets the flag for generating go.mod file. + * + * @return Returns if go.mod will be generated (true) or not (false) + */ + public Boolean getGenerateGoMod() { + return generateGoMod; + } + + /** + * Sets the flag for generating go.mod file. + * + * @param generateGoMod If go.mod will be generated (true) or not (false) + */ + public void setGenerateGoMod(Boolean generateGoMod) { + this.generateGoMod = Objects.requireNonNull(generateGoMod); + } + + /** + * Gets the configured protocol to generate. + * + * @return Returns the configured protocol. + */ + public ShapeId getProtocol() { + return protocol; + } + + /** + * Sets the protocol to generate. + * + * @param protocol Protocols to generate. + */ + public void setProtocol(ShapeId protocol) { + this.protocol = Objects.requireNonNull(protocol); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoWriter.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoWriter.java index aae981c2be..bf3ec60ac4 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoWriter.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoWriter.java @@ -1,5 +1,13 @@ package software.amazon.polymorph.smithygo.codegen; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.regex.Pattern; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolContainer; @@ -12,708 +20,840 @@ import software.amazon.smithy.model.traits.DeprecatedTrait; import software.amazon.smithy.utils.StringUtils; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.regex.Pattern; - public class GoWriter extends SymbolWriter { - private static final Pattern ARGUMENT_NAME_PATTERN = Pattern.compile("\\$([a-z][a-zA-Z_0-9]+)(:\\w)?"); - private final String fullPackageName; - private final ImportDeclarations imports = new ImportDeclarations(); - private final List dependencies = new ArrayList<>(); - private final boolean innerWriter; - - /** - * Initializes the GoWriter for the package and filename to be written to. - * - * @param fullPackageName package and filename to be written to. - */ - public GoWriter(String fullPackageName) { - this(fullPackageName, false); - } - - private GoWriter(String fullPackageName, boolean innerWriter) { - super(new ImportDeclarations()); - this.fullPackageName = fullPackageName; - this.innerWriter = innerWriter; - init(); - } - - private void init() { - trimBlankLines(); - trimTrailingSpaces(); - setIndentText("\t"); - putFormatter('T', new GoSymbolFormatter()); - putFormatter('P', new PointableGoSymbolFormatter()); - putFormatter('W', new GoWritableInjector()); - } - - // TODO figure out better way to annotate where the failure occurs, check templates and args - // TODO to try to find programming bugs. - - /** - * Returns a Writable for the string and args to be composed inline to another writer's contents. - * - * @param contents string to write. - * @param args Arguments to use when evaluating the contents string. - * @return Writable to be evaluated. - */ - @SafeVarargs - public static Writable goTemplate(String contents, Map... args) { - validateTemplateArgsNotNull(args); - return (GoWriter w) -> { - w.writeGoTemplate(contents, args); - }; - } - - public static final class GoWriterFactory implements SymbolWriter.Factory { - - @Override - public GoWriter apply(String filename, String namespace) { - GoWriter writer = new GoWriter(namespace); - return writer; - } - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Consumer fn - ) { - return goBlockTemplate(beforeNewLine, afterNewLine, new Map[0], fn); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Consumer fn - ) { - return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1}, fn); - } - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param args2 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Map args2, - Consumer fn - ) { - return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2}, fn); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param args2 template arguments - * @param args3 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Map args2, - Map args3, - Consumer fn - ) { - return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2, args3}, fn); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param args2 template arguments - * @param args3 template arguments - * @param args4 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Map args2, - Map args3, - Map args4, - Consumer fn - ) { - return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2, args3, args4}, fn); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param args2 template arguments - * @param args3 template arguments - * @param args4 template arguments - * @param args5 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Map args2, - Map args3, - Map args4, - Map args5, - Consumer fn - ) { - return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2, args3, args4, args5}, fn); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map[] args, - Consumer fn - ) { - validateTemplateArgsNotNull(args); - return (GoWriter w) -> { - w.writeGoBlockTemplate(beforeNewLine, afterNewLine, args, fn); - }; - } - - /** - * Returns a Writable that does nothing. - * - * @return Writable that does nothing - */ - public static Writable emptyGoTemplate() { - return (GoWriter w) -> { - }; - } + private static final Pattern ARGUMENT_NAME_PATTERN = Pattern.compile( + "\\$([a-z][a-zA-Z_0-9]+)(:\\w)?" + ); + private final String fullPackageName; + private final ImportDeclarations imports = new ImportDeclarations(); + private final List dependencies = new ArrayList<>(); + private final boolean innerWriter; + + /** + * Initializes the GoWriter for the package and filename to be written to. + * + * @param fullPackageName package and filename to be written to. + */ + public GoWriter(String fullPackageName) { + this(fullPackageName, false); + } + + private GoWriter(String fullPackageName, boolean innerWriter) { + super(new ImportDeclarations()); + this.fullPackageName = fullPackageName; + this.innerWriter = innerWriter; + init(); + } + + private void init() { + trimBlankLines(); + trimTrailingSpaces(); + setIndentText("\t"); + putFormatter('T', new GoSymbolFormatter()); + putFormatter('P', new PointableGoSymbolFormatter()); + putFormatter('W', new GoWritableInjector()); + } + + // TODO figure out better way to annotate where the failure occurs, check templates and args + // TODO to try to find programming bugs. + + /** + * Returns a Writable for the string and args to be composed inline to another writer's contents. + * + * @param contents string to write. + * @param args Arguments to use when evaluating the contents string. + * @return Writable to be evaluated. + */ + @SafeVarargs + public static Writable goTemplate( + String contents, + Map... args + ) { + validateTemplateArgsNotNull(args); + return (GoWriter w) -> { + w.writeGoTemplate(contents, args); + }; + } + + public static final class GoWriterFactory + implements SymbolWriter.Factory { - /** - * Writes the contents and arguments as a template to the writer. - * - * @param contents string to write - * @param args Arguments to use when evaluating the contents string. - */ - @SafeVarargs - public final void writeGoTemplate(String contents, Map... args) { - withTemplate(contents, args, (template) -> { - try { - write(contents); - } catch (Exception e) { - throw new CodegenException("Failed to render template\n" + contents + "\nReason: " + e.getMessage(), e); - } - }); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Consumer fn - ) { - writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[0], fn); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Consumer fn - ) { - writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1}, fn); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param arg2 second map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Map arg2, - Consumer fn - ) { - writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2}, fn); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param arg2 second map argument - * @param arg3 third map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Map arg2, - Map arg3, - Consumer fn - ) { - writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2, arg3}, fn); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param arg2 second map argument - * @param arg3 third map argument - * @param arg4 forth map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Map arg2, - Map arg3, - Map arg4, - Consumer fn - ) { - writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2, arg3, arg4}, fn); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param arg2 second map argument - * @param arg3 third map argument - * @param arg4 forth map argument - * @param arg5 forth map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Map arg2, - Map arg3, - Map arg4, - Map arg5, - Consumer fn - ) { - writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2, arg3, arg4, arg5}, fn); - } - - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map[] args, - Consumer fn - ) { - withTemplate(beforeNewLine, args, (header) -> { - conditionalBlock(header, afterNewLine, true, new Object[0], fn); - }); - } - - private void withTemplate( - String template, - Map[] argMaps, - Consumer fn - ) { - pushState(); - for (var args : argMaps) { - putContext(args); + @Override + public GoWriter apply(String filename, String namespace) { + GoWriter writer = new GoWriter(namespace); + return writer; + } + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Consumer fn + ) { + return goBlockTemplate(beforeNewLine, afterNewLine, new Map[0], fn); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Consumer fn + ) { + return goBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { args1 }, + fn + ); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param args2 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Map args2, + Consumer fn + ) { + return goBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { args1, args2 }, + fn + ); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param args2 template arguments + * @param args3 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Map args2, + Map args3, + Consumer fn + ) { + return goBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { args1, args2, args3 }, + fn + ); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param args2 template arguments + * @param args3 template arguments + * @param args4 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Map args2, + Map args3, + Map args4, + Consumer fn + ) { + return goBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { args1, args2, args3, args4 }, + fn + ); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param args2 template arguments + * @param args3 template arguments + * @param args4 template arguments + * @param args5 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Map args2, + Map args3, + Map args4, + Map args5, + Consumer fn + ) { + return goBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { args1, args2, args3, args4, args5 }, + fn + ); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map[] args, + Consumer fn + ) { + validateTemplateArgsNotNull(args); + return (GoWriter w) -> { + w.writeGoBlockTemplate(beforeNewLine, afterNewLine, args, fn); + }; + } + + /** + * Returns a Writable that does nothing. + * + * @return Writable that does nothing + */ + public static Writable emptyGoTemplate() { + return (GoWriter w) -> {}; + } + + /** + * Writes the contents and arguments as a template to the writer. + * + * @param contents string to write + * @param args Arguments to use when evaluating the contents string. + */ + @SafeVarargs + public final void writeGoTemplate( + String contents, + Map... args + ) { + withTemplate( + contents, + args, + template -> { + try { + write(contents); + } catch (Exception e) { + throw new CodegenException( + "Failed to render template\n" + + contents + + "\nReason: " + + e.getMessage(), + e + ); } - validateContext(template); - fn.accept(template); - popState(); - } - - private GoWriter conditionalBlock( - String beforeNewLine, - String afterNewLine, - boolean conditional, - Object[] args, - Consumer fn - ) { - if (conditional) { - openBlock(beforeNewLine.trim(), args); + } + ); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Consumer fn + ) { + writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[0], fn); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Consumer fn + ) { + writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[] { arg1 }, fn); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param arg2 second map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Map arg2, + Consumer fn + ) { + writeGoBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { arg1, arg2 }, + fn + ); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param arg2 second map argument + * @param arg3 third map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Map arg2, + Map arg3, + Consumer fn + ) { + writeGoBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { arg1, arg2, arg3 }, + fn + ); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param arg2 second map argument + * @param arg3 third map argument + * @param arg4 forth map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Map arg2, + Map arg3, + Map arg4, + Consumer fn + ) { + writeGoBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { arg1, arg2, arg3, arg4 }, + fn + ); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param arg2 second map argument + * @param arg3 third map argument + * @param arg4 forth map argument + * @param arg5 forth map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Map arg2, + Map arg3, + Map arg4, + Map arg5, + Consumer fn + ) { + writeGoBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { arg1, arg2, arg3, arg4, arg5 }, + fn + ); + } + + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map[] args, + Consumer fn + ) { + withTemplate( + beforeNewLine, + args, + header -> { + conditionalBlock(header, afterNewLine, true, new Object[0], fn); + } + ); + } + + private void withTemplate( + String template, + Map[] argMaps, + Consumer fn + ) { + pushState(); + for (var args : argMaps) { + putContext(args); + } + validateContext(template); + fn.accept(template); + popState(); + } + + private GoWriter conditionalBlock( + String beforeNewLine, + String afterNewLine, + boolean conditional, + Object[] args, + Consumer fn + ) { + if (conditional) { + openBlock(beforeNewLine.trim(), args); + } + + fn.accept(this); + + if (conditional) { + closeBlock(afterNewLine.trim()); + } + + return this; + } + + private static void validateTemplateArgsNotNull( + Map[] argMaps + ) { + for (var args : argMaps) { + args.forEach((k, v) -> { + if (v == null) { + throw new CodegenException( + "Template argument " + k + " cannot be null" + ); } - - fn.accept(this); - - if (conditional) { - closeBlock(afterNewLine.trim()); + }); + } + } + + private void validateContext(String template) { + var matcher = ARGUMENT_NAME_PATTERN.matcher(template); + + while (matcher.find()) { + var keyName = matcher.group(1); + var value = getContext(keyName); + if (value == null) { + throw new CodegenException( + "Go template expected " + + keyName + + " but was not present in context scope." + + " Template: \n" + + template + ); + } + } + } + + /** + * Imports one or more symbols if necessary, using the name of the + * symbol and only "USE" references. + * + * @param container Container of symbols to add. + * @return Returns the writer. + */ + public GoWriter addUseImports(SymbolContainer container) { + for (Symbol symbol : container.getSymbols()) { + addImport( + symbol, + CodegenUtils.getSymbolNamespaceAlias(symbol), + SymbolReference.ContextOption.USE + ); + } + return this; + } + + /** + * Imports a symbol reference if necessary, using the alias of the + * reference and only associated "USE" references. + * + * @param symbolReference Symbol reference to import. + * @return Returns the writer. + */ + public GoWriter addUseImports(SymbolReference symbolReference) { + return addImport( + symbolReference.getSymbol(), + symbolReference.getAlias(), + SymbolReference.ContextOption.USE + ); + } + + /** + * Adds and imports the given dependency. + * + * @param goDependency The GoDependency to import. + * @return Returns the writer. + */ + public GoWriter addUseImports(GoDependency goDependency) { + dependencies.addAll(goDependency.getDependencies()); + return addImport(goDependency.getImportPath(), goDependency.getAlias()); + } + + private GoWriter addImports(GoWriter other) { + this.imports.addImports(other.imports); + return this; + } + + private boolean isExternalNamespace(String namespace) { + return ( + !StringUtils.isBlank(namespace) && !namespace.equals(fullPackageName) + ); + } + + void addImportReferences( + Symbol symbol, + SymbolReference.ContextOption... options + ) { + for (SymbolReference reference : symbol.getReferences()) { + for (SymbolReference.ContextOption option : options) { + if (reference.hasOption(option)) { + addImport(reference.getSymbol(), reference.getAlias(), options); + break; } - - return this; - } - - private static void validateTemplateArgsNotNull(Map[] argMaps) { - for (var args : argMaps) { - args.forEach((k, v) -> { - if (v == null) { - throw new CodegenException("Template argument " + k + " cannot be null"); - } - }); + } + } + } + + /** + * Imports a package using an alias if necessary. + * + * @param packageName Package to import. + * @param as Alias to refer to the package as. + * @return Returns the writer. + */ + public GoWriter addImport(String packageName, String as) { + imports.addImport(packageName, as); + return this; + } + + public GoWriter addImportFromModule( + String moduleName, + String packageName, + String as + ) { + imports.addImport(moduleName.concat("/").concat(packageName), as); + return this; + } + + public GoWriter addImportFromModule(String moduleName, String packageName) { + imports.addImport(moduleName.concat("/").concat(packageName), ""); + return this; + } + + public GoWriter addImport(String packageName) { + imports.addImport(packageName, ""); + return this; + } + + private GoWriter addDependencies(GoWriter other) { + this.dependencies.addAll(other.getDependencies()); + return this; + } + + private boolean isTargetDeprecated(Model model, MemberShape member) { + return ( + model + .expectShape(member.getTarget()) + .getTrait(DeprecatedTrait.class) + .isPresent() && + // don't consider deprecated prelude shapes (like PrimitiveBoolean) + !Prelude.isPreludeShape(member.getTarget()) + ); + } + + @Override + public String toString() { + String contents = super.toString(); + + if (innerWriter) { + return contents; + } + + String[] packageParts = fullPackageName.split("/"); + String header = String.format( + "// Code generated by smithy-go-codegen DO NOT EDIT.%n%n" + ); + + String packageName = packageParts[packageParts.length - 1]; + if (packageName.startsWith("v") && packageParts.length >= 2) { + String remaining = packageName.substring(1); + try { + int value = Integer.parseInt(remaining); + packageName = packageParts[packageParts.length - 2]; + if (value == 0 || value == 1) { + throw new CodegenException( + "module paths vN version component must only be N >= 2" + ); } + } catch (NumberFormatException ne) { + // Do nothing + } } - private void validateContext(String template) { - var matcher = ARGUMENT_NAME_PATTERN.matcher(template); - - while (matcher.find()) { - var keyName = matcher.group(1); - var value = getContext(keyName); - if (value == null) { - throw new CodegenException( - "Go template expected " + keyName + " but was not present in context scope." - + " Template: \n" + template); - } - } - } - - /** - * Imports one or more symbols if necessary, using the name of the - * symbol and only "USE" references. - * - * @param container Container of symbols to add. - * @return Returns the writer. - */ - public GoWriter addUseImports(SymbolContainer container) { - for (Symbol symbol : container.getSymbols()) { - addImport(symbol, - CodegenUtils.getSymbolNamespaceAlias(symbol), - SymbolReference.ContextOption.USE); - } - return this; - } - - /** - * Imports a symbol reference if necessary, using the alias of the - * reference and only associated "USE" references. - * - * @param symbolReference Symbol reference to import. - * @return Returns the writer. - */ - public GoWriter addUseImports(SymbolReference symbolReference) { - return addImport(symbolReference.getSymbol(), symbolReference.getAlias(), SymbolReference.ContextOption.USE); - } - - /** - * Adds and imports the given dependency. - * - * @param goDependency The GoDependency to import. - * @return Returns the writer. - */ - public GoWriter addUseImports(GoDependency goDependency) { - dependencies.addAll(goDependency.getDependencies()); - return addImport(goDependency.getImportPath(), goDependency.getAlias()); - } - - private GoWriter addImports(GoWriter other) { - this.imports.addImports(other.imports); - return this; - } - - private boolean isExternalNamespace(String namespace) { - return !StringUtils.isBlank(namespace) && !namespace.equals(fullPackageName); - } + String packageStatement = String.format("package %s%n%n", packageName); - void addImportReferences(Symbol symbol, SymbolReference.ContextOption... options) { - for (SymbolReference reference : symbol.getReferences()) { - for (SymbolReference.ContextOption option : options) { - if (reference.hasOption(option)) { - addImport(reference.getSymbol(), reference.getAlias(), options); - break; - } - } - } - } + String importString = imports.toString(); + String strippedContents = StringUtils.stripStart(contents, null); + String strippedImportString = StringUtils.strip(importString, null); - /** - * Imports a package using an alias if necessary. - * - * @param packageName Package to import. - * @param as Alias to refer to the package as. - * @return Returns the writer. - */ - public GoWriter addImport(String packageName, String as) { - imports.addImport(packageName, as); - return this; - } - - public GoWriter addImportFromModule(String moduleName, String packageName, String as) { - imports.addImport(moduleName.concat("/").concat(packageName), as); - return this; - } - - public GoWriter addImportFromModule(String moduleName, String packageName) { - imports.addImport(moduleName.concat("/").concat(packageName), ""); - return this; - } - - public GoWriter addImport(String packageName) { - imports.addImport(packageName, ""); - return this; - } - - private GoWriter addDependencies(GoWriter other) { - this.dependencies.addAll(other.getDependencies()); - return this; + // Don't add an additional new line between explicit imports and managed imports. + if ( + !strippedImportString.isEmpty() && strippedContents.startsWith("import ") + ) { + return header + strippedImportString + "\n" + strippedContents; } + return header + packageStatement + importString + contents; + } - private boolean isTargetDeprecated(Model model, MemberShape member) { - return model.expectShape(member.getTarget()).getTrait(DeprecatedTrait.class).isPresent() - // don't consider deprecated prelude shapes (like PrimitiveBoolean) - && !Prelude.isPreludeShape(member.getTarget()); - } + /** + * Implements Go symbol formatting for the {@code $T} formatter. + */ + private class GoSymbolFormatter + implements BiFunction { @Override - public String toString() { - String contents = super.toString(); - - if (innerWriter) { - return contents; + public String apply(Object type, String indent) { + if (type instanceof Symbol) { + Symbol resolvedSymbol = (Symbol) type; + String literal = resolvedSymbol.getName(); + + boolean isSlice = resolvedSymbol + .getProperty(SymbolUtils.GO_SLICE, Boolean.class) + .orElse(false); + boolean isMap = resolvedSymbol + .getProperty(SymbolUtils.GO_MAP, Boolean.class) + .orElse(false); + if (isSlice || isMap) { + resolvedSymbol = + resolvedSymbol + .getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class) + .orElseThrow(() -> + new CodegenException( + "Expected go element type property to be defined" + ) + ); + literal = + new PointableGoSymbolFormatter().apply(resolvedSymbol, "nested"); + } else if ( + !SymbolUtils.isUniverseType(resolvedSymbol) && + isExternalNamespace(resolvedSymbol.getNamespace()) + ) { + literal = formatWithNamespace(resolvedSymbol); } - - - String[] packageParts = fullPackageName.split("/"); - String header = String.format("// Code generated by smithy-go-codegen DO NOT EDIT.%n%n"); - - String packageName = packageParts[packageParts.length - 1]; - if (packageName.startsWith("v") && packageParts.length >= 2) { - String remaining = packageName.substring(1); - try { - int value = Integer.parseInt(remaining); - packageName = packageParts[packageParts.length - 2]; - if (value == 0 || value == 1) { - throw new CodegenException("module paths vN version component must only be N >= 2"); - } - } catch (NumberFormatException ne) { - // Do nothing - } + addUseImports(resolvedSymbol); + + if (isSlice) { + return "[]" + literal; + } else if (isMap) { + return "map[string]" + literal; + } else { + return literal; } + } else if (type instanceof SymbolReference) { + SymbolReference typeSymbol = (SymbolReference) type; + addImport( + typeSymbol.getSymbol(), + typeSymbol.getAlias(), + SymbolReference.ContextOption.USE + ); + return typeSymbol.getAlias(); + } else { + throw new CodegenException( + "Invalid type provided to $T. Expected a Symbol, but found `" + + type + + "`" + ); + } + } + + private String formatWithNamespace(Symbol symbol) { + if (StringUtils.isEmpty(symbol.getNamespace())) { + return symbol.getName(); + } + return String.format( + "%s.%s", + CodegenUtils.getSymbolNamespaceAlias(symbol), + symbol.getName() + ); + } + } + + /** + * Implements Go symbol formatting for the {@code $P} formatter. This is identical to the $T + * formatter, except that it will add a * to symbols that can be pointers. + */ + private class PointableGoSymbolFormatter extends GoSymbolFormatter { - String packageStatement = String.format("package %s%n%n", packageName); - - String importString = imports.toString(); - String strippedContents = StringUtils.stripStart(contents, null); - String strippedImportString = StringUtils.strip(importString, null); - - // Don't add an additional new line between explicit imports and managed imports. - if (!strippedImportString.isEmpty() && strippedContents.startsWith("import ")) { - return header + strippedImportString + "\n" + strippedContents; - } + @Override + public String apply(Object type, String indent) { + String formatted = super.apply(type, indent); + if (isPointer(type)) { + formatted = "*" + formatted; + } + return formatted; + } + + private boolean isPointer(Object type) { + if (type instanceof Symbol) { + Symbol typeSymbol = (Symbol) type; + return typeSymbol + .getProperty(SymbolUtils.POINTABLE, Boolean.class) + .orElse(false); + } else if (type instanceof SymbolReference) { + SymbolReference typeSymbol = (SymbolReference) type; + return ( + typeSymbol + .getProperty(SymbolUtils.POINTABLE, Boolean.class) + .orElse(false) || + typeSymbol + .getSymbol() + .getProperty(SymbolUtils.POINTABLE, Boolean.class) + .orElse(false) + ); + } else if (type instanceof String) { + return true; + } else { + throw new CodegenException( + "Invalid type provided to $P. Expected a Symbol, but found `" + + type + + "`" + ); + } + } + } + + class GoWritableInjector extends GoSymbolFormatter { - return header + packageStatement + importString + contents; + @Override + public String apply(Object type, String indent) { + if (!(type instanceof Writable)) { + throw new CodegenException( + "expect Writable for GoWriter W injector, but got " + type + ); + } + var innerWriter = new GoWriter(fullPackageName, true); + ((Writable) type).accept(innerWriter); + addImports(innerWriter); + addDependencies(innerWriter); + return innerWriter.toString().trim(); } + } - /** - * Implements Go symbol formatting for the {@code $T} formatter. - */ - private class GoSymbolFormatter implements BiFunction { - @Override - public String apply(Object type, String indent) { - if (type instanceof Symbol) { - Symbol resolvedSymbol = (Symbol) type; - String literal = resolvedSymbol.getName(); - - boolean isSlice = resolvedSymbol.getProperty(SymbolUtils.GO_SLICE, Boolean.class).orElse(false); - boolean isMap = resolvedSymbol.getProperty(SymbolUtils.GO_MAP, Boolean.class).orElse(false); - if (isSlice || isMap) { - resolvedSymbol = resolvedSymbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class) - .orElseThrow(() -> new CodegenException("Expected go element type property to be defined")); - literal = new PointableGoSymbolFormatter().apply(resolvedSymbol, "nested"); - } else if (!SymbolUtils.isUniverseType(resolvedSymbol) - && isExternalNamespace(resolvedSymbol.getNamespace())) { - literal = formatWithNamespace(resolvedSymbol); - } - addUseImports(resolvedSymbol); - - if (isSlice) { - return "[]" + literal; - } else if (isMap) { - return "map[string]" + literal; - } else { - return literal; - } - } else if (type instanceof SymbolReference) { - SymbolReference typeSymbol = (SymbolReference) type; - addImport(typeSymbol.getSymbol(), typeSymbol.getAlias(), SymbolReference.ContextOption.USE); - return typeSymbol.getAlias(); - } else { - throw new CodegenException( - "Invalid type provided to $T. Expected a Symbol, but found `" + type + "`"); - } - } + public interface Writable extends Consumer {} - private String formatWithNamespace(Symbol symbol) { - if (StringUtils.isEmpty(symbol.getNamespace())) { - return symbol.getName(); - } - return String.format("%s.%s", CodegenUtils.getSymbolNamespaceAlias(symbol), symbol.getName()); - } - } + /** + * Chains together multiple Writables that can be composed into one Writable. + */ + public static final class ChainWritable { - /** - * Implements Go symbol formatting for the {@code $P} formatter. This is identical to the $T - * formatter, except that it will add a * to symbols that can be pointers. - */ - private class PointableGoSymbolFormatter extends GoSymbolFormatter { - @Override - public String apply(Object type, String indent) { - String formatted = super.apply(type, indent); - if (isPointer(type)) { - formatted = "*" + formatted; - } - return formatted; - } + private final List writables; - private boolean isPointer(Object type) { - if (type instanceof Symbol) { - Symbol typeSymbol = (Symbol) type; - return typeSymbol.getProperty(SymbolUtils.POINTABLE, Boolean.class).orElse(false); - } else if (type instanceof SymbolReference) { - SymbolReference typeSymbol = (SymbolReference) type; - return typeSymbol.getProperty(SymbolUtils.POINTABLE, Boolean.class).orElse(false) - || typeSymbol.getSymbol().getProperty(SymbolUtils.POINTABLE, Boolean.class).orElse(false); - } else if (type instanceof String) { - return true; - } else { - throw new CodegenException( - "Invalid type provided to $P. Expected a Symbol, but found `" + type + "`"); - } - } + public ChainWritable() { + writables = new ArrayList<>(); } - class GoWritableInjector extends GoSymbolFormatter { - @Override - public String apply(Object type, String indent) { - if (!(type instanceof Writable)) { - throw new CodegenException( - "expect Writable for GoWriter W injector, but got " + type); - } - var innerWriter = new GoWriter(fullPackageName, true); - ((Writable) type).accept(innerWriter); - addImports(innerWriter); - addDependencies(innerWriter); - return innerWriter.toString().trim(); - } + public ChainWritable add(GoWriter.Writable writable) { + writables.add(writable); + return this; } - public interface Writable extends Consumer { + public ChainWritable add(Optional value, Function fn) { + value.ifPresent(t -> writables.add(fn.apply(t))); + return this; } - /** - * Chains together multiple Writables that can be composed into one Writable. - */ - public static final class ChainWritable { - private final List writables; - - public ChainWritable() { - writables = new ArrayList<>(); - } - - public ChainWritable add(GoWriter.Writable writable) { - writables.add(writable); - return this; - } - - public ChainWritable add(Optional value, Function fn) { - value.ifPresent(t -> writables.add(fn.apply(t))); - return this; - } - - public ChainWritable add(boolean include, GoWriter.Writable writable) { - if (!include) { - writables.add(writable); - } - return this; - } + public ChainWritable add(boolean include, GoWriter.Writable writable) { + if (!include) { + writables.add(writable); + } + return this; + } - public GoWriter.Writable compose() { - return (GoWriter writer) -> { - var hasPrevious = false; - for (GoWriter.Writable writable : writables) { - if (hasPrevious) { - writer.write(""); - } - hasPrevious = true; - writer.write("$W", writable); - } - }; + public GoWriter.Writable compose() { + return (GoWriter writer) -> { + var hasPrevious = false; + for (GoWriter.Writable writable : writables) { + if (hasPrevious) { + writer.write(""); + } + hasPrevious = true; + writer.write("$W", writable); } + }; } + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ImportDeclarations.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ImportDeclarations.java index a8c3dcf30f..bd528e9d3c 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ImportDeclarations.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ImportDeclarations.java @@ -1,62 +1,65 @@ package software.amazon.polymorph.smithygo.codegen; +import java.util.Map; +import java.util.TreeMap; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.ImportContainer; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.utils.StringUtils; -import java.util.Map; -import java.util.TreeMap; - public class ImportDeclarations implements ImportContainer { - private final Map imports = new TreeMap<>(); - - ImportDeclarations addImport(String importPath, String alias) { - String importAlias = CodegenUtils.getDefaultPackageImportName(importPath); - if (!StringUtils.isBlank(alias)) { - if (alias.equals(".")) { - // Global imports are generally a bad practice. - throw new CodegenException("Globally importing packages is forbidden: " + importPath); - } - importAlias = alias; - } - imports.putIfAbsent(importAlias, importPath); - return this; - } + private final Map imports = new TreeMap<>(); - ImportDeclarations addImports(ImportDeclarations other) { - other.imports.forEach((importAlias, importPath) -> { - addImport(importPath, importAlias); - }); - return this; + ImportDeclarations addImport(String importPath, String alias) { + String importAlias = CodegenUtils.getDefaultPackageImportName(importPath); + if (!StringUtils.isBlank(alias)) { + if (alias.equals(".")) { + // Global imports are generally a bad practice. + throw new CodegenException( + "Globally importing packages is forbidden: " + importPath + ); + } + importAlias = alias; } + imports.putIfAbsent(importAlias, importPath); + return this; + } - @Override - public String toString() { - if (imports.isEmpty()) { - return ""; - } - - StringBuilder builder = new StringBuilder("import (\n"); - for (Map.Entry entry : imports.entrySet()) { - builder.append('\t'); - builder.append(createImportStatement(entry)); - builder.append('\n'); - } - builder.append(")\n\n"); - return builder.toString(); - } + ImportDeclarations addImports(ImportDeclarations other) { + other.imports.forEach((importAlias, importPath) -> { + addImport(importPath, importAlias); + }); + return this; + } - private String createImportStatement(Map.Entry entry) { - String formattedPackageName = "\"" + entry.getValue() + "\""; - return CodegenUtils.getDefaultPackageImportName(entry.getValue()).equals(entry.getKey()) - ? formattedPackageName - : entry.getKey() + " " + formattedPackageName; + @Override + public String toString() { + if (imports.isEmpty()) { + return ""; } - @Override - public void importSymbol(Symbol symbol, String alias) { - addImport(symbol.getName(), alias); + StringBuilder builder = new StringBuilder("import (\n"); + for (Map.Entry entry : imports.entrySet()) { + builder.append('\t'); + builder.append(createImportStatement(entry)); + builder.append('\n'); } + builder.append(")\n\n"); + return builder.toString(); + } + + private String createImportStatement(Map.Entry entry) { + String formattedPackageName = "\"" + entry.getValue() + "\""; + return CodegenUtils + .getDefaultPackageImportName(entry.getValue()) + .equals(entry.getKey()) + ? formattedPackageName + : entry.getKey() + " " + formattedPackageName; + } + + @Override + public void importSymbol(Symbol symbol, String alias) { + addImport(symbol.getName(), alias); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/IntEnumGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/IntEnumGenerator.java index 3d23121ce3..55387111bc 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/IntEnumGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/IntEnumGenerator.java @@ -32,60 +32,87 @@ * Renders intEnums and their constants. */ public final class IntEnumGenerator implements Runnable { - private static final Logger LOGGER = Logger.getLogger(IntEnumGenerator.class.getName()); - private final SymbolProvider symbolProvider; - private final GoWriter writer; - private final IntEnumShape shape; + private static final Logger LOGGER = Logger.getLogger( + IntEnumGenerator.class.getName() + ); - public IntEnumGenerator(SymbolProvider symbolProvider, GoWriter writer, IntEnumShape shape) { - this.symbolProvider = symbolProvider; - this.writer = writer; - this.shape = shape; - } + private final SymbolProvider symbolProvider; + private final GoWriter writer; + private final IntEnumShape shape; - @Override - public void run() { - Symbol symbol = symbolProvider.toSymbol(shape); + public IntEnumGenerator( + SymbolProvider symbolProvider, + GoWriter writer, + IntEnumShape shape + ) { + this.symbolProvider = symbolProvider; + this.writer = writer; + this.shape = shape; + } -// TODO(smithy): Use type alias instead of type definition until refactoring -// protocol generators is prioritized. - writer.write("type $L = int32", symbol.getName()).write(""); + @Override + public void run() { + Symbol symbol = symbolProvider.toSymbol(shape); - Set constants = new LinkedHashSet<>(); - writer.openBlock("const (", ")", () -> { - for (Map.Entry entry : shape.getAllMembers().entrySet()) { - StringBuilder labelBuilder = new StringBuilder(symbol.getName()); - String name = entry.getKey(); + // TODO(smithy): Use type alias instead of type definition until refactoring + // protocol generators is prioritized. + writer.write("type $L = int32", symbol.getName()).write(""); - for (String part : name.split("(?U)[\\W_]")) { - if (part.matches(".*[a-z].*") && part.matches(".*[A-Z].*")) { -// Mixed case names should not be changed other than first letter capitalized. - labelBuilder.append(StringUtils.capitalize(part)); - } else { -// For all non-mixed case parts title case first letter, followed by all other lower cased. - labelBuilder.append(StringUtils.capitalize(part.toLowerCase(Locale.US))); - } - } - String label = labelBuilder.toString(); + Set constants = new LinkedHashSet<>(); + writer + .openBlock( + "const (", + ")", + () -> { + for (Map.Entry entry : shape + .getAllMembers() + .entrySet()) { + StringBuilder labelBuilder = new StringBuilder(symbol.getName()); + String name = entry.getKey(); -// If camel-casing would cause a conflict, don't camel-case this enum value. - if (constants.contains(label)) { - LOGGER.warning(String.format( - "Multiple enums resolved to the same name, `%s`, using unaltered value for: %s", - label, name)); - label = name; - } - constants.add(label); + for (String part : name.split("(?U)[\\W_]")) { + if (part.matches(".*[a-z].*") && part.matches(".*[A-Z].*")) { + // Mixed case names should not be changed other than first letter capitalized. + labelBuilder.append(StringUtils.capitalize(part)); + } else { + // For all non-mixed case parts title case first letter, followed by all other lower cased. + labelBuilder.append( + StringUtils.capitalize(part.toLowerCase(Locale.US)) + ); + } + } + String label = labelBuilder.toString(); - writer.write("$L $L = $L", label, symbol.getName(), - entry.getValue().expectTrait(EnumValueTrait.class).expectIntValue()); + // If camel-casing would cause a conflict, don't camel-case this enum value. + if (constants.contains(label)) { + LOGGER.warning( + String.format( + "Multiple enums resolved to the same name, `%s`, using unaltered value for: %s", + label, + name + ) + ); + label = name; } - }).write(""); + constants.add(label); -// TODO(smithy): type aliases don't allow defining methods on base types (e.g. int32). -// Uncomment generating the Value() method when the type alias is migrated to type definition. -/* + writer.write( + "$L $L = $L", + label, + symbol.getName(), + entry + .getValue() + .expectTrait(EnumValueTrait.class) + .expectIntValue() + ); + } + } + ) + .write(""); + // TODO(smithy): type aliases don't allow defining methods on base types (e.g. int32). + // Uncomment generating the Value() method when the type alias is migrated to type definition. + /* writer.writeDocs(String.format("Values returns all known values for %s. Note that this can be expanded in the " + "future, and so it is only as up to date as the client.%n%nThe ordering of this slice is not " + "guaranteed to be stable across updates.", symbol.getName())); @@ -97,5 +124,5 @@ public void run() { }); }); */ - } -} \ No newline at end of file + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SmithyGoDependency.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SmithyGoDependency.java index 20955d8ea8..c5c95d399c 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SmithyGoDependency.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SmithyGoDependency.java @@ -19,116 +19,171 @@ * A class of constants for dependencies used by this package. */ public final class SmithyGoDependency { - // The version in the stdlib dependencies should reflect the minimum Go version. - // The values aren't currently used, but they could potentially used to dynamically - // set the minimum go version. - public static final GoDependency BIG = stdlib("math/big"); - public static final GoDependency TIME = stdlib("time"); - public static final GoDependency FMT = stdlib("fmt"); - public static final GoDependency CONTEXT = stdlib("context"); - public static final GoDependency STRCONV = stdlib("strconv"); - public static final GoDependency BASE64 = stdlib("encoding/base64"); - public static final GoDependency NET = stdlib("net"); - public static final GoDependency NET_URL = stdlib("net/url"); - public static final GoDependency NET_HTTP = stdlib("net/http"); - public static final GoDependency NET_HTTP_TEST = stdlib("net/http/httptest"); - public static final GoDependency BYTES = stdlib("bytes"); - public static final GoDependency STRINGS = stdlib("strings"); - public static final GoDependency JSON = stdlib("encoding/json"); - public static final GoDependency IO = stdlib("io"); - public static final GoDependency IOUTIL = stdlib("io/ioutil"); - public static final GoDependency CRYPTORAND = stdlib("crypto/rand", "cryptorand"); - public static final GoDependency TESTING = stdlib("testing"); - public static final GoDependency ERRORS = stdlib("errors"); - public static final GoDependency XML = stdlib("encoding/xml"); - public static final GoDependency SYNC = stdlib("sync"); - public static final GoDependency PATH = stdlib("path"); - - public static final GoDependency SMITHY = smithy(null, "smithy"); - public static final GoDependency SMITHY_HTTP_TRANSPORT = smithy("transport/http", "smithyhttp"); - public static final GoDependency SMITHY_MIDDLEWARE = smithy("middleware"); - public static final GoDependency SMITHY_TIME = smithy("time", "smithytime"); - public static final GoDependency SMITHY_HTTP_BINDING = smithy("encoding/httpbinding"); - public static final GoDependency SMITHY_JSON = smithy("encoding/json", "smithyjson"); - public static final GoDependency SMITHY_XML = smithy("encoding/xml", "smithyxml"); - public static final GoDependency SMITHY_IO = smithy("io", "smithyio"); - public static final GoDependency SMITHY_LOGGING = smithy("logging"); - public static final GoDependency SMITHY_PTR = smithy("ptr"); - public static final GoDependency SMITHY_RAND = smithy("rand", "smithyrand"); - public static final GoDependency SMITHY_TESTING = smithy("testing", "smithytesting"); - public static final GoDependency SMITHY_WAITERS = smithy("waiter", "smithywaiter"); - public static final GoDependency SMITHY_DOCUMENT = smithy("document", "smithydocument"); - public static final GoDependency SMITHY_DOCUMENT_JSON = smithy("document/json", "smithydocumentjson"); - public static final GoDependency SMITHY_SYNC = smithy("sync", "smithysync"); - public static final GoDependency SMITHY_AUTH_BEARER = smithy("auth/bearer"); - - public static final GoDependency GO_CMP = goCmp("cmp"); - public static final GoDependency GO_CMP_OPTIONS = goCmp("cmp/cmpopts"); - - public static final GoDependency GO_JMESPATH = goJmespath(null); - public static final GoDependency MATH = stdlib("math"); - - private static final String SMITHY_SOURCE_PATH = "github.com/aws/smithy-go"; - private static final String GO_CMP_SOURCE_PATH = "github.com/google/go-cmp"; - private static final String GO_JMESPATH_SOURCE_PATH = "github.com/jmespath/go-jmespath"; - - private SmithyGoDependency() { - } - /** - * Get a {@link GoDependency} representing the standard library package import path. - * - * @param importPath standard library import path - * @return the {@link GoDependency} for the package import path - */ - public static GoDependency stdlib(String importPath) { - return GoDependency.standardLibraryDependency(importPath, Versions.GO_STDLIB); - } + // The version in the stdlib dependencies should reflect the minimum Go version. + // The values aren't currently used, but they could potentially used to dynamically + // set the minimum go version. + public static final GoDependency BIG = stdlib("math/big"); + public static final GoDependency TIME = stdlib("time"); + public static final GoDependency FMT = stdlib("fmt"); + public static final GoDependency CONTEXT = stdlib("context"); + public static final GoDependency STRCONV = stdlib("strconv"); + public static final GoDependency BASE64 = stdlib("encoding/base64"); + public static final GoDependency NET = stdlib("net"); + public static final GoDependency NET_URL = stdlib("net/url"); + public static final GoDependency NET_HTTP = stdlib("net/http"); + public static final GoDependency NET_HTTP_TEST = stdlib("net/http/httptest"); + public static final GoDependency BYTES = stdlib("bytes"); + public static final GoDependency STRINGS = stdlib("strings"); + public static final GoDependency JSON = stdlib("encoding/json"); + public static final GoDependency IO = stdlib("io"); + public static final GoDependency IOUTIL = stdlib("io/ioutil"); + public static final GoDependency CRYPTORAND = stdlib( + "crypto/rand", + "cryptorand" + ); + public static final GoDependency TESTING = stdlib("testing"); + public static final GoDependency ERRORS = stdlib("errors"); + public static final GoDependency XML = stdlib("encoding/xml"); + public static final GoDependency SYNC = stdlib("sync"); + public static final GoDependency PATH = stdlib("path"); - /** - * Get a {@link GoDependency} representing the standard library package import path with the given alias. - * - * @param importPath standard library package import path - * @param alias the package alias - * @return the {@link GoDependency} for the package import path - */ - public static GoDependency stdlib(String importPath, String alias) { - return GoDependency.standardLibraryDependency(importPath, Versions.GO_STDLIB, alias); - } + public static final GoDependency SMITHY = smithy(null, "smithy"); + public static final GoDependency SMITHY_HTTP_TRANSPORT = smithy( + "transport/http", + "smithyhttp" + ); + public static final GoDependency SMITHY_MIDDLEWARE = smithy("middleware"); + public static final GoDependency SMITHY_TIME = smithy("time", "smithytime"); + public static final GoDependency SMITHY_HTTP_BINDING = smithy( + "encoding/httpbinding" + ); + public static final GoDependency SMITHY_JSON = smithy( + "encoding/json", + "smithyjson" + ); + public static final GoDependency SMITHY_XML = smithy( + "encoding/xml", + "smithyxml" + ); + public static final GoDependency SMITHY_IO = smithy("io", "smithyio"); + public static final GoDependency SMITHY_LOGGING = smithy("logging"); + public static final GoDependency SMITHY_PTR = smithy("ptr"); + public static final GoDependency SMITHY_RAND = smithy("rand", "smithyrand"); + public static final GoDependency SMITHY_TESTING = smithy( + "testing", + "smithytesting" + ); + public static final GoDependency SMITHY_WAITERS = smithy( + "waiter", + "smithywaiter" + ); + public static final GoDependency SMITHY_DOCUMENT = smithy( + "document", + "smithydocument" + ); + public static final GoDependency SMITHY_DOCUMENT_JSON = smithy( + "document/json", + "smithydocumentjson" + ); + public static final GoDependency SMITHY_SYNC = smithy("sync", "smithysync"); + public static final GoDependency SMITHY_AUTH_BEARER = smithy("auth/bearer"); - private static GoDependency smithy(String relativePath) { - return smithy(relativePath, null); - } + public static final GoDependency GO_CMP = goCmp("cmp"); + public static final GoDependency GO_CMP_OPTIONS = goCmp("cmp/cmpopts"); - private static GoDependency smithy(String relativePath, String alias) { - return relativePackage(SMITHY_SOURCE_PATH, relativePath, Versions.SMITHY_GO, alias); - } + public static final GoDependency GO_JMESPATH = goJmespath(null); + public static final GoDependency MATH = stdlib("math"); - private static GoDependency goCmp(String relativePath) { - return relativePackage(GO_CMP_SOURCE_PATH, relativePath, Versions.GO_CMP, null); - } + private static final String SMITHY_SOURCE_PATH = "github.com/aws/smithy-go"; + private static final String GO_CMP_SOURCE_PATH = "github.com/google/go-cmp"; + private static final String GO_JMESPATH_SOURCE_PATH = + "github.com/jmespath/go-jmespath"; - private static GoDependency goJmespath(String relativePath) { - return relativePackage(GO_JMESPATH_SOURCE_PATH, relativePath, Versions.GO_JMESPATH, null); - } + private SmithyGoDependency() {} - private static GoDependency relativePackage( - String moduleImportPath, - String relativePath, - String version, - String alias - ) { - String importPath = moduleImportPath; - if (relativePath != null) { - importPath = importPath + "/" + relativePath; - } - return GoDependency.moduleDependency(moduleImportPath, importPath, version, alias); - } + /** + * Get a {@link GoDependency} representing the standard library package import path. + * + * @param importPath standard library import path + * @return the {@link GoDependency} for the package import path + */ + public static GoDependency stdlib(String importPath) { + return GoDependency.standardLibraryDependency( + importPath, + Versions.GO_STDLIB + ); + } - private static final class Versions { - private static final String GO_STDLIB = "1.15"; - private static final String GO_CMP = "v0.5.4"; - private static final String SMITHY_GO = "v1.4.0"; - private static final String GO_JMESPATH = "v0.4.0"; + /** + * Get a {@link GoDependency} representing the standard library package import path with the given alias. + * + * @param importPath standard library package import path + * @param alias the package alias + * @return the {@link GoDependency} for the package import path + */ + public static GoDependency stdlib(String importPath, String alias) { + return GoDependency.standardLibraryDependency( + importPath, + Versions.GO_STDLIB, + alias + ); + } + + private static GoDependency smithy(String relativePath) { + return smithy(relativePath, null); + } + + private static GoDependency smithy(String relativePath, String alias) { + return relativePackage( + SMITHY_SOURCE_PATH, + relativePath, + Versions.SMITHY_GO, + alias + ); + } + + private static GoDependency goCmp(String relativePath) { + return relativePackage( + GO_CMP_SOURCE_PATH, + relativePath, + Versions.GO_CMP, + null + ); + } + + private static GoDependency goJmespath(String relativePath) { + return relativePackage( + GO_JMESPATH_SOURCE_PATH, + relativePath, + Versions.GO_JMESPATH, + null + ); + } + + private static GoDependency relativePackage( + String moduleImportPath, + String relativePath, + String version, + String alias + ) { + String importPath = moduleImportPath; + if (relativePath != null) { + importPath = importPath + "/" + relativePath; } + return GoDependency.moduleDependency( + moduleImportPath, + importPath, + version, + alias + ); + } + + private static final class Versions { + + private static final String GO_STDLIB = "1.15"; + private static final String GO_CMP = "v0.5.4"; + private static final String SMITHY_GO = "v1.4.0"; + private static final String GO_JMESPATH = "v0.4.0"; + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java index 8f0415c4ec..74ef4633e8 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java @@ -15,14 +15,21 @@ package software.amazon.polymorph.smithygo.codegen; +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + +import java.math.BigDecimal; +import java.util.HashSet; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; import software.amazon.polymorph.smithygo.localservice.nameresolver.SmithyNameResolver; import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; import software.amazon.polymorph.traits.ReferenceTrait; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.MemberShape; +import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.LengthTrait; @@ -31,147 +38,193 @@ import software.amazon.smithy.model.traits.StreamingTrait; import software.amazon.smithy.utils.SetUtils; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - -import java.math.BigDecimal; -import java.util.HashSet; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; - /** * Renders structures. */ public final class StructureGenerator implements Runnable { - private static final Set ERROR_MEMBER_NAMES = SetUtils.of("ErrorMessage", "Message", "ErrorCodeOverride"); - - private final Model model; - private final SymbolProvider symbolProvider; - private final GoWriter writer; - private final StructureShape shape; - private final GenerationContext context; - private final ValidationGenerator validationGenerator; - - public StructureGenerator( - final GenerationContext context, - GoWriter writer, - StructureShape shape) { - this.context = context; - this.model = context.model(); - this.symbolProvider = context.symbolProvider(); - this.writer = writer; - this.shape = shape; - this.validationGenerator = new ValidationGenerator(model, symbolProvider, writer); - } - @Override - public void run() { - if (!shape.hasTrait(ErrorTrait.class)) { - renderStructure(() -> { - }); + private static final Set ERROR_MEMBER_NAMES = SetUtils.of( + "ErrorMessage", + "Message", + "ErrorCodeOverride" + ); + + private final Model model; + private final SymbolProvider symbolProvider; + private final GoWriter writer; + private final StructureShape shape; + private final GenerationContext context; + private final ValidationGenerator validationGenerator; + + public StructureGenerator( + final GenerationContext context, + GoWriter writer, + StructureShape shape + ) { + this.context = context; + this.model = context.model(); + this.symbolProvider = context.symbolProvider(); + this.writer = writer; + this.shape = shape; + this.validationGenerator = + new ValidationGenerator(model, symbolProvider, writer); + } + + @Override + public void run() { + if (!shape.hasTrait(ErrorTrait.class)) { + renderStructure(() -> {}); + } else { + renderErrorStructure(); + } + } + + /** + * Renders a non-error structure. + * + * @param runnable A runnable that runs before the structure definition is closed. This can be used to write + * additional members. + */ + public void renderStructure(Runnable runnable) { + renderStructure(runnable, false); + } + + /** + * Renders a non-error structure. + * + * @param runnable A runnable that runs before the structure definition is closed. This can be used to write + * additional members. + * @param isInputStructure A boolean indicating if input variants for member symbols should be used. + */ + public void renderStructure(Runnable runnable, boolean isInputStructure) { + writer.addImport("fmt"); + Symbol symbol = symbolProvider.toSymbol(shape); + writer.openBlock("type $L struct {", symbol.getName()); + CodegenUtils.SortedMembers sortedMembers = new CodegenUtils.SortedMembers( + symbolProvider + ); + shape + .getAllMembers() + .values() + .stream() + .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) + .sorted(sortedMembers) + .forEach(member -> { + writer.write(""); + + String memberName = symbolProvider.toMemberName(member); + + Symbol memberSymbol = symbolProvider.toSymbol(member); + + var targetShape = model.expectShape(member.getTarget()); + + if (isInputStructure) { + memberSymbol = + memberSymbol + .getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) + .orElse(memberSymbol); + } + var namespace = SmithyNameResolver.smithyTypesNamespace(targetShape); + + if (targetShape.hasTrait(ReferenceTrait.class)) { + memberSymbol = + memberSymbol.getProperty("Referred", Symbol.class).get(); + var refShape = targetShape.expectTrait(ReferenceTrait.class); + if (refShape.isService()) { + namespace = + SmithyNameResolver.shapeNamespace( + model.expectShape(refShape.getReferentId()) + ); + } + if ( + !member + .toShapeId() + .getNamespace() + .equals(refShape.getReferentId().getNamespace()) + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + refShape.getReferentId().getNamespace() + ), + namespace + ); + } } else { - renderErrorStructure(); + if ( + !member + .toShapeId() + .getNamespace() + .equals(targetShape.toShapeId().getNamespace()) && + !targetShape.toShapeId().getNamespace().startsWith("smithy") && + targetShape.asStructureShape().isPresent() + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + targetShape.toShapeId().getNamespace() + ), + namespace + ); + } } - } - /** - * Renders a non-error structure. - * - * @param runnable A runnable that runs before the structure definition is closed. This can be used to write - * additional members. - */ - public void renderStructure(Runnable runnable) { - renderStructure(runnable, false); - } - - /** - * Renders a non-error structure. - * - * @param runnable A runnable that runs before the structure definition is closed. This can be used to write - * additional members. - * @param isInputStructure A boolean indicating if input variants for member symbols should be used. - */ - public void renderStructure(Runnable runnable, boolean isInputStructure) { - writer.addImport("fmt"); - Symbol symbol = symbolProvider.toSymbol(shape); - writer.openBlock("type $L struct {", symbol.getName()); - CodegenUtils.SortedMembers sortedMembers = new CodegenUtils.SortedMembers(symbolProvider); - shape.getAllMembers().values().stream() - .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) - .sorted(sortedMembers) - .forEach((member) -> { - writer.write(""); - - String memberName = symbolProvider.toMemberName(member); - - Symbol memberSymbol = symbolProvider.toSymbol(member); - - var targetShape = model.expectShape(member.getTarget()); - - if (isInputStructure) { - memberSymbol = memberSymbol.getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) - .orElse(memberSymbol); - } - var namespace = SmithyNameResolver.smithyTypesNamespace(targetShape); - - if (targetShape.hasTrait(ReferenceTrait.class)) { - memberSymbol = memberSymbol.getProperty("Referred", Symbol.class).get(); - var refShape = targetShape.expectTrait(ReferenceTrait.class); - if (refShape.isService()) { - namespace = SmithyNameResolver.shapeNamespace(model.expectShape(refShape.getReferentId())); - } - if (!member.toShapeId().getNamespace().equals(refShape.getReferentId().getNamespace())) { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(refShape.getReferentId().getNamespace()), namespace); - } - } else { - if (!member.toShapeId().getNamespace().equals(targetShape.toShapeId().getNamespace()) && !targetShape.toShapeId().getNamespace().startsWith("smithy") && targetShape.asStructureShape().isPresent()) { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(targetShape.toShapeId().getNamespace()), namespace); - } - } - - writer.write("$L $P", memberName, memberSymbol); - - }); - writer.closeBlock("}").write(""); - validationGenerator.renderValidator(shape, isInputStructure); - } - - /** - * Renders an error structure and supporting methods. - */ - private void renderErrorStructure() { - Symbol structureSymbol = symbolProvider.toSymbol(shape); - writer.addUseImports(SmithyGoDependency.FMT); - ErrorTrait errorTrait = shape.expectTrait(ErrorTrait.class); - - // Write out a struct to hold the error data. - writer.openBlock("type $L struct {", "}", structureSymbol.getName(), () -> { - writer.write("$LBaseException", context.settings().getService().getName()); - Set memberNameSet = new HashSet<>(); - // TODO: Revisit if message has to be strictly pointer or not (even with required trait). - // When any shape is required we don't add pointer in local service but AWS SDK does. - for (MemberShape member : shape.getAllMembers().values()) { - String memberName = symbolProvider.toMemberName(member); - memberNameSet.add(memberName); - writer.write("$L $P", memberName, symbolProvider.toSymbol(member)); - } - - // The message is the only part of the standard APIError interface that isn't known ahead of time. - // Message is a pointer mostly for the sake of consistency. - - // If Message and ErrorCodeOverride is not defined in model. - if (!memberNameSet.contains("Message")) { - writer.write("Message *string").write(""); - } - if (!memberNameSet.contains("ErrorCodeOverride")) { - writer.write("ErrorCodeOverride *string").write(""); - } - - }).write(""); - - // write the Error method to satisfy the standard error interface - writer.openBlock("func (e $L) Error() string {", "}", structureSymbol.getName(), () -> { - writer.write("return fmt.Sprintf(\"%s: %s\", e.ErrorCodeOverride, e.Message)"); - }); - } + writer.write("$L $P", memberName, memberSymbol); + }); + writer.closeBlock("}").write(""); + validationGenerator.renderValidator(shape, isInputStructure); + } + + /** + * Renders an error structure and supporting methods. + */ + private void renderErrorStructure() { + Symbol structureSymbol = symbolProvider.toSymbol(shape); + writer.addUseImports(SmithyGoDependency.FMT); + ErrorTrait errorTrait = shape.expectTrait(ErrorTrait.class); + + // Write out a struct to hold the error data. + writer + .openBlock( + "type $L struct {", + "}", + structureSymbol.getName(), + () -> { + writer.write( + "$LBaseException", + context.settings().getService().getName() + ); + Set memberNameSet = new HashSet<>(); + // TODO: Revisit if message has to be strictly pointer or not (even with required trait). + // When any shape is required we don't add pointer in local service but AWS SDK does. + for (MemberShape member : shape.getAllMembers().values()) { + String memberName = symbolProvider.toMemberName(member); + memberNameSet.add(memberName); + writer.write("$L $P", memberName, symbolProvider.toSymbol(member)); + } + + // The message is the only part of the standard APIError interface that isn't known ahead of time. + // Message is a pointer mostly for the sake of consistency. + + // If Message and ErrorCodeOverride is not defined in model. + if (!memberNameSet.contains("Message")) { + writer.write("Message *string").write(""); + } + if (!memberNameSet.contains("ErrorCodeOverride")) { + writer.write("ErrorCodeOverride *string").write(""); + } + } + ) + .write(""); + + // write the Error method to satisfy the standard error interface + writer.openBlock( + "func (e $L) Error() string {", + "}", + structureSymbol.getName(), + () -> { + writer.write( + "return fmt.Sprintf(\"%s: %s\", e.ErrorCodeOverride, e.Message)" + ); + } + ); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolUtils.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolUtils.java index 390a6919d8..ec7d1aba80 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolUtils.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolUtils.java @@ -23,173 +23,217 @@ */ public final class SymbolUtils { - public static final String POINTABLE = "pointable"; - public static final String NAMESPACE_ALIAS = "namespaceAlias"; - public static final String GO_UNIVERSE_TYPE = "universeType"; - public static final String GO_SLICE = "goSlice"; - public static final String GO_MAP = "goMap"; - public static final String GO_ELEMENT_TYPE = "goElementType"; - - // Used when a given shape must be represented differently on input. - public static final String INPUT_VARIANT = "inputVariant"; - - private SymbolUtils() { - } - - /** - * Create a value symbol builder. - * - * @param typeName the name of the type. - * @return the symbol builder type. - */ - public static Symbol.Builder createValueSymbolBuilder(String typeName) { - return Symbol.builder() - .putProperty(POINTABLE, false) - .name(typeName); - } - - /** - * Create a pointable symbol builder. - * - * @param typeName the name of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder(String typeName) { - return Symbol.builder() - .putProperty(POINTABLE, true) - .name(typeName); - } - - /** - * Create a value symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder(Shape shape, String typeName) { - return createValueSymbolBuilder(typeName).putProperty("shape", shape); - } - - /** - * Create a pointable symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder(Shape shape, String typeName) { - return createPointableSymbolBuilder(typeName).putProperty("shape", shape); - } - - /** - * Create a pointable symbol builder. - * - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder(String typeName, String namespace) { - return createPointableSymbolBuilder(typeName).namespace(namespace, "."); - } - - /** - * Create a value symbol builder. - * - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder(String typeName, String namespace) { - return createValueSymbolBuilder(typeName).namespace(namespace, "."); - } - - /** - * Create a pointable symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder(Shape shape, String typeName, String namespace) { - return createPointableSymbolBuilder(shape, typeName).namespace(namespace, "."); - } - - /** - * Create a value symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder(Shape shape, String typeName, String namespace) { - return createValueSymbolBuilder(shape, typeName).namespace(namespace, "."); - } - - /** - * Create a pointable symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder(Shape shape, String typeName, GoDependency namespace) { - return setImportedNamespace(createPointableSymbolBuilder(shape, typeName), namespace); - } - - /** - * Create a value symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder(Shape shape, String typeName, GoDependency namespace) { - return setImportedNamespace(createValueSymbolBuilder(shape, typeName), namespace); - } - - /** - * Create a pointable symbol builder. - * - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder(String typeName, GoDependency namespace) { - return setImportedNamespace(createPointableSymbolBuilder(typeName), namespace); - } - - /** - * Create a value symbol builder. - * - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder(String typeName, GoDependency namespace) { - return setImportedNamespace(createValueSymbolBuilder(typeName), namespace); - } - - private static Symbol.Builder setImportedNamespace(Symbol.Builder builder, GoDependency dependency) { - return builder.namespace(dependency.getImportPath(), ".") - .addDependency(dependency) - .putProperty(NAMESPACE_ALIAS, dependency.getAlias()); - } - - /** - * Go declares several built-in language types in what is known as the Universe block. This function determines - * whether the provided symbol represents a Go universe type. - * - * @param symbol the symbol to check - * @return whether the symbol type is in the Go universe block - * @see The Go Programming Language Specification - */ - public static boolean isUniverseType(Symbol symbol) { - return symbol.getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class) - .orElse(false); - } + public static final String POINTABLE = "pointable"; + public static final String NAMESPACE_ALIAS = "namespaceAlias"; + public static final String GO_UNIVERSE_TYPE = "universeType"; + public static final String GO_SLICE = "goSlice"; + public static final String GO_MAP = "goMap"; + public static final String GO_ELEMENT_TYPE = "goElementType"; + + // Used when a given shape must be represented differently on input. + public static final String INPUT_VARIANT = "inputVariant"; + + private SymbolUtils() {} + + /** + * Create a value symbol builder. + * + * @param typeName the name of the type. + * @return the symbol builder type. + */ + public static Symbol.Builder createValueSymbolBuilder(String typeName) { + return Symbol.builder().putProperty(POINTABLE, false).name(typeName); + } + + /** + * Create a pointable symbol builder. + * + * @param typeName the name of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder(String typeName) { + return Symbol.builder().putProperty(POINTABLE, true).name(typeName); + } + + /** + * Create a value symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder( + Shape shape, + String typeName + ) { + return createValueSymbolBuilder(typeName).putProperty("shape", shape); + } + + /** + * Create a pointable symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder( + Shape shape, + String typeName + ) { + return createPointableSymbolBuilder(typeName).putProperty("shape", shape); + } + + /** + * Create a pointable symbol builder. + * + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder( + String typeName, + String namespace + ) { + return createPointableSymbolBuilder(typeName).namespace(namespace, "."); + } + + /** + * Create a value symbol builder. + * + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder( + String typeName, + String namespace + ) { + return createValueSymbolBuilder(typeName).namespace(namespace, "."); + } + + /** + * Create a pointable symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder( + Shape shape, + String typeName, + String namespace + ) { + return createPointableSymbolBuilder(shape, typeName) + .namespace(namespace, "."); + } + + /** + * Create a value symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder( + Shape shape, + String typeName, + String namespace + ) { + return createValueSymbolBuilder(shape, typeName).namespace(namespace, "."); + } + + /** + * Create a pointable symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder( + Shape shape, + String typeName, + GoDependency namespace + ) { + return setImportedNamespace( + createPointableSymbolBuilder(shape, typeName), + namespace + ); + } + + /** + * Create a value symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder( + Shape shape, + String typeName, + GoDependency namespace + ) { + return setImportedNamespace( + createValueSymbolBuilder(shape, typeName), + namespace + ); + } + + /** + * Create a pointable symbol builder. + * + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder( + String typeName, + GoDependency namespace + ) { + return setImportedNamespace( + createPointableSymbolBuilder(typeName), + namespace + ); + } + + /** + * Create a value symbol builder. + * + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder( + String typeName, + GoDependency namespace + ) { + return setImportedNamespace(createValueSymbolBuilder(typeName), namespace); + } + + private static Symbol.Builder setImportedNamespace( + Symbol.Builder builder, + GoDependency dependency + ) { + return builder + .namespace(dependency.getImportPath(), ".") + .addDependency(dependency) + .putProperty(NAMESPACE_ALIAS, dependency.getAlias()); + } + + /** + * Go declares several built-in language types in what is known as the Universe block. This function determines + * whether the provided symbol represents a Go universe type. + * + * @param symbol the symbol to check + * @return whether the symbol type is in the Go universe block + * @see The Go Programming Language Specification + */ + public static boolean isUniverseType(Symbol symbol) { + return symbol + .getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class) + .orElse(false); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolVisitor.java index 7bd6ee95ff..d23cbda14f 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolVisitor.java @@ -15,6 +15,10 @@ package software.amazon.polymorph.smithygo.codegen; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.logging.Logger; import software.amazon.polymorph.smithygo.codegen.knowledge.GoPointableIndex; import software.amazon.polymorph.smithygo.localservice.nameresolver.SmithyNameResolver; import software.amazon.polymorph.traits.ReferenceTrait; @@ -61,11 +65,6 @@ import software.amazon.smithy.model.traits.StreamingTrait; import software.amazon.smithy.utils.StringUtils; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.logging.Logger; - /** * Responsible for type mapping and file/identifier formatting. * @@ -73,449 +72,593 @@ * suffixed with "_". See "reserved-words.txt" for the list of words. */ public class SymbolVisitor implements SymbolProvider, ShapeVisitor { - private static final Logger LOGGER = Logger.getLogger(SymbolVisitor.class.getName()); - - private final Model model; - private final String rootModuleName; - private final ReservedWordSymbolProvider.Escaper escaper; - private final ReservedWordSymbolProvider.Escaper errorMemberEscaper; - private final Map structureSpecificMemberEscapers = new HashMap<>(); - private final GoPointableIndex pointableIndex; - private final GoSettings settings; - - public SymbolVisitor(Model model, GoSettings settings) { - this.model = model; - this.settings = settings; - this.rootModuleName = SmithyNameResolver.shapeNamespace(settings.getService(model)); - this.pointableIndex = GoPointableIndex.of(model); - - // Reserve the generated names for union members, including the unknown case. - ReservedWordsBuilder reservedNames = new ReservedWordsBuilder(); - reserveUnionMemberNames(model, reservedNames); - - ReservedWords reservedMembers = new ReservedWordsBuilder() - // Since Go only exports names if the first character is upper case and all - // the go reserved words are lower case, it's functionally impossible to conflict, - // so we only need to protect against common names. As of now there's only one. - .put("String", "String_") - .put("GetStream", "GetStream_") - .build(); - - model.shapes(StructureShape.class) - .filter(this::supportsInheritance) - .forEach(this::reserveInterfaceMemberAccessors); - - escaper = ReservedWordSymbolProvider.builder() - .nameReservedWords(reservedNames.build()) - .memberReservedWords(reservedMembers) - // Only escape words when the symbol has a definition file to - // prevent escaping intentional references to built-in types. - .escapePredicate((shape, symbol) -> !StringUtils.isEmpty(symbol.getDefinitionFile())) - .buildEscaper(); - - // Reserved words that only apply to error members. - ReservedWords reservedErrorMembers = new ReservedWordsBuilder() - .put("ErrorCode", "ErrorCode_") - .put("ErrorMessage", "ErrorMessage_") - .put("ErrorFault", "ErrorFault_") - .put("Unwrap", "Unwrap_") - .put("Error", "Error_") - .put("ErrorCodeOverride", "ErrorCodeOverride_") - .build(); - - errorMemberEscaper = ReservedWordSymbolProvider.builder() - .memberReservedWords(ReservedWords.compose(reservedMembers, reservedErrorMembers)) - .escapePredicate((shape, symbol) -> !StringUtils.isEmpty(symbol.getDefinitionFile())) - .buildEscaper(); - } - - /** - * Reserves generated member names for unions. - * - *

These have the format {UnionName}Member{MemberName}. - * - * @param model The model whose unions should be reserved. - * @param builder A reserved words builder to add on to. - */ - private void reserveUnionMemberNames(Model model, ReservedWordsBuilder builder) { - model.shapes(UnionShape.class).forEach(union -> { - for (MemberShape member : union.getAllMembers().values()) { - String memberName = formatUnionMemberName(union, member); - builder.put(memberName, escapeWithTrailingUnderscore(memberName)); - } - }); - } - - private boolean supportsInheritance(Shape shape) { - return shape.isStructureShape() && shape.hasTrait(ErrorTrait.class); - } - - /** - * Reserves Get* and Has* member names for the given structure for use as accessor methods. - * - *

These reservations will only apply to the given structure, not to other structures. - * - * @param shape The structure shape whose members should be reserved. - */ - private void reserveInterfaceMemberAccessors(StructureShape shape) { - ReservedWordsBuilder builder = new ReservedWordsBuilder(); - for (MemberShape member : shape.getAllMembers().values()) { - String name = getDefaultMemberName(member); - String getterName = "Get" + name; - String haserName = "Has" + name; - builder.put(getterName, escapeWithTrailingUnderscore(getterName)); - builder.put(haserName, escapeWithTrailingUnderscore(haserName)); - } - ReservedWordSymbolProvider.Escaper structureSpecificMemberEscaper = ReservedWordSymbolProvider.builder() - .memberReservedWords(builder.build()) - .buildEscaper(); - structureSpecificMemberEscapers.put(shape.getId(), structureSpecificMemberEscaper); - } - - private String escapeWithTrailingUnderscore(String symbolName) { - return symbolName + "_"; - } - - @Override - public Symbol toSymbol(Shape shape) { - Symbol symbol = shape.accept(this); - LOGGER.fine(() -> String.format("Creating symbol from %s: %s", shape, symbol)); - return linkArchetypeShape(shape, escaper.escapeSymbol(shape, symbol)); - } - - /** - * Links the archetype shape id for the symbol. - * - * @param shape the model shape - * @param symbol the symbol to set the archetype property on - * @return the symbol with archetype set if shape is a synthetic clone otherwise the original symbol - */ - private Symbol linkArchetypeShape(Shape shape, Symbol symbol) { - return shape.getTrait(Synthetic.class) - .map(synthetic -> symbol.toBuilder() - .putProperty("archetype", synthetic.getArchetype()) - .build()) - .orElse(symbol); - } - - @Override - public String toMemberName(MemberShape shape) { - Shape container = model.expectShape(shape.getContainer()); - if (container.isUnionShape()) { - // Union member names are not escaped as they are used to build the escape set. - return formatUnionMemberName(container.asUnionShape().get(), shape); - } - - String memberName = getDefaultMemberName(shape); - memberName = escaper.escapeMemberName(memberName); - - // Escape words reserved for the specific container. - if (structureSpecificMemberEscapers.containsKey(shape.getContainer())) { - memberName = structureSpecificMemberEscapers.get(shape.getContainer()).escapeMemberName(memberName); - } - - // Escape words that are only reserved for error members. - if (isErrorMember(shape)) { - memberName = errorMemberEscaper.escapeMemberName(memberName); - } - return memberName; - } - - private String formatUnionMemberName(UnionShape union, MemberShape member) { - return String.format("%sMember%s", getDefaultShapeName(union), getDefaultMemberName(member)); - } - - private String getDefaultShapeName(Shape shape) { - ServiceShape serviceShape = model.expectShape(settings.getService(), ServiceShape.class); - return StringUtils.capitalize(removeLeadingInvalidIdentCharacters(shape.getId().getName(serviceShape))); - } - - private String getDefaultMemberName(MemberShape shape) { - String memberName = StringUtils.capitalize(removeLeadingInvalidIdentCharacters(shape.getMemberName())); - - return memberName; - } - - private String removeLeadingInvalidIdentCharacters(String value) { - if (Character.isAlphabetic(value.charAt(0))) { - return value; - } - - int i; - for (i = 0; i < value.length(); i++) { - if (Character.isAlphabetic(value.charAt(i))) { - break; - } - } - - String remaining = value.substring(i); - if (remaining.length() == 0) { - throw new CodegenException("tried to clean name " + value + ", but resulted in empty string"); - } - - return remaining; - } - - - private boolean isErrorMember(MemberShape shape) { - return model.getShape(shape.getContainer()) - .map(container -> container.hasTrait(ErrorTrait.ID)) - .orElse(false); - } - - @Override - public Symbol blobShape(BlobShape shape) { - if (shape.hasTrait(StreamingTrait.ID)) { - Symbol inputVariant = symbolBuilderFor(shape, "Reader", SmithyGoDependency.IO).build(); - return symbolBuilderFor(shape, "ReadCloser", SmithyGoDependency.IO) - .putProperty(SymbolUtils.INPUT_VARIANT, inputVariant) - .build(); - } - return symbolBuilderFor(shape, "[]byte") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol booleanShape(BooleanShape shape) { - return symbolBuilderFor(shape, "bool") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol listShape(ListShape shape) { - return createCollectionSymbol(shape); - } - - @Override - public Symbol setShape(SetShape shape) { - // Go doesn't have a set type. Rather than hack together a set using a map, - // we instead just create a list and let the service be responsible for - // asserting that there are no duplicates. - return createCollectionSymbol(shape); - } - - private Symbol createCollectionSymbol(CollectionShape shape) { - Symbol reference = toSymbol(shape.getMember()); - // Shape name will be unused for symbols that represent a slice, but in the event it does we set the collection - // shape's name to make debugging simpler. - return symbolBuilderFor(shape, getDefaultShapeName(shape)) - .putProperty(SymbolUtils.GO_SLICE, true) - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, - reference.getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class).orElse(false)) - .putProperty(SymbolUtils.GO_ELEMENT_TYPE, reference) - .build(); - } - - @Override - public Symbol mapShape(MapShape shape) { - Symbol reference = toSymbol(shape.getValue()); - // Shape name will be unused for symbols that represent a map, but in the event it does we set the map shape's - // name to make debugging simpler. - return symbolBuilderFor(shape, getDefaultShapeName(shape)) - .putProperty(SymbolUtils.GO_MAP, true) - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, - reference.getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class).orElse(false)) - .putProperty(SymbolUtils.GO_ELEMENT_TYPE, reference) - .build(); - } - - private Symbol.Builder symbolBuilderFor(Shape shape, String typeName) { - if (pointableIndex.isPointable(shape)) { - return SymbolUtils.createPointableSymbolBuilder(shape, typeName, SmithyNameResolver.smithyTypesNamespace(shape)); - } - - return SymbolUtils.createValueSymbolBuilder(shape, typeName, SmithyNameResolver.smithyTypesNamespace(shape)); - } - - private Symbol.Builder symbolBuilderFor(Shape shape, String typeName, GoDependency namespace) { - if (pointableIndex.isPointable(shape)) { - return SymbolUtils.createPointableSymbolBuilder(shape, typeName, namespace); - } - - return SymbolUtils.createValueSymbolBuilder(shape, typeName, namespace); - } - private Symbol.Builder symbolBuilderFor(Shape shape, String typeName, String namespace) { - if (pointableIndex.isPointable(shape)) { - return SymbolUtils.createPointableSymbolBuilder(shape, typeName, namespace); + private static final Logger LOGGER = Logger.getLogger( + SymbolVisitor.class.getName() + ); + + private final Model model; + private final String rootModuleName; + private final ReservedWordSymbolProvider.Escaper escaper; + private final ReservedWordSymbolProvider.Escaper errorMemberEscaper; + private final Map< + ShapeId, + ReservedWordSymbolProvider.Escaper + > structureSpecificMemberEscapers = new HashMap<>(); + private final GoPointableIndex pointableIndex; + private final GoSettings settings; + + public SymbolVisitor(Model model, GoSettings settings) { + this.model = model; + this.settings = settings; + this.rootModuleName = + SmithyNameResolver.shapeNamespace(settings.getService(model)); + this.pointableIndex = GoPointableIndex.of(model); + + // Reserve the generated names for union members, including the unknown case. + ReservedWordsBuilder reservedNames = new ReservedWordsBuilder(); + reserveUnionMemberNames(model, reservedNames); + + ReservedWords reservedMembers = new ReservedWordsBuilder() + // Since Go only exports names if the first character is upper case and all + // the go reserved words are lower case, it's functionally impossible to conflict, + // so we only need to protect against common names. As of now there's only one. + .put("String", "String_") + .put("GetStream", "GetStream_") + .build(); + + model + .shapes(StructureShape.class) + .filter(this::supportsInheritance) + .forEach(this::reserveInterfaceMemberAccessors); + + escaper = + ReservedWordSymbolProvider + .builder() + .nameReservedWords(reservedNames.build()) + .memberReservedWords(reservedMembers) + // Only escape words when the symbol has a definition file to + // prevent escaping intentional references to built-in types. + .escapePredicate((shape, symbol) -> + !StringUtils.isEmpty(symbol.getDefinitionFile()) + ) + .buildEscaper(); + + // Reserved words that only apply to error members. + ReservedWords reservedErrorMembers = new ReservedWordsBuilder() + .put("ErrorCode", "ErrorCode_") + .put("ErrorMessage", "ErrorMessage_") + .put("ErrorFault", "ErrorFault_") + .put("Unwrap", "Unwrap_") + .put("Error", "Error_") + .put("ErrorCodeOverride", "ErrorCodeOverride_") + .build(); + + errorMemberEscaper = + ReservedWordSymbolProvider + .builder() + .memberReservedWords( + ReservedWords.compose(reservedMembers, reservedErrorMembers) + ) + .escapePredicate((shape, symbol) -> + !StringUtils.isEmpty(symbol.getDefinitionFile()) + ) + .buildEscaper(); + } + + /** + * Reserves generated member names for unions. + * + *

These have the format {UnionName}Member{MemberName}. + * + * @param model The model whose unions should be reserved. + * @param builder A reserved words builder to add on to. + */ + private void reserveUnionMemberNames( + Model model, + ReservedWordsBuilder builder + ) { + model + .shapes(UnionShape.class) + .forEach(union -> { + for (MemberShape member : union.getAllMembers().values()) { + String memberName = formatUnionMemberName(union, member); + builder.put(memberName, escapeWithTrailingUnderscore(memberName)); } - - return SymbolUtils.createValueSymbolBuilder(shape, typeName, namespace); - } - - @Override - public Symbol byteShape(ByteShape shape) { - return symbolBuilderFor(shape, "int8") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol shortShape(ShortShape shape) { - return symbolBuilderFor(shape, "int16") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol integerShape(IntegerShape shape) { - return symbolBuilderFor(shape, "int32") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol longShape(LongShape shape) { - return symbolBuilderFor(shape, "int64") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol floatShape(FloatShape shape) { - return symbolBuilderFor(shape, "float32") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol documentShape(DocumentShape shape) { - return null; - } - - @Override - public Symbol doubleShape(DoubleShape shape) { - return symbolBuilderFor(shape, "float64") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol bigIntegerShape(BigIntegerShape shape) { - return createBigSymbol(shape, "Int"); - } - - @Override - public Symbol bigDecimalShape(BigDecimalShape shape) { - - return createBigSymbol(shape, "Float"); - } - - private Symbol createBigSymbol(Shape shape, String symbolName) { - return symbolBuilderFor(shape, symbolName, SmithyGoDependency.BIG) - .build(); - } - - @Override - public Symbol operationShape(OperationShape shape) { - String name = getDefaultShapeName(shape); - return SymbolUtils.createPointableSymbolBuilder(shape, name, rootModuleName) - .definitionFile(String.format("./api_op_%s.go", name)) - .addDependency("./types", "./types") - .build(); - } - - @Override - public Symbol resourceShape(ResourceShape shape) { - // TODO: implement resources - return SymbolUtils.createPointableSymbolBuilder(shape, "nil").build(); - } - - @Override - public Symbol serviceShape(ServiceShape shape) { - return symbolBuilderFor(shape, "Client", rootModuleName) - .definitionFile("./%s/api_client.go".formatted(SmithyNameResolver.shapeNamespace(shape))) - .build(); - } - - @Override - public Symbol stringShape(StringShape shape) { - if (shape.hasTrait(EnumTrait.class)) { - String name = getDefaultShapeName(shape); - return symbolBuilderFor(shape, name, SmithyNameResolver.smithyTypesNamespace(settings.getService(model))) - .definitionFile("./%s/enums.go".formatted(SmithyNameResolver.smithyTypesNamespace(shape))) - .build(); - } - - return symbolBuilderFor(shape, "string") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol structureShape(StructureShape shape) { - String name = getDefaultShapeName(shape); - if (shape.getId().getNamespace().equals(CodegenUtils.getSyntheticTypeNamespace())) { - Optional boundOperationName = getNameOfBoundOperation(shape); - if (boundOperationName.isPresent()) { - return symbolBuilderFor(shape, name, rootModuleName) - .definitionFile("./api_op_" + boundOperationName.get() + ".go") - .build(); - } - } - Symbol.Builder builder = symbolBuilderFor(shape, name); - if (shape.hasTrait(ErrorTrait.ID)) { - builder.definitionFile("./%s/errors.go".formatted(SmithyNameResolver.smithyTypesNamespace(shape))); - } else { - builder.definitionFile("./%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(shape))); - } - - if (shape.hasTrait(ReferenceTrait.class)) { - var referredShape = model.expectShape(shape.expectTrait(ReferenceTrait.class).getReferentId()); - var isService = shape.expectTrait(ReferenceTrait.class).isService(); - if (isService) { - builder.putProperty("Referred", symbolBuilderFor(referredShape, "Client", SmithyNameResolver.shapeNamespace(referredShape)) - .putProperty(SymbolUtils.POINTABLE, true).build()); - } else { - builder.putProperty("Referred", symbolBuilderFor(referredShape, "I".concat(getDefaultShapeName(referredShape))) - .putProperty(SymbolUtils.POINTABLE, false).build()); - } - - } - - return builder.build(); - } - - private Optional getNameOfBoundOperation(StructureShape shape) { - NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); - for (Relationship relationship : provider.getNeighbors(shape)) { - RelationshipType relationshipType = relationship.getRelationshipType(); - if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { - return Optional.of(getDefaultShapeName(relationship.getNeighborShape().get())); - } - } - return Optional.empty(); - } - - @Override - public Symbol unionShape(UnionShape shape) { - String name = getDefaultShapeName(shape); - return symbolBuilderFor(shape, name, SmithyNameResolver.smithyTypesNamespace(settings.getService(model))) - .definitionFile("./types/types.go") - .build(); - } - - @Override - public Symbol memberShape(MemberShape member) { - Shape targetShape = model.expectShape(member.getTarget()); - return toSymbol(targetShape) - .toBuilder() - .putProperty(SymbolUtils.POINTABLE, pointableIndex.isPointable(member)) - .build(); - } - - @Override - public Symbol timestampShape(TimestampShape shape) { - return symbolBuilderFor(shape, "Time", SmithyGoDependency.TIME).build(); - } - - @Override - public Symbol intEnumShape(IntEnumShape shape) { - String name = getDefaultShapeName(shape); - return symbolBuilderFor(shape, name, SmithyNameResolver.smithyTypesNamespace(settings.getService(model))) - .definitionFile("./%s/enums.go".formatted(SmithyNameResolver.smithyTypesNamespace(shape))) - .build(); - } + }); + } + + private boolean supportsInheritance(Shape shape) { + return shape.isStructureShape() && shape.hasTrait(ErrorTrait.class); + } + + /** + * Reserves Get* and Has* member names for the given structure for use as accessor methods. + * + *

These reservations will only apply to the given structure, not to other structures. + * + * @param shape The structure shape whose members should be reserved. + */ + private void reserveInterfaceMemberAccessors(StructureShape shape) { + ReservedWordsBuilder builder = new ReservedWordsBuilder(); + for (MemberShape member : shape.getAllMembers().values()) { + String name = getDefaultMemberName(member); + String getterName = "Get" + name; + String haserName = "Has" + name; + builder.put(getterName, escapeWithTrailingUnderscore(getterName)); + builder.put(haserName, escapeWithTrailingUnderscore(haserName)); + } + ReservedWordSymbolProvider.Escaper structureSpecificMemberEscaper = + ReservedWordSymbolProvider + .builder() + .memberReservedWords(builder.build()) + .buildEscaper(); + structureSpecificMemberEscapers.put( + shape.getId(), + structureSpecificMemberEscaper + ); + } + + private String escapeWithTrailingUnderscore(String symbolName) { + return symbolName + "_"; + } + + @Override + public Symbol toSymbol(Shape shape) { + Symbol symbol = shape.accept(this); + LOGGER.fine(() -> + String.format("Creating symbol from %s: %s", shape, symbol) + ); + return linkArchetypeShape(shape, escaper.escapeSymbol(shape, symbol)); + } + + /** + * Links the archetype shape id for the symbol. + * + * @param shape the model shape + * @param symbol the symbol to set the archetype property on + * @return the symbol with archetype set if shape is a synthetic clone otherwise the original symbol + */ + private Symbol linkArchetypeShape(Shape shape, Symbol symbol) { + return shape + .getTrait(Synthetic.class) + .map(synthetic -> + symbol + .toBuilder() + .putProperty("archetype", synthetic.getArchetype()) + .build() + ) + .orElse(symbol); + } + + @Override + public String toMemberName(MemberShape shape) { + Shape container = model.expectShape(shape.getContainer()); + if (container.isUnionShape()) { + // Union member names are not escaped as they are used to build the escape set. + return formatUnionMemberName(container.asUnionShape().get(), shape); + } + + String memberName = getDefaultMemberName(shape); + memberName = escaper.escapeMemberName(memberName); + + // Escape words reserved for the specific container. + if (structureSpecificMemberEscapers.containsKey(shape.getContainer())) { + memberName = + structureSpecificMemberEscapers + .get(shape.getContainer()) + .escapeMemberName(memberName); + } + + // Escape words that are only reserved for error members. + if (isErrorMember(shape)) { + memberName = errorMemberEscaper.escapeMemberName(memberName); + } + return memberName; + } + + private String formatUnionMemberName(UnionShape union, MemberShape member) { + return String.format( + "%sMember%s", + getDefaultShapeName(union), + getDefaultMemberName(member) + ); + } + + private String getDefaultShapeName(Shape shape) { + ServiceShape serviceShape = model.expectShape( + settings.getService(), + ServiceShape.class + ); + return StringUtils.capitalize( + removeLeadingInvalidIdentCharacters(shape.getId().getName(serviceShape)) + ); + } + + private String getDefaultMemberName(MemberShape shape) { + String memberName = StringUtils.capitalize( + removeLeadingInvalidIdentCharacters(shape.getMemberName()) + ); + + return memberName; + } + + private String removeLeadingInvalidIdentCharacters(String value) { + if (Character.isAlphabetic(value.charAt(0))) { + return value; + } + + int i; + for (i = 0; i < value.length(); i++) { + if (Character.isAlphabetic(value.charAt(i))) { + break; + } + } + + String remaining = value.substring(i); + if (remaining.length() == 0) { + throw new CodegenException( + "tried to clean name " + value + ", but resulted in empty string" + ); + } + + return remaining; + } + + private boolean isErrorMember(MemberShape shape) { + return model + .getShape(shape.getContainer()) + .map(container -> container.hasTrait(ErrorTrait.ID)) + .orElse(false); + } + + @Override + public Symbol blobShape(BlobShape shape) { + if (shape.hasTrait(StreamingTrait.ID)) { + Symbol inputVariant = symbolBuilderFor( + shape, + "Reader", + SmithyGoDependency.IO + ) + .build(); + return symbolBuilderFor(shape, "ReadCloser", SmithyGoDependency.IO) + .putProperty(SymbolUtils.INPUT_VARIANT, inputVariant) + .build(); + } + return symbolBuilderFor(shape, "[]byte") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol booleanShape(BooleanShape shape) { + return symbolBuilderFor(shape, "bool") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol listShape(ListShape shape) { + return createCollectionSymbol(shape); + } + + @Override + public Symbol setShape(SetShape shape) { + // Go doesn't have a set type. Rather than hack together a set using a map, + // we instead just create a list and let the service be responsible for + // asserting that there are no duplicates. + return createCollectionSymbol(shape); + } + + private Symbol createCollectionSymbol(CollectionShape shape) { + Symbol reference = toSymbol(shape.getMember()); + // Shape name will be unused for symbols that represent a slice, but in the event it does we set the collection + // shape's name to make debugging simpler. + return symbolBuilderFor(shape, getDefaultShapeName(shape)) + .putProperty(SymbolUtils.GO_SLICE, true) + .putProperty( + SymbolUtils.GO_UNIVERSE_TYPE, + reference + .getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class) + .orElse(false) + ) + .putProperty(SymbolUtils.GO_ELEMENT_TYPE, reference) + .build(); + } + + @Override + public Symbol mapShape(MapShape shape) { + Symbol reference = toSymbol(shape.getValue()); + // Shape name will be unused for symbols that represent a map, but in the event it does we set the map shape's + // name to make debugging simpler. + return symbolBuilderFor(shape, getDefaultShapeName(shape)) + .putProperty(SymbolUtils.GO_MAP, true) + .putProperty( + SymbolUtils.GO_UNIVERSE_TYPE, + reference + .getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class) + .orElse(false) + ) + .putProperty(SymbolUtils.GO_ELEMENT_TYPE, reference) + .build(); + } + + private Symbol.Builder symbolBuilderFor(Shape shape, String typeName) { + if (pointableIndex.isPointable(shape)) { + return SymbolUtils.createPointableSymbolBuilder( + shape, + typeName, + SmithyNameResolver.smithyTypesNamespace(shape) + ); + } + + return SymbolUtils.createValueSymbolBuilder( + shape, + typeName, + SmithyNameResolver.smithyTypesNamespace(shape) + ); + } + + private Symbol.Builder symbolBuilderFor( + Shape shape, + String typeName, + GoDependency namespace + ) { + if (pointableIndex.isPointable(shape)) { + return SymbolUtils.createPointableSymbolBuilder( + shape, + typeName, + namespace + ); + } + + return SymbolUtils.createValueSymbolBuilder(shape, typeName, namespace); + } + + private Symbol.Builder symbolBuilderFor( + Shape shape, + String typeName, + String namespace + ) { + if (pointableIndex.isPointable(shape)) { + return SymbolUtils.createPointableSymbolBuilder( + shape, + typeName, + namespace + ); + } + + return SymbolUtils.createValueSymbolBuilder(shape, typeName, namespace); + } + + @Override + public Symbol byteShape(ByteShape shape) { + return symbolBuilderFor(shape, "int8") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol shortShape(ShortShape shape) { + return symbolBuilderFor(shape, "int16") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol integerShape(IntegerShape shape) { + return symbolBuilderFor(shape, "int32") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol longShape(LongShape shape) { + return symbolBuilderFor(shape, "int64") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol floatShape(FloatShape shape) { + return symbolBuilderFor(shape, "float32") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol documentShape(DocumentShape shape) { + return null; + } + + @Override + public Symbol doubleShape(DoubleShape shape) { + return symbolBuilderFor(shape, "float64") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol bigIntegerShape(BigIntegerShape shape) { + return createBigSymbol(shape, "Int"); + } + + @Override + public Symbol bigDecimalShape(BigDecimalShape shape) { + return createBigSymbol(shape, "Float"); + } + + private Symbol createBigSymbol(Shape shape, String symbolName) { + return symbolBuilderFor(shape, symbolName, SmithyGoDependency.BIG).build(); + } + + @Override + public Symbol operationShape(OperationShape shape) { + String name = getDefaultShapeName(shape); + return SymbolUtils + .createPointableSymbolBuilder(shape, name, rootModuleName) + .definitionFile(String.format("./api_op_%s.go", name)) + .addDependency("./types", "./types") + .build(); + } + + @Override + public Symbol resourceShape(ResourceShape shape) { + // TODO: implement resources + return SymbolUtils.createPointableSymbolBuilder(shape, "nil").build(); + } + + @Override + public Symbol serviceShape(ServiceShape shape) { + return symbolBuilderFor(shape, "Client", rootModuleName) + .definitionFile( + "./%s/api_client.go".formatted(SmithyNameResolver.shapeNamespace(shape)) + ) + .build(); + } + + @Override + public Symbol stringShape(StringShape shape) { + if (shape.hasTrait(EnumTrait.class)) { + String name = getDefaultShapeName(shape); + return symbolBuilderFor( + shape, + name, + SmithyNameResolver.smithyTypesNamespace(settings.getService(model)) + ) + .definitionFile( + "./%s/enums.go".formatted( + SmithyNameResolver.smithyTypesNamespace(shape) + ) + ) + .build(); + } + + return symbolBuilderFor(shape, "string") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol structureShape(StructureShape shape) { + String name = getDefaultShapeName(shape); + if ( + shape + .getId() + .getNamespace() + .equals(CodegenUtils.getSyntheticTypeNamespace()) + ) { + Optional boundOperationName = getNameOfBoundOperation(shape); + if (boundOperationName.isPresent()) { + return symbolBuilderFor(shape, name, rootModuleName) + .definitionFile("./api_op_" + boundOperationName.get() + ".go") + .build(); + } + } + Symbol.Builder builder = symbolBuilderFor(shape, name); + if (shape.hasTrait(ErrorTrait.ID)) { + builder.definitionFile( + "./%s/errors.go".formatted( + SmithyNameResolver.smithyTypesNamespace(shape) + ) + ); + } else { + builder.definitionFile( + "./%s/types.go".formatted( + SmithyNameResolver.smithyTypesNamespace(shape) + ) + ); + } + + if (shape.hasTrait(ReferenceTrait.class)) { + var referredShape = model.expectShape( + shape.expectTrait(ReferenceTrait.class).getReferentId() + ); + var isService = shape.expectTrait(ReferenceTrait.class).isService(); + if (isService) { + builder.putProperty( + "Referred", + symbolBuilderFor( + referredShape, + "Client", + SmithyNameResolver.shapeNamespace(referredShape) + ) + .putProperty(SymbolUtils.POINTABLE, true) + .build() + ); + } else { + builder.putProperty( + "Referred", + symbolBuilderFor( + referredShape, + "I".concat(getDefaultShapeName(referredShape)) + ) + .putProperty(SymbolUtils.POINTABLE, false) + .build() + ); + } + } + + return builder.build(); + } + + private Optional getNameOfBoundOperation(StructureShape shape) { + NeighborProvider provider = NeighborProviderIndex + .of(model) + .getReverseProvider(); + for (Relationship relationship : provider.getNeighbors(shape)) { + RelationshipType relationshipType = relationship.getRelationshipType(); + if ( + relationshipType == RelationshipType.INPUT || + relationshipType == RelationshipType.OUTPUT + ) { + return Optional.of( + getDefaultShapeName(relationship.getNeighborShape().get()) + ); + } + } + return Optional.empty(); + } + + @Override + public Symbol unionShape(UnionShape shape) { + String name = getDefaultShapeName(shape); + return symbolBuilderFor( + shape, + name, + SmithyNameResolver.smithyTypesNamespace(settings.getService(model)) + ) + .definitionFile("./types/types.go") + .build(); + } + + @Override + public Symbol memberShape(MemberShape member) { + Shape targetShape = model.expectShape(member.getTarget()); + return toSymbol(targetShape) + .toBuilder() + .putProperty(SymbolUtils.POINTABLE, pointableIndex.isPointable(member)) + .build(); + } + + @Override + public Symbol timestampShape(TimestampShape shape) { + return symbolBuilderFor(shape, "Time", SmithyGoDependency.TIME).build(); + } + + @Override + public Symbol intEnumShape(IntEnumShape shape) { + String name = getDefaultShapeName(shape); + return symbolBuilderFor( + shape, + name, + SmithyNameResolver.smithyTypesNamespace(settings.getService(model)) + ) + .definitionFile( + "./%s/enums.go".formatted( + SmithyNameResolver.smithyTypesNamespace(shape) + ) + ) + .build(); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/Synthetic.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/Synthetic.java index 5a762dd69b..e71f52778b 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/Synthetic.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/Synthetic.java @@ -15,6 +15,7 @@ package software.amazon.polymorph.smithygo.codegen; +import java.util.Optional; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.shapes.ShapeId; @@ -23,95 +24,106 @@ import software.amazon.smithy.utils.SmithyBuilder; import software.amazon.smithy.utils.ToSmithyBuilder; -import java.util.Optional; - /** * Defines a shape as being a clone of another modeled shape. *

* Must only be used as a runtime trait-only applied to shapes based on model processing */ -public final class Synthetic extends AbstractTrait implements ToSmithyBuilder { - public static final ShapeId ID = ShapeId.from("smithy.go.traits#Synthetic"); - - private static final String ARCHETYPE = "archetype"; - - private final Optional archetype; - - private Synthetic(Builder builder) { - super(ID, builder.getSourceLocation()); - this.archetype = builder.archetype; - } - - /** - * Get the archetype shape that this clone is based on. - * - * @return the original archetype shape - */ - public Optional getArchetype() { - return archetype; - } - - @Override - protected Node createNode() { - throw new CodegenException("attempted to serialize runtime only trait"); - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } else if (!(other instanceof Synthetic)) { - return false; - } else { - Synthetic b = (Synthetic) other; - return toShapeId().equals(b.toShapeId()) && archetype.equals(b.getArchetype()); - } +public final class Synthetic + extends AbstractTrait + implements ToSmithyBuilder { + + public static final ShapeId ID = ShapeId.from("smithy.go.traits#Synthetic"); + + private static final String ARCHETYPE = "archetype"; + + private final Optional archetype; + + private Synthetic(Builder builder) { + super(ID, builder.getSourceLocation()); + this.archetype = builder.archetype; + } + + /** + * Get the archetype shape that this clone is based on. + * + * @return the original archetype shape + */ + public Optional getArchetype() { + return archetype; + } + + @Override + protected Node createNode() { + throw new CodegenException("attempted to serialize runtime only trait"); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } else if (!(other instanceof Synthetic)) { + return false; + } else { + Synthetic b = (Synthetic) other; + return ( + toShapeId().equals(b.toShapeId()) && archetype.equals(b.getArchetype()) + ); } + } + + @Override + public int hashCode() { + return ( + toShapeId().hashCode() * 17 + + Node + .objectNode() + .withOptionalMember( + ARCHETYPE, + archetype.map(ShapeId::toString).map(Node::from) + ) + .hashCode() + ); + } + + @Override + public SmithyBuilder toBuilder() { + Builder builder = builder(); + getArchetype().ifPresent(builder::archetype); + + return builder; + } + + /** + * @return Returns a builder used to create {@link Synthetic}. + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Builder for {@link Synthetic}. + */ + public static final class Builder + extends AbstractTraitBuilder { + + private Optional archetype = Optional.empty(); + + private Builder() {} @Override - public int hashCode() { - return toShapeId().hashCode() * 17 + Node.objectNode() - .withOptionalMember(ARCHETYPE, archetype.map(ShapeId::toString).map(Node::from)) - .hashCode(); - } - - @Override - public SmithyBuilder toBuilder() { - Builder builder = builder(); - getArchetype().ifPresent(builder::archetype); - - return builder; + public Synthetic build() { + return new Synthetic(this); } - /** - * @return Returns a builder used to create {@link Synthetic}. - */ - public static Builder builder() { - return new Builder(); + public Builder archetype(ShapeId archetype) { + this.archetype = Optional.ofNullable(archetype); + return this; } - /** - * Builder for {@link Synthetic}. - */ - public static final class Builder extends AbstractTraitBuilder { - private Optional archetype = Optional.empty(); - - private Builder() { - } - - @Override - public Synthetic build() { - return new Synthetic(this); - } - - public Builder archetype(ShapeId archetype) { - this.archetype = Optional.ofNullable(archetype); - return this; - } - - public Builder removeArchetype() { - this.archetype = Optional.empty(); - return this; - } + public Builder removeArchetype() { + this.archetype = Optional.empty(); + return this; } + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/UnionGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/UnionGenerator.java index 68cfbbfb26..7d800dac15 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/UnionGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/UnionGenerator.java @@ -5,100 +5,137 @@ import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; - import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.MemberShape; +import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.SimpleShape; import software.amazon.smithy.model.shapes.UnionShape; -import software.amazon.smithy.model.traits.StreamingTrait; -import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.traits.ErrorTrait; +import software.amazon.smithy.model.traits.StreamingTrait; public class UnionGenerator { - public static final String UNKNOWN_MEMBER_NAME = "UnknownUnionMember"; - private final Model model; - private final SymbolProvider symbolProvider; - private final UnionShape shape; - private final boolean isEventStream; + public static final String UNKNOWN_MEMBER_NAME = "UnknownUnionMember"; - public UnionGenerator(Model model, SymbolProvider symbolProvider, UnionShape shape) { - this.model = model; - this.symbolProvider = symbolProvider; - this.shape = shape; - this.isEventStream = StreamingTrait.isEventStream(shape); - } + private final Model model; + private final SymbolProvider symbolProvider; + private final UnionShape shape; + private final boolean isEventStream; - /** - * Generates the Go type definitions for the UnionShape. - * - * @param writer the writer - */ - public void generateUnion(GoWriter writer) { - Symbol symbol = symbolProvider.toSymbol(shape); - Collection memberShapes = shape.getAllMembers().values() - .stream() - .filter(memberShape -> !isEventStreamErrorMember(memberShape)) - .collect(Collectors.toCollection(TreeSet::new)); + public UnionGenerator( + Model model, + SymbolProvider symbolProvider, + UnionShape shape + ) { + this.model = model; + this.symbolProvider = symbolProvider; + this.shape = shape; + this.isEventStream = StreamingTrait.isEventStream(shape); + } - memberShapes.stream().map(symbolProvider::toMemberName).forEach(name -> { - writer.write("// " + name); - }); - writer.openBlock("type $L interface {", "}", symbol.getName(), () -> { - writer.write("is$L()", symbol.getName()); - }).write(""); + /** + * Generates the Go type definitions for the UnionShape. + * + * @param writer the writer + */ + public void generateUnion(GoWriter writer) { + Symbol symbol = symbolProvider.toSymbol(shape); + Collection memberShapes = shape + .getAllMembers() + .values() + .stream() + .filter(memberShape -> !isEventStreamErrorMember(memberShape)) + .collect(Collectors.toCollection(TreeSet::new)); - // Create structs for each member that satisfy the interface. - for (MemberShape member : memberShapes) { - Symbol memberSymbol = symbolProvider.toSymbol(member); - String exportedMemberName = symbolProvider.toMemberName(member); - Shape target = model.expectShape(member.getTarget()); + memberShapes + .stream() + .map(symbolProvider::toMemberName) + .forEach(name -> { + writer.write("// " + name); + }); + writer + .openBlock( + "type $L interface {", + "}", + symbol.getName(), + () -> { + writer.write("is$L()", symbol.getName()); + } + ) + .write(""); - writer.openBlock("type $L struct {", "}", exportedMemberName, () -> { - // Union members can't have null values, so for simple shapes we don't - // use pointers. We have to use pointers for complex shapes since, - // for example, we could still have a map that's empty or which has - // null values. - if (target instanceof SimpleShape) { - writer.write("Value $T", memberSymbol); - } else { - writer.write("Value $P", memberSymbol); - } - writer.write(""); - }); + // Create structs for each member that satisfy the interface. + for (MemberShape member : memberShapes) { + Symbol memberSymbol = symbolProvider.toSymbol(member); + String exportedMemberName = symbolProvider.toMemberName(member); + Shape target = model.expectShape(member.getTarget()); - writer.write("func (*$L) is$L() {}", exportedMemberName, symbol.getName()); + writer.openBlock( + "type $L struct {", + "}", + exportedMemberName, + () -> { + // Union members can't have null values, so for simple shapes we don't + // use pointers. We have to use pointers for complex shapes since, + // for example, we could still have a map that's empty or which has + // null values. + if (target instanceof SimpleShape) { + writer.write("Value $T", memberSymbol); + } else { + writer.write("Value $P", memberSymbol); + } + writer.write(""); } - } + ); - private boolean isEventStreamErrorMember(MemberShape memberShape) { - return isEventStream && memberShape.getMemberTrait(model, ErrorTrait.class).isPresent(); + writer.write( + "func (*$L) is$L() {}", + exportedMemberName, + symbol.getName() + ); } + } - /** - * Generates a struct for unknown union values that applies to every union in the given set. - * - * @param writer The writer to write the union to. - * @param unions A set of unions whose interfaces the union should apply to. - * @param symbolProvider A symbol provider used to get the symbols for the unions. - */ - public static void generateUnknownUnion( - final GoWriter writer, - final Collection unions, - final SymbolProvider symbolProvider - ) { - writer.openBlock("type $L struct {", "}", UNKNOWN_MEMBER_NAME, () -> { - // The tag (member) name received over the wire. - writer.write("Tag string"); - // The value received. - writer.write("Value []byte"); - writer.write(""); - }); + private boolean isEventStreamErrorMember(MemberShape memberShape) { + return ( + isEventStream && + memberShape.getMemberTrait(model, ErrorTrait.class).isPresent() + ); + } - for (UnionShape union : unions) { - writer.write("func (*$L) is$L() {}", UNKNOWN_MEMBER_NAME, symbolProvider.toSymbol(union).getName()); - } + /** + * Generates a struct for unknown union values that applies to every union in the given set. + * + * @param writer The writer to write the union to. + * @param unions A set of unions whose interfaces the union should apply to. + * @param symbolProvider A symbol provider used to get the symbols for the unions. + */ + public static void generateUnknownUnion( + final GoWriter writer, + final Collection unions, + final SymbolProvider symbolProvider + ) { + writer.openBlock( + "type $L struct {", + "}", + UNKNOWN_MEMBER_NAME, + () -> { + // The tag (member) name received over the wire. + writer.write("Tag string"); + // The value received. + writer.write("Value []byte"); + writer.write(""); + } + ); + + for (UnionShape union : unions) { + writer.write( + "func (*$L) is$L() {}", + UNKNOWN_MEMBER_NAME, + symbolProvider.toSymbol(union).getName() + ); } + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ValidationGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ValidationGenerator.java index 9d8ddc14a4..13107c50a3 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ValidationGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ValidationGenerator.java @@ -1,306 +1,395 @@ package software.amazon.polymorph.smithygo.codegen; +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + import java.math.BigDecimal; import java.util.Optional; - import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; import software.amazon.polymorph.traits.ReferenceTrait; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.Model; +import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.SimpleShape; -import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.traits.LengthTrait; import software.amazon.smithy.model.traits.RangeTrait; import software.amazon.smithy.model.traits.RequiredTrait; import software.amazon.smithy.model.traits.StreamingTrait; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - // Renders constraint validation public class ValidationGenerator { - private final Model model; - private final SymbolProvider symbolProvider; - private final GoWriter writer; - private final CodegenUtils.SortedMembers sortedMembers; - private static final String LIST_ITEM = "item"; - private static final String MAP_KEY = "key"; - private static final String MAP_VALUE = "value"; - private static final String UNION_DATASOURCE = "unionType.Value"; + private final Model model; + private final SymbolProvider symbolProvider; + private final GoWriter writer; + private final CodegenUtils.SortedMembers sortedMembers; + + private static final String LIST_ITEM = "item"; + private static final String MAP_KEY = "key"; + private static final String MAP_VALUE = "value"; + private static final String UNION_DATASOURCE = "unionType.Value"; + + public ValidationGenerator( + final Model model, + final SymbolProvider symbolProvider, + final GoWriter writer + ) { + this.model = model; + this.symbolProvider = symbolProvider; + this.writer = writer; + this.sortedMembers = new CodegenUtils.SortedMembers(symbolProvider); + } + + public void renderValidator( + final Shape shape, + final boolean isInputStructure + ) { + Symbol symbol = symbolProvider.toSymbol(shape); + writer.openBlock("func (input $L) Validate() (error) {", symbol.getName()); + renderValidatorHelper(shape, isInputStructure, "input"); + writer.write("return nil"); + writer.closeBlock("}").write(""); + } - public ValidationGenerator( - final Model model, - final SymbolProvider symbolProvider, - final GoWriter writer + private void renderValidatorHelper( + final Shape containerShape, + final boolean isInputStructure, + final String dataSource + ) { + containerShape + .getAllMembers() + .values() + .stream() + .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) + .sorted(sortedMembers) + .forEach(member -> { + String memberName; + if ( + containerShape.isListShape() || containerShape.isMapShape() + ) memberName = dataSource; else memberName = + dataSource + "." + symbolProvider.toMemberName(member); + renderValidatorForEachShape( + model.expectShape(member.getTarget()), + member, + isInputStructure, + memberName + ); + }); + } + + private void renderValidatorForEachShape( + final Shape currentShape, + final MemberShape memberShape, + final boolean isInputStructure, + final String dataSource + ) { + Symbol symbol = symbolProvider.toSymbol(currentShape); + if (isInputStructure) { + symbol = + symbol + .getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) + .orElse(symbol); + } + if (currentShape.hasTrait(ReferenceTrait.class)) { + symbol = symbol.getProperty("Referred", Symbol.class).get(); + } + String pointableString = ""; + if ( + !(dataSource.equals(LIST_ITEM) || + dataSource.equals(MAP_KEY) || + dataSource.equals(MAP_VALUE) || + (dataSource.equals(UNION_DATASOURCE) && + currentShape instanceof SimpleShape)) ) { - this.model = model; - this.symbolProvider = symbolProvider; - this.writer = writer; - this.sortedMembers = new CodegenUtils.SortedMembers(symbolProvider); + if ( + (boolean) symbol.getProperty(POINTABLE, Boolean.class).orElse(false) && + memberShape.isOptional() + ) { + pointableString = "*"; + } } - - public void renderValidator (final Shape shape, final boolean isInputStructure) { - Symbol symbol = symbolProvider.toSymbol(shape); - writer.openBlock("func (input $L) Validate() (error) {", symbol.getName()); - renderValidatorHelper( shape, isInputStructure, "input"); - writer.write("return nil"); - writer.closeBlock("}").write(""); + if (currentShape.hasTrait(RangeTrait.class)) { + addRangeCheck(currentShape, dataSource, pointableString); } - - private void renderValidatorHelper (final Shape containerShape, final boolean isInputStructure, final String dataSource) { - containerShape.getAllMembers().values().stream() - .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) - .sorted(sortedMembers) - .forEach((member) -> { - String memberName; - if (containerShape.isListShape() || containerShape.isMapShape()) - memberName = dataSource; - else - memberName = dataSource + "." + symbolProvider.toMemberName(member); - renderValidatorForEachShape(model.expectShape(member.getTarget()), member, isInputStructure, memberName); - }); + if (currentShape.hasTrait(LengthTrait.class)) { + addLengthCheck(currentShape, dataSource, pointableString); } - - private void renderValidatorForEachShape (final Shape currentShape, final MemberShape memberShape, final boolean isInputStructure, final String dataSource) { - Symbol symbol = symbolProvider.toSymbol(currentShape); - if (isInputStructure) { - symbol = symbol.getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) - .orElse(symbol); - } - if (currentShape.hasTrait(ReferenceTrait.class)) { - symbol = symbol.getProperty("Referred", Symbol.class).get(); - } - String pointableString = ""; - if (!(dataSource.equals(LIST_ITEM) || dataSource.equals(MAP_KEY) || dataSource.equals(MAP_VALUE) || dataSource.equals(UNION_DATASOURCE) && currentShape instanceof SimpleShape)) { - if ((boolean) symbol.getProperty(POINTABLE, Boolean.class).orElse(false) && memberShape.isOptional()){ - pointableString = "*"; - } - } - if (currentShape.hasTrait(RangeTrait.class)) { - addRangeCheck(currentShape, dataSource, pointableString); - } - if (currentShape.hasTrait(LengthTrait.class)) { - addLengthCheck(currentShape, dataSource, pointableString); - } - if (currentShape.hasTrait(RequiredTrait.class)) { - addRequiredCheck(symbol, currentShape, dataSource); - } - if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { - addUTFCheck(currentShape, dataSource, pointableString); - } - // Broke list and map into two different if else because for _, item := range %s looked good for list - // And for key, value := range %s looked good for map - if (currentShape.isListShape()) { - writer.write(""" - for _, %s := range %s { - // To avoid declared and not used error for shapes which does not need validation check - _ = item - """.formatted(LIST_ITEM, dataSource)); - renderValidatorHelper(currentShape, false, LIST_ITEM); - writer.write(""" - } - """); - } - else if (currentShape.isMapShape()) { - writer.write(""" - for %s, %s := range %s { - // To avoid declared and not used error for shapes which does not need validation check - _ = key - _ = value - """.formatted(MAP_KEY, MAP_VALUE, dataSource)); - renderValidatorHelper(currentShape, false, MAP_KEY); - renderValidatorHelper(currentShape, false, MAP_VALUE); - writer.write(""" - } - """); - } - else if (currentShape.isUnionShape()) { - writer.write(""" - switch unionType := %s.(type) { - """.formatted(dataSource)); - for (var memberInUnion : currentShape.getAllMembers().values()) { - writer.write(""" - case *%s: - """.formatted( - symbolProvider.toMemberName(memberInUnion) - )); - - renderValidatorForEachShape(model.expectShape(memberInUnion.getTarget()), memberInUnion, false, "unionType.Value"); - } - writer.write(""" - // Default case should not be reached. - default: - // To avoid used and not used error when nothing to validate - _ = unionType - panic("Unhandled union type") - } - """); - } - else { - renderValidatorHelper(currentShape, isInputStructure, dataSource); - } + if (currentShape.hasTrait(RequiredTrait.class)) { + addRequiredCheck(symbol, currentShape, dataSource); } - - private void addRangeCheck(final Shape currentShape, final String dataSource, final String pointableString) { - StringBuilder rangeCheck = new StringBuilder(); - RangeTrait rangeTraitShape = currentShape.expectTrait(RangeTrait.class); - Optional min = rangeTraitShape.getMin(); - Optional max = rangeTraitShape.getMax(); - if (pointableString.equals("*")){ - rangeCheck.append(""" - if (%s != nil) { - """.formatted(dataSource)); - } - if (min.isPresent()) { - rangeCheck.append(""" - if (%s%s < %s) { - return fmt.Errorf(\"%s has a minimum of %s but has the value of %%d.\", %s%s) - } - """.formatted( - pointableString, - dataSource, - min.get().toString(), - currentShape.getId().getName(), - min.get().toString(), - pointableString, - dataSource)); - } - if (max.isPresent()) { - rangeCheck.append(""" - if (%s%s > %s) { - return fmt.Errorf(\"%s has a maximum of %s but has the value of %%d.\", %s%s) - } - """.formatted( - pointableString, - dataSource, - max.get().toString(), - currentShape.getId().getName(), - max.get().toString(), - pointableString, - dataSource)); + if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { + addUTFCheck(currentShape, dataSource, pointableString); + } + // Broke list and map into two different if else because for _, item := range %s looked good for list + // And for key, value := range %s looked good for map + if (currentShape.isListShape()) { + writer.write( + """ + for _, %s := range %s { + // To avoid declared and not used error for shapes which does not need validation check + _ = item + """.formatted(LIST_ITEM, dataSource) + ); + renderValidatorHelper(currentShape, false, LIST_ITEM); + writer.write( + """ } - if (pointableString.equals("*")){ - rangeCheck.append(""" + """ + ); + } else if (currentShape.isMapShape()) { + writer.write( + """ + for %s, %s := range %s { + // To avoid declared and not used error for shapes which does not need validation check + _ = key + _ = value + """.formatted(MAP_KEY, MAP_VALUE, dataSource) + ); + renderValidatorHelper(currentShape, false, MAP_KEY); + renderValidatorHelper(currentShape, false, MAP_VALUE); + writer.write( + """ + } + """ + ); + } else if (currentShape.isUnionShape()) { + writer.write( + """ + switch unionType := %s.(type) { + """.formatted(dataSource) + ); + for (var memberInUnion : currentShape.getAllMembers().values()) { + writer.write( + """ + case *%s: + """.formatted(symbolProvider.toMemberName(memberInUnion)) + ); + + renderValidatorForEachShape( + model.expectShape(memberInUnion.getTarget()), + memberInUnion, + false, + "unionType.Value" + ); + } + writer.write( + """ + // Default case should not be reached. + default: + // To avoid used and not used error when nothing to validate + _ = unionType + panic("Unhandled union type") } - """); - } - writer.write(rangeCheck); + """ + ); + } else { + renderValidatorHelper(currentShape, isInputStructure, dataSource); } + } - private void addLengthCheck(final Shape currentShape, final String dataSource, final String pointableString) { - StringBuilder lengthCheck = new StringBuilder(); - LengthTrait lengthTraitShape = currentShape.expectTrait(LengthTrait.class); - Optional min = lengthTraitShape.getMin(); - Optional max = lengthTraitShape.getMax(); - if (pointableString.equals("*")){ - lengthCheck.append(""" - if (%s != nil) { - """.formatted(dataSource)); - } - if (min.isPresent()) { - if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { - lengthCheck.append(""" - if (utf8.RuneCountInString(%s%s) < %s) { - return fmt.Errorf(\"%s has a minimum length of %s but has the length of %%d.\", utf8.RuneCountInString(%s%s)) - } - """.formatted( - pointableString, - dataSource, - min.get().toString(), - currentShape.getId().getName(), - min.get().toString(), - pointableString, - dataSource)); - } - else { - lengthCheck.append(""" - if (len(%s%s) < %s) { - return fmt.Errorf(\"%s has a minimum length of %s but has the length of %%d.\", len(%s%s)) - } - """.formatted( - pointableString, - dataSource, - min.get().toString(), - currentShape.getId().getName(), - min.get().toString(), - pointableString, - dataSource)); - } + private void addRangeCheck( + final Shape currentShape, + final String dataSource, + final String pointableString + ) { + StringBuilder rangeCheck = new StringBuilder(); + RangeTrait rangeTraitShape = currentShape.expectTrait(RangeTrait.class); + Optional min = rangeTraitShape.getMin(); + Optional max = rangeTraitShape.getMax(); + if (pointableString.equals("*")) { + rangeCheck.append( + """ + if (%s != nil) { + """.formatted(dataSource) + ); + } + if (min.isPresent()) { + rangeCheck.append( + """ + if (%s%s < %s) { + return fmt.Errorf(\"%s has a minimum of %s but has the value of %%d.\", %s%s) } - if (max.isPresent()) { - if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { - lengthCheck.append(""" - if (utf8.RuneCountInString(%s%s) > %s) { - return fmt.Errorf(\"%s has a maximum length of %s but has the length of %%d.\", utf8.RuneCountInString(%s%s)) - } - """.formatted( - pointableString, - dataSource, - max.get().toString(), - currentShape.getId().getName(), - max.get().toString(), - pointableString, - dataSource)); - } - else { - lengthCheck.append(""" - if (len(%s%s) > %s) { - return fmt.Errorf(\"%s has a maximum length of %s but has the length of %%d.\", len(%s%s)) - } - """.formatted( - pointableString, - dataSource, - max.get().toString(), - currentShape.getId().getName(), - max.get().toString(), - pointableString, - dataSource)); - } + """.formatted( + pointableString, + dataSource, + min.get().toString(), + currentShape.getId().getName(), + min.get().toString(), + pointableString, + dataSource + ) + ); + } + if (max.isPresent()) { + rangeCheck.append( + """ + if (%s%s > %s) { + return fmt.Errorf(\"%s has a maximum of %s but has the value of %%d.\", %s%s) } - if (pointableString.equals("*")){ - lengthCheck.append(""" - } - """); + """.formatted( + pointableString, + dataSource, + max.get().toString(), + currentShape.getId().getName(), + max.get().toString(), + pointableString, + dataSource + ) + ); + } + if (pointableString.equals("*")) { + rangeCheck.append( + """ } - writer.write(lengthCheck); + """ + ); } + writer.write(rangeCheck); + } - private void addRequiredCheck(final Symbol memberSymbol, final Shape currentShape, final String dataSource) { - StringBuilder RequiredCheck = new StringBuilder(); - if( memberSymbol.getProperty(POINTABLE).isPresent() && (boolean) memberSymbol.getProperty(POINTABLE).get()) - RequiredCheck.append(""" - if ( %s == nil ) { - return fmt.Errorf(\"%s is required but has a nil value.\") - } - """.formatted( - dataSource, - dataSource)); - writer.write(RequiredCheck); + private void addLengthCheck( + final Shape currentShape, + final String dataSource, + final String pointableString + ) { + StringBuilder lengthCheck = new StringBuilder(); + LengthTrait lengthTraitShape = currentShape.expectTrait(LengthTrait.class); + Optional min = lengthTraitShape.getMin(); + Optional max = lengthTraitShape.getMax(); + if (pointableString.equals("*")) { + lengthCheck.append( + """ + if (%s != nil) { + """.formatted(dataSource) + ); } - - private void addUTFCheck(final Shape currentShape, final String dataSource, final String pointableString) { - StringBuilder UTFCheck = new StringBuilder(); - if (pointableString.equals("*")){ - UTFCheck.append(""" - if ( %s != nil ) { - """.formatted(dataSource)); + if (min.isPresent()) { + if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { + lengthCheck.append( + """ + if (utf8.RuneCountInString(%s%s) < %s) { + return fmt.Errorf(\"%s has a minimum length of %s but has the length of %%d.\", utf8.RuneCountInString(%s%s)) + } + """.formatted( + pointableString, + dataSource, + min.get().toString(), + currentShape.getId().getName(), + min.get().toString(), + pointableString, + dataSource + ) + ); + } else { + lengthCheck.append( + """ + if (len(%s%s) < %s) { + return fmt.Errorf(\"%s has a minimum length of %s but has the length of %%d.\", len(%s%s)) + } + """.formatted( + pointableString, + dataSource, + min.get().toString(), + currentShape.getId().getName(), + min.get().toString(), + pointableString, + dataSource + ) + ); + } + } + if (max.isPresent()) { + if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { + lengthCheck.append( + """ + if (utf8.RuneCountInString(%s%s) > %s) { + return fmt.Errorf(\"%s has a maximum length of %s but has the length of %%d.\", utf8.RuneCountInString(%s%s)) + } + """.formatted( + pointableString, + dataSource, + max.get().toString(), + currentShape.getId().getName(), + max.get().toString(), + pointableString, + dataSource + ) + ); + } else { + lengthCheck.append( + """ + if (len(%s%s) > %s) { + return fmt.Errorf(\"%s has a maximum length of %s but has the length of %%d.\", len(%s%s)) + } + """.formatted( + pointableString, + dataSource, + max.get().toString(), + currentShape.getId().getName(), + max.get().toString(), + pointableString, + dataSource + ) + ); + } + } + if (pointableString.equals("*")) { + lengthCheck.append( + """ } - UTFCheck.append(""" - if (!utf8.ValidString(%s%s)) { - return fmt.Errorf(\"Invalid UTF bytes %%s \", %s%s) - } - """.formatted( - pointableString, - dataSource, - pointableString, - dataSource)); - if (pointableString.equals("*")){ - UTFCheck.append(""" - } - """); + """ + ); + } + writer.write(lengthCheck); + } + + private void addRequiredCheck( + final Symbol memberSymbol, + final Shape currentShape, + final String dataSource + ) { + StringBuilder RequiredCheck = new StringBuilder(); + if ( + memberSymbol.getProperty(POINTABLE).isPresent() && + (boolean) memberSymbol.getProperty(POINTABLE).get() + ) RequiredCheck.append( + """ + if ( %s == nil ) { + return fmt.Errorf(\"%s is required but has a nil value.\") + } + """.formatted(dataSource, dataSource) + ); + writer.write(RequiredCheck); + } + + private void addUTFCheck( + final Shape currentShape, + final String dataSource, + final String pointableString + ) { + StringBuilder UTFCheck = new StringBuilder(); + if (pointableString.equals("*")) { + UTFCheck.append( + """ + if ( %s != nil ) { + """.formatted(dataSource) + ); + } + UTFCheck.append( + """ + if (!utf8.ValidString(%s%s)) { + return fmt.Errorf(\"Invalid UTF bytes %%s \", %s%s) + } + """.formatted(pointableString, dataSource, pointableString, dataSource) + ); + if (pointableString.equals("*")) { + UTFCheck.append( + """ } - writer.write(UTFCheck); + """ + ); } + writer.write(UTFCheck); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/GoIntegration.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/GoIntegration.java index acf1f770c4..5eb8b38504 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/GoIntegration.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/GoIntegration.java @@ -8,5 +8,5 @@ import software.amazon.polymorph.smithygo.codegen.GoWriter; import software.amazon.smithy.codegen.core.SmithyIntegration; -public interface GoIntegration extends SmithyIntegration { -} +public interface GoIntegration + extends SmithyIntegration {} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/ProtocolGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/ProtocolGenerator.java index abda4b6764..c63f0803a0 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/ProtocolGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/ProtocolGenerator.java @@ -14,57 +14,57 @@ */ package software.amazon.polymorph.smithygo.codegen.integration; +import static java.lang.String.format; + import software.amazon.polymorph.smithygo.codegen.ApplicationProtocol; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.utils.SmithyUnstableApi; -import static java.lang.String.format; - /** * Generates code to implement a protocol for both servers and clients. */ @SmithyUnstableApi public interface ProtocolGenerator { - /** - * Gets the supported protocol {@link ShapeId}. - * - * @return Returns the protocol supported - */ - ShapeId getProtocol(); + /** + * Gets the supported protocol {@link ShapeId}. + * + * @return Returns the protocol supported + */ + ShapeId getProtocol(); - /** - * Gets the name of the protocol. - * - *

The default implementation is the ShapeId name of the protocol trait in - * Smithy models (e.g., "aws.protocols#restJson1" would return "restJson1"). - * - * @return Returns the protocol name. - */ - default String getName() { - return getProtocol().getName(); - } + /** + * Gets the name of the protocol. + * + *

The default implementation is the ShapeId name of the protocol trait in + * Smithy models (e.g., "aws.protocols#restJson1" would return "restJson1"). + * + * @return Returns the protocol name. + */ + default String getName() { + return getProtocol().getName(); + } - /** - * Creates an application protocol for the generator. - * - * @return Returns the created application protocol. - */ - ApplicationProtocol getApplicationProtocol(); + /** + * Creates an application protocol for the generator. + * + * @return Returns the created application protocol. + */ + ApplicationProtocol getApplicationProtocol(); - /** - * Generates the code used to serialize the shapes of a service - * for requests. - * - * @param context Serialization context. - */ - void generateSerializers(GenerationContext context); + /** + * Generates the code used to serialize the shapes of a service + * for requests. + * + * @param context Serialization context. + */ + void generateSerializers(GenerationContext context); - /** - * Generates the code used to deserialize the shapes of a service - * for responses. - * - * @param context Deserialization context. - */ - void generateDeserializers(GenerationContext context); + /** + * Generates the code used to deserialize the shapes of a service + * for responses. + * + * @param context Deserialization context. + */ + void generateDeserializers(GenerationContext context); } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java index 0a7e5834f4..9f490144f0 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java @@ -17,6 +17,9 @@ package software.amazon.polymorph.smithygo.codegen.knowledge; +import java.util.HashSet; +import java.util.Set; +import java.util.logging.Logger; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.KnowledgeIndex; import software.amazon.smithy.model.knowledge.NeighborProviderIndex; @@ -34,253 +37,276 @@ import software.amazon.smithy.model.traits.StreamingTrait; import software.amazon.smithy.utils.SetUtils; -import java.util.HashSet; -import java.util.Set; -import java.util.logging.Logger; - /** * An index that checks if a member or shape type should be a pointer type in Go. *

* Extends the rules of smithy's NullableIndex for Go's translation of the smithy shapes to Go types. */ public class GoPointableIndex implements KnowledgeIndex { - private static final Logger LOGGER = Logger.getLogger(GoPointableIndex.class.getName()); - - // All types that are Go value types - private static final Set INHERENTLY_VALUE = SetUtils.of( - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - ShapeType.UNION, - ShapeType.DOCUMENT - ); - - // All types that are Go pointer types - private static final Set INHERENTLY_POINTABLE = SetUtils.of( - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - // All types that cannot be dereferenced - private static final Set INHERENTLY_NONDEREFERENCABLE = SetUtils.of( - // built in slice/map - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - - // Interfaces - ShapeType.UNION, - ShapeType.DOCUMENT, - - // known pointer types. - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER + private static final Logger LOGGER = Logger.getLogger( + GoPointableIndex.class.getName() + ); + + // All types that are Go value types + private static final Set INHERENTLY_VALUE = SetUtils.of( + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + ShapeType.UNION, + ShapeType.DOCUMENT + ); + + // All types that are Go pointer types + private static final Set INHERENTLY_POINTABLE = SetUtils.of( + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + // All types that cannot be dereferenced + private static final Set INHERENTLY_NONDEREFERENCABLE = + SetUtils.of( + // built in slice/map + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + // Interfaces + ShapeType.UNION, + ShapeType.DOCUMENT, + // known pointer types. + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER ); - // All types types that are comparable to nil - private static final Set INHERENTLY_NILLABLE = SetUtils.of( - // built in slice/map - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - - // Interfaces - ShapeType.UNION, - ShapeType.DOCUMENT, - - // known pointer types. - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER + // All types types that are comparable to nil + private static final Set INHERENTLY_NILLABLE = SetUtils.of( + // built in slice/map + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + // Interfaces + ShapeType.UNION, + ShapeType.DOCUMENT, + // known pointer types. + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + // All the known pointer type if not required + private static final Set KNOWN_POINTER_TYPE = SetUtils.of( + ShapeType.BYTE, + ShapeType.SHORT, + ShapeType.INTEGER, + ShapeType.LONG, + ShapeType.FLOAT, + ShapeType.DOUBLE, + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + private final Model model; + private final NullableIndex nullableIndex; + private final Set pointableShapes = new HashSet<>(); + private final Set nillableShapes = new HashSet<>(); + private final Set dereferencableShapes = new HashSet<>(); + + public GoPointableIndex(Model model) { + this.model = model; + this.nullableIndex = NullableIndex.of(model); + + for (Shape shape : model.toSet()) { + if (shape.asMemberShape().isPresent()) { + MemberShape member = shape.asMemberShape().get(); + Shape targetShape = model.expectShape(member.getTarget()); + + if (isMemberPointable(member, targetShape)) { + pointableShapes.add(shape.getId()); + } + if (isMemberNillable(member, targetShape)) { + nillableShapes.add(shape.getId()); + } + if (isMemberDereferencable(member, targetShape)) { + dereferencableShapes.add(shape.getId()); + } + } else { + if (isShapePointable(shape)) { + pointableShapes.add(shape.getId()); + nillableShapes.add(shape.getId()); + } + if (isShapeNillable(shape)) { + nillableShapes.add(shape.getId()); + } + if (isShapeDereferencable(shape)) { + dereferencableShapes.add(shape.getId()); + } + } + } + } + + public static GoPointableIndex of(Model model) { + return model.getKnowledge(GoPointableIndex.class, GoPointableIndex::new); + } + + private boolean isMemberDereferencable( + MemberShape member, + Shape targetShape + ) { + return ( + !INHERENTLY_NONDEREFERENCABLE.contains(targetShape.getType()) && + isMemberPointable(member, targetShape) ); + } - // All the known pointer type if not required - private static final Set KNOWN_POINTER_TYPE = SetUtils.of( - ShapeType.BYTE, - ShapeType.SHORT, - ShapeType.INTEGER, - ShapeType.LONG, - ShapeType.FLOAT, - ShapeType.DOUBLE, - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER + private boolean isMemberNillable(MemberShape member, Shape targetShape) { + return ( + INHERENTLY_NILLABLE.contains(targetShape.getType()) || + isMemberPointable(member, targetShape) ); + } - private final Model model; - private final NullableIndex nullableIndex; - private final Set pointableShapes = new HashSet<>(); - private final Set nillableShapes = new HashSet<>(); - private final Set dereferencableShapes = new HashSet<>(); - - public GoPointableIndex(Model model) { - this.model = model; - this.nullableIndex = NullableIndex.of(model); - - for (Shape shape : model.toSet()) { - if (shape.asMemberShape().isPresent()) { - MemberShape member = shape.asMemberShape().get(); - Shape targetShape = model.expectShape(member.getTarget()); - - if (isMemberPointable(member, targetShape)) { - pointableShapes.add(shape.getId()); - } - if (isMemberNillable(member, targetShape)) { - nillableShapes.add(shape.getId()); - } - if (isMemberDereferencable(member, targetShape)) { - dereferencableShapes.add(shape.getId()); - } - } else { - if (isShapePointable(shape)) { - pointableShapes.add(shape.getId()); - nillableShapes.add(shape.getId()); - } - if (isShapeNillable(shape)) { - nillableShapes.add(shape.getId()); - } - if (isShapeDereferencable(shape)) { - dereferencableShapes.add(shape.getId()); - } - } - } + private boolean isMemberPointable(MemberShape member, Shape targetShape) { + // Streamed blob shapes are never pointers because they are interfaces + if (isBlobStream(targetShape)) { + return false; } - public static GoPointableIndex of(Model model) { - return model.getKnowledge(GoPointableIndex.class, GoPointableIndex::new); + if (INHERENTLY_VALUE.contains(targetShape.getType())) { + return false; } - private boolean isMemberDereferencable(MemberShape member, Shape targetShape) { - return !INHERENTLY_NONDEREFERENCABLE.contains(targetShape.getType()) && isMemberPointable(member, targetShape); + //if membershape is required return it is not pointable + if (member.hasTrait(RequiredTrait.class)) { + return false; } - private boolean isMemberNillable(MemberShape member, Shape targetShape) { - return INHERENTLY_NILLABLE.contains(targetShape.getType()) || isMemberPointable(member, targetShape); + if (model.expectShape(member.getContainer()).isMapShape()) { + return false; } - private boolean isMemberPointable(MemberShape member, Shape targetShape) { - // Streamed blob shapes are never pointers because they are interfaces - if (isBlobStream(targetShape)) { - return false; - } - - if (INHERENTLY_VALUE.contains(targetShape.getType())) { - return false; - } + if (KNOWN_POINTER_TYPE.contains(targetShape.getType())) { + return true; + } - //if membershape is required return it is not pointable - if (member.hasTrait(RequiredTrait.class)) { - return false; - } + return nullableIndex.isMemberNullable( + member, + NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1_NO_INPUT + ); + } - if (model.expectShape(member.getContainer()).isMapShape()) { - return false; - } + private boolean isShapeDereferencable(Shape shape) { + return ( + !INHERENTLY_NONDEREFERENCABLE.contains(shape.getType()) && + isShapePointable(shape) + ); + } - if (KNOWN_POINTER_TYPE.contains(targetShape.getType())) { - return true; - } + private boolean isShapeNillable(Shape shape) { + return ( + INHERENTLY_NILLABLE.contains(shape.getType()) || isShapePointable(shape) + ); + } - return nullableIndex.isMemberNullable(member, NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1_NO_INPUT); + private boolean isShapePointable(Shape shape) { + // All operation input and output shapes are pointable. + if (isOperationStruct(shape)) { + return true; } - private boolean isShapeDereferencable(Shape shape) { - return !INHERENTLY_NONDEREFERENCABLE.contains(shape.getType()) && isShapePointable(shape); + // Streamed blob shapes are never pointers because they are interfaces + if (isBlobStream(shape)) { + return false; } - private boolean isShapeNillable(Shape shape) { - return INHERENTLY_NILLABLE.contains(shape.getType()) || isShapePointable(shape); + if (shape.isServiceShape()) { + return true; } - private boolean isShapePointable(Shape shape) { - // All operation input and output shapes are pointable. - if (isOperationStruct(shape)) { - return true; - } - - // Streamed blob shapes are never pointers because they are interfaces - if (isBlobStream(shape)) { - return false; - } - - if (shape.isServiceShape()) { - return true; - } - - // This is odd because its not a go type but a function with receiver - if (shape.isOperationShape()) { - return false; - } - - if (INHERENTLY_POINTABLE.contains(shape.getType())) { - return true; - } - - if (INHERENTLY_VALUE.contains(shape.getType())) { - return false; - } - - if (shape.hasTrait(RequiredTrait.class)) { - return false; - } - - if (KNOWN_POINTER_TYPE.contains(shape.getType())) { - return true; - } - - return nullableIndex.isNullable(shape); + // This is odd because its not a go type but a function with receiver + if (shape.isOperationShape()) { + return false; } - private boolean isShapeEnum(Shape shape) { - return shape.getType() == ShapeType.STRING && shape.hasTrait(EnumTrait.class) - || shape.getType() == ShapeType.ENUM - || shape.getType() == ShapeType.INT_ENUM; + if (INHERENTLY_POINTABLE.contains(shape.getType())) { + return true; } - private boolean isBlobStream(Shape shape) { - return shape.getType() == ShapeType.BLOB && shape.hasTrait(StreamingTrait.ID); + if (INHERENTLY_VALUE.contains(shape.getType())) { + return false; } - private boolean isOperationStruct(Shape shape) { - NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); - for (Relationship relationship : provider.getNeighbors(shape)) { - RelationshipType relationshipType = relationship.getRelationshipType(); - if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { - return true; - } - } - - return false; + if (shape.hasTrait(RequiredTrait.class)) { + return false; } - /** - * Returns if the shape should be generated as a Go pointer type or not. - * - * @param shape the shape to check if should be pointable type. - * @return if the shape is should be a Go pointer type. - */ - public final boolean isPointable(ToShapeId shape) { - return pointableShapes.contains(shape.toShapeId()); + if (KNOWN_POINTER_TYPE.contains(shape.getType())) { + return true; } - /** - * Returns if the Go type generated for the shape is comparable to nil. - * - * @param shape the shape to check - * @return if the shape's go type is comparable to nil - */ - public final boolean isNillable(ToShapeId shape) { - return nillableShapes.contains(shape.toShapeId()); - } + return nullableIndex.isNullable(shape); + } + + private boolean isShapeEnum(Shape shape) { + return ( + (shape.getType() == ShapeType.STRING && + shape.hasTrait(EnumTrait.class)) || + shape.getType() == ShapeType.ENUM || + shape.getType() == ShapeType.INT_ENUM + ); + } - /** - * Returns if the Go type generated for the shape can be dereferenced. - * - * @param shape the shape to check - * @return if the shape's go type is dereferencable - */ - public final boolean isDereferencable(ToShapeId shape) { - return dereferencableShapes.contains(shape.toShapeId()); + private boolean isBlobStream(Shape shape) { + return ( + shape.getType() == ShapeType.BLOB && shape.hasTrait(StreamingTrait.ID) + ); + } + + private boolean isOperationStruct(Shape shape) { + NeighborProvider provider = NeighborProviderIndex + .of(model) + .getReverseProvider(); + for (Relationship relationship : provider.getNeighbors(shape)) { + RelationshipType relationshipType = relationship.getRelationshipType(); + if ( + relationshipType == RelationshipType.INPUT || + relationshipType == RelationshipType.OUTPUT + ) { + return true; + } } + + return false; + } + + /** + * Returns if the shape should be generated as a Go pointer type or not. + * + * @param shape the shape to check if should be pointable type. + * @return if the shape is should be a Go pointer type. + */ + public final boolean isPointable(ToShapeId shape) { + return pointableShapes.contains(shape.toShapeId()); + } + + /** + * Returns if the Go type generated for the shape is comparable to nil. + * + * @param shape the shape to check + * @return if the shape's go type is comparable to nil + */ + public final boolean isNillable(ToShapeId shape) { + return nillableShapes.contains(shape.toShapeId()); + } + + /** + * Returns if the Go type generated for the shape can be dereferenced. + * + * @param shape the shape to check + * @return if the shape's go type is dereferencable + */ + public final boolean isDereferencable(ToShapeId shape) { + return dereferencableShapes.contains(shape.toShapeId()); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoUsageIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoUsageIndex.java index e8e00b0fa0..8bd7b5226f 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoUsageIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoUsageIndex.java @@ -15,6 +15,9 @@ package software.amazon.polymorph.smithygo.codegen.knowledge; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.KnowledgeIndex; import software.amazon.smithy.model.knowledge.OperationIndex; @@ -27,65 +30,87 @@ import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.ToShapeId; -import java.util.HashSet; -import java.util.Set; -import java.util.stream.Collectors; - /** * Provides {@link KnowledgeIndex} of how shapes are used in the model. */ public class GoUsageIndex implements KnowledgeIndex { - private final Model model; - private final Walker walker; - private final Set inputShapes = new HashSet<>(); - private final Set outputShapes = new HashSet<>(); + private final Model model; + private final Walker walker; - public GoUsageIndex(Model model) { - this.model = model; - this.walker = new Walker(model); + private final Set inputShapes = new HashSet<>(); + private final Set outputShapes = new HashSet<>(); - TopDownIndex topDownIndex = TopDownIndex.of(model); - OperationIndex operationIndex = OperationIndex.of(model); + public GoUsageIndex(Model model) { + this.model = model; + this.walker = new Walker(model); - model.shapes(ServiceShape.class).forEach(serviceShape -> { - topDownIndex.getContainedOperations(serviceShape).forEach(operationShape -> { - StructureShape inputShape = operationIndex.getInput(operationShape).get(); - StructureShape outputShape = operationIndex.getOutput(operationShape).get(); + TopDownIndex topDownIndex = TopDownIndex.of(model); + OperationIndex operationIndex = OperationIndex.of(model); - inputShapes.addAll(walker.walkShapes(inputShape, relationship -> - relationship.getDirection() == RelationshipDirection.DIRECTED).stream() - .map(Shape::toShapeId).collect(Collectors.toList())); + model + .shapes(ServiceShape.class) + .forEach(serviceShape -> { + topDownIndex + .getContainedOperations(serviceShape) + .forEach(operationShape -> { + StructureShape inputShape = operationIndex + .getInput(operationShape) + .get(); + StructureShape outputShape = operationIndex + .getOutput(operationShape) + .get(); - outputShapes.addAll(walker.walkShapes(outputShape, relationship -> - relationship.getDirection() == RelationshipDirection.DIRECTED).stream() - .map(Shape::toShapeId).collect(Collectors.toList())); + inputShapes.addAll( + walker + .walkShapes( + inputShape, + relationship -> + relationship.getDirection() == + RelationshipDirection.DIRECTED + ) + .stream() + .map(Shape::toShapeId) + .collect(Collectors.toList()) + ); - }); - }); - } + outputShapes.addAll( + walker + .walkShapes( + outputShape, + relationship -> + relationship.getDirection() == + RelationshipDirection.DIRECTED + ) + .stream() + .map(Shape::toShapeId) + .collect(Collectors.toList()) + ); + }); + }); + } - /** - * Returns whether shape is used as part of an input to an operation. - * - * @param shape the shape - * @return whether the shape is used as input. - */ - public boolean isUsedForInput(ToShapeId shape) { - return inputShapes.contains(shape.toShapeId()); - } + /** + * Returns whether shape is used as part of an input to an operation. + * + * @param shape the shape + * @return whether the shape is used as input. + */ + public boolean isUsedForInput(ToShapeId shape) { + return inputShapes.contains(shape.toShapeId()); + } - /** - * Returns whether shape is used as output of an operation. - * - * @param shape the shape - * @return whether the shape is used as input. - */ - public boolean isUsedForOutput(ToShapeId shape) { - return outputShapes.contains(shape.toShapeId()); - } + /** + * Returns whether shape is used as output of an operation. + * + * @param shape the shape + * @return whether the shape is used as input. + */ + public boolean isUsedForOutput(ToShapeId shape) { + return outputShapes.contains(shape.toShapeId()); + } - public static GoUsageIndex of(Model model) { - return model.getKnowledge(GoUsageIndex.class, GoUsageIndex::new); - } + public static GoUsageIndex of(Model model) { + return model.getKnowledge(GoUsageIndex.class, GoUsageIndex::new); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoValidationIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoValidationIndex.java index 60ef46d1b5..c4410f6eca 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoValidationIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoValidationIndex.java @@ -30,6 +30,13 @@ package software.amazon.polymorph.smithygo.codegen.knowledge; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.Consumer; +import java.util.stream.Collectors; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.KnowledgeIndex; import software.amazon.smithy.model.knowledge.TopDownIndex; @@ -44,148 +51,209 @@ import software.amazon.smithy.model.traits.RequiredTrait; import software.amazon.smithy.utils.SetUtils; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.TreeSet; -import java.util.function.Consumer; -import java.util.stream.Collectors; - /** * Provides a knowledge index of which service operations and shapes require validation helpers. */ public class GoValidationIndex implements KnowledgeIndex { - private final Map> serviceToOperationMap = new HashMap<>(); - private final Map> serviceValidationHelpers = new HashMap<>(); - - public GoValidationIndex(Model model) { - TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - Walker walker = new Walker(model); - - model.shapes(ServiceShape.class).forEach(serviceShape -> { - // Go uses unique input shapes per operation so we can index using the input shape as our key - Map inputShapeToOperation = new HashMap<>(); - Set requireValidationHelpers = new TreeSet<>(); - - // First pass is to collect member containers that contain members requiring validation - Set operations = topDownIndex.getContainedOperations(serviceShape); - operations.forEach(operationShape -> { - Shape inputShape = model.expectShape(operationShape.getInput().get()); - GoValidationIndex.walkValidationTree(walker, inputShape, shape -> { - if (shape.isMemberShape()) { - Shape container = model.expectShape(((MemberShape) shape).getContainer()); - if (isRequiredParameter(model, (MemberShape) shape, inputShape.equals(container))) { - inputShapeToOperation.put(inputShape, operationShape); - requireValidationHelpers.add(container.toShapeId()); - } - } - }); - }); - - // 2nd step is final all containers that reference the initial containers which require validation until - // we've discovered all intermediate containing types - inputShapeToOperation.keySet().forEach(input -> { - Set helpers = new TreeSet<>(); - do { - GoValidationIndex.walkValidationTree(walker, input, shape -> { - if (shape.isMemberShape()) { - MemberShape memberShape = shape.asMemberShape().get(); - Shape container = model.expectShape(memberShape.getContainer()); - Shape target = model.expectShape(memberShape.getTarget()); - if (requireValidationHelpers.contains(target.toShapeId()) - && !requireValidationHelpers.contains(container.toShapeId())) { - helpers.add(container.toShapeId()); - } - } - }); - if (helpers.isEmpty()) { - break; - } - requireValidationHelpers.addAll(helpers); - helpers.clear(); - } while (true); - }); - - serviceToOperationMap.put(serviceShape.toShapeId(), new TreeSet<>(inputShapeToOperation.values().stream() - .map(OperationShape::toShapeId).collect(Collectors.toSet()))); - serviceValidationHelpers.put(serviceShape.toShapeId(), requireValidationHelpers); - }); - } - - public static GoValidationIndex of(Model model) { - return model.getKnowledge(GoValidationIndex.class, GoValidationIndex::new); - } - - /** - * Get the set of operations that require validation. - * - * @param service service to find operations for - * @return operations requiring validation - */ - public Set getOperationsRequiringValidation(ToShapeId service) { - return serviceToOperationMap.getOrDefault(service.toShapeId(), SetUtils.of()); - } - - /** - * Get a set of shapes that require validation helpers. - * - * @param service service to find operations for - * @return operations requiring validation - */ - public Set getShapesRequiringValidationHelpers(ToShapeId service) { - return serviceValidationHelpers.getOrDefault(service.toShapeId(), SetUtils.of()); - } - - /** - * Returns whether the given shape requires a validation helper. - * - * @param shape the shape to check - * @return whether the shape requires a validation helper - */ - public boolean isValidationHelperRequired(ToShapeId shape) { - return serviceValidationHelpers.containsKey(shape.toShapeId()); - } - - /** - * Checks whether a {@link MemberShape} has any validation constraints. - * - * @param model the model - * @param shape the {@link MemberShape} to check - * @param validateHttpBindings whether http bindings should be checked for additional implicit constraints - * @return whether the {@link MemberShape} has validation costraints - */ - public static boolean hasValidation(Model model, MemberShape shape, boolean validateHttpBindings) { - return isRequiredParameter(model, shape, validateHttpBindings); - } - - /** - * Checks whether a {@link MemberShape} is marked as being required explicitly or implicitly. - * - * @param model the model - * @param shape the {@link MemberShape} to check - * @param validateHttpBindings whether http bindings should be checked for additional implicit constraints - * @return whether the {@link MemberShape} is a required parameter - */ - public static boolean isRequiredParameter(Model model, MemberShape shape, boolean validateHttpBindings) { - Optional requiredTrait = shape.getMemberTrait(model, RequiredTrait.class); - return requiredTrait.isPresent() || (validateHttpBindings && shape.getMemberTrait(model, - HttpLabelTrait.class).isPresent()); - } - - private static void walkValidationTree(Walker walker, Shape shape, Consumer visitor) { - walker.walkShapes(shape, relationship -> { - switch (relationship.getRelationshipType()) { - case STRUCTURE_MEMBER: - case UNION_MEMBER: - case MAP_VALUE: - case LIST_MEMBER: - case SET_MEMBER: - case MEMBER_TARGET: - return true; - default: - return false; + + private final Map> serviceToOperationMap = + new HashMap<>(); + private final Map> serviceValidationHelpers = + new HashMap<>(); + + public GoValidationIndex(Model model) { + TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); + Walker walker = new Walker(model); + + model + .shapes(ServiceShape.class) + .forEach(serviceShape -> { + // Go uses unique input shapes per operation so we can index using the input shape as our key + Map inputShapeToOperation = new HashMap<>(); + Set requireValidationHelpers = new TreeSet<>(); + + // First pass is to collect member containers that contain members requiring validation + Set operations = topDownIndex.getContainedOperations( + serviceShape + ); + operations.forEach(operationShape -> { + Shape inputShape = model.expectShape(operationShape.getInput().get()); + GoValidationIndex.walkValidationTree( + walker, + inputShape, + shape -> { + if (shape.isMemberShape()) { + Shape container = model.expectShape( + ((MemberShape) shape).getContainer() + ); + if ( + isRequiredParameter( + model, + (MemberShape) shape, + inputShape.equals(container) + ) + ) { + inputShapeToOperation.put(inputShape, operationShape); + requireValidationHelpers.add(container.toShapeId()); + } + } } - }).forEach(visitor::accept); - } + ); + }); + + // 2nd step is final all containers that reference the initial containers which require validation until + // we've discovered all intermediate containing types + inputShapeToOperation + .keySet() + .forEach(input -> { + Set helpers = new TreeSet<>(); + do { + GoValidationIndex.walkValidationTree( + walker, + input, + shape -> { + if (shape.isMemberShape()) { + MemberShape memberShape = shape.asMemberShape().get(); + Shape container = model.expectShape( + memberShape.getContainer() + ); + Shape target = model.expectShape(memberShape.getTarget()); + if ( + requireValidationHelpers.contains(target.toShapeId()) && + !requireValidationHelpers.contains(container.toShapeId()) + ) { + helpers.add(container.toShapeId()); + } + } + } + ); + if (helpers.isEmpty()) { + break; + } + requireValidationHelpers.addAll(helpers); + helpers.clear(); + } while (true); + }); + + serviceToOperationMap.put( + serviceShape.toShapeId(), + new TreeSet<>( + inputShapeToOperation + .values() + .stream() + .map(OperationShape::toShapeId) + .collect(Collectors.toSet()) + ) + ); + serviceValidationHelpers.put( + serviceShape.toShapeId(), + requireValidationHelpers + ); + }); + } + + public static GoValidationIndex of(Model model) { + return model.getKnowledge(GoValidationIndex.class, GoValidationIndex::new); + } + + /** + * Get the set of operations that require validation. + * + * @param service service to find operations for + * @return operations requiring validation + */ + public Set getOperationsRequiringValidation(ToShapeId service) { + return serviceToOperationMap.getOrDefault( + service.toShapeId(), + SetUtils.of() + ); + } + + /** + * Get a set of shapes that require validation helpers. + * + * @param service service to find operations for + * @return operations requiring validation + */ + public Set getShapesRequiringValidationHelpers(ToShapeId service) { + return serviceValidationHelpers.getOrDefault( + service.toShapeId(), + SetUtils.of() + ); + } + + /** + * Returns whether the given shape requires a validation helper. + * + * @param shape the shape to check + * @return whether the shape requires a validation helper + */ + public boolean isValidationHelperRequired(ToShapeId shape) { + return serviceValidationHelpers.containsKey(shape.toShapeId()); + } + + /** + * Checks whether a {@link MemberShape} has any validation constraints. + * + * @param model the model + * @param shape the {@link MemberShape} to check + * @param validateHttpBindings whether http bindings should be checked for additional implicit constraints + * @return whether the {@link MemberShape} has validation costraints + */ + public static boolean hasValidation( + Model model, + MemberShape shape, + boolean validateHttpBindings + ) { + return isRequiredParameter(model, shape, validateHttpBindings); + } + + /** + * Checks whether a {@link MemberShape} is marked as being required explicitly or implicitly. + * + * @param model the model + * @param shape the {@link MemberShape} to check + * @param validateHttpBindings whether http bindings should be checked for additional implicit constraints + * @return whether the {@link MemberShape} is a required parameter + */ + public static boolean isRequiredParameter( + Model model, + MemberShape shape, + boolean validateHttpBindings + ) { + Optional requiredTrait = shape.getMemberTrait( + model, + RequiredTrait.class + ); + return ( + requiredTrait.isPresent() || + (validateHttpBindings && + shape.getMemberTrait(model, HttpLabelTrait.class).isPresent()) + ); + } + + private static void walkValidationTree( + Walker walker, + Shape shape, + Consumer visitor + ) { + walker + .walkShapes( + shape, + relationship -> { + switch (relationship.getRelationshipType()) { + case STRUCTURE_MEMBER: + case UNION_MEMBER: + case MAP_VALUE: + case LIST_MEMBER: + case SET_MEMBER: + case MEMBER_TARGET: + return true; + default: + return false; + } + } + ) + .forEach(visitor::accept); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyGoPointableIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyGoPointableIndex.java index 7d23954f7d..e9d301b029 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyGoPointableIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyGoPointableIndex.java @@ -7,7 +7,10 @@ public class DafnyGoPointableIndex { - public static boolean isNillable(final Model model, final Shape shape) { - return !shape.hasTrait(RequiredTrait.class) && !GoCodegenUtils.isOperationStruct(model, shape); - } + public static boolean isNillable(final Model model, final Shape shape) { + return ( + !shape.hasTrait(RequiredTrait.class) && + !GoCodegenUtils.isOperationStruct(model, shape) + ); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceCodegenPlugin.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceCodegenPlugin.java index eea7ae096f..40c1b2e659 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceCodegenPlugin.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceCodegenPlugin.java @@ -1,5 +1,6 @@ package software.amazon.polymorph.smithygo.localservice; +import java.util.Map; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoSettings; import software.amazon.polymorph.smithygo.codegen.GoWriter; @@ -9,51 +10,58 @@ import software.amazon.smithy.build.SmithyBuildPlugin; import software.amazon.smithy.codegen.core.directed.CodegenDirector; -import java.util.Map; - public class DafnyLocalServiceCodegenPlugin implements SmithyBuildPlugin { - public DafnyLocalServiceCodegenPlugin(final Map smithyNamespaceToPythonModuleNameMap) { - super(); - SmithyNameResolver.setSmithyNamespaceToGoModuleNameMap(smithyNamespaceToPythonModuleNameMap); - } - public void run(PluginContext context) { - CodegenDirector runner - = new CodegenDirector<>(); + public DafnyLocalServiceCodegenPlugin( + final Map smithyNamespaceToPythonModuleNameMap + ) { + super(); + SmithyNameResolver.setSmithyNamespaceToGoModuleNameMap( + smithyNamespaceToPythonModuleNameMap + ); + } + + public void run(PluginContext context) { + CodegenDirector< + GoWriter, + GoIntegration, + GenerationContext, + GoSettings + > runner = new CodegenDirector<>(); - runner.directedCodegen(new DafnyLocalServiceDirectedCodegen()); + runner.directedCodegen(new DafnyLocalServiceDirectedCodegen()); - // Set the SmithyIntegration class to look for and apply using SPI. - runner.integrationClass(GoIntegration.class); + // Set the SmithyIntegration class to look for and apply using SPI. + runner.integrationClass(GoIntegration.class); - // Set the FileManifest and Model from the plugin. - runner.fileManifest(context.getFileManifest()); - runner.model(context.getModel()); + // Set the FileManifest and Model from the plugin. + runner.fileManifest(context.getFileManifest()); + runner.model(context.getModel()); - // Create the GoSettings object from the plugin settings. - GoSettings settings = GoSettings.from(context.getSettings()); - runner.settings(settings); + // Create the GoSettings object from the plugin settings. + GoSettings settings = GoSettings.from(context.getSettings()); + runner.settings(settings); - runner.service(settings.getService()); + runner.service(settings.getService()); - // Configure the director to perform some common model transforms. - runner.performDefaultCodegenTransforms(); + // Configure the director to perform some common model transforms. + runner.performDefaultCodegenTransforms(); - // TODO: Not using below because it would break existing AWS SDKs. Maybe it should be configurable - // so generic SDKs call this by default, but AWS SDKs can opt-out of it via a setting. - // runner.createDedicatedInputsAndOutputs(); + // TODO: Not using below because it would break existing AWS SDKs. Maybe it should be configurable + // so generic SDKs call this by default, but AWS SDKs can opt-out of it via a setting. + // runner.createDedicatedInputsAndOutputs(); - // Run it! - runner.run(); - } + // Run it! + runner.run(); + } - @Override - public String getName() { - return "go-client-codegen"; - } + @Override + public String getName() { + return "go-client-codegen"; + } - @Override - public void execute(PluginContext context) { - this.run(context); - } + @Override + public void execute(PluginContext context) { + this.run(context); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceDirectedCodegen.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceDirectedCodegen.java index cd22bd32c5..7c3b043bee 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceDirectedCodegen.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceDirectedCodegen.java @@ -1,5 +1,6 @@ package software.amazon.polymorph.smithygo.localservice; +import java.util.logging.Logger; import software.amazon.polymorph.smithygo.codegen.EnumGenerator; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoDelegator; @@ -20,112 +21,191 @@ import software.amazon.smithy.codegen.core.directed.GenerateStructureDirective; import software.amazon.smithy.codegen.core.directed.GenerateUnionDirective; -import java.util.logging.Logger; - -public class DafnyLocalServiceDirectedCodegen implements DirectedCodegen { - private static final Logger LOGGER = Logger.getLogger(DafnyLocalServiceDirectedCodegen.class.getName()); - @Override - public SymbolProvider createSymbolProvider(CreateSymbolProviderDirective directive) { - return new SymbolVisitor(directive.model(), directive.settings()); +public class DafnyLocalServiceDirectedCodegen + implements DirectedCodegen { + + private static final Logger LOGGER = Logger.getLogger( + DafnyLocalServiceDirectedCodegen.class.getName() + ); + + @Override + public SymbolProvider createSymbolProvider( + CreateSymbolProviderDirective directive + ) { + return new SymbolVisitor(directive.model(), directive.settings()); + } + + @Override + public GenerationContext createContext( + CreateContextDirective directive + ) { + return GenerationContext + .builder() + .model(directive.model()) + .settings(directive.settings()) + .symbolProvider(directive.symbolProvider()) + .fileManifest(directive.fileManifest()) + .integrations(directive.integrations()) + .writerDelegator( + new GoDelegator(directive.fileManifest(), directive.symbolProvider()) + ) + .protocolGenerator(new DafnyLocalServiceTypeConversionProtocol()) + .build(); + } + + @Override + public void generateService( + GenerateServiceDirective directive + ) { + if ( + !directive + .shape() + .getId() + .getNamespace() + .equals(directive.context().settings().getService().getNamespace()) + ) { + return; } + new DafnyLocalServiceGenerator(directive.context(), directive.service()) + .run(); - @Override - public GenerationContext createContext(CreateContextDirective directive) { - return GenerationContext.builder() - .model(directive.model()) - .settings(directive.settings()) - .symbolProvider(directive.symbolProvider()) - .fileManifest(directive.fileManifest()) - .integrations(directive.integrations()) - .writerDelegator(new GoDelegator(directive.fileManifest(), directive.symbolProvider())) - .protocolGenerator(new DafnyLocalServiceTypeConversionProtocol()) - .build(); + var protocolGenerator = directive.context().protocolGenerator(); + if (protocolGenerator == null) { + return; } - @Override - public void generateService(GenerateServiceDirective directive) { - if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) - { - return; - } - new DafnyLocalServiceGenerator(directive.context(), directive.service()).run(); - - var protocolGenerator = directive.context().protocolGenerator(); - if (protocolGenerator == null) { - return; - } - - protocolGenerator.generateSerializers(directive.context()); - - protocolGenerator.generateDeserializers(directive.context()); - + protocolGenerator.generateSerializers(directive.context()); + + protocolGenerator.generateDeserializers(directive.context()); + } + + @Override + public void generateStructure( + GenerateStructureDirective directive + ) { + if ( + !directive + .shape() + .getId() + .getNamespace() + .equals(directive.context().settings().getService().getNamespace()) + ) { + return; } - - @Override - public void generateStructure(GenerateStructureDirective directive) { - if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) - { - return; + directive + .context() + .writerDelegator() + .useShapeWriter( + directive.shape(), + writer -> { + StructureGenerator generator = new StructureGenerator( + directive.context(), + writer, + directive.shape() + ); + generator.run(); } - directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { - StructureGenerator generator = new StructureGenerator( - directive.context(), - writer, - directive.shape() - ); - generator.run(); - }); + ); + } + + @Override + public void generateError( + GenerateErrorDirective directive + ) { + if ( + !directive + .shape() + .getId() + .getNamespace() + .equals(directive.context().settings().getService().getNamespace()) + ) { + return; } - - @Override - public void generateError(GenerateErrorDirective directive) { - if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) - { - return; + directive + .context() + .writerDelegator() + .useShapeWriter( + directive.shape(), + writer -> { + StructureGenerator generator = new StructureGenerator( + directive.context(), + writer, + directive.shape() + ); + generator.run(); } - directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { - StructureGenerator generator = new StructureGenerator( - directive.context(), - writer, - directive.shape() - ); - generator.run(); - }); + ); + } + + @Override + public void generateUnion( + GenerateUnionDirective directive + ) {} + + @Override + public void generateEnumShape( + GenerateEnumDirective directive + ) { + if ( + !directive + .shape() + .getId() + .getNamespace() + .equals(directive.context().settings().getService().getNamespace()) + ) { + return; } - - @Override - public void generateUnion(GenerateUnionDirective directive) { - - } - - @Override - public void generateEnumShape(GenerateEnumDirective directive) { - if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) - { - return; + directive + .context() + .writerDelegator() + .useShapeWriter( + directive.shape(), + writer -> { + EnumGenerator enumGenerator = new EnumGenerator( + directive.symbolProvider(), + writer, + directive.shape() + ); + enumGenerator.run(); } - directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { - EnumGenerator enumGenerator = new EnumGenerator(directive.symbolProvider(), writer, directive.shape()); - enumGenerator.run(); - }); + ); + } + + @Override + public void generateIntEnumShape( + GenerateIntEnumDirective directive + ) { + if ( + !directive + .shape() + .getId() + .getNamespace() + .equals(directive.context().settings().getService().getNamespace()) + ) { + return; } - - @Override - public void generateIntEnumShape(GenerateIntEnumDirective directive) { - if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) - { - return; + directive + .context() + .writerDelegator() + .useShapeWriter( + directive.shape(), + writer -> { + IntEnumGenerator intEnumGenerator = new IntEnumGenerator( + directive.symbolProvider(), + writer, + directive.shape().asIntEnumShape().get() + ); + intEnumGenerator.run(); } - directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { - IntEnumGenerator intEnumGenerator = new IntEnumGenerator(directive.symbolProvider(), writer, directive.shape().asIntEnumShape().get()); - intEnumGenerator.run(); - }); - } - - @Override - public void generateResource(GenerateResourceDirective directive) { -// System.out.println("##############" + directive.shape()); -// directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { -// }); - } + ); + } + + @Override + public void generateResource( + GenerateResourceDirective directive + ) { + // System.out.println("##############" + directive.shape()); + // directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { + // }); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java index c985d33cd8..f23c4c2c40 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java @@ -3,6 +3,8 @@ package software.amazon.polymorph.smithygo.localservice; +import java.util.Collection; +import java.util.stream.Collectors; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoDelegator; import software.amazon.polymorph.smithygo.codegen.GoWriter; @@ -25,500 +27,924 @@ import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.UnitTypeTrait; -import java.util.Collection; -import java.util.stream.Collectors; - - public class DafnyLocalServiceGenerator implements Runnable { - private final GenerationContext context; - private final ServiceShape service; - private final TopDownIndex topDownIndex; - private final GoDelegator writerDelegator; - private final Model model; - private final SymbolProvider symbolProvider; - - public DafnyLocalServiceGenerator(GenerationContext context, ServiceShape service) { - this.context = context; - this.service = service; - model = context.model(); - topDownIndex = TopDownIndex.of(model); - writerDelegator = context.writerDelegator(); - symbolProvider = context.symbolProvider(); - } - @Override - public void run() { - writerDelegator.useShapeWriter(service, this::generateService); + private final GenerationContext context; + private final ServiceShape service; + private final TopDownIndex topDownIndex; + private final GoDelegator writerDelegator; + private final Model model; + private final SymbolProvider symbolProvider; + + public DafnyLocalServiceGenerator( + GenerationContext context, + ServiceShape service + ) { + this.context = context; + this.service = service; + model = context.model(); + topDownIndex = TopDownIndex.of(model); + writerDelegator = context.writerDelegator(); + symbolProvider = context.symbolProvider(); + } + + @Override + public void run() { + writerDelegator.useShapeWriter(service, this::generateService); + } + + private void generateService(GoWriter writer) { + if (service.hasTrait(LocalServiceTrait.class)) { + generateClient(writer); + generateUnmodelledErrors(context); + generateReferencedResources(context); + generateUnboundedStructures(context); } + generateShim(); + } + + void generateClient(GoWriter writer) { + // Generate each operation for the service. We do this here instead of via the operation visitor method to + // limit it to the operations bound to the service. + final var serviceSymbol = symbolProvider.toSymbol(service); + final var serviceTrait = service.expectTrait(LocalServiceTrait.class); + final var configSymbol = symbolProvider.toSymbol( + model.expectShape(serviceTrait.getConfigId()) + ); + + writerDelegator.useFileWriter( + "%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), + SmithyNameResolver.smithyTypesNamespace(service), + writer1 -> { + new StructureGenerator( + context, + writer1, + model.expectShape(serviceTrait.getConfigId()).asStructureShape().get() + ) + .run(); + model + .getUnionShapes() + .stream() + .filter(unionShape -> + unionShape + .getId() + .getNamespace() + .equals(service.getId().getNamespace()) + ) + .forEach(unionShape -> { + new UnionGenerator(model, symbolProvider, unionShape) + .generateUnion(writer1); + }); + } + ); + + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(service) + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + DafnyNameResolver.dafnyNamespace(service) + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(service) + ); + writer.addUseImports(SmithyGoDependency.CONTEXT); + + final var dafnyClient = DafnyNameResolver.getDafnyClient( + service, + serviceTrait.getSdkId() + ); + writer.write( + """ + type $T struct { + DafnyClient *$L + } + + func NewClient(clientConfig $L) (*$T, error) { + var dafnyConfig = $L(clientConfig) + var dafny_response = $L(dafnyConfig) + if (dafny_response.Is_Failure()) { + panic("Client construction failed. This should never happen") + } + var dafnyClient = dafny_response.Extract().(*$L) + client := &$T { dafnyClient } + return client, nil + } + """, + serviceSymbol, + dafnyClient, + SmithyNameResolver.getSmithyType(service, configSymbol), + serviceSymbol, + SmithyNameResolver.getToDafnyMethodName( + service, + context.model().expectShape(serviceTrait.getConfigId()), + "" + ), + DafnyNameResolver.createDafnyClient(service, serviceTrait.getSdkId()), + dafnyClient, + serviceSymbol + ); + + service + .getOperations() + .forEach(operation -> { + final var operationShape = model.expectShape( + operation, + OperationShape.class + ); + final var inputShape = model.expectShape( + operationShape.getInputShape() + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + inputShape.toShapeId().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(inputShape) + ); + if ( + !inputShape + .toShapeId() + .getNamespace() + .equals(service.toShapeId().getNamespace()) + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + inputShape.toShapeId().getNamespace() + ), + SmithyNameResolver.shapeNamespace(inputShape) + ); + } + final var outputShape = model.expectShape( + operationShape.getOutputShape() + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + outputShape.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(outputShape) + ); + if ( + !outputShape + .toShapeId() + .getNamespace() + .equals(service.toShapeId().getNamespace()) + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + outputShape.toShapeId().getNamespace() + ), + SmithyNameResolver.shapeNamespace(outputShape) + ); + } + final var inputType = inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : ", params %s.%s".formatted( + SmithyNameResolver.smithyTypesNamespace(inputShape), + inputShape.toShapeId().getName() + ); + final var outputType = outputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "*%s.%s,".formatted( + SmithyNameResolver.smithyTypesNamespace(outputShape), + outputShape.toShapeId().getName() + ); + String validationCheck = ""; + if (!inputType.equals("")) { + validationCheck = + """ + err := params.Validate() + if err != nil { + opaqueErr := %s.OpaqueError{ + ErrObject: err, + } + """.formatted(SmithyNameResolver.smithyTypesNamespace(inputShape)); + if (outputType.equals("")) { + validationCheck += "return opaqueErr }"; + } else { + validationCheck += "return nil, opaqueErr }"; + } + } + String baseClientCall; + if (inputShape.hasTrait(UnitTypeTrait.class)) { + baseClientCall = + "var dafny_response = client.DafnyClient.%s()".formatted( + operationShape.getId().getName() + ); + } else { + baseClientCall = + """ + var dafny_request %s = %s(params) + var dafny_response = client.DafnyClient.%s(dafny_request) + """.formatted( + DafnyNameResolver.getDafnyType( + inputShape, + symbolProvider.toSymbol(inputShape) + ), + SmithyNameResolver.getToDafnyMethodName( + service, + inputShape, + "" + ), + operationShape.getId().getName() + ); + } - private void generateService(GoWriter writer) { - if (service.hasTrait(LocalServiceTrait.class)) { - generateClient(writer); - generateUnmodelledErrors(context); - generateReferencedResources(context); - generateUnboundedStructures(context); + String returnResponse, returnError; + if (outputShape.hasTrait(UnitTypeTrait.class)) { + returnResponse = "return nil"; + returnError = "return"; + } else { + returnResponse = + """ + var native_response = %s(dafny_response.Extract().(%s)) + return &native_response, nil + """.formatted( + SmithyNameResolver.getFromDafnyMethodName( + service, + outputShape, + "" + ), + DafnyNameResolver.getDafnyType( + outputShape, + symbolProvider.toSymbol(outputShape) + ) + ); + returnError = "return nil,"; } - generateShim(); - } - void generateClient(GoWriter writer) { - // Generate each operation for the service. We do this here instead of via the operation visitor method to - // limit it to the operations bound to the service. - final var serviceSymbol = symbolProvider.toSymbol(service); - final var serviceTrait = service.expectTrait(LocalServiceTrait.class); - final var configSymbol = symbolProvider.toSymbol(model.expectShape(serviceTrait.getConfigId())); - - writerDelegator.useFileWriter("%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), SmithyNameResolver.smithyTypesNamespace(service), writer1 -> { - new StructureGenerator(context, writer1, - model.expectShape(serviceTrait.getConfigId()).asStructureShape().get()).run(); - model.getUnionShapes().stream() - .filter(unionShape -> unionShape.getId().getNamespace().equals(service.getId().getNamespace())) - .forEach(unionShape -> { - new UnionGenerator(model, symbolProvider, unionShape).generateUnion(writer1); - }); - }); - - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(service)); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), DafnyNameResolver.dafnyNamespace(service)); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.smithyTypesNamespace(service)); + writer.write( + """ + func (client *$T) $L(ctx context.Context $L) ($L error) { + $L + $L + if (dafny_response.Is_Failure()) { + err := dafny_response.Dtor_error().($L.Error); + $L Error_FromDafny(err) + } + $L + } + """, + serviceSymbol, + operationShape.getId().getName(), + inputType, + outputType, + validationCheck, + baseClientCall, + DafnyNameResolver.dafnyTypesNamespace(service), + returnError, + returnResponse + ); + }); + } + + void generateShim() { + final var namespace = + "%swrapped".formatted(DafnyNameResolver.dafnyNamespace(service)); + + writerDelegator.useFileWriter( + "%s/shim.go".formatted(namespace), + namespace, + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(service) + ); + writer.addImportFromModule( + "github.com/dafny-lang/DafnyStandardLibGo", + "Wrappers" + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(service) + ); writer.addUseImports(SmithyGoDependency.CONTEXT); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + SmithyNameResolver.shapeNamespace(service) + ); - final var dafnyClient = DafnyNameResolver.getDafnyClient(service, serviceTrait.getSdkId()); - writer.write(""" - type $T struct { - DafnyClient *$L - } - - func NewClient(clientConfig $L) (*$T, error) { - var dafnyConfig = $L(clientConfig) - var dafny_response = $L(dafnyConfig) - if (dafny_response.Is_Failure()) { - panic("Client construction failed. This should never happen") - } - var dafnyClient = dafny_response.Extract().(*$L) - client := &$T { dafnyClient } - return client, nil - } - """, - serviceSymbol, dafnyClient, SmithyNameResolver.getSmithyType(service, configSymbol), serviceSymbol, - SmithyNameResolver.getToDafnyMethodName(service, context.model().expectShape(serviceTrait.getConfigId()), ""), - DafnyNameResolver.createDafnyClient(service, serviceTrait.getSdkId()), - dafnyClient, serviceSymbol); - - service.getOperations().forEach(operation -> { - final var operationShape = model.expectShape(operation, OperationShape.class); - final var inputShape = model.expectShape(operationShape.getInputShape()); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(inputShape.toShapeId().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(inputShape)); - if (!inputShape.toShapeId().getNamespace().equals(service.toShapeId().getNamespace())) { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(inputShape.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(inputShape)); - } - final var outputShape = model.expectShape(operationShape.getOutputShape()); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(outputShape.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(outputShape)); - if (!outputShape.toShapeId().getNamespace().equals(service.toShapeId().getNamespace())) { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(outputShape.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(outputShape)); + if (service.hasTrait(LocalServiceTrait.class)) { + final var serviceTrait = service.expectTrait(LocalServiceTrait.class); + final var configShape = model.expectShape(serviceTrait.getConfigId()); + final var configSymbol = symbolProvider.toSymbol(configShape); + + writer.write( + """ + type Shim struct { + $L + client *$L.Client } - final var inputType = inputShape.hasTrait(UnitTypeTrait.class) ? "" - : ", params %s.%s".formatted(SmithyNameResolver.smithyTypesNamespace(inputShape), inputShape.toShapeId().getName()); - final var outputType = outputShape.hasTrait(UnitTypeTrait.class) ? "" - : "*%s.%s,".formatted(SmithyNameResolver.smithyTypesNamespace(outputShape), outputShape.toShapeId().getName()); - String validationCheck = ""; - if(!inputType.equals("")) { - validationCheck = """ - err := params.Validate() - if err != nil { - opaqueErr := %s.OpaqueError{ - ErrObject: err, - } - """.formatted(SmithyNameResolver.smithyTypesNamespace(inputShape)); - if(outputType.equals("")) { - validationCheck += "return opaqueErr }"; + """, + DafnyNameResolver.getDafnyInterfaceClient(service), + SmithyNameResolver.shapeNamespace(service) + ); + + writer.write( + """ + func Wrapped$L(inputConfig $L) Wrappers.Result { + var nativeConfig = $L.$L(inputConfig) + var nativeClient, nativeError = $L.NewClient(nativeConfig) + if nativeError != nil { + return Wrappers.Companion_Result_.Create_Failure_($L.Companion_Error_.Create_Opaque_(nativeError)) } - else{ - validationCheck += "return nil, opaqueErr }"; - } - } - String baseClientCall; - if (inputShape.hasTrait(UnitTypeTrait.class)) { - baseClientCall = "var dafny_response = client.DafnyClient.%s()".formatted(operationShape.getId().getName()); - } else { - baseClientCall = """ - var dafny_request %s = %s(params) - var dafny_response = client.DafnyClient.%s(dafny_request) - """.formatted(DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(inputShape)), - SmithyNameResolver.getToDafnyMethodName(service, inputShape, ""), operationShape.getId().getName()); - } - - String returnResponse, returnError; - if (outputShape.hasTrait(UnitTypeTrait.class)) { - returnResponse = "return nil"; - returnError = "return"; - } else { - returnResponse = """ - var native_response = %s(dafny_response.Extract().(%s)) - return &native_response, nil - """.formatted(SmithyNameResolver.getFromDafnyMethodName(service, outputShape, ""), - DafnyNameResolver.getDafnyType(outputShape, symbolProvider.toSymbol(outputShape))); - returnError = "return nil,"; + return Wrappers.Companion_Result_.Create_Success_(&Shim{client: nativeClient}) } + """, + serviceTrait.getSdkId(), + DafnyNameResolver.getDafnyType(configShape, configSymbol), + SmithyNameResolver.shapeNamespace( + model.expectShape(serviceTrait.getConfigId()) + ), + SmithyNameResolver.getFromDafnyMethodName( + service, + model.expectShape(serviceTrait.getConfigId()), + "" + ), + SmithyNameResolver.shapeNamespace(service), + DafnyNameResolver.dafnyTypesNamespace(service) + ); + } - writer.write(""" - func (client *$T) $L(ctx context.Context $L) ($L error) { - $L - $L - if (dafny_response.Is_Failure()) { - err := dafny_response.Dtor_error().($L.Error); - $L Error_FromDafny(err) - } - $L - } - """, - serviceSymbol, - operationShape.getId().getName(), - inputType, outputType, - validationCheck, - baseClientCall, DafnyNameResolver.dafnyTypesNamespace(service), returnError, returnResponse + service + .getOperations() + .forEach(operation -> { + final var operationShape = model.expectShape( + operation, + OperationShape.class ); - }); - } - - void generateShim() { - final var namespace = "%swrapped".formatted(DafnyNameResolver.dafnyNamespace(service)); - - writerDelegator.useFileWriter("%s/shim.go".formatted(namespace), namespace, writer -> { - - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(service)); - writer.addImportFromModule("github.com/dafny-lang/DafnyStandardLibGo", "Wrappers"); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.smithyTypesNamespace(service)); - writer.addUseImports(SmithyGoDependency.CONTEXT); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.shapeNamespace(service)); - - if (service.hasTrait(LocalServiceTrait.class)) { - final var serviceTrait = service.expectTrait(LocalServiceTrait.class); - final var configShape = model.expectShape(serviceTrait.getConfigId()); - final var configSymbol = symbolProvider.toSymbol(configShape); - - writer.write(""" - type Shim struct { - $L - client *$L.Client - } - """, - DafnyNameResolver.getDafnyInterfaceClient(service), - SmithyNameResolver.shapeNamespace(service) + final var inputShape = model.expectShape( + operationShape.getInputShape() + ); + final var outputShape = model.expectShape( + operationShape.getOutputShape() + ); + final var inputType = inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "input %s".formatted( + DafnyNameResolver.getDafnyType( + inputShape, + symbolProvider.toSymbol(inputShape) + ) ); - writer.write(""" - func Wrapped$L(inputConfig $L) Wrappers.Result { - var nativeConfig = $L.$L(inputConfig) - var nativeClient, nativeError = $L.NewClient(nativeConfig) - if nativeError != nil { - return Wrappers.Companion_Result_.Create_Failure_($L.Companion_Error_.Create_Opaque_(nativeError)) - } - return Wrappers.Companion_Result_.Create_Success_(&Shim{client: nativeClient}) - } - """, - serviceTrait.getSdkId(), DafnyNameResolver.getDafnyType(configShape, configSymbol), - SmithyNameResolver.shapeNamespace(model.expectShape(serviceTrait.getConfigId())), SmithyNameResolver.getFromDafnyMethodName(service, model.expectShape(serviceTrait.getConfigId()), ""), - SmithyNameResolver.shapeNamespace(service), DafnyNameResolver.dafnyTypesNamespace(service) + final var typeConversion = inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "var native_request = %s(input)".formatted( + SmithyNameResolver.getFromDafnyMethodName(inputShape, "") ); - } + final var clientCall = + "shim.client.%s(context.Background() %s)".formatted( + operationShape.getId().getName(), + inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : ", native_request" + ); - service.getOperations().forEach(operation -> { - final var operationShape = model.expectShape(operation, OperationShape.class); - final var inputShape = model.expectShape(operationShape.getInputShape()); - final var outputShape = model.expectShape(operationShape.getOutputShape()); - final var inputType = inputShape.hasTrait(UnitTypeTrait.class) ? "" - : "input %s".formatted(DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(inputShape))); - - final var typeConversion = inputShape.hasTrait(UnitTypeTrait.class) ? "" - : "var native_request = %s(input)".formatted(SmithyNameResolver.getFromDafnyMethodName(inputShape, "")); - - final var clientCall = "shim.client.%s(context.Background() %s)".formatted(operationShape.getId().getName(), - inputShape.hasTrait(UnitTypeTrait.class) ? "" : ", native_request"); + String clientResponse, returnResponse; + if (outputShape.hasTrait(UnitTypeTrait.class)) { + clientResponse = "var native_error"; + returnResponse = "dafny.TupleOf()"; + writer.addImportFromModule( + "github.com/dafny-lang/DafnyRuntimeGo", + "dafny" + ); + } else { + clientResponse = "var native_response, native_error"; + returnResponse = + "%s(*native_response)".formatted( + SmithyNameResolver.getToDafnyMethodName(outputShape, "") + ); + } - String clientResponse, returnResponse; - if (outputShape.hasTrait(UnitTypeTrait.class)) { - clientResponse = "var native_error"; - returnResponse = "dafny.TupleOf()"; - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - } else { - clientResponse = "var native_response, native_error"; - returnResponse = "%s(*native_response)".formatted(SmithyNameResolver.getToDafnyMethodName(outputShape, "")); + writer.write( + """ + func (shim *Shim) $L($L) Wrappers.Result { + $L + $L = $L + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_($L.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_($L) } - - writer.write(""" - func (shim *Shim) $L($L) Wrappers.Result { - $L - $L = $L - if native_error != nil { - return Wrappers.Companion_Result_.Create_Failure_($L.Error_ToDafny(native_error)) - } - return Wrappers.Companion_Result_.Create_Success_($L) - } - """, - operationShape.getId().getName(), - inputType, typeConversion, clientResponse, clientCall, - SmithyNameResolver.shapeNamespace(service), - returnResponse - ); - }); - }); + """, + operationShape.getId().getName(), + inputType, + typeConversion, + clientResponse, + clientCall, + SmithyNameResolver.shapeNamespace(service), + returnResponse + ); + }); + } + ); + } + + void shimErrors(GoWriter writer) { + for (final var error : model.getShapesWithTrait(ErrorTrait.class)) { + writer.write( + """ + case $L.$L: + return Wrappers.Companion_Result_.Create_Failure_($L(native_error.($L.$L))) + + + """, + SmithyNameResolver.smithyTypesNamespace(error), + symbolProvider.toSymbol(error).getName(), + SmithyNameResolver.getToDafnyMethodName(service, error, ""), + SmithyNameResolver.smithyTypesNamespace(error), + symbolProvider.toSymbol(error).getName() + ); } + } - void shimErrors(GoWriter writer) { - for (final var error : model.getShapesWithTrait(ErrorTrait.class)) { - writer.write(""" - case $L.$L: - return Wrappers.Companion_Result_.Create_Failure_($L(native_error.($L.$L))) - - - """, - SmithyNameResolver.smithyTypesNamespace(error), - symbolProvider.toSymbol(error).getName(), - SmithyNameResolver.getToDafnyMethodName(service, error, ""), SmithyNameResolver.smithyTypesNamespace(error), - symbolProvider.toSymbol(error).getName()); - } - } + void resourceErrors(GoWriter writer) { + for (final var error : model.getShapesWithTrait(ErrorTrait.class)) { + writer.write( + """ + case $L: + return Wrappers.Companion_Result_.Create_Failure_($L(native_error.($L))) - void resourceErrors(GoWriter writer) { - for (final var error : model.getShapesWithTrait(ErrorTrait.class)) { - writer.write(""" - case $L: - return Wrappers.Companion_Result_.Create_Failure_($L(native_error.($L))) - - - """, - SmithyNameResolver.getSmithyType(error, symbolProvider.toSymbol(error)), SmithyNameResolver.getToDafnyMethodName(service, error, ""), - SmithyNameResolver.getSmithyType(error, symbolProvider.toSymbol(error))); - } - } - void generateUnmodelledErrors(GenerationContext context) { - writerDelegator.useFileWriter("%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), SmithyNameResolver.smithyTypesNamespace(service), writer -> { - writer.write(""" - type $LBaseException interface { - // This is a dummy method to allow type assertion since Go empty interfaces - // aren't useful for type assertion checks. No concrete class is expected to implement - // this method. This is also not exported. - interfaceBindingMethod() - } - """, service.toShapeId().getName()); - }); - writerDelegator.useFileWriter("%s/unmodelled_errors.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), SmithyNameResolver.smithyTypesNamespace(service), writer -> { - writer.addUseImports(SmithyGoDependency.FMT); - writer.write(""" - type CollectionOfErrors struct { - $LBaseException - ListOfErrors []error - Message string - } - - func (e CollectionOfErrors) Error() string { - return fmt.Sprintf("message: %s\\n err %v", e.Message, e.ListOfErrors) - } - - type OpaqueError struct { - $LBaseException - ErrObject interface{} - } - - func (e OpaqueError) Error() string { - return fmt.Sprintf("message: %v", e.ErrObject ) - } - """, service.toShapeId().getName(), service.toShapeId().getName()); - }); + """, + SmithyNameResolver.getSmithyType(error, symbolProvider.toSymbol(error)), + SmithyNameResolver.getToDafnyMethodName(service, error, ""), + SmithyNameResolver.getSmithyType(error, symbolProvider.toSymbol(error)) + ); } - - void generateUnboundedStructures(GenerationContext context) { - final var serviceOperationShapes = model.getServiceShapes().stream() - .map(topDownIndex::getContainedOperations) - .flatMap(Collection::stream) - .map(OperationShape::toShapeId) - .collect(Collectors.toSet()); - final var nonServiceOperationShapes = model.getOperationShapes() - .stream() - .map(Shape::getId) - .filter(operationShapeId -> operationShapeId.getNamespace() - .equals(service.getId().getNamespace())) - .collect(Collectors.toSet()); - nonServiceOperationShapes.removeAll(serviceOperationShapes); - for (final var operationShapeId : nonServiceOperationShapes) { - OperationShape operationShape = model.expectShape(operationShapeId, OperationShape.class); - StructureShape inputShape = model.expectShape(operationShape.getInputShape(), StructureShape.class); - writerDelegator.useShapeWriter(inputShape, w -> new StructureGenerator(context, w, inputShape).run()); - StructureShape outputShape = model.expectShape(operationShape.getOutputShape(), StructureShape.class); - writerDelegator.useShapeWriter(outputShape, w -> new StructureGenerator(context, w, outputShape).run()); - } + } + + void generateUnmodelledErrors(GenerationContext context) { + writerDelegator.useFileWriter( + "%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), + SmithyNameResolver.smithyTypesNamespace(service), + writer -> { + writer.write( + """ + type $LBaseException interface { + // This is a dummy method to allow type assertion since Go empty interfaces + // aren't useful for type assertion checks. No concrete class is expected to implement + // this method. This is also not exported. + interfaceBindingMethod() + } + """, + service.toShapeId().getName() + ); + } + ); + writerDelegator.useFileWriter( + "%s/unmodelled_errors.go".formatted( + SmithyNameResolver.smithyTypesNamespace(service) + ), + SmithyNameResolver.smithyTypesNamespace(service), + writer -> { + writer.addUseImports(SmithyGoDependency.FMT); + writer.write( + """ + type CollectionOfErrors struct { + $LBaseException + ListOfErrors []error + Message string + } + + func (e CollectionOfErrors) Error() string { + return fmt.Sprintf("message: %s\\n err %v", e.Message, e.ListOfErrors) + } + + type OpaqueError struct { + $LBaseException + ErrObject interface{} + } + + func (e OpaqueError) Error() string { + return fmt.Sprintf("message: %v", e.ErrObject ) + } + """, + service.toShapeId().getName(), + service.toShapeId().getName() + ); + } + ); + } + + void generateUnboundedStructures(GenerationContext context) { + final var serviceOperationShapes = model + .getServiceShapes() + .stream() + .map(topDownIndex::getContainedOperations) + .flatMap(Collection::stream) + .map(OperationShape::toShapeId) + .collect(Collectors.toSet()); + final var nonServiceOperationShapes = model + .getOperationShapes() + .stream() + .map(Shape::getId) + .filter(operationShapeId -> + operationShapeId.getNamespace().equals(service.getId().getNamespace()) + ) + .collect(Collectors.toSet()); + nonServiceOperationShapes.removeAll(serviceOperationShapes); + for (final var operationShapeId : nonServiceOperationShapes) { + OperationShape operationShape = model.expectShape( + operationShapeId, + OperationShape.class + ); + StructureShape inputShape = model.expectShape( + operationShape.getInputShape(), + StructureShape.class + ); + writerDelegator.useShapeWriter( + inputShape, + w -> new StructureGenerator(context, w, inputShape).run() + ); + StructureShape outputShape = model.expectShape( + operationShape.getOutputShape(), + StructureShape.class + ); + writerDelegator.useShapeWriter( + outputShape, + w -> new StructureGenerator(context, w, outputShape).run() + ); } + } + + void generateReferencedResources(GenerationContext context) { + var refResources = model.getShapesWithTrait(ReferenceTrait.class); + for (final var refResource : refResources) { + if (!refResource.expectTrait(ReferenceTrait.class).isService()) { + final var resource = refResource + .expectTrait(ReferenceTrait.class) + .getReferentId(); + final var resourceShape = model.expectShape(resource); + + if ( + !service.toShapeId().getNamespace().equals(resource.getNamespace()) + ) { + continue; + } + writerDelegator.useFileWriter( + "%s/types.go".formatted( + SmithyNameResolver.smithyTypesNamespace(service) + ), + SmithyNameResolver.smithyTypesNamespace(service), + writer -> { + writer.write( + """ + type I$L interface { + ${C|} + } + """, + resource.getName(), + writer.consumer(w -> { + model + .expectShape(resource, ResourceShape.class) + .getOperations() + .forEach(operation -> { + var operationShape = model.expectShape( + operation, + OperationShape.class + ); + w.write( + """ + $L($L) (*$L, error) + """, + operationShape.getId().getName(), + operationShape.getInputShape().getName(), + operationShape.getOutputShape().getName() + ); + }); + }) + ); + } + ); + + if ( + model + .expectShape(resource, ResourceShape.class) + .hasTrait(ExtendableTrait.class) + ) { + generateNativeResourceWrapper( + context, + model.expectShape(resource, ResourceShape.class) + ); + } - void generateReferencedResources(GenerationContext context) { - var refResources = model.getShapesWithTrait(ReferenceTrait.class); - for (final var refResource : refResources) { - if (!refResource.expectTrait(ReferenceTrait.class).isService()) { - final var resource = refResource.expectTrait(ReferenceTrait.class).getReferentId(); - final var resourceShape = model.expectShape(resource); + writerDelegator.useFileWriter( + "%s/%s.go".formatted( + SmithyNameResolver.shapeNamespace(service), + resource.getName() + ), + SmithyNameResolver.shapeNamespace(service), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(service) + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + resource.getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(resourceShape) + ); + writer.write( + """ + type %s struct { + Impl %s.I%s + } + """.formatted( + resource.getName(), + DafnyNameResolver.dafnyTypesNamespace(resourceShape), + resource.getName() + ) + ); - if (!service.toShapeId().getNamespace().equals(resource.getNamespace())) { + model + .expectShape(resource, ResourceShape.class) + .getOperations() + .forEach(operation -> { + final var operationShape = model.expectShape( + operation, + OperationShape.class + ); + final var inputShape = model.expectShape( + operationShape.getInputShape() + ); - continue; - } - writerDelegator.useFileWriter("%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), SmithyNameResolver.smithyTypesNamespace(service), writer -> { - writer.write(""" - type I$L interface { - ${C|} - } - """, resource.getName(), writer.consumer((w) -> { - model.expectShape(resource, ResourceShape.class).getOperations().forEach(operation -> { - var operationShape = model.expectShape(operation, OperationShape.class); - w.write(""" - $L($L) (*$L, error) - """, operationShape.getId().getName(), operationShape.getInputShape().getName(), operationShape.getOutputShape().getName()); - }); - })); - }); - - if (model.expectShape(resource, ResourceShape.class).hasTrait(ExtendableTrait.class)) { - generateNativeResourceWrapper(context, model.expectShape(resource, ResourceShape.class)); + final var outputShape = model.expectShape( + operationShape.getOutputShape() + ); + final var inputType = inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "params %s".formatted( + SmithyNameResolver.getSmithyType( + inputShape, + symbolProvider.toSymbol(inputShape) + ) + ); + final var outputType = outputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "*%s".formatted( + SmithyNameResolver.getSmithyType( + outputShape, + symbolProvider.toSymbol(outputShape) + ) + ); + + String baseClientCall; + if (inputShape.hasTrait(UnitTypeTrait.class)) { + baseClientCall = + "var dafny_response = this.Impl.%s()".formatted( + operationShape.getId().getName() + ); + } else { + baseClientCall = + """ + var dafny_request %s = %s(params) + var dafny_response = this.Impl.%s(dafny_request) + """.formatted( + DafnyNameResolver.getDafnyType( + inputShape, + symbolProvider.toSymbol(inputShape) + ), + SmithyNameResolver.getToDafnyMethodName( + service, + inputShape, + "" + ), + operationShape.getId().getName() + ); } - writerDelegator.useFileWriter("%s/%s.go".formatted(SmithyNameResolver.shapeNamespace(service), resource.getName()), SmithyNameResolver.shapeNamespace(service), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.smithyTypesNamespace(service)); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resource.getNamespace()), DafnyNameResolver.dafnyTypesNamespace(resourceShape)); - writer.write(""" - type %s struct { - Impl %s.I%s - } - """.formatted(resource.getName(), DafnyNameResolver.dafnyTypesNamespace(resourceShape), resource.getName())); - - model.expectShape(resource, ResourceShape.class).getOperations().forEach(operation -> { - final var operationShape = model.expectShape(operation, OperationShape.class); - final var inputShape = model.expectShape(operationShape.getInputShape()); - - - final var outputShape = model.expectShape(operationShape.getOutputShape()); - final var inputType = inputShape.hasTrait(UnitTypeTrait.class) ? "" : "params %s".formatted(SmithyNameResolver.getSmithyType(inputShape, symbolProvider.toSymbol(inputShape))); - final var outputType = outputShape.hasTrait(UnitTypeTrait.class) ? "" : "*%s".formatted(SmithyNameResolver.getSmithyType(outputShape, symbolProvider.toSymbol(outputShape))); - - String baseClientCall; - if (inputShape.hasTrait(UnitTypeTrait.class)) { - baseClientCall = "var dafny_response = this.Impl.%s()".formatted(operationShape.getId().getName()); - } else { - baseClientCall = """ - var dafny_request %s = %s(params) - var dafny_response = this.Impl.%s(dafny_request) - """.formatted(DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(inputShape)), - SmithyNameResolver.getToDafnyMethodName(service, inputShape, ""), operationShape.getId().getName()); - } - - String returnResponse, returnError; - if (outputShape.hasTrait(UnitTypeTrait.class)) { - returnResponse = "return nil"; - returnError = "return"; - } else { - returnResponse = """ - var native_response = %s(dafny_response.Extract().(%s)) - return &native_response, nil - """.formatted(SmithyNameResolver.getFromDafnyMethodName(service, outputShape, ""), - DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(outputShape))); - returnError = "return nil,"; - } - - - writer.write(""" - func (this *$L) $L($L) ($L, error) { - $L - if (dafny_response.Is_Failure()) { - err := dafny_response.Dtor_error().($L.Error); - ${C|} - if err.Is_CollectionOfErrors() { - $L CollectionOfErrors_Output_FromDafny(err) - } - if err.Is_Opaque() { - $L OpaqueError_Output_FromDafny(err) - } - } - $L - } - """, - resource.getName(), - operationShape.getId().getName(), - inputType, outputType, - baseClientCall, - DafnyNameResolver.dafnyTypesNamespace(service), - writer.consumer(w -> { - for (var errorShape : - model.getShapesWithTrait(ErrorTrait.class)) { - w.write(""" - if err.Is_$L() { - $L $L(err) - } - """, errorShape.toShapeId().getName(), returnError, SmithyNameResolver.getFromDafnyMethodName(service, errorShape, "")); - } - }), returnError, returnError, returnResponse - ); - }); - }); - } else { - //Generate Service - } - } - } - - void generateNativeResourceWrapper(GenerationContext context, ResourceShape resourceShape) { - writerDelegator.useFileWriter("%s/NativeWrapper.go".formatted(SmithyNameResolver.shapeNamespace(service)), SmithyNameResolver.shapeNamespace(service), writer -> { - writer.addImportFromModule(context.settings().getModuleName(), SmithyNameResolver.smithyTypesNamespace(service)); - writer.addImportFromModule("github.com/dafny-lang/DafnyStandardLibGo", "Wrappers"); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resourceShape.toShapeId().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(resourceShape)); - - writer.write(""" - type NativeWrapper struct { - %s.I%s - Impl %s.I%s - } - """.formatted(DafnyNameResolver.dafnyTypesNamespace(resourceShape), resourceShape.getId().getName(), SmithyNameResolver.smithyTypesNamespace(resourceShape), resourceShape.getId().getName())); - - resourceShape.getOperations().forEach(operation -> { - final var operationShape = model.expectShape(operation, OperationShape.class); - final var inputShape = model.expectShape(operationShape.getInputShape()); - final var outputShape = model.expectShape(operationShape.getOutputShape()); - final var inputType = inputShape.hasTrait(UnitTypeTrait.class) ? "" : "input %s".formatted(DafnyNameResolver.getDafnyType(resourceShape, symbolProvider.toSymbol(inputShape))); - final var outputType = outputShape.hasTrait(UnitTypeTrait.class) ? "" : "*%s,".formatted(SmithyNameResolver.getSmithyType(outputShape, symbolProvider.toSymbol(outputShape))); - - final var typeConversion = inputShape.hasTrait(UnitTypeTrait.class) ? "" : "var native_request = %s(input)".formatted(SmithyNameResolver.getFromDafnyMethodName(service, inputShape, "")); - final var clientCall = "this.Impl.%s(%s)".formatted(operationShape.getId().getName(), inputShape.hasTrait(UnitTypeTrait.class) ? "" : "native_request"); - String clientResponse, returnResponse; + String returnResponse, returnError; if (outputShape.hasTrait(UnitTypeTrait.class)) { - clientResponse = "var native_error"; - returnResponse = "dafny.TupleOf()"; - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + returnResponse = "return nil"; + returnError = "return"; } else { - clientResponse = "var native_response, native_error"; - returnResponse = "%s(*native_response)".formatted( - SmithyNameResolver.getToDafnyMethodName(service, outputShape, "")); + returnResponse = + """ + var native_response = %s(dafny_response.Extract().(%s)) + return &native_response, nil + """.formatted( + SmithyNameResolver.getFromDafnyMethodName( + service, + outputShape, + "" + ), + DafnyNameResolver.getDafnyType( + inputShape, + symbolProvider.toSymbol(outputShape) + ) + ); + returnError = "return nil,"; } - writer.write(""" - func (this *NativeWrapper) $L($L) Wrappers.Result { - $L - $L = $L - if native_error != nil { - switch native_error.(type) { - ${C|} - case $L.CollectionOfErrors: - return Wrappers.Companion_Result_.Create_Failure_(CollectionOfErrors_Input_ToDafny(native_error.($L.CollectionOfErrors))) - default: - return Wrappers.Companion_Result_.Create_Failure_(OpaqueError_Input_ToDafny(native_error.($L.OpaqueError))) - } + + writer.write( + """ + func (this *$L) $L($L) ($L, error) { + $L + if (dafny_response.Is_Failure()) { + err := dafny_response.Dtor_error().($L.Error); + ${C|} + if err.Is_CollectionOfErrors() { + $L CollectionOfErrors_Output_FromDafny(err) + } + if err.Is_Opaque() { + $L OpaqueError_Output_FromDafny(err) + } + } + $L + } + """, + resource.getName(), + operationShape.getId().getName(), + inputType, + outputType, + baseClientCall, + DafnyNameResolver.dafnyTypesNamespace(service), + writer.consumer(w -> { + for (var errorShape : model.getShapesWithTrait( + ErrorTrait.class + )) { + w.write( + """ + if err.Is_$L() { + $L $L(err) } - return Wrappers.Companion_Result_.Create_Success_($L) - } - """, - operationShape.getId().getName(), - inputType, typeConversion, clientResponse, clientCall, - writer.consumer(w -> resourceErrors(w)), SmithyNameResolver.smithyTypesNamespace(service), SmithyNameResolver.smithyTypesNamespace(service), SmithyNameResolver.smithyTypesNamespace(service), - returnResponse + """, + errorShape.toShapeId().getName(), + returnError, + SmithyNameResolver.getFromDafnyMethodName( + service, + errorShape, + "" + ) + ); + } + }), + returnError, + returnError, + returnResponse ); - }); - }); + }); + } + ); + } else { + //Generate Service + } } + } + + void generateNativeResourceWrapper( + GenerationContext context, + ResourceShape resourceShape + ) { + writerDelegator.useFileWriter( + "%s/NativeWrapper.go".formatted( + SmithyNameResolver.shapeNamespace(service) + ), + SmithyNameResolver.shapeNamespace(service), + writer -> { + writer.addImportFromModule( + context.settings().getModuleName(), + SmithyNameResolver.smithyTypesNamespace(service) + ); + writer.addImportFromModule( + "github.com/dafny-lang/DafnyStandardLibGo", + "Wrappers" + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + resourceShape.toShapeId().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(resourceShape) + ); + + writer.write( + """ + type NativeWrapper struct { + %s.I%s + Impl %s.I%s + } + """.formatted( + DafnyNameResolver.dafnyTypesNamespace(resourceShape), + resourceShape.getId().getName(), + SmithyNameResolver.smithyTypesNamespace(resourceShape), + resourceShape.getId().getName() + ) + ); + + resourceShape + .getOperations() + .forEach(operation -> { + final var operationShape = model.expectShape( + operation, + OperationShape.class + ); + final var inputShape = model.expectShape( + operationShape.getInputShape() + ); + final var outputShape = model.expectShape( + operationShape.getOutputShape() + ); + final var inputType = inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "input %s".formatted( + DafnyNameResolver.getDafnyType( + resourceShape, + symbolProvider.toSymbol(inputShape) + ) + ); + final var outputType = outputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "*%s,".formatted( + SmithyNameResolver.getSmithyType( + outputShape, + symbolProvider.toSymbol(outputShape) + ) + ); + + final var typeConversion = inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "var native_request = %s(input)".formatted( + SmithyNameResolver.getFromDafnyMethodName( + service, + inputShape, + "" + ) + ); + final var clientCall = + "this.Impl.%s(%s)".formatted( + operationShape.getId().getName(), + inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "native_request" + ); + String clientResponse, returnResponse; + if (outputShape.hasTrait(UnitTypeTrait.class)) { + clientResponse = "var native_error"; + returnResponse = "dafny.TupleOf()"; + writer.addImportFromModule( + "github.com/dafny-lang/DafnyRuntimeGo", + "dafny" + ); + } else { + clientResponse = "var native_response, native_error"; + returnResponse = + "%s(*native_response)".formatted( + SmithyNameResolver.getToDafnyMethodName( + service, + outputShape, + "" + ) + ); + } + writer.write( + """ + func (this *NativeWrapper) $L($L) Wrappers.Result { + $L + $L = $L + if native_error != nil { + switch native_error.(type) { + ${C|} + case $L.CollectionOfErrors: + return Wrappers.Companion_Result_.Create_Failure_(CollectionOfErrors_Input_ToDafny(native_error.($L.CollectionOfErrors))) + default: + return Wrappers.Companion_Result_.Create_Failure_(OpaqueError_Input_ToDafny(native_error.($L.OpaqueError))) + } + } + return Wrappers.Companion_Result_.Create_Success_($L) + } + """, + operationShape.getId().getName(), + inputType, + typeConversion, + clientResponse, + clientCall, + writer.consumer(w -> resourceErrors(w)), + SmithyNameResolver.smithyTypesNamespace(service), + SmithyNameResolver.smithyTypesNamespace(service), + SmithyNameResolver.smithyTypesNamespace(service), + returnResponse + ); + }); + } + ); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java index 44e2371479..229b0a1d7b 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java @@ -1,5 +1,8 @@ package software.amazon.polymorph.smithygo.localservice; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Set; import software.amazon.polymorph.smithygo.codegen.ApplicationProtocol; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoDelegator; @@ -19,629 +22,1228 @@ import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.UnitTypeTrait; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Set; +public class DafnyLocalServiceTypeConversionProtocol + implements ProtocolGenerator { -public class DafnyLocalServiceTypeConversionProtocol implements ProtocolGenerator { - public static String TO_DAFNY = "to_dafny.go"; - public static String TO_NATIVE = "to_native.go"; + public static String TO_DAFNY = "to_dafny.go"; + public static String TO_NATIVE = "to_native.go"; - @Override - public ShapeId getProtocol() { - return ShapeId.from("aws.polymorph#localService"); - } + @Override + public ShapeId getProtocol() { + return ShapeId.from("aws.polymorph#localService"); + } - @Override - public ApplicationProtocol getApplicationProtocol() { - return null; - } + @Override + public ApplicationProtocol getApplicationProtocol() { + return null; + } + + @Override + public void generateSerializers(GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var model = context.model(); + final var serviceShape = model.expectShape( + context.settings().getService(), + ServiceShape.class + ); + final var symbolProvider = context.symbolProvider(); + final var writerDelegator = context.writerDelegator(); + serviceShape + .getOperations() + .forEach(eachOperation -> { + final var operation = model.expectShape( + eachOperation, + OperationShape.class + ); + final var input = model.expectShape(operation.getInputShape()); + if (!alreadyVisited.contains(input.toShapeId())) { + alreadyVisited.add(input.toShapeId()); + if ( + !input.hasTrait(UnitTypeTrait.class) && + input + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var inputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName(serviceShape, input, ""); + final var inputSymbol = symbolProvider.toSymbol(input); + writerDelegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + input.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(input) + ); + writer.write( + """ + func $L(nativeInput $L)($L) { + ${C|} + }""", + inputToDafnyMethodName, + SmithyNameResolver.getSmithyType(input, inputSymbol), + DafnyNameResolver.getDafnyType(input, inputSymbol), + writer.consumer(w -> + generateRequestSerializer( + context, + operation, + context.writerDelegator() + ) + ) + ); + } + ); + } + } + + final var output = model.expectShape(operation.getOutputShape()); + if (!alreadyVisited.contains(output.toShapeId())) { + alreadyVisited.add(output.toShapeId()); + if ( + !output.hasTrait(UnitTypeTrait.class) && + output + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var outputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName(serviceShape, output, ""); + final var outputSymbol = symbolProvider.toSymbol(output); + writerDelegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + output.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(output) + ); + writer.write( + """ + func $L(nativeOutput $L)($L) { + ${C|} + }""", + outputToDafnyMethodName, + SmithyNameResolver.getSmithyType(output, outputSymbol), + DafnyNameResolver.getDafnyType(output, outputSymbol), + writer.consumer(w -> + generateResponseSerializer( + context, + operation, + context.writerDelegator() + ) + ) + ); + } + ); + } + } + }); - @Override - public void generateSerializers(GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var model = context.model(); - final var serviceShape = model.expectShape(context.settings().getService(), ServiceShape.class); - final var symbolProvider = context.symbolProvider(); - final var writerDelegator = context.writerDelegator(); - serviceShape.getOperations().forEach(eachOperation -> { - final var operation = model.expectShape(eachOperation, OperationShape.class); + final var refResources = context + .model() + .getShapesWithTrait(ReferenceTrait.class); + for (var refResource : refResources) { + final var resource = refResource + .expectTrait(ReferenceTrait.class) + .getReferentId(); + if (!refResource.expectTrait(ReferenceTrait.class).isService()) { + var resourceShape = model.expectShape(resource, ResourceShape.class); + resourceShape + .getOperations() + .forEach(eachOperation -> { + final var operation = model.expectShape( + eachOperation, + OperationShape.class + ); final var input = model.expectShape(operation.getInputShape()); if (!alreadyVisited.contains(input.toShapeId())) { - alreadyVisited.add(input.toShapeId()); - if (!input.hasTrait(UnitTypeTrait.class) && input.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var inputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, input, ""); - final var inputSymbol = symbolProvider.toSymbol(input); - writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(input.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(input)); - writer.write(""" - func $L(nativeInput $L)($L) { - ${C|} - }""", inputToDafnyMethodName, SmithyNameResolver.getSmithyType(input, inputSymbol), - DafnyNameResolver.getDafnyType(input, inputSymbol), - writer.consumer(w -> generateRequestSerializer(context, operation, context.writerDelegator()))); - }); - } + alreadyVisited.add(input.toShapeId()); + if ( + !input.hasTrait(UnitTypeTrait.class) && + input + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var inputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName( + serviceShape, + input, + "" + ); + final var inputSymbol = symbolProvider.toSymbol(input); + writerDelegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + input.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(input) + ); + writer.write( + """ + func $L(nativeInput $L)($L) { + ${C|} + }""", + inputToDafnyMethodName, + SmithyNameResolver.getSmithyType(input, inputSymbol), + DafnyNameResolver.getDafnyType(input, inputSymbol), + writer.consumer(w -> + generateRequestSerializer( + context, + operation, + context.writerDelegator() + ) + ) + ); + } + ); + } } final var output = model.expectShape(operation.getOutputShape()); if (!alreadyVisited.contains(output.toShapeId())) { - alreadyVisited.add(output.toShapeId()); - if (!output.hasTrait(UnitTypeTrait.class) && output.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var outputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, output, ""); - final var outputSymbol = symbolProvider.toSymbol(output); - writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(output.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(output)); - writer.write(""" - func $L(nativeOutput $L)($L) { - ${C|} - }""", outputToDafnyMethodName, - SmithyNameResolver.getSmithyType(output, outputSymbol), - DafnyNameResolver.getDafnyType(output, outputSymbol), - writer.consumer(w -> generateResponseSerializer(context, operation, context.writerDelegator()))); - }); - } + alreadyVisited.add(output.toShapeId()); + if ( + !output.hasTrait(UnitTypeTrait.class) && + output + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var outputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName( + serviceShape, + output, + "" + ); + final var outputSymbol = symbolProvider.toSymbol(output); + writerDelegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + output.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(output) + ); + writer.write( + """ + func $L(nativeOutput $L)($L) { + ${C|} + }""", + outputToDafnyMethodName, + SmithyNameResolver.getSmithyType(output, outputSymbol), + DafnyNameResolver.getDafnyType(output, outputSymbol), + writer.consumer(w -> + generateResponseSerializer( + context, + operation, + context.writerDelegator() + ) + ) + ); + } + ); + } } - }); - - final var refResources = context.model().getShapesWithTrait(ReferenceTrait.class); - for (var refResource : refResources) { - final var resource = refResource.expectTrait(ReferenceTrait.class).getReferentId(); - if (!refResource.expectTrait(ReferenceTrait.class).isService()) { - var resourceShape = model.expectShape(resource, ResourceShape.class); - resourceShape.getOperations().forEach(eachOperation -> { - final var operation = model.expectShape(eachOperation, OperationShape.class); - final var input = model.expectShape(operation.getInputShape()); - if (!alreadyVisited.contains(input.toShapeId())) { - alreadyVisited.add(input.toShapeId()); - if (!input.hasTrait(UnitTypeTrait.class) && input.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var inputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, input, ""); - final var inputSymbol = symbolProvider.toSymbol(input); - writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(input.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(input)); - writer.write(""" - func $L(nativeInput $L)($L) { - ${C|} - }""", inputToDafnyMethodName, SmithyNameResolver.getSmithyType(input, inputSymbol), - DafnyNameResolver.getDafnyType(input, inputSymbol), - writer.consumer(w -> generateRequestSerializer(context, operation, context.writerDelegator()))); - }); - } - } - - final var output = model.expectShape(operation.getOutputShape()); - if (!alreadyVisited.contains(output.toShapeId())) { - alreadyVisited.add(output.toShapeId()); - if (!output.hasTrait(UnitTypeTrait.class) && output.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var outputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, output, ""); - final var outputSymbol = symbolProvider.toSymbol(output); - writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(output.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(output)); - writer.write(""" - func $L(nativeOutput $L)($L) { - ${C|} - }""", outputToDafnyMethodName, SmithyNameResolver.getSmithyType(output, outputSymbol), - DafnyNameResolver.getDafnyType(output, outputSymbol), - writer.consumer(w -> generateResponseSerializer(context, operation, context.writerDelegator()))); - }); - } - } - if (!alreadyVisited.contains(resourceShape.toShapeId()) && resourceShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - alreadyVisited.add(resourceShape.toShapeId()); - writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - var goBody = """ - return nativeResource.(*%s).Impl - """.formatted(resourceShape.getId().getName()); - if (resourceShape.hasTrait(ExtendableTrait.class)) { - goBody = """ - val, ok := nativeResource.(*%s) - if ok { - return val.Impl - } - return %s{&NativeWrapper{Impl: nativeResource}}.Impl - """.formatted(resourceShape.getId().getName(), resourceShape.getId().getName()); - } - writer.write(""" - func $L_ToDafny(nativeResource $L.I$L) $L.I$L { - $L - } - """, resourceShape.getId().getName(), SmithyNameResolver.smithyTypesNamespace(resourceShape), resourceShape.getId().getName(), DafnyNameResolver.dafnyTypesNamespace(resourceShape), resourceShape.getId().getName(), goBody); - }); + if ( + !alreadyVisited.contains(resourceShape.toShapeId()) && + resourceShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + alreadyVisited.add(resourceShape.toShapeId()); + writerDelegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + var goBody = + """ + return nativeResource.(*%s).Impl + """.formatted(resourceShape.getId().getName()); + if (resourceShape.hasTrait(ExtendableTrait.class)) { + goBody = + """ + val, ok := nativeResource.(*%s) + if ok { + return val.Impl + } + return %s{&NativeWrapper{Impl: nativeResource}}.Impl + """.formatted( + resourceShape.getId().getName(), + resourceShape.getId().getName() + ); + } + writer.write( + """ + func $L_ToDafny(nativeResource $L.I$L) $L.I$L { + $L } - }); + """, + resourceShape.getId().getName(), + SmithyNameResolver.smithyTypesNamespace(resourceShape), + resourceShape.getId().getName(), + DafnyNameResolver.dafnyTypesNamespace(resourceShape), + resourceShape.getId().getName(), + goBody + ); + } + ); } - } - generateErrorSerializer(context); - if (serviceShape.hasTrait(LocalServiceTrait.class)) { - generateConfigSerializer(context); - } + }); + } + } + generateErrorSerializer(context); + if (serviceShape.hasTrait(LocalServiceTrait.class)) { + generateConfigSerializer(context); } + } - @Override - public void generateDeserializers(GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var serviceShape = context.settings().getService(context.model()); - final var delegator = context.writerDelegator(); + @Override + public void generateDeserializers(GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var serviceShape = context.settings().getService(context.model()); + final var delegator = context.writerDelegator(); - serviceShape.getOperations().forEach(eachOperation -> { - var operation = context.model().expectShape(eachOperation, OperationShape.class); + serviceShape + .getOperations() + .forEach(eachOperation -> { + var operation = context + .model() + .expectShape(eachOperation, OperationShape.class); - final var input = context.model().expectShape(operation.getInputShape()); + final var input = context + .model() + .expectShape(operation.getInputShape()); + if (!alreadyVisited.contains(input.toShapeId())) { + alreadyVisited.add(input.toShapeId()); + if ( + !input.hasTrait(UnitTypeTrait.class) && + input + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var inputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + input, + "" + ); + final var inputSymbol = context.symbolProvider().toSymbol(input); + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + input.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(input) + ); + + writer.write( + """ + func $L(dafnyInput $L)($L) { + ${C|} + }""", + inputFromDafnyMethodName, + DafnyNameResolver.getDafnyType(input, inputSymbol), + SmithyNameResolver.getSmithyType(input, inputSymbol), + writer.consumer(w -> + generateRequestDeserializer( + context, + operation, + context.writerDelegator() + ) + ) + ); + } + ); + } + } + + final var output = context + .model() + .expectShape(operation.getOutputShape()); + if (!alreadyVisited.contains(output.toShapeId())) { + alreadyVisited.add(output.toShapeId()); + if ( + !output.hasTrait(UnitTypeTrait.class) && + output + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var outputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + output, + "" + ); + final var outputSymbol = context.symbolProvider().toSymbol(output); + + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + output.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(output) + ); + + writer.write( + """ + func $L(dafnyOutput $L)($L) { + ${C|} + }""", + outputFromDafnyMethodName, + DafnyNameResolver.getDafnyType(output, outputSymbol), + SmithyNameResolver.getSmithyType(output, outputSymbol), + writer.consumer(w -> + generateResponseDeserializer( + context, + operation, + context.writerDelegator() + ) + ) + ); + } + ); + } + } + }); + + var refResources = context.model().getShapesWithTrait(ReferenceTrait.class); + for (var refResource : refResources) { + final var resource = refResource + .expectTrait(ReferenceTrait.class) + .getReferentId(); + + if (!refResource.expectTrait(ReferenceTrait.class).isService()) { + var resourceShape = context + .model() + .expectShape(resource, ResourceShape.class); + resourceShape + .getOperations() + .forEach(eachOperation -> { + final var operation = context + .model() + .expectShape(eachOperation, OperationShape.class); + final var input = context + .model() + .expectShape(operation.getInputShape()); if (!alreadyVisited.contains(input.toShapeId())) { - alreadyVisited.add(input.toShapeId()); - if (!input.hasTrait(UnitTypeTrait.class) && input.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var inputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, input, ""); - final var inputSymbol = context.symbolProvider().toSymbol(input); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(input.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(input)); - - writer.write(""" - func $L(dafnyInput $L)($L) { - ${C|} - }""", inputFromDafnyMethodName, DafnyNameResolver.getDafnyType(input, inputSymbol), - SmithyNameResolver.getSmithyType(input, inputSymbol), - writer.consumer(w -> generateRequestDeserializer(context, operation, context.writerDelegator()))); - }); - } + alreadyVisited.add(input.toShapeId()); + if ( + !input.hasTrait(UnitTypeTrait.class) && + input + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var inputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + input, + "" + ); + final var inputSymbol = context + .symbolProvider() + .toSymbol(input); + + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + input.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(input) + ); + + writer.write( + """ + func $L(dafnyInput $L)($L) { + ${C|} + }""", + inputFromDafnyMethodName, + DafnyNameResolver.getDafnyType(input, inputSymbol), + SmithyNameResolver.getSmithyType(input, inputSymbol), + writer.consumer(w -> + generateRequestDeserializer( + context, + operation, + context.writerDelegator() + ) + ) + ); + } + ); + } } - final var output = context.model().expectShape(operation.getOutputShape()); + final var output = context + .model() + .expectShape(operation.getOutputShape()); if (!alreadyVisited.contains(output.toShapeId())) { - alreadyVisited.add(output.toShapeId()); - if (!output.hasTrait(UnitTypeTrait.class) && output.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var outputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, output, ""); - final var outputSymbol = context.symbolProvider().toSymbol(output); - - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(output.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(output)); - - writer.write(""" - func $L(dafnyOutput $L)($L) { - ${C|} - }""", outputFromDafnyMethodName, DafnyNameResolver.getDafnyType(output, outputSymbol), - SmithyNameResolver.getSmithyType(output, outputSymbol), - writer.consumer(w -> generateResponseDeserializer(context, operation, context.writerDelegator()))); - }); - } + alreadyVisited.add(output.toShapeId()); + if ( + !output.hasTrait(UnitTypeTrait.class) && + output + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var outputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + output, + "" + ); + final var outputSymbol = context + .symbolProvider() + .toSymbol(output); + + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + output.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(output) + ); + + writer.write( + """ + func $L(dafnyOutput $L)($L) { + ${C|} + }""", + outputFromDafnyMethodName, + DafnyNameResolver.getDafnyType(output, outputSymbol), + SmithyNameResolver.getSmithyType(output, outputSymbol), + writer.consumer(w -> + generateResponseDeserializer( + context, + operation, + context.writerDelegator() + ) + ) + ); + } + ); + } } - }); - - var refResources = context.model().getShapesWithTrait(ReferenceTrait.class); - for (var refResource : refResources) { - final var resource = refResource.expectTrait(ReferenceTrait.class).getReferentId(); - - if (!refResource.expectTrait(ReferenceTrait.class).isService()) { - var resourceShape = context.model().expectShape(resource, ResourceShape.class); - resourceShape.getOperations().forEach(eachOperation -> { - final var operation = context.model().expectShape(eachOperation, OperationShape.class); - final var input = context.model().expectShape(operation.getInputShape()); - if (!alreadyVisited.contains(input.toShapeId())) { - alreadyVisited.add(input.toShapeId()); - if (!input.hasTrait(UnitTypeTrait.class) && input.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var inputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, input, ""); - final var inputSymbol = context.symbolProvider().toSymbol(input); - - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(input.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(input)); - - writer.write(""" - func $L(dafnyInput $L)($L) { - ${C|} - }""", inputFromDafnyMethodName, DafnyNameResolver.getDafnyType(input, inputSymbol), - SmithyNameResolver.getSmithyType(input, inputSymbol), - writer.consumer(w -> generateRequestDeserializer(context, operation, context.writerDelegator()))); - }); - } + if ( + !alreadyVisited.contains(resourceShape.toShapeId()) && + resourceShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + alreadyVisited.add(resourceShape.toShapeId()); + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + var extendableResourceWrapperCheck = ""; + if (resourceShape.hasTrait(ExtendableTrait.class)) { + extendableResourceWrapperCheck = + """ + val, ok := dafnyResource.(*NativeWrapper) + if ok { + return val.Impl + } + """; + } + writer.write( + """ + func $L_FromDafny(dafnyResource $L.I$L)($L.I$L) { + $L + return &$L{dafnyResource} } + """, + resourceShape.getId().getName(), + DafnyNameResolver.dafnyTypesNamespace(resourceShape), + resourceShape.getId().getName(), + SmithyNameResolver.smithyTypesNamespace(resourceShape), + resourceShape.getId().getName(), + extendableResourceWrapperCheck, + resourceShape.getId().getName() + ); + } + ); + } + }); + } + } + generateErrorDeserializer(context); + if (serviceShape.hasTrait(LocalServiceTrait.class)) { + generateConfigDeserializer(context); + } + } - final var output = context.model().expectShape(operation.getOutputShape()); - if (!alreadyVisited.contains(output.toShapeId())) { - alreadyVisited.add(output.toShapeId()); - if (!output.hasTrait(UnitTypeTrait.class) && output.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var outputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, output, ""); - final var outputSymbol = context.symbolProvider().toSymbol(output); - - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(output.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(output)); - - writer.write(""" - func $L(dafnyOutput $L)($L) { - ${C|} - }""", outputFromDafnyMethodName, DafnyNameResolver.getDafnyType(output, outputSymbol), - SmithyNameResolver.getSmithyType(output, outputSymbol), - writer.consumer(w -> generateResponseDeserializer(context, operation, context.writerDelegator()))); - }); - } - } - if (!alreadyVisited.contains(resourceShape.toShapeId()) && resourceShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - alreadyVisited.add(resourceShape.toShapeId()); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - var extendableResourceWrapperCheck = ""; - if (resourceShape.hasTrait(ExtendableTrait.class)) { - extendableResourceWrapperCheck = """ - val, ok := dafnyResource.(*NativeWrapper) - if ok { - return val.Impl - } - """; - } - writer.write(""" - func $L_FromDafny(dafnyResource $L.I$L)($L.I$L) { - $L - return &$L{dafnyResource} - } - """, resourceShape.getId().getName(), DafnyNameResolver.dafnyTypesNamespace(resourceShape), resourceShape.getId().getName(), SmithyNameResolver.smithyTypesNamespace(resourceShape), resourceShape.getId().getName(), extendableResourceWrapperCheck, resourceShape.getId().getName()); - }); - } + private void generateRequestSerializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + final var targetShape = context + .model() + .expectShape(operation.getInputShape()); + delegator.useFileWriter( + "%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var input = targetShape.accept( + new SmithyToDafnyShapeVisitor( + context, + "nativeInput", + writer, + false, + false, + false + ) + ); + writer.write( + """ + return $L + """, + input + ); + } + ); + } - }); - } - } - generateErrorDeserializer(context); - if (serviceShape.hasTrait(LocalServiceTrait.class)) { - generateConfigDeserializer(context); - } + private void generateResponseSerializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + final var targetShape = context + .model() + .expectShape(operation.getOutputShape()); + delegator.useFileWriter( + "%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var input = targetShape.accept( + new SmithyToDafnyShapeVisitor( + context, + "nativeOutput", + writer, + false, + false, + false + ) + ); + writer.write( + """ + return $L + """, + input + ); + } + ); + } - } + private void generateRequestDeserializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(operation), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var inputShape = operation.getInputShape(); - private void generateRequestSerializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - final var targetShape = context.model().expectShape(operation.getInputShape()); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), SmithyNameResolver.shapeNamespace(operation), writer -> { - final var input = targetShape.accept(new SmithyToDafnyShapeVisitor( - context, - "nativeInput", - writer, - false, false, false - )); - writer.write(""" - return $L - """, - input); - } + final var targetShape = context.model().expectShape(inputShape); + final var input = targetShape.accept( + new DafnyToSmithyShapeVisitor(context, "dafnyInput", writer, false) ); - } - private void generateResponseSerializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - final var targetShape = context.model().expectShape(operation.getOutputShape()); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), SmithyNameResolver.shapeNamespace(operation), writer -> { - final var input = targetShape.accept(new SmithyToDafnyShapeVisitor( - context, - "nativeOutput", - writer, - false, false, false - )); - writer.write(""" - return $L - """, - input); - } + writer.write( + """ + return $L + """, + input ); - } + } + ); + } - private void generateRequestDeserializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_NATIVE), SmithyNameResolver.shapeNamespace(operation), writer -> { - - final var inputShape = operation.getInputShape(); - - final var targetShape = context.model().expectShape(inputShape); - final var input = targetShape.accept(new DafnyToSmithyShapeVisitor( - context, - "dafnyInput", - writer, - false - )); - - writer.write(""" - return $L - """, input); - }); - } + private void generateResponseDeserializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(operation), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var outputShape = operation.getOutputShape(); - private void generateResponseDeserializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_NATIVE), SmithyNameResolver.shapeNamespace(operation), writer -> { - - final var outputShape = operation.getOutputShape(); - - final var targetShape = context.model().expectShape(outputShape); - final var output = targetShape.accept(new DafnyToSmithyShapeVisitor( - context, - "dafnyOutput", - writer, - false - )); - - writer.write(""" - return $L - """, output); - }); - } + final var targetShape = context.model().expectShape(outputShape); + final var output = targetShape.accept( + new DafnyToSmithyShapeVisitor(context, "dafnyOutput", writer, false) + ); - private void generateConfigSerializer(final GenerationContext context) { - final var service = context.settings().getService(context.model()); - final var localServiceTrait = service.expectTrait(LocalServiceTrait.class); - final var configShape = context.model().expectShape(localServiceTrait.getConfigId(), StructureShape.class); - final var getInputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(service, configShape, ""); - - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(service), TO_DAFNY), SmithyNameResolver.shapeNamespace(service), writer -> { - writer.write(""" - func $L(nativeInput $L)($L) { - ${C|} - }""", - getInputToDafnyMethodName, SmithyNameResolver.getSmithyType(configShape, context.symbolProvider().toSymbol(configShape)), DafnyNameResolver.getDafnyType(configShape, context.symbolProvider().toSymbol(configShape)), - writer.consumer(w -> { - String output = configShape.accept(new SmithyToDafnyShapeVisitor( - context, - "nativeInput", - writer, - true, false, false - )); - writer.write(""" - return $L - """, output); - })); - }); - } + writer.write( + """ + return $L + """, + output + ); + } + ); + } - private void generateErrorSerializer(final GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var serviceShape = context.settings().getService(context.model()); - final var errorShapes = context.model().getShapesWithTrait(ErrorTrait.class); + private void generateConfigSerializer(final GenerationContext context) { + final var service = context.settings().getService(context.model()); + final var localServiceTrait = service.expectTrait(LocalServiceTrait.class); + final var configShape = context + .model() + .expectShape(localServiceTrait.getConfigId(), StructureShape.class); + final var getInputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName(service, configShape, ""); - for (final var errorShape : - errorShapes) { - if (!errorShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - continue; - } - if (!alreadyVisited.contains(errorShape.toShapeId())) { - alreadyVisited.add(errorShape.toShapeId()); - final var getInputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, errorShape, ""); - - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(errorShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(errorShape), writer -> { - writer.write(""" - func $L(nativeInput $L)($L) { - ${C|} - }""", - getInputToDafnyMethodName, SmithyNameResolver.getSmithyType(errorShape, context.symbolProvider().toSymbol(errorShape)), DafnyNameResolver.getDafnyBaseErrorType(errorShape), - writer.consumer(w -> { - String output = errorShape.accept(new SmithyToDafnyShapeVisitor( - context, - "nativeInput", - writer, - false, false, false - )); - writer.write(""" - return $L - """, output); - })); - }); - } + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted(SmithyNameResolver.shapeNamespace(service), TO_DAFNY), + SmithyNameResolver.shapeNamespace(service), + writer -> { + writer.write( + """ + func $L(nativeInput $L)($L) { + ${C|} + }""", + getInputToDafnyMethodName, + SmithyNameResolver.getSmithyType( + configShape, + context.symbolProvider().toSymbol(configShape) + ), + DafnyNameResolver.getDafnyType( + configShape, + context.symbolProvider().toSymbol(configShape) + ), + writer.consumer(w -> { + String output = configShape.accept( + new SmithyToDafnyShapeVisitor( + context, + "nativeInput", + writer, + true, + false, + false + ) + ); + writer.write( + """ + return $L + """, + output + ); + }) + ); } + ); + } - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.write(""" - func CollectionOfErrors_Input_ToDafny(nativeInput $L.CollectionOfErrors)($L.Error) { - var e []interface{} - for _, i2 := range nativeInput.ListOfErrors { - e = append(e, Error_ToDafny(i2)) - } - return $L.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) - } - func OpaqueError_Input_ToDafny(nativeInput $L.OpaqueError)($L.Error) { - return $L.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) - }""", SmithyNameResolver.smithyTypesNamespace(serviceShape), - DafnyNameResolver.dafnyTypesNamespace(serviceShape), - DafnyNameResolver.dafnyTypesNamespace(serviceShape), SmithyNameResolver.smithyTypesNamespace(serviceShape), DafnyNameResolver.dafnyTypesNamespace(serviceShape), DafnyNameResolver.dafnyTypesNamespace(serviceShape)); - }); - - - context.writerDelegator() - .useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), TO_DAFNY), - SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), writer -> { - writer.write(""" - func Error_ToDafny(err error)($L.Error) { - switch err.(type) { - // Service Errors - ${C|} - //DependentErrors - ${C|} - - //Unmodelled Errors - case $L.CollectionOfErrors: - return CollectionOfErrors_Input_ToDafny(err.($L.CollectionOfErrors)) - - default: - error, ok := err.($L.OpaqueError) - if !ok { - panic("Error is not an OpaqueError") - } - return OpaqueError_Input_ToDafny(error) - } - } - """, DafnyNameResolver.dafnyTypesNamespace(serviceShape), - writer.consumer(w -> { - for (var error : serviceShape.getErrors()) { - w.write(""" - case $L: - return $L(err.($L)) - """, SmithyNameResolver.getSmithyType(context.model().expectShape(error), context.symbolProvider().toSymbol(context.model().expectShape(error))), - SmithyNameResolver.getToDafnyMethodName(serviceShape, context.model().expectShape(error), ""), - SmithyNameResolver.getSmithyType(context.model().expectShape(error), context.symbolProvider().toSymbol(context.model().expectShape(error)))); - } - }), - writer.consumer(w -> { - var dependencies = serviceShape.hasTrait(LocalServiceTrait.class) ? serviceShape.expectTrait(LocalServiceTrait.class).getDependencies() : new LinkedList(); - if (dependencies != null) { - for (var dep : dependencies) { - var depShape = context.model().expectShape(dep); - w.write(""" - case $L.$LBaseException: - return $L.Create_$L_($L.Error_ToDafny(err)) - """, SmithyNameResolver.smithyTypesNamespace(depShape), dep.getName(), DafnyNameResolver.getDafnyErrorCompanion(serviceShape), dep.getName(), SmithyNameResolver.shapeNamespace(depShape)); - } - } - }), - SmithyNameResolver.smithyTypesNamespace(serviceShape), SmithyNameResolver.smithyTypesNamespace(serviceShape), SmithyNameResolver.smithyTypesNamespace(serviceShape) - ); - }); - } + private void generateErrorSerializer(final GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var serviceShape = context.settings().getService(context.model()); + final var errorShapes = context + .model() + .getShapesWithTrait(ErrorTrait.class); + + for (final var errorShape : errorShapes) { + if ( + !errorShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + continue; + } + if (!alreadyVisited.contains(errorShape.toShapeId())) { + alreadyVisited.add(errorShape.toShapeId()); + final var getInputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName(serviceShape, errorShape, ""); - private void generateConfigDeserializer(final GenerationContext context) { - final var serviceShape = context.settings().getService(context.model()); - final var localServiceTrait = serviceShape.expectTrait(LocalServiceTrait.class); - final var configShape = context.model().expectShape(localServiceTrait.getConfigId(), StructureShape.class); - final var getOutputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, configShape, ""); - - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(configShape), writer -> { - writer.write(""" - func $L(dafnyOutput $L)($L) { - ${C|} - }""", - getOutputFromDafnyMethodName, DafnyNameResolver.getDafnyType(configShape, context.symbolProvider().toSymbol(configShape)), SmithyNameResolver.getSmithyType(configShape, context.symbolProvider().toSymbol(configShape)), - writer.consumer(w -> { - String output = configShape.accept(new DafnyToSmithyShapeVisitor( - context, - "dafnyOutput", - writer, - true - )); - writer.write(""" - return $L - """, output); - })); - }); + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(errorShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(errorShape), + writer -> { + writer.write( + """ + func $L(nativeInput $L)($L) { + ${C|} + }""", + getInputToDafnyMethodName, + SmithyNameResolver.getSmithyType( + errorShape, + context.symbolProvider().toSymbol(errorShape) + ), + DafnyNameResolver.getDafnyBaseErrorType(errorShape), + writer.consumer(w -> { + String output = errorShape.accept( + new SmithyToDafnyShapeVisitor( + context, + "nativeInput", + writer, + false, + false, + false + ) + ); + writer.write( + """ + return $L + """, + output + ); + }) + ); + } + ); + } } - private void generateErrorDeserializer(final GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var serviceShape = context.settings().getService(context.model()); - final var errorShapes = context.model().getShapesWithTrait(ErrorTrait.class); - for (final var errorShape : - errorShapes) { - if (!errorShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - continue; + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.write( + """ + func CollectionOfErrors_Input_ToDafny(nativeInput $L.CollectionOfErrors)($L.Error) { + var e []interface{} + for _, i2 := range nativeInput.ListOfErrors { + e = append(e, Error_ToDafny(i2)) + } + return $L.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) } - if (!alreadyVisited.contains(errorShape.toShapeId())) { - alreadyVisited.add(errorShape.toShapeId()); - final var getOutputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, errorShape, ""); - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(errorShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(errorShape), writer -> { - writer.write(""" - func $L(dafnyOutput $L)($L) { - ${C|} - }""", - getOutputFromDafnyMethodName, DafnyNameResolver.getDafnyBaseErrorType(errorShape), SmithyNameResolver.getSmithyType(errorShape, context.symbolProvider().toSymbol(errorShape)), - writer.consumer(w -> { - String output = errorShape.accept(new DafnyToSmithyShapeVisitor( - context, - "dafnyOutput", - writer, - false - )); - writer.write(""" - return $L - """, output); - })); - }); + func OpaqueError_Input_ToDafny(nativeInput $L.OpaqueError)($L.Error) { + return $L.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) + }""", + SmithyNameResolver.smithyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape) + ); + } + ); + + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace( + context.settings().getService(context.model()) + ), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace( + context.settings().getService(context.model()) + ), + writer -> { + writer.write( + """ + func Error_ToDafny(err error)($L.Error) { + switch err.(type) { + // Service Errors + ${C|} + //DependentErrors + ${C|} + + //Unmodelled Errors + case $L.CollectionOfErrors: + return CollectionOfErrors_Input_ToDafny(err.($L.CollectionOfErrors)) + + default: + error, ok := err.($L.OpaqueError) + if !ok { + panic("Error is not an OpaqueError") + } + return OpaqueError_Input_ToDafny(error) + } } + """, + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + writer.consumer(w -> { + for (var error : serviceShape.getErrors()) { + w.write( + """ + case $L: + return $L(err.($L)) + """, + SmithyNameResolver.getSmithyType( + context.model().expectShape(error), + context + .symbolProvider() + .toSymbol(context.model().expectShape(error)) + ), + SmithyNameResolver.getToDafnyMethodName( + serviceShape, + context.model().expectShape(error), + "" + ), + SmithyNameResolver.getSmithyType( + context.model().expectShape(error), + context + .symbolProvider() + .toSymbol(context.model().expectShape(error)) + ) + ); + } + }), + writer.consumer(w -> { + var dependencies = serviceShape.hasTrait(LocalServiceTrait.class) + ? serviceShape + .expectTrait(LocalServiceTrait.class) + .getDependencies() + : new LinkedList(); + if (dependencies != null) { + for (var dep : dependencies) { + var depShape = context.model().expectShape(dep); + w.write( + """ + case $L.$LBaseException: + return $L.Create_$L_($L.Error_ToDafny(err)) + """, + SmithyNameResolver.smithyTypesNamespace(depShape), + dep.getName(), + DafnyNameResolver.getDafnyErrorCompanion(serviceShape), + dep.getName(), + SmithyNameResolver.shapeNamespace(depShape) + ); + } + } + }), + SmithyNameResolver.smithyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape) + ); + } + ); + } + + private void generateConfigDeserializer(final GenerationContext context) { + final var serviceShape = context.settings().getService(context.model()); + final var localServiceTrait = serviceShape.expectTrait( + LocalServiceTrait.class + ); + final var configShape = context + .model() + .expectShape(localServiceTrait.getConfigId(), StructureShape.class); + final var getOutputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName(serviceShape, configShape, ""); + + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(configShape), + writer -> { + writer.write( + """ + func $L(dafnyOutput $L)($L) { + ${C|} + }""", + getOutputFromDafnyMethodName, + DafnyNameResolver.getDafnyType( + configShape, + context.symbolProvider().toSymbol(configShape) + ), + SmithyNameResolver.getSmithyType( + configShape, + context.symbolProvider().toSymbol(configShape) + ), + writer.consumer(w -> { + String output = configShape.accept( + new DafnyToSmithyShapeVisitor( + context, + "dafnyOutput", + writer, + true + ) + ); + writer.write( + """ + return $L + """, + output + ); + }) + ); } + ); + } - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), TO_NATIVE), SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), writer -> { - writer.write(""" - func CollectionOfErrors_Output_FromDafny(dafnyOutput $L.Error)($L.CollectionOfErrors) { - listOfErrors := dafnyOutput.Dtor_list() - message := dafnyOutput.Dtor_message() - t := $L.CollectionOfErrors {} - for i := dafny.Iterate(listOfErrors) ; ; { - val, ok := i() - if !ok { - break; - } - err := val.($L.Error) - t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) - - } - t.Message = func() (string) { - var s string - for i := dafny.Iterate(message) ; ; { - val, ok := i() - if !ok { - return s - } else { - s = s + string(val.(dafny.Char)) - } - } - }() - return t - } - func OpaqueError_Output_FromDafny(dafnyOutput $L.Error)($L.OpaqueError) { - return $L.OpaqueError { - ErrObject: dafnyOutput.Dtor_obj(), - } - }""", DafnyNameResolver.dafnyTypesNamespace(serviceShape), SmithyNameResolver.smithyTypesNamespace(serviceShape), - SmithyNameResolver.smithyTypesNamespace(serviceShape), - DafnyNameResolver.dafnyTypesNamespace(serviceShape), DafnyNameResolver.dafnyTypesNamespace(serviceShape), - SmithyNameResolver.smithyTypesNamespace(serviceShape), - SmithyNameResolver.smithyTypesNamespace(serviceShape)); - }); - - context.writerDelegator() - .useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), TO_NATIVE), - SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), writer -> { - writer.write(""" - func Error_FromDafny(err $L.Error)(error) { - // Service Errors - ${C|} - - //DependentErrors - ${C|} - - //Unmodelled Errors - if err.Is_CollectionOfErrors() { - return CollectionOfErrors_Output_FromDafny(err) - } - - return OpaqueError_Output_FromDafny(err) - } - """, DafnyNameResolver.dafnyTypesNamespace(serviceShape), - writer.consumer(w -> { - for (var error : serviceShape.getErrors()) { - w.write(""" - if err.Is_$L() { - return $L(err) - } - """, error.getName(), SmithyNameResolver.getFromDafnyMethodName(serviceShape, context.model().expectShape(error), "")); - } - }), - writer.consumer(w -> { - var dependencies = serviceShape.hasTrait(LocalServiceTrait.class) ? serviceShape.expectTrait(LocalServiceTrait.class).getDependencies() : null; - if (dependencies == null) { - return; - } - for (var dep : dependencies) { - var depService = context.model().expectShape(dep, ServiceShape.class); - w.write(""" - if err.Is_$L() { - return $L.Error_FromDafny(err.Dtor_$L()) - } - """, depService.expectTrait(LocalServiceTrait.class).getSdkId(), SmithyNameResolver.shapeNamespace(depService), depService.expectTrait(LocalServiceTrait.class).getSdkId()); - } - }) - ); - }); + private void generateErrorDeserializer(final GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var serviceShape = context.settings().getService(context.model()); + final var errorShapes = context + .model() + .getShapesWithTrait(ErrorTrait.class); + for (final var errorShape : errorShapes) { + if ( + !errorShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + continue; + } + if (!alreadyVisited.contains(errorShape.toShapeId())) { + alreadyVisited.add(errorShape.toShapeId()); + final var getOutputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + errorShape, + "" + ); + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(errorShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(errorShape), + writer -> { + writer.write( + """ + func $L(dafnyOutput $L)($L) { + ${C|} + }""", + getOutputFromDafnyMethodName, + DafnyNameResolver.getDafnyBaseErrorType(errorShape), + SmithyNameResolver.getSmithyType( + errorShape, + context.symbolProvider().toSymbol(errorShape) + ), + writer.consumer(w -> { + String output = errorShape.accept( + new DafnyToSmithyShapeVisitor( + context, + "dafnyOutput", + writer, + false + ) + ); + writer.write( + """ + return $L + """, + output + ); + }) + ); + } + ); + } } + + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace( + context.settings().getService(context.model()) + ), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace( + context.settings().getService(context.model()) + ), + writer -> { + writer.write( + """ + func CollectionOfErrors_Output_FromDafny(dafnyOutput $L.Error)($L.CollectionOfErrors) { + listOfErrors := dafnyOutput.Dtor_list() + message := dafnyOutput.Dtor_message() + t := $L.CollectionOfErrors {} + for i := dafny.Iterate(listOfErrors) ; ; { + val, ok := i() + if !ok { + break; + } + err := val.($L.Error) + t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) + + } + t.Message = func() (string) { + var s string + for i := dafny.Iterate(message) ; ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() + return t + } + func OpaqueError_Output_FromDafny(dafnyOutput $L.Error)($L.OpaqueError) { + return $L.OpaqueError { + ErrObject: dafnyOutput.Dtor_obj(), + } + }""", + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape) + ); + } + ); + + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace( + context.settings().getService(context.model()) + ), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace( + context.settings().getService(context.model()) + ), + writer -> { + writer.write( + """ + func Error_FromDafny(err $L.Error)(error) { + // Service Errors + ${C|} + + //DependentErrors + ${C|} + + //Unmodelled Errors + if err.Is_CollectionOfErrors() { + return CollectionOfErrors_Output_FromDafny(err) + } + + return OpaqueError_Output_FromDafny(err) + } + """, + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + writer.consumer(w -> { + for (var error : serviceShape.getErrors()) { + w.write( + """ + if err.Is_$L() { + return $L(err) + } + """, + error.getName(), + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + context.model().expectShape(error), + "" + ) + ); + } + }), + writer.consumer(w -> { + var dependencies = serviceShape.hasTrait(LocalServiceTrait.class) + ? serviceShape + .expectTrait(LocalServiceTrait.class) + .getDependencies() + : null; + if (dependencies == null) { + return; + } + for (var dep : dependencies) { + var depService = context + .model() + .expectShape(dep, ServiceShape.class); + w.write( + """ + if err.Is_$L() { + return $L.Error_FromDafny(err.Dtor_$L()) + } + """, + depService.expectTrait(LocalServiceTrait.class).getSdkId(), + SmithyNameResolver.shapeNamespace(depService), + depService.expectTrait(LocalServiceTrait.class).getSdkId() + ); + } + }) + ); + } + ); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/Constants.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/Constants.java index e443603dff..2d1e961fc6 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/Constants.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/Constants.java @@ -1,8 +1,9 @@ package software.amazon.polymorph.smithygo.localservice.nameresolver; public class Constants { - public static final String DOT = "."; - public static final String BLANK = ""; - public static final String INTERNAL_DAFNY_TYPES = "internaldafnytypes"; - public static final String INTERNAL_DAFNY = "internaldafny"; + + public static final String DOT = "."; + public static final String BLANK = ""; + public static final String INTERNAL_DAFNY_TYPES = "internaldafnytypes"; + public static final String INTERNAL_DAFNY = "internaldafny"; } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java index b671fe228b..dab3528f0a 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java @@ -1,153 +1,199 @@ package software.amazon.polymorph.smithygo.localservice.nameresolver; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.DOT; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.INTERNAL_DAFNY; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.INTERNAL_DAFNY_TYPES; + import software.amazon.smithy.aws.traits.ServiceTrait; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.traits.SensitiveTrait; - import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.shapes.UnionShape; import software.amazon.smithy.model.traits.EnumTrait; - -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.DOT; -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.INTERNAL_DAFNY; -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.INTERNAL_DAFNY_TYPES; +import software.amazon.smithy.model.traits.SensitiveTrait; public class DafnyNameResolver { - public static String dafnyTypesNamespace(final Shape shape) { - return shape.toShapeId().getNamespace() - .replace(DOT, BLANK).toLowerCase() - .concat(INTERNAL_DAFNY_TYPES); - } - - public static String dafnyNamespace(final Shape shape) { - return shape.toShapeId().getNamespace() - .replace(DOT, BLANK).toLowerCase() - .concat(INTERNAL_DAFNY); - } - - /** - * Returns the Dafny type for a given Shape. - * - * @param shape The Shape for which the Dafny type needs to be determined. - * @param symbol The Symbol representing the Shape. - * @return The Dafny type as a String. - */ - public static String getDafnyType(final Shape shape, final Symbol symbol) { - ShapeType type = shape.getType(); - if (shape.hasTrait(EnumTrait.class)) { - type = ShapeType.ENUM; - } - switch (type) { - case INTEGER, LONG, BOOLEAN: - return symbol.getName(); - case MAP: - return "dafny.Map"; - case DOUBLE, STRING, BLOB, LIST: - return "dafny.Sequence"; - // default catches a case where users may author their own classes that implement and extend resource (ExtendableTrait) - // ENUM, STRUCTURE, UNION can be removed but for posterity it looks great to see all the shapes being covered. - case ENUM, STRUCTURE, UNION: - default: - return DafnyNameResolver.dafnyTypesNamespace(shape) - .concat(DOT) - .concat(symbol.getName()); - } - } - - public static String getDafnySubErrorType(final Shape shape, final Symbol symbol) { - return DafnyNameResolver.getDafnyBaseErrorType(shape) - .concat("_") - .concat(symbol.getName()); - } - - public static String getDafnyBaseErrorType(final Shape shape) { - return DafnyNameResolver.dafnyTypesNamespace(shape) - .concat(DOT) - .concat("Error"); - } - - public static String getDafnyCompanionType(final Shape shape, final Symbol symbol) { - return DafnyNameResolver.dafnyTypesNamespace(shape) - .concat(DOT) - .concat("Companion_%s_".formatted(symbol.getName())); - } - - public static String getDafnyErrorCompanion(final Shape shape) { - return DafnyNameResolver.dafnyTypesNamespace(shape) - .concat(DOT) - .concat("Companion_Error_"); - } - - public static String getDafnyErrorCompanionCreate(final Shape shape, final Symbol symbol) { - return DafnyNameResolver.getDafnyErrorCompanion(shape) - .concat(DOT) - .concat("Create_%s_".formatted(symbol.getName())); - } - - public static String getDafnyCompanionStructType(final Shape shape, final Symbol symbol) { - return DafnyNameResolver.dafnyTypesNamespace(shape) - .concat(DOT) - .concat("CompanionStruct_%s_".formatted(symbol.getName())); - } - - public static String getDafnyCompanionTypeCreate(final Shape shape, final Symbol symbol) { - return DafnyNameResolver.getDafnyCompanionType(shape, symbol) - .concat(DOT) - .concat("Create_%s_".formatted(symbol.getName())); - } - - /** - * Returns the path to Create_ function for creating member shape within a union shape. - * - * @param unionShape The union shape containing the member shape. - * @param memberName The name of the member shape within the union shape. - */ - public static String getDafnyCreateFuncForUnionMemberShape(final UnionShape unionShape, final String memberName) { - return "companion" - .concat(DOT) - .concat(memberName.replace(unionShape.getId().getName() + "Member", "Create_")) - .concat("_"); - } - - public static String getDafnyClient(final Shape shape, final String sdkId) { - return DafnyNameResolver.dafnyNamespace(shape) - .concat(DOT) - .concat(sdkId) - .concat("Client"); - } - public static String getDafnyInterfaceClient(final Shape shape) { - return DafnyNameResolver.dafnyTypesNamespace(shape) - .concat(DOT).concat("I") - .concat(shape.toShapeId().getName()) - .concat("Client"); - } - - public static String getDafnyInterfaceClient(final ServiceShape serviceShape, - final ServiceTrait awsSdkServiceTrait) { - return DafnyNameResolver.dafnyTypesNamespace(serviceShape) - .concat(DOT).concat("I") - .concat(awsSdkServiceTrait.getSdkId()) - .concat("Client"); - } - - - public static String createDafnyClient(final Shape shape, final String sdkId) { - return DafnyNameResolver.dafnyNamespace(shape) - .concat(".Companion_Default___") - .concat(DOT) - .concat(sdkId); - } - - public static String getDafnyDependentErrorType(final Shape shape, final String sdkId) { - return DafnyNameResolver.dafnyNamespace(shape) - .concat(".Companion_Default___") - .concat(DOT) - .concat(sdkId); - } - + public static String dafnyTypesNamespace(final Shape shape) { + return shape + .toShapeId() + .getNamespace() + .replace(DOT, BLANK) + .toLowerCase() + .concat(INTERNAL_DAFNY_TYPES); + } + + public static String dafnyNamespace(final Shape shape) { + return shape + .toShapeId() + .getNamespace() + .replace(DOT, BLANK) + .toLowerCase() + .concat(INTERNAL_DAFNY); + } + + /** + * Returns the Dafny type for a given Shape. + * + * @param shape The Shape for which the Dafny type needs to be determined. + * @param symbol The Symbol representing the Shape. + * @return The Dafny type as a String. + */ + public static String getDafnyType(final Shape shape, final Symbol symbol) { + ShapeType type = shape.getType(); + if (shape.hasTrait(EnumTrait.class)) { + type = ShapeType.ENUM; + } + switch (type) { + case INTEGER, LONG, BOOLEAN: + return symbol.getName(); + case MAP: + return "dafny.Map"; + case DOUBLE, STRING, BLOB, LIST: + return "dafny.Sequence"; + // default catches a case where users may author their own classes that implement and extend resource (ExtendableTrait) + // ENUM, STRUCTURE, UNION can be removed but for posterity it looks great to see all the shapes being covered. + case ENUM, STRUCTURE, UNION: + default: + return DafnyNameResolver + .dafnyTypesNamespace(shape) + .concat(DOT) + .concat(symbol.getName()); + } + } + + public static String getDafnySubErrorType( + final Shape shape, + final Symbol symbol + ) { + return DafnyNameResolver + .getDafnyBaseErrorType(shape) + .concat("_") + .concat(symbol.getName()); + } + + public static String getDafnyBaseErrorType(final Shape shape) { + return DafnyNameResolver + .dafnyTypesNamespace(shape) + .concat(DOT) + .concat("Error"); + } + + public static String getDafnyCompanionType( + final Shape shape, + final Symbol symbol + ) { + return DafnyNameResolver + .dafnyTypesNamespace(shape) + .concat(DOT) + .concat("Companion_%s_".formatted(symbol.getName())); + } + + public static String getDafnyErrorCompanion(final Shape shape) { + return DafnyNameResolver + .dafnyTypesNamespace(shape) + .concat(DOT) + .concat("Companion_Error_"); + } + + public static String getDafnyErrorCompanionCreate( + final Shape shape, + final Symbol symbol + ) { + return DafnyNameResolver + .getDafnyErrorCompanion(shape) + .concat(DOT) + .concat("Create_%s_".formatted(symbol.getName())); + } + + public static String getDafnyCompanionStructType( + final Shape shape, + final Symbol symbol + ) { + return DafnyNameResolver + .dafnyTypesNamespace(shape) + .concat(DOT) + .concat("CompanionStruct_%s_".formatted(symbol.getName())); + } + + public static String getDafnyCompanionTypeCreate( + final Shape shape, + final Symbol symbol + ) { + return DafnyNameResolver + .getDafnyCompanionType(shape, symbol) + .concat(DOT) + .concat("Create_%s_".formatted(symbol.getName())); + } + + /** + * Returns the path to Create_ function for creating member shape within a union shape. + * + * @param unionShape The union shape containing the member shape. + * @param memberName The name of the member shape within the union shape. + */ + public static String getDafnyCreateFuncForUnionMemberShape( + final UnionShape unionShape, + final String memberName + ) { + return "companion".concat(DOT) + .concat( + memberName.replace(unionShape.getId().getName() + "Member", "Create_") + ) + .concat("_"); + } + + public static String getDafnyClient(final Shape shape, final String sdkId) { + return DafnyNameResolver + .dafnyNamespace(shape) + .concat(DOT) + .concat(sdkId) + .concat("Client"); + } + + public static String getDafnyInterfaceClient(final Shape shape) { + return DafnyNameResolver + .dafnyTypesNamespace(shape) + .concat(DOT) + .concat("I") + .concat(shape.toShapeId().getName()) + .concat("Client"); + } + + public static String getDafnyInterfaceClient( + final ServiceShape serviceShape, + final ServiceTrait awsSdkServiceTrait + ) { + return DafnyNameResolver + .dafnyTypesNamespace(serviceShape) + .concat(DOT) + .concat("I") + .concat(awsSdkServiceTrait.getSdkId()) + .concat("Client"); + } + + public static String createDafnyClient( + final Shape shape, + final String sdkId + ) { + return DafnyNameResolver + .dafnyNamespace(shape) + .concat(".Companion_Default___") + .concat(DOT) + .concat(sdkId); + } + + public static String getDafnyDependentErrorType( + final Shape shape, + final String sdkId + ) { + return DafnyNameResolver + .dafnyNamespace(shape) + .concat(".Companion_Default___") + .concat(DOT) + .concat(sdkId); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java index 92913d681a..47c7d52bf5 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java @@ -1,101 +1,177 @@ package software.amazon.polymorph.smithygo.localservice.nameresolver; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.DOT; + +import java.util.Map; import software.amazon.smithy.aws.traits.ServiceTrait; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.SimpleShape; -import java.util.Map; - -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.DOT; - public class SmithyNameResolver { - private static Map smithyNamespaceToGoModuleNameMap; - - public static void setSmithyNamespaceToGoModuleNameMap( - Map smithyNamespaceToGoModuleNameMap) { - SmithyNameResolver.smithyNamespaceToGoModuleNameMap = smithyNamespaceToGoModuleNameMap; - } - - public static String getGoModuleNameForSmithyNamespace(final String smithyNamespace) { - if (smithyNamespace.contains("smithy.")) return ""; - if (!smithyNamespaceToGoModuleNameMap.containsKey(smithyNamespace)) { - throw new IllegalArgumentException("Go module name not found for Smithy namespace: " + smithyNamespace); - } - return smithyNamespaceToGoModuleNameMap.get(smithyNamespace); + private static Map smithyNamespaceToGoModuleNameMap; + + public static void setSmithyNamespaceToGoModuleNameMap( + Map smithyNamespaceToGoModuleNameMap + ) { + SmithyNameResolver.smithyNamespaceToGoModuleNameMap = + smithyNamespaceToGoModuleNameMap; + } + + public static String getGoModuleNameForSmithyNamespace( + final String smithyNamespace + ) { + if (smithyNamespace.contains("smithy.")) return ""; + if (!smithyNamespaceToGoModuleNameMap.containsKey(smithyNamespace)) { + throw new IllegalArgumentException( + "Go module name not found for Smithy namespace: " + smithyNamespace + ); } - - public static String shapeNamespace(final Shape shape) { - return shape.toShapeId().getNamespace().replace(DOT, BLANK).toLowerCase(); + return smithyNamespaceToGoModuleNameMap.get(smithyNamespace); + } + + public static String shapeNamespace(final Shape shape) { + return shape.toShapeId().getNamespace().replace(DOT, BLANK).toLowerCase(); + } + + public static String smithyTypesNamespace(final Shape shape) { + return shape + .toShapeId() + .getNamespace() + .replace(DOT, BLANK) + .toLowerCase() + .concat("types"); + } + + public static String getGoModuleNameForSdkNamespace( + final String smithyNamespace + ) { + return getGoModuleNameForSmithyNamespace("sdk.".concat(smithyNamespace)); + } + + public static String smithyTypesNamespaceAws( + final ServiceTrait serviceTrait, + boolean isAwsSubType + ) { + if (isAwsSubType) { + return "types"; } - - public static String smithyTypesNamespace(final Shape shape) { - return shape.toShapeId().getNamespace().replace(DOT, BLANK).toLowerCase().concat("types"); + return serviceTrait.getSdkId().toLowerCase(); + } + + public static String getSmithyType(final Shape shape, final Symbol symbol) { + if ( + symbol.getNamespace().contains("smithy.") || + symbol.getName().contains("string") + ) { + return symbol.getName(); } - - public static String getGoModuleNameForSdkNamespace(final String smithyNamespace) { - return getGoModuleNameForSmithyNamespace("sdk.".concat(smithyNamespace)); + return SmithyNameResolver + .smithyTypesNamespace(shape) + .concat(DOT) + .concat(symbol.getName()); + } + + public static String getSmithyTypeAws( + final ServiceTrait serviceTrait, + final Symbol symbol, + boolean subtype + ) { + if ( + symbol.getNamespace().contains("smithy.") || + symbol.getName().equals("string") || + symbol.getName().equals("float64") + ) { + return symbol.getName(); } - - public static String smithyTypesNamespaceAws(final ServiceTrait serviceTrait, boolean isAwsSubType) { - if (isAwsSubType) { - return "types"; - } - return serviceTrait.getSdkId().toLowerCase(); + return SmithyNameResolver + .smithyTypesNamespaceAws(serviceTrait, subtype) + .concat(DOT) + .concat(symbol.getName()); + } + + public static String getSmithyType(final Shape shape) { + return SmithyNameResolver + .smithyTypesNamespace(shape) + .concat(DOT) + .concat(shape.toShapeId().getName()); + } + + public static String getToDafnyMethodName( + final ServiceShape serviceShape, + final Shape shape, + final String disambiguator + ) { + final var methodName = serviceShape + .getContextualName(shape) + .concat("_ToDafny"); + if ( + serviceShape + .toShapeId() + .getNamespace() + .equals(shape.toShapeId().getNamespace()) + ) { + return methodName; + } else { + return SmithyNameResolver + .shapeNamespace(shape) + .concat(DOT) + .concat(methodName); } - - public static String getSmithyType(final Shape shape, final Symbol symbol) { - if(symbol.getNamespace().contains("smithy.") || symbol.getName().contains("string")) { - return symbol.getName(); - } - return SmithyNameResolver.smithyTypesNamespace(shape).concat(DOT).concat(symbol.getName()); - } - - public static String getSmithyTypeAws(final ServiceTrait serviceTrait, final Symbol symbol, boolean subtype) { - if(symbol.getNamespace().contains("smithy.") || symbol.getName().equals("string") || symbol.getName().equals("float64")) { - return symbol.getName(); - } - return SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, subtype).concat(DOT).concat(symbol.getName()); - } - - public static String getSmithyType(final Shape shape) { - return SmithyNameResolver.smithyTypesNamespace(shape).concat(DOT).concat(shape.toShapeId().getName()); - } - - public static String getToDafnyMethodName(final ServiceShape serviceShape, final Shape shape, final String disambiguator) { - final var methodName = serviceShape.getContextualName(shape).concat("_ToDafny"); - if (serviceShape.toShapeId().getNamespace().equals(shape.toShapeId().getNamespace())) { - return methodName; - } else { - return SmithyNameResolver.shapeNamespace(shape).concat(DOT).concat(methodName); - } - } - - public static String getToDafnyMethodName(final Shape shape, final String disambiguator) { - final var methodName = shape.getId().getName().concat("_ToDafny"); - return SmithyNameResolver.shapeNamespace(shape).concat(DOT).concat(methodName); - } - - public static String getFromDafnyMethodName(final ServiceShape serviceShape, final Shape shape, final String disambiguator) { - final var methodName = serviceShape.getContextualName(shape).concat("_FromDafny"); - if (serviceShape.toShapeId().getNamespace().equals(shape.toShapeId().getNamespace())) { - return methodName; - } else { - return SmithyNameResolver.shapeNamespace(shape).concat(DOT).concat(methodName); - } - } - - public static String getFromDafnyMethodName(final Shape shape, final String disambiguator) { - final var methodName = shape.getId().getName().concat("_FromDafny"); - return SmithyNameResolver.shapeNamespace(shape).concat(DOT).concat(methodName); - } - - public static String getAwsServiceClient(final ServiceTrait serviceTrait) { - return SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, false) - .concat(DOT) - .concat("Client"); + } + + public static String getToDafnyMethodName( + final Shape shape, + final String disambiguator + ) { + final var methodName = shape.getId().getName().concat("_ToDafny"); + return SmithyNameResolver + .shapeNamespace(shape) + .concat(DOT) + .concat(methodName); + } + + public static String getFromDafnyMethodName( + final ServiceShape serviceShape, + final Shape shape, + final String disambiguator + ) { + final var methodName = serviceShape + .getContextualName(shape) + .concat("_FromDafny"); + if ( + serviceShape + .toShapeId() + .getNamespace() + .equals(shape.toShapeId().getNamespace()) + ) { + return methodName; + } else { + return SmithyNameResolver + .shapeNamespace(shape) + .concat(DOT) + .concat(methodName); } + } + + public static String getFromDafnyMethodName( + final Shape shape, + final String disambiguator + ) { + final var methodName = shape.getId().getName().concat("_FromDafny"); + return SmithyNameResolver + .shapeNamespace(shape) + .concat(DOT) + .concat(methodName); + } + + public static String getAwsServiceClient(final ServiceTrait serviceTrait) { + return SmithyNameResolver + .smithyTypesNamespaceAws(serviceTrait, false) + .concat(DOT) + .concat("Client"); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java index 2ef2b435d0..3444cbea2b 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java @@ -1,5 +1,7 @@ package software.amazon.polymorph.smithygo.localservice.shapevisitor; +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoWriter; import software.amazon.polymorph.smithygo.codegen.SmithyGoDependency; @@ -27,426 +29,626 @@ import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.utils.StringUtils; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - public class DafnyToSmithyShapeVisitor extends ShapeVisitor.Default { - private final GenerationContext context; - private final String dataSource; - private final GoWriter writer; - private final boolean isConfigShape; - private final boolean isOptional; - public DafnyToSmithyShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isConfigShape - ) { - this(context, dataSource, writer, isConfigShape, false); - } + private final GenerationContext context; + private final String dataSource; + private final GoWriter writer; + private final boolean isConfigShape; + private final boolean isOptional; + + public DafnyToSmithyShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isConfigShape + ) { + this(context, dataSource, writer, isConfigShape, false); + } - public DafnyToSmithyShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isConfigShape, - final boolean isOptional - ) { - this.context = context; - this.dataSource = dataSource; - this.writer = writer; - this.isConfigShape = isConfigShape; - this.isOptional = isOptional; + public DafnyToSmithyShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isConfigShape, + final boolean isOptional + ) { + this.context = context; + this.dataSource = dataSource; + this.writer = writer; + this.isConfigShape = isConfigShape; + this.isOptional = isOptional; + } + + protected String referenceStructureShape(StructureShape shape) { + ReferenceTrait referenceTrait = shape.expectTrait(ReferenceTrait.class); + Shape resourceOrService = context + .model() + .expectShape(referenceTrait.getReferentId()); + var namespace = ""; + if (resourceOrService.asResourceShape().isPresent()) { + var resourceShape = resourceOrService.asResourceShape().get(); + if ( + !resourceOrService + .toShapeId() + .getNamespace() + .equals(context.settings().getService().getNamespace()) + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + resourceOrService.toShapeId().getNamespace() + ), + SmithyNameResolver.shapeNamespace(resourceShape) + ); + namespace = + SmithyNameResolver.shapeNamespace(resourceOrService).concat("."); + } + if (!this.isOptional) { + return "%s_FromDafny(%s)".formatted( + namespace.concat(resourceShape.toShapeId().getName()), + dataSource + ); + } + return """ + func () %s.I%s { + if %s == nil { + return nil; + } + return %s + }()""".formatted( + SmithyNameResolver.smithyTypesNamespace(resourceShape), + resourceShape.getId().getName(), + dataSource, + "%s_FromDafny(%s.(%s.I%s))".formatted( + namespace.concat(resourceShape.toShapeId().getName()), + dataSource, + DafnyNameResolver.dafnyTypesNamespace(resourceShape), + resourceShape.getId().getName() + ) + ); + } else { + var serviceShape = resourceOrService.asServiceShape().get(); + if ( + !resourceOrService + .toShapeId() + .getNamespace() + .equals(context.settings().getService().getNamespace()) + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + resourceOrService.toShapeId().getNamespace() + ), + SmithyNameResolver.shapeNamespace(serviceShape) + ); + namespace = + SmithyNameResolver.shapeNamespace(resourceOrService).concat("."); + } + if (!this.isOptional) { + return "%1$s{%2$s}".formatted( + namespace.concat( + context.symbolProvider().toSymbol(serviceShape).getName() + ), + dataSource + ); + } + return """ + func () *%s { + if %s == nil { + return nil; + } + return &%s{%s.(*%s)} + }()""".formatted( + namespace.concat( + context.symbolProvider().toSymbol(serviceShape).getName() + ), + dataSource, + namespace.concat( + context.symbolProvider().toSymbol(serviceShape).getName() + ), + dataSource, + DafnyNameResolver.getDafnyClient( + serviceShape, + serviceShape.toShapeId().getName() + ) + ); } + } - protected String referenceStructureShape(StructureShape shape) { - ReferenceTrait referenceTrait = shape.expectTrait(ReferenceTrait.class); - Shape resourceOrService = context.model().expectShape(referenceTrait.getReferentId()); - var namespace = ""; - if (resourceOrService.asResourceShape().isPresent()) { - var resourceShape = resourceOrService.asResourceShape().get(); - if (!resourceOrService.toShapeId().getNamespace().equals(context.settings().getService().getNamespace())) { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resourceOrService.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(resourceShape)); - namespace = SmithyNameResolver.shapeNamespace(resourceOrService).concat("."); - } - if (!this.isOptional) { - return "%s_FromDafny(%s)".formatted(namespace.concat(resourceShape.toShapeId().getName()), dataSource); - } - return """ - func () %s.I%s { - if %s == nil { - return nil; - } - return %s - }()""".formatted(SmithyNameResolver.smithyTypesNamespace(resourceShape), resourceShape.getId().getName(), dataSource, - "%s_FromDafny(%s.(%s.I%s))".formatted(namespace.concat(resourceShape.toShapeId().getName()), dataSource, - DafnyNameResolver.dafnyTypesNamespace(resourceShape), resourceShape.getId().getName())); + @Override + protected String getDefault(Shape shape) { + throw new CodegenException( + String.format( + "Unsupported conversion of %s to %s using the %s protocol", + shape, + shape.getType(), + context.protocolGenerator().getName() + ) + ); + } + + @Override + public String blobShape(BlobShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + return """ + func () []byte { + var b []byte + if %s == nil { + return nil + } + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return b } else { - var serviceShape = resourceOrService.asServiceShape().get(); - if (!resourceOrService.toShapeId().getNamespace().equals(context.settings().getService().getNamespace())) { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resourceOrService.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(serviceShape)); - namespace = SmithyNameResolver.shapeNamespace(resourceOrService).concat("."); - } - if (!this.isOptional) { - return "%1$s{%2$s}".formatted(namespace.concat(context.symbolProvider().toSymbol(serviceShape).getName()), dataSource); - } - return """ - func () *%s { - if %s == nil { - return nil; - } - return &%s{%s.(*%s)} - }()""".formatted(namespace.concat(context.symbolProvider().toSymbol(serviceShape).getName()), dataSource, namespace.concat(context.symbolProvider().toSymbol(serviceShape).getName()), - dataSource, DafnyNameResolver.getDafnyClient(serviceShape, serviceShape.toShapeId().getName())); + b = append(b, val.(byte)) } } + }()""".formatted(dataSource, dataSource); + } - @Override - protected String getDefault(Shape shape) { - throw new CodegenException(String.format( - "Unsupported conversion of %s to %s using the %s protocol", - shape, shape.getType(), context.protocolGenerator().getName())); + @Override + public String structureShape(final StructureShape shape) { + if (shape.hasTrait(ReferenceTrait.class)) { + return referenceStructureShape(shape); } + final var builder = new StringBuilder(); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + shape.toShapeId().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(shape) + ); - @Override - public String blobShape(BlobShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - return """ - func () []byte { - var b []byte - if %s == nil { - return nil - } - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return b - } else { - b = append(b, val.(byte)) - } - } - }()""".formatted(dataSource, dataSource); + builder.append( + "%1$s{".formatted( + SmithyNameResolver + .smithyTypesNamespace(shape) + .concat(".") + .concat(shape.getId().getName()) + ) + ); + String fieldSeparator = ","; + for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { + final var memberName = memberShapeEntry.getKey(); + final var memberShape = memberShapeEntry.getValue(); + final var targetShape = context + .model() + .expectShape(memberShape.getTarget()); + //TODO: Is it ever possible for structure to be nil? + final var derivedDataSource = + "%1$s%2$s%3$s%4$s".formatted( + dataSource, + ".Dtor_%s()".formatted(memberName), + memberShape.isOptional() ? ".UnwrapOr(nil)" : "", + memberShape.isOptional() && + targetShape.isStructureShape() && + !targetShape.hasTrait(ReferenceTrait.class) + ? ".(%s)".formatted( + DafnyNameResolver.getDafnyType( + targetShape, + context.symbolProvider().toSymbol(memberShape) + ) + ) + : "" + ); + builder.append( + "%1$s: %2$s%3$s,".formatted( + StringUtils.capitalize(memberName), + (targetShape.isStructureShape() && memberShape.isOptional()) && + !targetShape.hasTrait(ReferenceTrait.class) + ? "&" + : "", + targetShape.accept( + new DafnyToSmithyShapeVisitor( + context, + derivedDataSource, + writer, + isConfigShape, + memberShape.isOptional() + ) + ) + ) + ); } - @Override - public String structureShape(final StructureShape shape) { - if (shape.hasTrait(ReferenceTrait.class)) { - return referenceStructureShape(shape); - } - final var builder = new StringBuilder(); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(shape.toShapeId().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(shape)); - - builder.append("%1$s{".formatted(SmithyNameResolver.smithyTypesNamespace(shape).concat(".").concat(shape.getId().getName()))); - String fieldSeparator = ","; - for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { - final var memberName = memberShapeEntry.getKey(); - final var memberShape = memberShapeEntry.getValue(); - final var targetShape = context.model().expectShape(memberShape.getTarget()); - //TODO: Is it ever possible for structure to be nil? - final var derivedDataSource = "%1$s%2$s%3$s%4$s".formatted(dataSource, - ".Dtor_%s()".formatted(memberName), - memberShape.isOptional() ? ".UnwrapOr(nil)" : "", - memberShape.isOptional() && targetShape.isStructureShape() && !targetShape.hasTrait(ReferenceTrait.class) ? ".(%s)".formatted(DafnyNameResolver.getDafnyType(targetShape, context.symbolProvider().toSymbol(memberShape))) : ""); - builder.append("%1$s: %2$s%3$s,".formatted( - StringUtils.capitalize(memberName), - (targetShape.isStructureShape() && memberShape.isOptional()) && !targetShape.hasTrait(ReferenceTrait.class) ? "&" : "", - targetShape.accept( - new DafnyToSmithyShapeVisitor(context, derivedDataSource, writer, isConfigShape, memberShape.isOptional()) - ) - )); - } + return builder.append("}").toString(); + } - return builder.append("}").toString(); - } + // TODO: smithy-dafny-conversion library + @Override + public String listShape(ListShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + StringBuilder builder = new StringBuilder(); - // TODO: smithy-dafny-conversion library - @Override - public String listShape(ListShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - StringBuilder builder = new StringBuilder(); + MemberShape memberShape = shape.getMember(); + final Shape targetShape = context + .model() + .expectShape(memberShape.getTarget()); + var typeName = targetShape.isStructureShape() + ? context.symbolProvider().toSymbol(memberShape) + : context.symbolProvider().toSymbol(memberShape); + builder.append( + """ + func() []%s{ + var fieldValue []%s + if %s == nil { + return nil + } + for i := dafny.Iterate(%s.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, %s)} + """.formatted( + SmithyNameResolver.getSmithyType(shape, typeName), + SmithyNameResolver.getSmithyType(shape, typeName), + dataSource, + dataSource, + targetShape.accept( + new DafnyToSmithyShapeVisitor( + context, + "val%s".formatted( + targetShape.isStructureShape() + ? ".(%s)".formatted( + DafnyNameResolver.getDafnyType( + targetShape, + context.symbolProvider().toSymbol(targetShape) + ) + ) + : "" + ), + writer, + isConfigShape + ) + ) + ) + ); - MemberShape memberShape = shape.getMember(); - final Shape targetShape = context.model().expectShape(memberShape.getTarget()); - var typeName = targetShape.isStructureShape() ? context.symbolProvider().toSymbol(memberShape) : context.symbolProvider().toSymbol(memberShape); - builder.append(""" - func() []%s{ - var fieldValue []%s - if %s == nil { - return nil - } - for i := dafny.Iterate(%s.(dafny.Sequence)); ; { - val, ok := i() - if !ok { - break - } - fieldValue = append(fieldValue, %s)} - """.formatted(SmithyNameResolver.getSmithyType(shape, typeName), SmithyNameResolver.getSmithyType(shape, typeName), dataSource, dataSource, - targetShape.accept( - new DafnyToSmithyShapeVisitor(context, "val%s".formatted(targetShape.isStructureShape() ? ".(%s)".formatted(DafnyNameResolver.getDafnyType(targetShape, context.symbolProvider().toSymbol(targetShape))) : ""), writer, isConfigShape) - ))); + // Close structure + return builder + .append("return fieldValue }()".formatted(dataSource)) + .toString(); + } - // Close structure - return builder.append("return fieldValue }()".formatted(dataSource)).toString(); - } + @Override + public String mapShape(MapShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + StringBuilder builder = new StringBuilder(); - @Override - public String mapShape(MapShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - StringBuilder builder = new StringBuilder(); + MemberShape keyMemberShape = shape.getKey(); + final Shape keyTargetShape = context + .model() + .expectShape(keyMemberShape.getTarget()); + MemberShape valueMemberShape = shape.getValue(); + final Shape valueTargetShape = context + .model() + .expectShape(valueMemberShape.getTarget()); + final var type = context + .symbolProvider() + .toSymbol(valueTargetShape) + .getName(); - MemberShape keyMemberShape = shape.getKey(); - final Shape keyTargetShape = context.model().expectShape(keyMemberShape.getTarget()); - MemberShape valueMemberShape = shape.getValue(); - final Shape valueTargetShape = context.model().expectShape(valueMemberShape.getTarget()); - final var type = context.symbolProvider().toSymbol(valueTargetShape).getName(); + builder.append( + """ + func() map[string]%s { + var m map[string]%s = make(map[string]%s) + if %s == nil { + return nil + } + for i := dafny.Iterate(%s.(dafny.Map).Items());; { + val, ok := i() + if !ok { + break; + } + m[%s] = %s + } + return m + }()""".formatted( + type, + type, + type, + dataSource, + dataSource, + keyTargetShape.accept( + new DafnyToSmithyShapeVisitor( + context, + "(*val.(dafny.Tuple).IndexInt(0))", + writer, + isConfigShape + ) + ), + valueTargetShape.accept( + new DafnyToSmithyShapeVisitor( + context, + "(*val.(dafny.Tuple).IndexInt(1))", + writer, + isConfigShape + ) + ) + ) + ); + return builder.toString(); + } - builder.append(""" - func() map[string]%s { - var m map[string]%s = make(map[string]%s) - if %s == nil { - return nil - } - for i := dafny.Iterate(%s.(dafny.Map).Items());; { - val, ok := i() - if !ok { - break; - } - m[%s] = %s - } - return m - }()""".formatted(type, type, type, dataSource, dataSource, keyTargetShape.accept( - new DafnyToSmithyShapeVisitor(context, "(*val.(dafny.Tuple).IndexInt(0))", writer, isConfigShape) - ), - valueTargetShape.accept( - new DafnyToSmithyShapeVisitor(context, "(*val.(dafny.Tuple).IndexInt(1))", writer, isConfigShape) - ) - )); - return builder.toString(); + @Override + public String booleanShape(BooleanShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (this.isOptional) { + return """ + func() *bool { + var b bool + if %s == nil { + return nil + } + b = %s.(%s) + return &b + }()""".formatted( + dataSource, + dataSource, + context.symbolProvider().toSymbol(shape).getName() + ); + } else { + return "%s.(%s)".formatted( + dataSource, + context.symbolProvider().toSymbol(shape).getName() + ); } + } - @Override - public String booleanShape(BooleanShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (this.isOptional) { - return """ - func() *bool { - var b bool - if %s == nil { - return nil - } - b = %s.(%s) - return &b - }()""".formatted(dataSource, dataSource, context.symbolProvider().toSymbol(shape).getName()); - } else { - return "%s.(%s)".formatted(dataSource, context.symbolProvider().toSymbol(shape).getName()); - } + @Override + public String stringShape(StringShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (shape.hasTrait(EnumTrait.class)) { + return """ + func () *%s.%s { + var u %s.%s + if %s == nil { + return nil + } + inputEnum := %s.(%s) + index := -1; + for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(%s).Equals(inputEnum) { + break; + } + } + } + + return &u.Values()[index] + }()""".formatted( + SmithyNameResolver.smithyTypesNamespace(shape), + context.symbolProvider().toSymbol(shape).getName(), + SmithyNameResolver.smithyTypesNamespace(shape), + context.symbolProvider().toSymbol(shape).getName(), + dataSource, + dataSource, + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ), + DafnyNameResolver.getDafnyCompanionStructType( + shape, + context.symbolProvider().toSymbol(shape) + ), + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ) + ); } - @Override - public String stringShape(StringShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (shape.hasTrait(EnumTrait.class)) { - return """ - func () *%s.%s { - var u %s.%s - if %s == nil { - return nil - } - inputEnum := %s.(%s) - index := -1; - for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { - enum, ok := allEnums() - if ok { - index++ - if enum.(%s).Equals(inputEnum) { - break; - } - } - } - - return &u.Values()[index] - }()""".formatted(SmithyNameResolver.smithyTypesNamespace(shape), context.symbolProvider().toSymbol(shape).getName(), SmithyNameResolver.smithyTypesNamespace(shape), context.symbolProvider().toSymbol(shape).getName(), dataSource, dataSource, DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)), DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), - DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))); - } + var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) + ? "uint8" + : "dafny.Char"; + var strConv = "s = s + string(val.(%s))".formatted(underlyingType); + if (underlyingType == "uint8") { + strConv = + """ + // UTF bytes should be always converted from bytes to string in go + // Otherwise go treats the string as a unicode codepoint - var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) ? "uint8" : "dafny.Char"; - var strConv = "s = s + string(val.(%s))".formatted(underlyingType); - if( underlyingType == "uint8" ) { - strConv = """ - // UTF bytes should be always converted from bytes to string in go - // Otherwise go treats the string as a unicode codepoint - - var valUint, _ = val.(%s) - var byteSlice = []byte{valUint} - s = s + string(byteSlice) - """.formatted(underlyingType); - } - if ((boolean)isOptional) { - return """ - func() (*string) { - var s string - if %s == nil { - return nil - } - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - %s - } - } - }()""".formatted(dataSource, dataSource, strConv); - } - else { - return """ - func() (string) { - var s string - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return s - } else { - %s - } - } - }()""".formatted(dataSource, strConv); - } + var valUint, _ = val.(%s) + var byteSlice = []byte{valUint} + s = s + string(byteSlice) + """.formatted(underlyingType); } + if ((boolean) isOptional) { + return """ + func() (*string) { + var s string + if %s == nil { + return nil + } + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + %s + } + } + }()""".formatted(dataSource, dataSource, strConv); + } else { + return """ + func() (string) { + var s string + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return s + } else { + %s + } + } + }()""".formatted(dataSource, strConv); + } + } - @Override - public String integerShape(IntegerShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + @Override + public String integerShape(IntegerShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if ((boolean)isOptional) { - return (""" - func() *int32 { - var b int32 - if %s == nil { - return nil - } - b = %s.(int32) - return &b - }()""".formatted(dataSource, dataSource)); - }else { - return """ - func() int32 { - var b = %s.(int32) - return b - }() - """.formatted(dataSource); - } + if ((boolean) isOptional) { + return ( + """ + func() *int32 { + var b int32 + if %s == nil { + return nil + } + b = %s.(int32) + return &b + }()""".formatted(dataSource, dataSource) + ); + } else { + return """ + func() int32 { + var b = %s.(int32) + return b + }() + """.formatted(dataSource); } + } - @Override - public String longShape(LongShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - return (""" - func() *int64 { - var b int64 - if %s == nil { - return nil - } - b = %s.(int64) - return &b - }()""").formatted(dataSource, dataSource); - } + @Override + public String longShape(LongShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + return ( + """ + func() *int64 { + var b int64 + if %s == nil { + return nil + } + b = %s.(int64) + return &b + }()""" + ).formatted(dataSource, dataSource); + } - @Override - public String doubleShape(DoubleShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - writer.addUseImports(SmithyGoDependency.MATH); - return """ - func () *float64 { - var b []byte - if %s == nil { - return nil - } - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return &[]float64{math.Float64frombits(binary.LittleEndian.Uint64(b))}[0] - } else { - b = append(b, val.(byte)) - } - } - }()""".formatted(dataSource, dataSource); + @Override + public String doubleShape(DoubleShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + writer.addUseImports(SmithyGoDependency.MATH); + return """ + func () *float64 { + var b []byte + if %s == nil { + return nil } - - @Override - public String unionShape(UnionShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilCheck; - if (GoPointableIndex.of(context.model()).isPointable(shape) == false) { - nilCheck = ""; - } else { - nilCheck = """ - if %s == nil { - return nil - }""".formatted( - dataSource - ); + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return &[]float64{math.Float64frombits(binary.LittleEndian.Uint64(b))}[0] + } else { + b = append(b, val.(byte)) + } } - final String functionInit = """ - func() %s { - var union %s - %s - """.formatted( - context.symbolProvider().toSymbol(shape), - context.symbolProvider().toSymbol(shape), - nilCheck + }()""".formatted(dataSource, dataSource); + } + + @Override + public String unionShape(UnionShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilCheck; + if (GoPointableIndex.of(context.model()).isPointable(shape) == false) { + nilCheck = ""; + } else { + nilCheck = + """ + if %s == nil { + return nil + }""".formatted(dataSource); + } + final String functionInit = + """ + func() %s { + var union %s + %s + """.formatted( + context.symbolProvider().toSymbol(shape), + context.symbolProvider().toSymbol(shape), + nilCheck + ); + StringBuilder eachMemberInUnion = new StringBuilder(); + for (var member : shape.getAllMembers().values()) { + final Shape targetShape = context.model().expectShape(member.getTarget()); + final String memberName = context.symbolProvider().toMemberName(member); + final String rawUnionDataSource = + "(" + + dataSource + + ".(" + + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ) + + "))"; + // unwrap union type, assert it then convert it to its member type with Dtor_ (example: Dtor_BlobValue()). unionDataSource is not a wrapper object until now. + String unionDataSource = + rawUnionDataSource + + ".Dtor_" + + memberName.replace(shape.getId().getName() + "Member", "") + + "()"; + final Boolean isMemberShapePointable = + (GoPointableIndex.of(context.model()).isPointable(targetShape) && + GoPointableIndex.of(context.model()).isDereferencable(targetShape)) && + !targetShape.isStructureShape(); + final String pointerForPointableShape = isMemberShapePointable ? "*" : ""; + final String isMemberCheck = + """ + if ((%s).%s()) {""".formatted( + rawUnionDataSource, + memberName.replace(shape.getId().getName() + "Member", "Is_") + ); + String wrappedDataSource = ""; + if (!(targetShape.isStructureShape())) { + // All other shape except structure needs a Wrapper object but unionDataSource is not a Wrapper object. + wrappedDataSource = + """ + var dataSource = Wrappers.Companion_Option_.Create_Some_(%s)""".formatted( + unionDataSource ); - StringBuilder eachMemberInUnion = new StringBuilder(); - for (var member : shape.getAllMembers().values()) { - final Shape targetShape = context.model().expectShape(member.getTarget()); - final String memberName = context.symbolProvider().toMemberName(member); - final String rawUnionDataSource = "(" + dataSource + ".(" + DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)) + "))"; - // unwrap union type, assert it then convert it to its member type with Dtor_ (example: Dtor_BlobValue()). unionDataSource is not a wrapper object until now. - String unionDataSource = rawUnionDataSource + ".Dtor_" + memberName.replace(shape.getId().getName() + "Member", "") + "()"; - final Boolean isMemberShapePointable = (GoPointableIndex.of(context.model()).isPointable(targetShape) && GoPointableIndex.of(context.model()).isDereferencable(targetShape)) && !targetShape.isStructureShape(); - final String pointerForPointableShape = isMemberShapePointable ? "*" : ""; - final String isMemberCheck = """ - if ((%s).%s()) {""".formatted( - rawUnionDataSource, - memberName.replace(shape.getId().getName() + "Member", "Is_") - ); - String wrappedDataSource = ""; - if (!(targetShape.isStructureShape())) { - // All other shape except structure needs a Wrapper object but unionDataSource is not a Wrapper object. - wrappedDataSource = """ - var dataSource = Wrappers.Companion_Option_.Create_Some_(%s)""".formatted(unionDataSource); - unionDataSource = "dataSource.UnwrapOr(nil)"; + unionDataSource = "dataSource.UnwrapOr(nil)"; + } + eachMemberInUnion.append( + """ + %s + %s + union = &%s.%s{ + Value: %s(%s), } - eachMemberInUnion.append(""" - %s - %s - union = &%s.%s{ - Value: %s(%s), - } - } - """.formatted( - isMemberCheck, - wrappedDataSource, - SmithyNameResolver.smithyTypesNamespace(shape), - memberName, - pointerForPointableShape, - targetShape.accept( - new DafnyToSmithyShapeVisitor(context, unionDataSource, writer, isConfigShape, isMemberShapePointable) - ))); } - return - """ - %s - %s - return union - }()""".formatted( - functionInit, - eachMemberInUnion - ); + """.formatted( + isMemberCheck, + wrappedDataSource, + SmithyNameResolver.smithyTypesNamespace(shape), + memberName, + pointerForPointableShape, + targetShape.accept( + new DafnyToSmithyShapeVisitor( + context, + unionDataSource, + writer, + isConfigShape, + isMemberShapePointable + ) + ) + ) + ); } + return """ + %s + %s + return union + }()""".formatted(functionInit, eachMemberInUnion); + } - @Override - public String timestampShape(TimestampShape shape) { - return "nil"; - } -} \ No newline at end of file + @Override + public String timestampShape(TimestampShape shape) { + return "nil"; + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java index f45c6ea4a8..e2afef2d91 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java @@ -1,5 +1,7 @@ package software.amazon.polymorph.smithygo.localservice.shapevisitor; +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoWriter; import software.amazon.polymorph.smithygo.codegen.SmithyGoDependency; @@ -28,481 +30,681 @@ import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.utils.StringUtils; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - public class SmithyToDafnyShapeVisitor extends ShapeVisitor.Default { - private final GenerationContext context; - private final String dataSource; - private final GoWriter writer; - private final boolean isConfigShape; - - private final boolean isOptional; - protected boolean isPointerType; - public void setPointerType() { - this.isPointerType = false; + private final GenerationContext context; + private final String dataSource; + private final GoWriter writer; + private final boolean isConfigShape; + + private final boolean isOptional; + protected boolean isPointerType; + + public void setPointerType() { + this.isPointerType = false; + } + + public SmithyToDafnyShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isConfigShape, + final boolean isOptional, + final boolean isPointerType + ) { + this.context = context; + this.dataSource = dataSource; + this.writer = writer; + this.isConfigShape = isConfigShape; + this.isOptional = isOptional; + this.isPointerType = isPointerType; + } + + protected String referenceStructureShape(StructureShape shape) { + ReferenceTrait referenceTrait = shape.expectTrait(ReferenceTrait.class); + Shape resourceOrService = context + .model() + .expectShape(referenceTrait.getReferentId()); + + if (resourceOrService.asResourceShape().isPresent()) { + ResourceShape resourceShape = resourceOrService.asResourceShape().get(); + var namespace = ""; + if ( + !resourceShape + .toShapeId() + .getNamespace() + .equals(context.settings().getService().getNamespace()) + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + resourceShape.toShapeId().getNamespace() + ), + SmithyNameResolver.shapeNamespace(resourceShape) + ); + namespace = + SmithyNameResolver.shapeNamespace(resourceShape).concat("."); + } + if (!this.isOptional) { + return "%s_ToDafny(%s)".formatted( + namespace.concat(resourceShape.toShapeId().getName()), + dataSource + ); + } else { + var goCodeBlock = + """ + func () Wrappers.Option { + if %s == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(%s) + }()"""; + return goCodeBlock.formatted( + dataSource, + "%s_ToDafny(%s)".formatted( + namespace.concat(resourceShape.toShapeId().getName()), + dataSource + ) + ); + } } - public SmithyToDafnyShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isConfigShape, - final boolean isOptional, - final boolean isPointerType - ) { - this.context = context; - this.dataSource = dataSource; - this.writer = writer; - this.isConfigShape = isConfigShape; - this.isOptional = isOptional; - this.isPointerType = isPointerType; + if (resourceOrService.asServiceShape().isPresent()) { + ServiceShape resourceShape = resourceOrService.asServiceShape().get(); + if (!this.isOptional) { + return dataSource; + } else { + var goCodeBlock = + """ + func () Wrappers.Option { + if %s == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(%s) + }()"""; + return goCodeBlock.formatted(dataSource, dataSource); + } } - protected String referenceStructureShape(StructureShape shape) { - ReferenceTrait referenceTrait = shape.expectTrait(ReferenceTrait.class); - Shape resourceOrService = context.model().expectShape(referenceTrait.getReferentId()); - - if (resourceOrService.asResourceShape().isPresent()) { - ResourceShape resourceShape = resourceOrService.asResourceShape().get(); - var namespace = ""; - if (!resourceShape.toShapeId().getNamespace().equals(context.settings().getService().getNamespace())) { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resourceShape.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(resourceShape)); - namespace = SmithyNameResolver.shapeNamespace(resourceShape).concat("."); - } - if(!this.isOptional) { - return "%s_ToDafny(%s)".formatted(namespace.concat(resourceShape.toShapeId().getName()), dataSource); - } else { - var goCodeBlock = """ - func () Wrappers.Option { - if %s == nil { - return Wrappers.Companion_Option_.Create_None_() - } - return Wrappers.Companion_Option_.Create_Some_(%s) - }()"""; - return goCodeBlock.formatted(dataSource, "%s_ToDafny(%s)".formatted(namespace.concat(resourceShape.toShapeId().getName()), dataSource)); - } - } - - if (resourceOrService.asServiceShape().isPresent()) { - ServiceShape resourceShape = resourceOrService.asServiceShape().get(); - if(!this.isOptional) { - return dataSource; - } else { - var goCodeBlock = """ - func () Wrappers.Option { - if %s == nil { - return Wrappers.Companion_Option_.Create_None_() - } - return Wrappers.Companion_Option_.Create_Some_(%s) - }()"""; - return goCodeBlock.formatted(dataSource, dataSource); - } + throw new UnsupportedOperationException( + "Unknown referenceStructureShape type: " + shape + ); + } + + @Override + protected String getDefault(Shape shape) { + throw new CodegenException( + String.format( + "Unsupported conversion of %s to %s using the %s protocol", + shape, + shape.getType(), + context.protocolGenerator().getName() + ) + ); + } + + @Override + public String blobShape(BlobShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + return """ + func () %s { + var v []interface{} + if %s == nil {return %s} + for _, e := range %s { + v = append(v, e) } - - throw new UnsupportedOperationException("Unknown referenceStructureShape type: " + shape); + return %s; + }()""".formatted( + returnType, + dataSource, + nilWrapIfRequired, + dataSource, + someWrapIfRequired.formatted("dafny.SeqOf(v...)") + ); + } + + @Override + public String structureShape(final StructureShape shape) { + if (shape.hasTrait(ReferenceTrait.class)) { + return referenceStructureShape(shape); } - - @Override - protected String getDefault(Shape shape) { - throw new CodegenException(String.format( - "Unsupported conversion of %s to %s using the %s protocol", - shape, shape.getType(), context.protocolGenerator().getName())); + final var builder = new StringBuilder(); + writer.addImportFromModule( + "github.com/dafny-lang/DafnyStandardLibGo", + "Wrappers" + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + shape.toShapeId().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(shape) + ); + + String someWrapIfRequired = "%s"; + + String companionStruct; + String returnType; + if (shape.hasTrait(ErrorTrait.class)) { + companionStruct = + DafnyNameResolver.getDafnyErrorCompanionCreate( + shape, + context.symbolProvider().toSymbol(shape) + ); + returnType = DafnyNameResolver.getDafnyBaseErrorType(shape); + } else { + companionStruct = + DafnyNameResolver.getDafnyCompanionTypeCreate( + shape, + context.symbolProvider().toSymbol(shape) + ); + returnType = + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ); } + String nilWrapIfRequired = returnType.concat("{}"); - @Override - public String blobShape(BlobShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - return """ - func () %s { - var v []interface{} - if %s == nil {return %s} - for _, e := range %s { - v = append(v, e) - } - return %s; - }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, someWrapIfRequired.formatted("dafny.SeqOf(v...)")); + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - @Override - public String structureShape(final StructureShape shape) { - if (shape.hasTrait(ReferenceTrait.class)) { - return referenceStructureShape(shape); - } - final var builder = new StringBuilder(); - writer.addImportFromModule("github.com/dafny-lang/DafnyStandardLibGo", "Wrappers"); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(shape.toShapeId().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(shape)); - - String someWrapIfRequired = "%s"; - - String companionStruct; - String returnType; - if (shape.hasTrait(ErrorTrait.class)) { - companionStruct = DafnyNameResolver.getDafnyErrorCompanionCreate(shape, context.symbolProvider().toSymbol(shape)); - returnType = DafnyNameResolver.getDafnyBaseErrorType(shape); - } else { - companionStruct = DafnyNameResolver.getDafnyCompanionTypeCreate(shape, context.symbolProvider().toSymbol(shape)); - returnType = DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)); - } - String nilWrapIfRequired = returnType.concat("{}"); - - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - var goCodeBlock = """ - func () %s { - %s - return %s - }()"""; - - - builder.append("%1$s(".formatted(companionStruct)); - String fieldSeparator = ","; - for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { - final var memberName = memberShapeEntry.getKey(); - final var memberShape = memberShapeEntry.getValue(); - final var targetShape = context.model().expectShape(memberShape.getTarget()); - builder.append("%1$s%2$s".formatted( - targetShape.accept( - new SmithyToDafnyShapeVisitor(context, dataSource + "." + StringUtils.capitalize(memberName), - writer, isConfigShape, memberShape.isOptional(), context.symbolProvider().toSymbol(memberShape).getProperty(POINTABLE, Boolean.class).orElse(false) - )), fieldSeparator - )); - } - - - return goCodeBlock.formatted(returnType, nilCheck, someWrapIfRequired.formatted(builder.append(")").toString())); + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); } - - @Override - public String mapShape(MapShape shape) { - StringBuilder builder = new StringBuilder(); - - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - MemberShape keyMemberShape = shape.getKey(); - final Shape keyTargetShape = context.model().expectShape(keyMemberShape.getTarget()); - MemberShape valueMemberShape = shape.getValue(); - final Shape valueTargetShape = context.model().expectShape(valueMemberShape.getTarget()); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Map"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - builder.append(""" - func () %s { - if %s == nil { return %s } - fieldValue := dafny.NewMapBuilder() - for key, val := range %s { - fieldValue.Add(%s, %s) - } - return %s - }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, - keyTargetShape.accept( - new SmithyToDafnyShapeVisitor(context, "key", writer, isConfigShape, false, false)), - valueTargetShape.accept( - new SmithyToDafnyShapeVisitor(context, "val", writer, isConfigShape, false, false)), - someWrapIfRequired.formatted("fieldValue.ToMap()") - ) - ); - - // Close structure - return builder.toString(); - + var goCodeBlock = + """ + func () %s { + %s + return %s + }()"""; + + builder.append("%1$s(".formatted(companionStruct)); + String fieldSeparator = ","; + for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { + final var memberName = memberShapeEntry.getKey(); + final var memberShape = memberShapeEntry.getValue(); + final var targetShape = context + .model() + .expectShape(memberShape.getTarget()); + builder.append( + "%1$s%2$s".formatted( + targetShape.accept( + new SmithyToDafnyShapeVisitor( + context, + dataSource + "." + StringUtils.capitalize(memberName), + writer, + isConfigShape, + memberShape.isOptional(), + context + .symbolProvider() + .toSymbol(memberShape) + .getProperty(POINTABLE, Boolean.class) + .orElse(false) + ) + ), + fieldSeparator + ) + ); } - @Override - public String listShape(ListShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - StringBuilder builder = new StringBuilder(); - - MemberShape memberShape = shape.getMember(); - final Shape targetShape = context.model().expectShape(memberShape.getTarget()); - - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - - builder.append(""" - func () %s { - if %s == nil { return %s } - var fieldValue []interface{} = make([]interface{}, 0) - for _, val := range %s { - element := %s - fieldValue = append(fieldValue, element) - } - return %s - }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, - targetShape.accept( - new SmithyToDafnyShapeVisitor(context, "val", writer, isConfigShape, false, false) - ), someWrapIfRequired.formatted("dafny.SeqOf(fieldValue...)"))); - - // Close structure - return builder.toString(); + return goCodeBlock.formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(builder.append(")").toString()) + ); + } + + @Override + public String mapShape(MapShape shape) { + StringBuilder builder = new StringBuilder(); + + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + MemberShape keyMemberShape = shape.getKey(); + final Shape keyTargetShape = context + .model() + .expectShape(keyMemberShape.getTarget()); + MemberShape valueMemberShape = shape.getValue(); + final Shape valueTargetShape = context + .model() + .expectShape(valueMemberShape.getTarget()); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Map"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - - @Override - public String booleanShape(BooleanShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s%s"; - String returnType = "interface {}"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; - } - - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); + builder.append( + """ + func () %s { + if %s == nil { return %s } + fieldValue := dafny.NewMapBuilder() + for key, val := range %s { + fieldValue.Add(%s, %s) + } + return %s + }()""".formatted( + returnType, + dataSource, + nilWrapIfRequired, + dataSource, + keyTargetShape.accept( + new SmithyToDafnyShapeVisitor( + context, + "key", + writer, + isConfigShape, + false, + false + ) + ), + valueTargetShape.accept( + new SmithyToDafnyShapeVisitor( + context, + "val", + writer, + isConfigShape, + false, + false + ) + ), + someWrapIfRequired.formatted("fieldValue.ToMap()") + ) + ); + + // Close structure + return builder.toString(); + } + + @Override + public String listShape(ListShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + StringBuilder builder = new StringBuilder(); + + MemberShape memberShape = shape.getMember(); + final Shape targetShape = context + .model() + .expectShape(memberShape.getTarget()); + + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - @Override - public String stringShape(StringShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (shape.hasTrait(EnumTrait.class)) { - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)); - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } + builder.append( + """ + func () %s { + if %s == nil { return %s } + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range %s { + element := %s + fieldValue = append(fieldValue, element) + } + return %s + }()""".formatted( + returnType, + dataSource, + nilWrapIfRequired, + dataSource, + targetShape.accept( + new SmithyToDafnyShapeVisitor( + context, + "val", + writer, + isConfigShape, + false, + false + ) + ), + someWrapIfRequired.formatted("dafny.SeqOf(fieldValue...)") + ) + ); + + // Close structure + return builder.toString(); + } + + @Override + public String booleanShape(BooleanShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s%s"; + String returnType = "interface {}"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; + } - var nilCheck = ""; - var dereferenceIfRequired = isPointerType ? "*" : ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - return """ - func () %s { - %s - var index int - for _, enumVal := range %s.Values() { - index++ - if enumVal == %s%s{ - break; - } - } - var enum interface{} - for allEnums, i := dafny.Iterate(%s{}.AllSingletonConstructors()), 0; i < index; i++ { - var ok bool - enum, ok = allEnums() - if !ok { - break; - } - } - return %s - }()""".formatted(returnType, nilCheck, dataSource, dereferenceIfRequired, dataSource, DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), someWrapIfRequired.formatted("enum.(%s)".formatted(DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))))); - } else { - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } - var nilCheck = ""; - var dereferenceIfRequired = isPointerType ? "*" : ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) + ); + } + + @Override + public String stringShape(StringShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (shape.hasTrait(EnumTrait.class)) { + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ); + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + var nilCheck = ""; + var dereferenceIfRequired = isPointerType ? "*" : ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + return """ + func () %s { + %s + var index int + for _, enumVal := range %s.Values() { + index++ + if enumVal == %s%s{ + break; + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(%s{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break; + } + } + return %s + }()""".formatted( + returnType, + nilCheck, + dataSource, + dereferenceIfRequired, + dataSource, + DafnyNameResolver.getDafnyCompanionStructType( + shape, + context.symbolProvider().toSymbol(shape) + ), + someWrapIfRequired.formatted( + "enum.(%s)".formatted( + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ) + ) + ) + ); + } else { + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + var nilCheck = ""; + var dereferenceIfRequired = isPointerType ? "*" : ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + + if (shape.hasTrait(DafnyUtf8BytesTrait.class)) writer.addUseImports( + SmithyGoDependency.stdlib("unicode/utf8") + ); + + var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) + ? """ + dafny.SeqOf(func () []interface{} { + utf8.ValidString(%s%s) + b := []byte(%s%s) + f := make([]interface{}, len(b)) + for i, v := range b { + f[i] = v } - - if (shape.hasTrait(DafnyUtf8BytesTrait.class)) - writer.addUseImports(SmithyGoDependency.stdlib("unicode/utf8")); - - var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) ? """ - dafny.SeqOf(func () []interface{} { - utf8.ValidString(%s%s) - b := []byte(%s%s) - f := make([]interface{}, len(b)) - for i, v := range b { - f[i] = v - } - return f - }()...)""".formatted(dereferenceIfRequired, dataSource, dereferenceIfRequired, dataSource) : "dafny.SeqOfChars([]dafny.Char(%s%s)...)".formatted(dereferenceIfRequired, dataSource); - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(underlyingType)); - } + return f + }()...)""".formatted( + dereferenceIfRequired, + dataSource, + dereferenceIfRequired, + dataSource + ) + : "dafny.SeqOfChars([]dafny.Char(%s%s)...)".formatted( + dereferenceIfRequired, + dataSource + ); + + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(underlyingType) + ); } - - @Override - public String integerShape(IntegerShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s%s"; - String returnType = "interface {}"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; - } - - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); - + } + + @Override + public String integerShape(IntegerShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s%s"; + String returnType = "interface {}"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; } - @Override - public String longShape(LongShape shape) { - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s%s"; - String returnType = "interface {}"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; - } - - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); } - @Override - public String doubleShape(DoubleShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); - writer.addUseImports(SmithyGoDependency.MATH); - - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "interface {}"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) + ); + } + + @Override + public String longShape(LongShape shape) { + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s%s"; + String returnType = "interface {}"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; + } - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } - return """ - func () %s { - %s - var bits = math.Float64bits(%s%s) - var bytes = make([]byte, 8) - binary.LittleEndian.PutUint64(bytes, bits) - var v []interface{} - for _, e := range bytes { - v = append(v, e) - } - return %s; - }()""".formatted(returnType, nilCheck, dereferenceIfRequired, dataSource, someWrapIfRequired.formatted("dafny.SeqOf(v...)")); + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) + ); + } + + @Override + public String doubleShape(DoubleShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); + writer.addUseImports(SmithyGoDependency.MATH); + + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "interface {}"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - @Override - public String unionShape(UnionShape shape) { - final String internalDafnyType = DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)); - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - final String functionInit = """ - func() Wrappers.Option { - switch %s.(type) {""".formatted(dataSource); - StringBuilder eachMemberInUnion = new StringBuilder(); - for (var member : shape.getAllMembers().values()) { - final String memberName = context.symbolProvider().toMemberName(member); - final Shape targetShape = context.model().expectShape(member.getTarget()); - final String someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s(%s))"; - final String baseType = DafnyNameResolver.getDafnyType(targetShape, context.symbolProvider().toSymbol(targetShape)); - eachMemberInUnion.append(""" - case *%s.%s: - var companion = %s - var inputToConversion = %s - return %s - """.formatted( - SmithyNameResolver.smithyTypesNamespace(shape), - context.symbolProvider().toMemberName(member), - internalDafnyType.replace(shape.getId().getName(), "CompanionStruct_" + shape.getId().getName() + "_{}"), - targetShape.accept( - new SmithyToDafnyShapeVisitor( - context, dataSource + ".(*" + SmithyNameResolver.smithyTypesNamespace(shape) + "." + context.symbolProvider().toMemberName(member) + ").Value", writer, isConfigShape, true, false - ) - ), - someWrapIfRequired.formatted( - DafnyNameResolver.getDafnyCreateFuncForUnionMemberShape(shape, memberName), - "inputToConversion.UnwrapOr(nil)%s".formatted(baseType != "" ? ".(" + baseType + ")" : "") - ) - )); - } - final String defaultCase = """ - default: - panic("Unhandled union type") - } - }()"""; - return """ - %s - %s - %s""".formatted( - functionInit, - eachMemberInUnion, - defaultCase - ); + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); } - @Override - public String timestampShape(TimestampShape shape) { - return "Wrappers.Companion_Option_.Create_None_()"; + return """ + func () %s { + %s + var bits = math.Float64bits(%s%s) + var bytes = make([]byte, 8) + binary.LittleEndian.PutUint64(bytes, bits) + var v []interface{} + for _, e := range bytes { + v = append(v, e) + } + return %s; + }()""".formatted( + returnType, + nilCheck, + dereferenceIfRequired, + dataSource, + someWrapIfRequired.formatted("dafny.SeqOf(v...)") + ); + } + + @Override + public String unionShape(UnionShape shape) { + final String internalDafnyType = DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ); + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + final String functionInit = + """ + func() Wrappers.Option { + switch %s.(type) {""".formatted(dataSource); + StringBuilder eachMemberInUnion = new StringBuilder(); + for (var member : shape.getAllMembers().values()) { + final String memberName = context.symbolProvider().toMemberName(member); + final Shape targetShape = context.model().expectShape(member.getTarget()); + final String someWrapIfRequired = + "Wrappers.Companion_Option_.Create_Some_(%s(%s))"; + final String baseType = DafnyNameResolver.getDafnyType( + targetShape, + context.symbolProvider().toSymbol(targetShape) + ); + eachMemberInUnion.append( + """ + case *%s.%s: + var companion = %s + var inputToConversion = %s + return %s + """.formatted( + SmithyNameResolver.smithyTypesNamespace(shape), + context.symbolProvider().toMemberName(member), + internalDafnyType.replace( + shape.getId().getName(), + "CompanionStruct_" + shape.getId().getName() + "_{}" + ), + targetShape.accept( + new SmithyToDafnyShapeVisitor( + context, + dataSource + + ".(*" + + SmithyNameResolver.smithyTypesNamespace(shape) + + "." + + context.symbolProvider().toMemberName(member) + + ").Value", + writer, + isConfigShape, + true, + false + ) + ), + someWrapIfRequired.formatted( + DafnyNameResolver.getDafnyCreateFuncForUnionMemberShape( + shape, + memberName + ), + "inputToConversion.UnwrapOr(nil)%s".formatted( + baseType != "" ? ".(" + baseType + ")" : "" + ) + ) + ) + ); } -} \ No newline at end of file + final String defaultCase = + """ + default: + panic("Unhandled union type") + } + }()"""; + return """ + %s + %s + %s""".formatted(functionInit, eachMemberInUnion, defaultCase); + } + + @Override + public String timestampShape(TimestampShape shape) { + return "Wrappers.Companion_Option_.Create_None_()"; + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/utils/GoCodegenUtils.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/utils/GoCodegenUtils.java index 086859e8ee..00f7ade743 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/utils/GoCodegenUtils.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/utils/GoCodegenUtils.java @@ -13,36 +13,50 @@ public class GoCodegenUtils { - public static String getType(Symbol symbol, ServiceTrait serviceTrait) { - if (symbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class).isEmpty()) { - return SmithyNameResolver.getSmithyTypeAws(serviceTrait, symbol, true); - } - var type = getType(symbol.expectProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class), serviceTrait); - if(symbol.getProperty(SymbolUtils.GO_MAP).isPresent()) { - return "map[string]" + type; - } - if (symbol.getProperty(SymbolUtils.GO_SLICE).isPresent()) { - return "[]" + type; - } - throw new RuntimeException("Failed to determine shape type"); + public static String getType(Symbol symbol, ServiceTrait serviceTrait) { + if ( + symbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class).isEmpty() + ) { + return SmithyNameResolver.getSmithyTypeAws(serviceTrait, symbol, true); } - - public static Symbol getRootSymbol(Symbol symbol) { - if (symbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class).isEmpty()) { - return symbol; - } - return getRootSymbol(symbol.expectProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class)); + var type = getType( + symbol.expectProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class), + serviceTrait + ); + if (symbol.getProperty(SymbolUtils.GO_MAP).isPresent()) { + return "map[string]" + type; + } + if (symbol.getProperty(SymbolUtils.GO_SLICE).isPresent()) { + return "[]" + type; } + throw new RuntimeException("Failed to determine shape type"); + } - public static boolean isOperationStruct(Model model, Shape shape) { - NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); - for (Relationship relationship : provider.getNeighbors(shape)) { - RelationshipType relationshipType = relationship.getRelationshipType(); - if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { - return true; - } - } + public static Symbol getRootSymbol(Symbol symbol) { + if ( + symbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class).isEmpty() + ) { + return symbol; + } + return getRootSymbol( + symbol.expectProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class) + ); + } - return false; + public static boolean isOperationStruct(Model model, Shape shape) { + NeighborProvider provider = NeighborProviderIndex + .of(model) + .getReverseProvider(); + for (Relationship relationship : provider.getNeighbors(shape)) { + RelationshipType relationshipType = relationship.getRelationshipType(); + if ( + relationshipType == RelationshipType.INPUT || + relationshipType == RelationshipType.OUTPUT + ) { + return true; + } } + + return false; + } } From ca4d375e21c76aa4dc2a45bd734670b5e8e0961c Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 9 Sep 2024 11:16:19 -0700 Subject: [PATCH 41/44] Revert "Merge branch 'Golang/dev' into rishav-positional" This reverts commit 61d7284d9495a08ba5284a540ca1e4ed8022479b, reversing changes made to 0a707a2e66fc492740d6a2c9b5b83eb0b569eca8. --- .github/workflows/manual.yml | 4 - .github/workflows/nightly_dafny.yml | 1 - .github/workflows/pull.yml | 29 +- .github/workflows/push.yml | 13 +- .github/workflows/test_models_go_tests.yml | 162 +- .github/workflows/test_models_rust_tests.yml | 2 +- SmithyDafnyMakefile.mk | 12 +- .../rust/src/standard_library_externs.rs | 80 - TestModels/Constraints/removeDotFromExtern.sh | 27 + .../rust/src/standard_library_externs.rs | 80 - TestModels/Errors/runtimes/rust/Cargo.toml | 8 +- .../rust/src/implementation_from_dafny.rs-e | 1745 +++++++++++++++ .../rust/src/standard_library_externs.rs | 80 - .../rust/src/standard_library_externs.rs | 80 - .../rust/src/standard_library_externs.rs | 80 - .../rust/src/standard_library_externs.rs | 80 - TestModels/SimpleTypes/SimpleBlob/Makefile | 3 +- .../SimpleBlob/runtimes/rust/Cargo.toml | 8 +- .../SimpleBlob/runtimes/rust/src/client.rs | 16 +- .../runtimes/rust/src/client/get_blob.rs | 8 +- .../rust/src/client/get_blob_known_value.rs | 17 + .../src/client/get_blob_known_value_test.rs | 15 - .../runtimes/rust/src/conversions.rs | 12 +- .../runtimes/rust/src/conversions/error.rs | 32 - .../runtimes/rust/src/conversions/get_blob.rs | 16 +- .../conversions/get_blob/_get_blob_input.rs | 44 +- .../conversions/get_blob/_get_blob_output.rs | 45 +- .../src/conversions/get_blob_known_value.rs | 39 + .../_get_blob_known_value_input.rs | 41 + .../_get_blob_known_value_output.rs | 43 + .../conversions/get_blob_known_value_test.rs | 33 - .../_get_blob_known_value_test_input.rs | 24 - .../_get_blob_known_value_test_output.rs | 24 - .../src/conversions/simple_blob_config.rs | 5 +- .../simple_blob_config/_simple_blob_config.rs | 9 +- .../SimpleBlob/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleBlob/runtimes/rust/src/lib.rs | 19 + .../SimpleBlob/runtimes/rust/src/operation.rs | 9 +- .../runtimes/rust/src/operation/get_blob.rs | 19 +- .../src/operation/get_blob/_get_blob_input.rs | 50 +- .../operation/get_blob/_get_blob_output.rs | 56 +- .../rust/src/operation/get_blob/builders.rs | 38 +- ..._value_test.rs => get_blob_known_value.rs} | 58 +- .../_get_blob_known_value_input.rs | 63 + .../_get_blob_known_value_output.rs | 63 + .../get_blob_known_value/builders.rs | 80 + .../_get_blob_input.rs | 58 - .../_get_blob_output.rs | 58 - .../get_blob_known_value_test/builders.rs | 74 - .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 - .../SimpleBlob/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_blob_config.rs | 5 +- .../SimpleBlob/runtimes/rust/src/wrapped.rs | 15 - .../runtimes/rust/src/wrapped/client.rs | 119 -- .../runtimes/rust/tests/simple_blob_test.rs | 10 +- .../rust/src/standard_library_externs.rs | 80 - TestModels/SimpleTypes/SimpleDouble/Makefile | 3 +- .../SimpleDouble/runtimes/rust/Cargo.toml | 8 +- .../SimpleDouble/runtimes/rust/src/client.rs | 7 +- .../runtimes/rust/src/client/get_double.rs | 8 +- .../runtimes/rust/src/conversions.rs | 10 +- .../runtimes/rust/src/conversions/error.rs | 32 - .../rust/src/conversions/get_double.rs | 8 +- .../get_double/_get_double_input.rs | 45 +- .../get_double/_get_double_output.rs | 45 +- .../src/conversions/simple_double_config.rs | 5 +- .../_simple_double_config.rs | 6 +- .../SimpleDouble/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleDouble/runtimes/rust/src/lib.rs | 19 + .../runtimes/rust/src/operation.rs | 5 +- .../runtimes/rust/src/operation/get_double.rs | 8 +- .../operation/get_double/_get_double_input.rs | 40 +- .../get_double/_get_double_output.rs | 46 +- .../rust/src/operation/get_double/builders.rs | 32 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 - .../SimpleDouble/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_double_config.rs | 5 +- .../SimpleDouble/runtimes/rust/src/wrapped.rs | 15 - .../runtimes/rust/src/wrapped/client.rs | 89 - TestModels/SimpleTypes/SimpleEnum/Makefile | 3 +- .../SimpleEnum/runtimes/rust/Cargo.toml | 8 +- .../SimpleEnum/runtimes/rust/src/client.rs | 9 +- .../runtimes/rust/src/client/get_enum.rs | 8 +- .../client/get_enum_first_known_value_test.rs | 23 +- .../get_enum_second_known_value_test.rs | 23 +- .../client/get_enum_third_known_value_test.rs | 23 +- .../runtimes/rust/src/conversions.rs | 21 +- .../runtimes/rust/src/conversions/error.rs | 32 - .../runtimes/rust/src/conversions/get_enum.rs | 5 +- .../conversions/get_enum/_get_enum_input.rs | 53 +- .../conversions/get_enum/_get_enum_output.rs | 53 +- .../get_enum_first_known_value_test.rs | 5 +- .../_get_enum_first_known_value_test_input.rs | 57 +- ..._get_enum_first_known_value_test_output.rs | 57 +- .../get_enum_second_known_value_test.rs | 5 +- ..._get_enum_second_known_value_test_input.rs | 57 +- ...get_enum_second_known_value_test_output.rs | 57 +- .../get_enum_third_known_value_test.rs | 5 +- .../_get_enum_third_known_value_test_input.rs | 57 +- ..._get_enum_third_known_value_test_output.rs | 57 +- .../src/conversions/simple_enum_config.rs | 5 +- .../simple_enum_config/_simple_enum_config.rs | 6 +- .../rust/src/conversions/simple_enum_shape.rs | 26 +- .../simple_enum_shape/_simple_enum_shape.rs | 23 + .../SimpleEnum/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleEnum/runtimes/rust/src/lib.rs | 19 + .../SimpleEnum/runtimes/rust/src/operation.rs | 11 +- .../runtimes/rust/src/operation/get_enum.rs | 19 +- .../src/operation/get_enum/_get_enum_input.rs | 55 +- .../operation/get_enum/_get_enum_output.rs | 59 +- .../rust/src/operation/get_enum/builders.rs | 40 +- .../get_enum_first_known_value_test.rs | 36 +- .../_get_enum_first_known_value_test_input.rs | 69 + ..._get_enum_first_known_value_test_output.rs | 69 + .../_get_enum_input.rs | 58 - .../_get_enum_output.rs | 58 - .../builders.rs | 62 +- .../get_enum_second_known_value_test.rs | 40 +- .../_get_enum_input.rs | 58 - .../_get_enum_output.rs | 58 - ..._get_enum_second_known_value_test_input.rs | 69 + ...get_enum_second_known_value_test_output.rs | 69 + .../builders.rs | 61 +- .../get_enum_third_known_value_test.rs | 36 +- .../_get_enum_input.rs | 58 - .../_get_enum_output.rs | 58 - .../_get_enum_third_known_value_test_input.rs | 68 + ..._get_enum_third_known_value_test_output.rs | 69 + .../builders.rs | 62 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 - .../SimpleEnum/runtimes/rust/src/types.rs | 11 +- .../rust/src/types/_simple_enum_shape.rs | 19 - .../rust/src/types/simple_enum_config.rs | 5 +- .../rust/src/types/simple_enum_shape.rs | 6 + .../SimpleEnum/runtimes/rust/src/wrapped.rs | 15 - .../runtimes/rust/src/wrapped/client.rs | 179 -- .../runtimes/rust/tests/simple_enum_test.rs | 18 +- TestModels/SimpleTypes/SimpleEnumV2/Makefile | 3 +- .../SimpleEnumV2/runtimes/rust/Cargo.toml | 8 +- .../SimpleEnumV2/runtimes/rust/src/client.rs | 9 +- .../runtimes/rust/src/client/get_enum_v2.rs | 8 +- .../get_enum_v2_first_known_value_test.rs | 23 +- .../get_enum_v2_second_known_value_test.rs | 23 +- .../get_enum_v2_third_known_value_test.rs | 23 +- .../runtimes/rust/src/conversions.rs | 21 +- .../runtimes/rust/src/conversions/error.rs | 32 - .../rust/src/conversions/get_enum_v2.rs | 16 +- .../get_enum_v2/_get_enum_v2_input.rs | 53 +- .../get_enum_v2/_get_enum_v2_output.rs | 53 +- .../get_enum_v2_first_known_value_test.rs | 5 +- ...et_enum_v2_first_known_value_test_input.rs | 59 +- ...t_enum_v2_first_known_value_test_output.rs | 59 +- .../get_enum_v2_second_known_value_test.rs | 5 +- ...t_enum_v2_second_known_value_test_input.rs | 59 +- ..._enum_v2_second_known_value_test_output.rs | 59 +- .../get_enum_v2_third_known_value_test.rs | 5 +- ...et_enum_v2_third_known_value_test_input.rs | 59 +- ...t_enum_v2_third_known_value_test_output.rs | 59 +- .../src/conversions/simple_enum_v2_config.rs | 5 +- .../_simple_enum_v2_config.rs | 6 +- .../src/conversions/simple_enum_v2_shape.rs | 26 +- .../_simple_enum_v2_shape.rs | 23 + .../SimpleEnumV2/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleEnumV2/runtimes/rust/src/lib.rs | 19 + .../runtimes/rust/src/operation.rs | 11 +- .../rust/src/operation/get_enum_v2.rs | 8 +- .../get_enum_v2/_get_enum_v2_input.rs | 51 +- .../get_enum_v2/_get_enum_v2_output.rs | 57 +- .../src/operation/get_enum_v2/builders.rs | 40 +- .../get_enum_v2_first_known_value_test.rs | 39 +- ...et_enum_v2_first_known_value_test_input.rs | 71 + ...t_enum_v2_first_known_value_test_output.rs | 71 + .../_get_enum_v2_input.rs | 58 - .../_get_enum_v2_output.rs | 58 - .../builders.rs | 62 +- .../get_enum_v2_second_known_value_test.rs | 39 +- .../_get_enum_v2_input.rs | 58 - .../_get_enum_v2_output.rs | 58 - ...t_enum_v2_second_known_value_test_input.rs | 71 + ..._enum_v2_second_known_value_test_output.rs | 71 + .../builders.rs | 61 +- .../get_enum_v2_third_known_value_test.rs | 39 +- .../_get_enum_v2_input.rs | 58 - .../_get_enum_v2_output.rs | 58 - ...et_enum_v2_third_known_value_test_input.rs | 70 + ...t_enum_v2_third_known_value_test_output.rs | 71 + .../builders.rs | 62 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 - .../SimpleEnumV2/runtimes/rust/src/types.rs | 11 +- .../rust/src/types/_simple_enum_v2_shape.rs | 19 - .../rust/src/types/simple_enum_v2_config.rs | 5 +- .../rust/src/types/simple_enum_v2_shape.rs | 6 + .../SimpleEnumV2/runtimes/rust/src/wrapped.rs | 15 - .../runtimes/rust/src/wrapped/client.rs | 179 -- .../rust/tests/simple_enum_v2_test.rs | 18 +- TestModels/SimpleTypes/SimpleInteger/Makefile | 3 +- .../SimpleInteger/runtimes/rust/Cargo.toml | 8 +- .../SimpleInteger/runtimes/rust/src/client.rs | 9 +- .../runtimes/rust/src/client/get_integer.rs | 8 +- .../src/client/get_integer_known_value.rs | 18 + .../client/get_integer_known_value_test.rs | 15 - .../runtimes/rust/src/conversions.rs | 12 +- .../runtimes/rust/src/conversions/error.rs | 32 - .../rust/src/conversions/get_integer.rs | 5 +- .../get_integer/_get_integer_input.rs | 35 +- .../get_integer/_get_integer_output.rs | 35 +- .../conversions/get_integer_known_value.rs | 32 + .../_get_integer_known_value_input.rs | 37 + .../_get_integer_known_value_output.rs | 37 + .../get_integer_known_value_test.rs | 33 - .../_get_integer_known_value_test_input.rs | 24 - .../_get_integer_known_value_test_output.rs | 24 - .../src/conversions/simple_integer_config.rs | 5 +- .../_simple_integer_config.rs | 6 +- .../SimpleInteger/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleInteger/runtimes/rust/src/lib.rs | 19 + .../runtimes/rust/src/operation.rs | 9 +- .../rust/src/operation/get_integer.rs | 8 +- .../get_integer/_get_integer_input.rs | 40 +- .../get_integer/_get_integer_output.rs | 46 +- .../src/operation/get_integer/builders.rs | 34 +- ...lue_test.rs => get_integer_known_value.rs} | 65 +- .../_get_integer_known_value_input.rs | 59 + .../_get_integer_known_value_output.rs | 60 + .../get_integer_known_value/builders.rs | 78 + .../_get_integer_input.rs | 58 - .../_get_integer_output.rs | 58 - .../get_integer_known_value_test/builders.rs | 74 - .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 - .../SimpleInteger/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_integer_config.rs | 33 +- .../runtimes/rust/src/wrapped.rs | 15 - .../runtimes/rust/src/wrapped/client.rs | 119 -- .../rust/tests/simple_integer_test.rs | 2 +- TestModels/SimpleTypes/SimpleLong/Makefile | 3 +- .../SimpleLong/runtimes/rust/Cargo.toml | 8 +- .../SimpleLong/runtimes/rust/src/client.rs | 9 +- .../runtimes/rust/src/client/get_long.rs | 8 +- .../rust/src/client/get_long_known_value.rs | 17 + .../src/client/get_long_known_value_test.rs | 15 - .../runtimes/rust/src/conversions.rs | 12 +- .../runtimes/rust/src/conversions/error.rs | 32 - .../runtimes/rust/src/conversions/get_long.rs | 5 +- .../conversions/get_long/_get_long_input.rs | 35 +- .../conversions/get_long/_get_long_output.rs | 35 +- .../src/conversions/get_long_known_value.rs | 32 + .../_get_long_known_value_input.rs | 37 + .../_get_long_known_value_output.rs | 37 + .../conversions/get_long_known_value_test.rs | 33 - .../_get_long_known_value_test_input.rs | 24 - .../_get_long_known_value_test_output.rs | 24 - .../src/conversions/simple_long_config.rs | 5 +- .../simple_long_config/_simple_long_config.rs | 6 +- .../SimpleLong/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleLong/runtimes/rust/src/lib.rs | 19 + .../SimpleLong/runtimes/rust/src/operation.rs | 9 +- .../runtimes/rust/src/operation/get_long.rs | 19 +- .../src/operation/get_long/_get_long_input.rs | 44 +- .../operation/get_long/_get_long_output.rs | 50 +- .../rust/src/operation/get_long/builders.rs | 32 +- ..._value_test.rs => get_long_known_value.rs} | 58 +- .../_get_long_known_value_input.rs | 57 + .../_get_long_known_value_output.rs | 57 + .../get_long_known_value/builders.rs | 74 + .../_get_long_input.rs | 58 - .../_get_long_output.rs | 58 - .../get_long_known_value_test/builders.rs | 74 - .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 - .../SimpleLong/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_long_config.rs | 5 +- .../SimpleLong/runtimes/rust/src/wrapped.rs | 15 - .../runtimes/rust/src/wrapped/client.rs | 119 -- .../runtimes/rust/tests/simple_long_test.rs | 2 +- TestModels/SimpleTypes/SimpleString/Makefile | 3 +- .../SimpleString/runtimes/rust/Cargo.toml | 10 +- .../SimpleString/runtimes/rust/src/client.rs | 11 +- .../runtimes/rust/src/client/get_string.rs | 8 +- .../rust/src/client/get_string_known_value.rs | 18 +- .../rust/src/client/get_string_utf8.rs | 12 +- .../src/client/get_string_utf8_known_value.rs | 14 +- .../runtimes/rust/src/conversions.rs | 16 +- .../runtimes/rust/src/conversions/error.rs | 32 - .../rust/src/conversions/get_string.rs | 8 +- .../get_string/_get_string_input.rs | 41 +- .../get_string/_get_string_output.rs | 45 +- .../src/conversions/get_string_known_value.rs | 8 +- .../_get_string_known_value_input.rs | 45 +- .../_get_string_known_value_output.rs | 49 +- .../rust/src/conversions/get_string_utf8.rs | 8 +- .../get_string_utf8/_get_string_utf8_input.rs | 47 +- .../_get_string_utf8_output.rs | 53 +- .../get_string_utf8_known_value.rs | 8 +- .../_get_string_utf8_known_value_input.rs | 51 +- .../_get_string_utf8_known_value_output.rs | 57 +- .../src/conversions/simple_string_config.rs | 5 +- .../_simple_string_config.rs | 6 +- .../SimpleString/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../rust/src/implementation_from_dafny.rs-e | 1880 +++++++++++++++++ .../SimpleString/runtimes/rust/src/lib.rs | 17 + .../runtimes/rust/src/operation.rs | 6 +- .../runtimes/rust/src/operation/get_string.rs | 8 +- .../operation/get_string/_get_string_input.rs | 38 +- .../get_string/_get_string_output.rs | 38 +- .../rust/src/operation/get_string/builders.rs | 36 +- .../src/operation/get_string_known_value.rs | 35 +- .../_get_string_input.rs | 58 - .../_get_string_known_value_input.rs | 60 + .../_get_string_known_value_output.rs | 59 + .../_get_string_output.rs | 58 - .../get_string_known_value/builders.rs | 59 +- .../rust/src/operation/get_string_utf8.rs | 11 +- .../get_string_utf8/_get_string_utf8_input.rs | 38 +- .../_get_string_utf8_output.rs | 38 +- .../src/operation/get_string_utf8/builders.rs | 42 +- .../operation/get_string_utf8_known_value.rs | 19 +- .../_get_string_utf8_input.rs | 58 - .../_get_string_utf8_known_value_input.rs | 56 + .../_get_string_utf8_known_value_output.rs | 56 + .../_get_string_utf8_output.rs | 58 - .../get_string_utf8_known_value/builders.rs | 52 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 - .../SimpleString/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_string_config.rs | 5 +- .../SimpleString/runtimes/rust/src/wrapped.rs | 15 - .../runtimes/rust/src/wrapped/client.rs | 179 -- .../SimpleTypes/SimpleTimestamp/Makefile | 5 +- .../SimpleTimestamp/runtimes/rust/Cargo.toml | 11 +- .../runtimes/rust/src/client.rs | 7 +- .../runtimes/rust/src/client/get_timestamp.rs | 12 +- .../runtimes/rust/src/conversions.rs | 10 +- .../runtimes/rust/src/conversions/error.rs | 32 - .../rust/src/conversions/get_timestamp.rs | 8 +- .../get_timestamp/_get_timestamp_input.rs | 39 +- .../get_timestamp/_get_timestamp_output.rs | 39 +- .../conversions/simple_timestamp_config.rs | 5 +- .../_simple_timestamp_config.rs | 8 +- .../runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleTimestamp/runtimes/rust/src/lib.rs | 19 + .../runtimes/rust/src/operation.rs | 5 +- .../rust/src/operation/get_timestamp.rs | 15 +- .../get_timestamp/_get_timestamp_input.rs | 44 +- .../get_timestamp/_get_timestamp_output.rs | 55 +- .../src/operation/get_timestamp/builders.rs | 32 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 - .../runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_timestamp_config.rs | 5 +- .../runtimes/rust/src/wrapped.rs | 15 - .../runtimes/rust/src/wrapped/client.rs | 89 - .../rust/tests/simple_timestamp_test.rs | 2 +- .../src/WrappedSimpleTypesTimestampImpl.dfy | 10 - .../test/SimpleTimestampImplTest.dfy | 22 +- .../test/WrappedSimpleTimestampTest.dfy | 1 - .../rust/src/standard_library_externs.rs | 80 - .../rust/src/conversions/attribute_action.rs | 12 +- .../batch_statement_error_code_enum.rs | 44 +- .../rust/src/conversions/billing_mode.rs | 8 +- .../src/conversions/comparison_operator.rs | 52 +- .../src/conversions/conditional_operator.rs | 8 +- .../rust/src/conversions/index_status.rs | 16 +- .../runtimes/rust/src/conversions/key_type.rs | 8 +- .../rust/src/conversions/projection_type.rs | 12 +- .../rust/src/conversions/replica_status.rs | 28 +- .../conversions/return_consumed_capacity.rs | 12 +- .../return_item_collection_metrics.rs | 8 +- .../rust/src/conversions/return_value.rs | 20 +- ...eturn_values_on_condition_check_failure.rs | 8 +- .../src/conversions/scalar_attribute_type.rs | 12 +- .../runtimes/rust/src/conversions/select.rs | 16 +- .../rust/src/conversions/sse_status.rs | 20 +- .../runtimes/rust/src/conversions/sse_type.rs | 8 +- .../rust/src/conversions/stream_view_type.rs | 16 +- .../rust/src/conversions/table_class.rs | 8 +- .../rust/src/conversions/table_status.rs | 28 +- .../rust/src/standard_library_externs.rs | 80 - .../conversions/customer_master_key_spec.rs | 52 +- .../rust/src/conversions/data_key_spec.rs | 8 +- .../conversions/encryption_algorithm_spec.rs | 12 +- .../key_agreement_algorithm_spec.rs | 4 +- .../conversions/key_encryption_mechanism.rs | 4 +- .../runtimes/rust/src/conversions/key_spec.rs | 52 +- .../rust/src/conversions/key_usage_type.rs | 16 +- .../rust/src/conversions/origin_type.rs | 16 +- .../src/conversions/signing_algorithm_spec.rs | 40 +- .../rust/src/standard_library_externs.rs | 80 - .../software/amazon/polymorph/CodegenCli.java | 25 +- .../polymorph/smithygo/GoTestModels.java | 47 - .../amazon/polymorph/CodegenEngine.java | 148 +- .../smithydotnet/TypeConversionCodegen.java | 17 +- .../awssdk/AwsSdkGoPointableIndex.java | 418 ++-- .../DafnyAwsSdkClientShimGenerator.java | 233 +- ...fnyAwsSdkClientTypeConversionProtocol.java | 1070 +++------- .../DafnyGoAwsSdkClientCodegenPlugin.java | 76 +- .../awssdk/DafnyGoAwsSdkDirectedCodegen.java | 134 +- .../AwsSdkToDafnyShapeVisitor.java | 870 ++++---- .../DafnyToAwsSdkShapeVisitor.java | 830 +++----- .../smithygo/codegen/AddOperationShapes.java | 191 +- .../smithygo/codegen/ApplicationProtocol.java | 8 +- .../smithygo/codegen/CodegenUtils.java | 751 ++++--- .../smithygo/codegen/EnumGenerator.java | 142 +- .../smithygo/codegen/GenerationContext.java | 264 ++- .../smithygo/codegen/GoDelegator.java | 7 +- .../smithygo/codegen/GoDependency.java | 604 +++--- .../smithygo/codegen/GoSettings.java | 346 ++- .../polymorph/smithygo/codegen/GoWriter.java | 1480 ++++++------- .../smithygo/codegen/ImportDeclarations.java | 93 +- .../smithygo/codegen/IntEnumGenerator.java | 119 +- .../smithygo/codegen/SmithyGoDependency.java | 261 +-- .../smithygo/codegen/StructureGenerator.java | 163 +- .../smithygo/codegen/SymbolUtils.java | 382 ++-- .../smithygo/codegen/SymbolVisitor.java | 1039 ++++----- .../polymorph/smithygo/codegen/Synthetic.java | 168 +- .../smithygo/codegen/UnionGenerator.java | 185 +- .../smithygo/codegen/ValidationGenerator.java | 623 +++--- .../codegen/integration/GoIntegration.java | 4 +- .../integration/ProtocolGenerator.java | 78 +- .../codegen/knowledge/GoPointableIndex.java | 438 ++-- .../codegen/knowledge/GoUsageIndex.java | 119 +- .../codegen/knowledge/GoValidationIndex.java | 346 ++- .../localservice/DafnyGoPointableIndex.java | 9 +- .../DafnyLocalServiceCodegenPlugin.java | 78 +- .../DafnyLocalServiceDirectedCodegen.java | 272 +-- .../DafnyLocalServiceGenerator.java | 1162 ++++------ ...fnyLocalServiceTypeConversionProtocol.java | 1477 +++++-------- .../localservice/nameresolver/Constants.java | 9 +- .../nameresolver/DafnyNameResolver.java | 327 ++- .../nameresolver/SmithyNameResolver.java | 161 +- .../DafnyToSmithyShapeVisitor.java | 943 ++++----- .../SmithyToDafnyShapeVisitor.java | 1033 ++++----- .../smithygo/utils/GoCodegenUtils.java | 68 +- .../generator/AbstractRustShimGenerator.java | 402 ++-- .../generator/RustAwsSdkShimGenerator.java | 86 +- .../generator/RustLibraryShimGenerator.java | 163 +- .../amazon/polymorph/utils/ModelUtils.java | 30 - .../runtimes/rust/conversions/operation.rs | 4 +- .../runtimes/rust/operation/outer.rs | 4 +- .../rust/src/standard_library_externs.rs | 80 - .../templates/runtimes/rust/types.rs | 4 +- .../templates/runtimes/rust/types/enum.rs | 12 - .../wrapped/client_operation_impl.part.rs | 4 +- .../smithyjava/ForEachDafnyTest.java | 1 - 456 files changed, 17478 insertions(+), 19904 deletions(-) delete mode 100644 TestModels/Aggregate/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/Constraints/removeDotFromExtern.sh delete mode 100644 TestModels/Constructor/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/Errors/runtimes/rust/src/implementation_from_dafny.rs-e delete mode 100644 TestModels/Errors/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/LanguageSpecificLogic/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/Refinement/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/Resource/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value_test.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/error.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_input.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/lib.rs rename TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/{get_blob_known_value_test.rs => get_blob_known_value.rs} (67%) create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_input.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_output.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/builders.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/builders.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped/client.rs delete mode 100644 TestModels/SimpleTypes/SimpleBoolean/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/error.rs create mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/lib.rs delete mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped.rs delete mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped/client.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/error.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape/_simple_enum_shape.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/lib.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/_simple_enum_shape.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_shape.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped/client.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/error.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape/_simple_enum_v2_shape.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/lib.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/_simple_enum_v2_shape.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_shape.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped/client.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value_test.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/error.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_input.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/lib.rs rename TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/{get_integer_known_value_test.rs => get_integer_known_value.rs} (67%) create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_input.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_output.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/builders.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/builders.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped/client.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value_test.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/error.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_input.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/lib.rs rename TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/{get_long_known_value_test.rs => get_long_known_value.rs} (67%) create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_input.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_output.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/builders.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/builders.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped/client.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/error.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/implementation_from_dafny.rs-e create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/lib.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_input.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_input.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_input.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped/client.rs delete mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/error.rs create mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/lib.rs delete mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped.rs delete mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped/client.rs delete mode 100644 TestModels/SimpleTypes/SimpleTimestamp/src/WrappedSimpleTypesTimestampImpl.dfy delete mode 100644 TestModels/Union/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/aws-sdks/ddb-lite/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/aws-sdks/kms-lite/runtimes/rust/src/standard_library_externs.rs delete mode 100644 codegen/smithy-dafny-codegen-test/src/test/java/software/amazon/polymorph/smithygo/GoTestModels.java delete mode 100644 codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/src/standard_library_externs.rs delete mode 100644 codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types/enum.rs diff --git a/.github/workflows/manual.yml b/.github/workflows/manual.yml index fc44ba70e6..de51a9e953 100644 --- a/.github/workflows/manual.yml +++ b/.github/workflows/manual.yml @@ -32,7 +32,3 @@ jobs: uses: ./.github/workflows/test_models_python_tests.yml with: dafny: ${{ inputs.dafny }} - manual-ci-go: - uses: ./.github/workflows/test_models_go_tests.yml - with: - dafny: ${{ inputs.dafny }} diff --git a/.github/workflows/nightly_dafny.yml b/.github/workflows/nightly_dafny.yml index 20b5baa2b4..4edb7ab15f 100644 --- a/.github/workflows/nightly_dafny.yml +++ b/.github/workflows/nightly_dafny.yml @@ -50,7 +50,6 @@ jobs: dafny-nightly-java, dafny-nightly-net, dafny-nightly-rust, - dafny-nightly-python, ] if: ${{ always() && contains(needs.*.result, 'failure') }} env: diff --git a/.github/workflows/pull.yml b/.github/workflows/pull.yml index c1954ad279..7ee82eede0 100644 --- a/.github/workflows/pull.yml +++ b/.github/workflows/pull.yml @@ -10,10 +10,10 @@ jobs: steps: - name: Populate Dafny versions list id: populate-dafny-versions-list - run: echo "dafny-versions-list=['4.2.0', '4.4.0', '4.8.0']" >> $GITHUB_OUTPUT + run: echo "dafny-versions-list=['4.2.0', '4.4.0']" >> $GITHUB_OUTPUT - name: Populate Dafny versions list for "only new versions" languages (Python) id: populate-only-new-dafny-versions-list - run: echo "only-new-dafny-versions-list=['4.8.0']" >> $GITHUB_OUTPUT + run: echo "only-new-dafny-versions-list=['4.7.0']" >> $GITHUB_OUTPUT outputs: dafny-version-list: ${{ steps.populate-dafny-versions-list.outputs.dafny-versions-list }} only-new-dafny-version-list: ${{ steps.populate-only-new-dafny-versions-list.outputs.only-new-dafny-versions-list }} @@ -66,28 +66,3 @@ jobs: uses: ./.github/workflows/test_models_python_tests.yml with: dafny: ${{ matrix.dafny-version }} - pr-ci-go: - needs: pr-populate-dafny-versions - strategy: - fail-fast: false - matrix: - dafny-version: ${{ fromJson(needs.pr-populate-dafny-versions.outputs.only-new-dafny-version-list) }} - uses: ./.github/workflows/test_models_go_tests.yml - with: - dafny: ${{ matrix.dafny-version }} - - pr-ci-all-required: - if: always() - needs: - - pr-ci-verification - - pr-ci-java - - pr-ci-net - - pr-ci-rust - - pr-ci-python - - pr-ci-go - runs-on: ubuntu-latest - steps: - - name: Verify all required jobs passed - uses: re-actors/alls-green@release/v1 - with: - jobs: ${{ toJSON(needs) }} diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml index 2f164cb8c2..43c1298b78 100644 --- a/.github/workflows/push.yml +++ b/.github/workflows/push.yml @@ -12,10 +12,10 @@ jobs: steps: - name: Populate Dafny versions list id: populate-dafny-versions-list - run: echo "dafny-versions-list=['4.2.0', '4.4.0', '4.8.0']" >> $GITHUB_OUTPUT + run: echo "dafny-versions-list=['4.2.0', '4.4.0']" >> $GITHUB_OUTPUT - name: Populate Dafny versions list for "only new versions" languages (Python) id: populate-only-new-dafny-versions-list - run: echo "only-new-dafny-versions-list=['4.8.0']" >> $GITHUB_OUTPUT + run: echo "only-new-dafny-versions-list=['4.7.0']" >> $GITHUB_OUTPUT outputs: dafny-version-list: ${{ steps.populate-dafny-versions-list.outputs.dafny-versions-list }} only-new-dafny-version-list: ${{ steps.populate-only-new-dafny-versions-list.outputs.only-new-dafny-versions-list }} @@ -68,12 +68,3 @@ jobs: uses: ./.github/workflows/test_models_python_tests.yml with: dafny: ${{ matrix.dafny-version }} - push-ci-go: - needs: pr-populate-dafny-versions - strategy: - fail-fast: false - matrix: - dafny-version: ${{ fromJson(needs.pr-populate-dafny-versions.outputs.only-new-dafny-version-list) }} - uses: ./.github/workflows/test_models_go_tests.yml - with: - dafny: ${{ matrix.dafny-version }} diff --git a/.github/workflows/test_models_go_tests.yml b/.github/workflows/test_models_go_tests.yml index 946630e1a9..69d0d4abee 100644 --- a/.github/workflows/test_models_go_tests.yml +++ b/.github/workflows/test_models_go_tests.yml @@ -1,64 +1,81 @@ name: Library Go tests -on: - workflow_call: - inputs: - dafny: - description: "The Dafny version to run" - required: true - type: string - num_shards: - required: false - type: number - default: 5 +on: ["pull_request", "push"] jobs: - populate-matrix-dimensions: - runs-on: ubuntu-latest - steps: - - name: Populate shard list - id: populate-shard-list - run: echo "shard-list=[`seq -s , 1 ${{ inputs.num_shards }}`]" >> $GITHUB_OUTPUT - outputs: - shard-list: ${{ steps.populate-shard-list.outputs.shard-list }} - testGo: - needs: populate-matrix-dimensions + test_go: strategy: - fail-fast: false # at least for development; see all errors + fail-fast: false matrix: - shard: ${{ fromJson(needs.populate-matrix-dimensions.outputs.shard-list) }} - runs-on: "ubuntu-latest" - permissions: - id-token: write - contents: read - env: - DOTNET_CLI_TELEMETRY_OPTOUT: 1 - DOTNET_NOLOGO: 1 + library: [ + # TODO: Uncomment below before making PR + # TestModels/dafny-dependencies/StandardLibrary, # This stores current Polymorph dependencies that all TestModels depend on + TestModels/Aggregate, + # TestModels/AggregateReferences, + TestModels/CodegenPatches, + TestModels/Constraints, + TestModels/Constructor, + TestModels/Dependencies, + TestModels/Errors, + TestModels/Extendable, + TestModels/Extern, + # TestModels/LanguageSpecificLogic, + # TestModels/LocalService, + # TestModels/MultipleModels, + TestModels/Positional, + TestModels/Refinement, + TestModels/Resource, + # TestModels/SimpleTypes/BigDecimal, + # TestModels/SimpleTypes/BigInteger, + TestModels/SimpleTypes/SimpleBlob, + TestModels/SimpleTypes/SimpleBoolean, + # TestModels/SimpleTypes/SimpleByte, + TestModels/SimpleTypes/SimpleDouble, + TestModels/SimpleTypes/SimpleEnum, + # TestModels/SimpleTypes/SimpleEnumV2, + # TestModels/SimpleTypes/SimpleFloat, + TestModels/SimpleTypes/SimpleInteger, + TestModels/SimpleTypes/SimpleLong, + # TestModels/SimpleTypes/SimpleShort, + TestModels/SimpleTypes/SimpleString, + # TestModels/SimpleTypes/SimpleTimestamp, + TestModels/Union, + # TestModels/aws-sdks/ddb, + TestModels/aws-sdks/kms + ] + runs-on: "macos-12" steps: - - name: Support longpaths on Git checkout - run: | - git config --global core.longpaths true + - uses: actions/checkout@v2 - - name: Configure AWS Credentials - uses: aws-actions/configure-aws-credentials@v1 + # - name: Setup Dafny 4.5.0 + # uses: dafny-lang/setup-dafny-action@v1.7.0 + # with: + # dafny-version: 4.5.0 + # TODO: Setup Dafny once its released + - name: Setup dotnet + uses: actions/setup-dotnet@v4 with: - aws-region: us-west-2 - role-to-assume: arn:aws:iam::370957321024:role/GitHub-CI-PolymorphTestModels-Role-us-west-2 - role-session-name: PythonTests + dotnet-version: 6.0.x - - uses: actions/checkout@v3 - with: - submodules: recursive + - name: Build Dafny from source + run: | + git clone https://github.com/dafny-lang/dafny.git --recurse-submodules + cd dafny + make exe + + - name: Install Z3 version 4.12.1 + run: | + cd $GITHUB_WORKSPACE/dafny + make z3-mac - - name: Setup Dafny - uses: dafny-lang/setup-dafny-action@v1.7.0 - with: - dafny-version: ${{ inputs.dafny }} + - name: Add Dafny to PATH + run: | + echo "$GITHUB_WORKSPACE/dafny/Scripts" >> $GITHUB_PATH - name: Install Go uses: actions/setup-go@v2 with: - go-version: "1.21" + go-version: '1.21' - name: Install Go imports run: | @@ -67,36 +84,33 @@ jobs: - name: Add go mod to Dafny Runtime Go shell: bash working-directory: ./DafnyRuntimeGo - run: | + run: | go mod init github.com/dafny-lang/DafnyRuntimeGo go mod tidy - - name: Setup Java 17 for codegen - uses: actions/setup-java@v3 - with: - distribution: "corretto" - java-version: 17 - - - name: Setup smithy-dafny-conversion - uses: gradle/gradle-build-action@v2 - with: - arguments: publishToMavenLocal - build-root-directory: smithy-dafny-conversion - - - name: Install Smithy-Dafny codegen dependencies - uses: ./.github/actions/install_smithy_dafny_codegen_dependencies + - name: polymorph dafny dependencies + shell: bash + working-directory: ./TestModels/dafny-dependencies/StandardLibrary + run: | + export DAFNY_VERSION=4.6 + make polymorph_dafny + make transpile_go + make polymorph_go + cd ./runtimes/go/ImplementationFromDafny-go/ + go mod init github.com/dafny-lang/DafnyStandardLibGo + # TODO: This should handwritten (in the makefile or something) + echo "replace github.com/dafny-lang/DafnyRuntimeGo => ../../../../../DafnyRuntimeGo/" >> go.mod; - - name: Install smithy-dafny-codegen locally - uses: gradle/gradle-build-action@v2 - with: - arguments: :smithy-dafny-codegen:pTML - build-root-directory: codegen + - name: Generate Polymorph Dafny and Go code + shell: bash + working-directory: ./${{ matrix.library }} + run: | + export DAFNY_VERSION=4.6 + make polymorph_dafny + sh ./removeDotFromExtern.sh + make transpile_go + make polymorph_go - - name: Execute smithy-dafny-codegen-test tests - uses: gradle/gradle-build-action@v2 - env: - JUNIT_SHARD: ${{ matrix.shard }} - JUNIT_SHARD_COUNT: ${{ inputs.num_shards }} - with: - arguments: :smithy-dafny-codegen-test:test --tests '*smithygo*' --info - build-root-directory: codegen + goimports -w runtimes/go/ + cd runtimes/go/TestsFromDafny-go/ + go run TestsFromDafny.go \ No newline at end of file diff --git a/.github/workflows/test_models_rust_tests.yml b/.github/workflows/test_models_rust_tests.yml index 7833df745f..5d0175142e 100644 --- a/.github/workflows/test_models_rust_tests.yml +++ b/.github/workflows/test_models_rust_tests.yml @@ -59,7 +59,7 @@ jobs: - name: Set up Rust uses: actions-rust-lang/setup-rust-toolchain@v1 with: - toolchain: "1.80.0" + toolchain: "1.76.0" rustflags: "" components: rustfmt diff --git a/SmithyDafnyMakefile.mk b/SmithyDafnyMakefile.mk index 6f598e4f7b..766df9d585 100644 --- a/SmithyDafnyMakefile.mk +++ b/SmithyDafnyMakefile.mk @@ -434,7 +434,7 @@ _polymorph_dafny: OUTPUT_DAFNY=\ --output-dafny $(if $(DIR_STRUCTURE_V2), $(LIBRARY_ROOT)/dafny/$(SERVICE)/Model, $(LIBRARY_ROOT)/Model) _polymorph_dafny: INPUT_DAFNY=\ --include-dafny $(PROJECT_ROOT)/$(STD_LIBRARY)/src/Index.dfy -_polymorph_dafny: _polymorph +_polymorph_dafny: _polymorph removeDots # Generates dotnet code for all namespaces in this project .PHONY: polymorph_dotnet @@ -767,10 +767,6 @@ clean_go: rm -rf $(LIBRARY_ROOT)/runtimes/go/ImplementationFromDafny-go rm -rf $(LIBRARY_ROOT)/runtimes/go/TestsFromDafny-go -test_go: - cd runtimes/go/TestFromDafny-go - go run TestsFromDafny.go - ########################## Python targets # Python MUST transpile dependencies first to generate .dtr files @@ -866,3 +862,9 @@ local_transpile_test_single: TRANSPILE_DEPENDENCIES= \ $(patsubst %, -library:$(PROJECT_ROOT)/%, $(PROJECT_INDEX)) \ -library:$(PROJECT_ROOT)/$(STD_LIBRARY)/src/Index.dfy local_transpile_test_single: transpile_test + +removeDots: + chmod +x ./removeDotFromExtern.sh + ./removeDotFromExtern.sh + +transpile_implementation_go: removeDots \ No newline at end of file diff --git a/TestModels/Aggregate/runtimes/rust/src/standard_library_externs.rs b/TestModels/Aggregate/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/Aggregate/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/Constraints/removeDotFromExtern.sh b/TestModels/Constraints/removeDotFromExtern.sh new file mode 100644 index 0000000000..410b6a0fe9 --- /dev/null +++ b/TestModels/Constraints/removeDotFromExtern.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# TODO: remove this file if codegen is not generating extern with "." in go + +removeDotFromExtern() { + local directory="$1" + # Recursively search for all files in the current directory and subdirectories + for file in $(find "$directory" -type f); do + # Check if the file contains the pattern "{:extern "XYZ" }" + if grep -q '{:extern ".*"' "$file"; then + # Extract the "XYZ" part from the pattern + xyz=$(grep -o '{:extern "\([^"]*\)"' "$file" | sed 's/{:extern "\([^"]*\)"/\1/') + # Check if the "XYZ" part contains a dot + if [[ "$xyz" == *"."* ]]; then + # Remove the dot from "XYZ" + new_xyz=$(echo "$xyz" | sed 's/\.//g') + # Update the file with the new pattern + sed "s/{:extern \"$xyz\"/{:extern \"$new_xyz\"/g" $file > $file.tmp + cat $file.tmp > $file + rm $file.tmp + fi + fi + done +} + +removeDotFromExtern "Model" +removeDotFromExtern "src" + diff --git a/TestModels/Constructor/runtimes/rust/src/standard_library_externs.rs b/TestModels/Constructor/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/Constructor/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/Errors/runtimes/rust/Cargo.toml b/TestModels/Errors/runtimes/rust/Cargo.toml index b14b9e9ec0..9434c16e44 100644 --- a/TestModels/Errors/runtimes/rust/Cargo.toml +++ b/TestModels/Errors/runtimes/rust/Cargo.toml @@ -6,10 +6,12 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -aws-smithy-runtime = {version = "1.7.1", features=["client"]} -aws-smithy-runtime-api = {version = "1.7.2", features=["client"]} -aws-smithy-types = "1.2.4" dafny_runtime = { path = "../../../dafny-dependencies/dafny_runtime_rust"} +[dependencies.aws-smithy-runtime] +features = ["client"] +[dependencies.aws-smithy-runtime-api] +features = ["client"] +[dependencies.aws-smithy-types] [dev-dependencies.tokio] version = "1.26.0" diff --git a/TestModels/Errors/runtimes/rust/src/implementation_from_dafny.rs-e b/TestModels/Errors/runtimes/rust/src/implementation_from_dafny.rs-e new file mode 100644 index 0000000000..742c6a6ba8 --- /dev/null +++ b/TestModels/Errors/runtimes/rust/src/implementation_from_dafny.rs-e @@ -0,0 +1,1745 @@ +#![allow(warnings, unconditional_panic)] +#![allow(nonstandard_style)] + +pub mod _module { + +} +pub mod simple { + pub mod errors { + pub mod internaldafny { + pub use ::dafny_runtime::UpcastObject; + pub use ::std::any::Any; + pub use crate::simple::errors::internaldafny::types::ISimpleErrorsClient; + + pub struct _default {} + + impl _default { + pub fn DefaultSimpleErrorsConfig() -> ::std::rc::Rc { + ::std::rc::Rc::new(crate::simple::errors::internaldafny::types::SimpleErrorsConfig::SimpleErrorsConfig {}) + } + pub fn SimpleErrors(config: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut res = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + let mut client = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object>::new(); + let mut _nw0: ::dafny_runtime::Object = crate::simple::errors::internaldafny::SimpleErrorsClient::_allocate_object(); + crate::simple::errors::internaldafny::SimpleErrorsClient::_ctor(&_nw0, &::std::rc::Rc::new(crate::r#_SimpleErrorsImpl_Compile::Config::Config {})); + client = ::dafny_runtime::MaybePlacebo::from(_nw0.clone()); + res = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Success { + value: client.read() + })); + return res.read(); + } + pub fn CreateSuccessOfClient(client: &::dafny_runtime::Object) -> ::std::rc::Rc, ::std::rc::Rc>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Success { + value: client.clone() + }) + } + pub fn CreateFailureOfError(error: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Failure { + error: error.clone() + }) + } + } + + pub struct SimpleErrorsClient { + pub r#__i_config: ::std::rc::Rc + } + + impl SimpleErrorsClient { + pub fn _allocate_object() -> ::dafny_runtime::Object { + ::dafny_runtime::allocate_object::() + } + pub fn _ctor(this: &::dafny_runtime::Object, config: &::std::rc::Rc) -> () { + let mut _set__i_config: bool = false; + ::dafny_runtime::update_field_uninit_object!(this.clone(), r#__i_config, _set__i_config, config.clone()); + return (); + } + pub fn config(&self) -> ::std::rc::Rc { + self.r#__i_config.clone() + } + } + + impl UpcastObject + for crate::simple::errors::internaldafny::SimpleErrorsClient { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); + } + + impl ISimpleErrorsClient + for crate::simple::errors::internaldafny::SimpleErrorsClient { + fn AlwaysError(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + let mut _out0 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + _out0 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleErrorsImpl_Compile::_default::AlwaysError(&self.config().clone(), input)); + output = ::dafny_runtime::MaybePlacebo::from(_out0.read()); + return output.read(); + } + fn AlwaysMultipleErrors(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + let mut _out1 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + _out1 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleErrorsImpl_Compile::_default::AlwaysMultipleErrors(&self.config().clone(), input)); + output = ::dafny_runtime::MaybePlacebo::from(_out1.read()); + return output.read(); + } + fn AlwaysNativeError(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + let mut _out2 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + _out2 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleErrorsImpl_Compile::_default::AlwaysNativeError(&self.config().clone(), input)); + output = ::dafny_runtime::MaybePlacebo::from(_out2.read()); + return output.read(); + } + } + + impl UpcastObject + for crate::simple::errors::internaldafny::SimpleErrorsClient { + ::dafny_runtime::UpcastObjectFn!(dyn crate::simple::errors::internaldafny::types::ISimpleErrorsClient); + } + + pub mod types { + pub use ::std::fmt::Debug; + pub use ::dafny_runtime::DafnyPrint; + pub use ::std::cmp::Eq; + pub use ::std::hash::Hash; + pub use ::std::default::Default; + pub use ::std::convert::AsRef; + pub use ::dafny_runtime::UpcastObject; + pub use ::std::any::Any; + + #[derive(PartialEq, Clone)] + pub enum DafnyCallEvent { + DafnyCallEvent { + input: I, + output: O + } + } + + impl DafnyCallEvent { + pub fn input(&self) -> &I { + match self { + DafnyCallEvent::DafnyCallEvent{input, output, } => input, + } + } + pub fn output(&self) -> &O { + match self { + DafnyCallEvent::DafnyCallEvent{input, output, } => output, + } + } + } + + impl Debug + for DafnyCallEvent { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for DafnyCallEvent { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + DafnyCallEvent::DafnyCallEvent{input, output, } => { + write!(_formatter, "simple.errors.internaldafny.types.DafnyCallEvent.DafnyCallEvent(")?; + ::dafny_runtime::DafnyPrint::fmt_print(input, _formatter, false)?; + write!(_formatter, ", ")?; + ::dafny_runtime::DafnyPrint::fmt_print(output, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Eq + for DafnyCallEvent {} + + impl Hash + for DafnyCallEvent { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + DafnyCallEvent::DafnyCallEvent{input, output, } => { + ::std::hash::Hash::hash(input, _state); + ::std::hash::Hash::hash(output, _state) + }, + } + } + } + + impl Default + for DafnyCallEvent { + fn default() -> DafnyCallEvent { + DafnyCallEvent::DafnyCallEvent { + input: ::std::default::Default::default(), + output: ::std::default::Default::default() + } + } + } + + impl AsRef> + for &DafnyCallEvent { + fn as_ref(&self) -> Self { + self + } + } + + #[derive(PartialEq, Clone)] + pub enum GetErrorsInput { + GetErrorsInput { + value: ::std::rc::Rc>> + } + } + + impl GetErrorsInput { + pub fn value(&self) -> &::std::rc::Rc>> { + match self { + GetErrorsInput::GetErrorsInput{value, } => value, + } + } + } + + impl Debug + for GetErrorsInput { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for GetErrorsInput { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + GetErrorsInput::GetErrorsInput{value, } => { + write!(_formatter, "simple.errors.internaldafny.types.GetErrorsInput.GetErrorsInput(")?; + ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Eq + for GetErrorsInput {} + + impl Hash + for GetErrorsInput { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + GetErrorsInput::GetErrorsInput{value, } => { + ::std::hash::Hash::hash(value, _state) + }, + } + } + } + + impl Default + for GetErrorsInput { + fn default() -> GetErrorsInput { + GetErrorsInput::GetErrorsInput { + value: ::std::default::Default::default() + } + } + } + + impl AsRef + for &GetErrorsInput { + fn as_ref(&self) -> Self { + self + } + } + + #[derive(PartialEq, Clone)] + pub enum GetErrorsOutput { + GetErrorsOutput { + value: ::std::rc::Rc>> + } + } + + impl GetErrorsOutput { + pub fn value(&self) -> &::std::rc::Rc>> { + match self { + GetErrorsOutput::GetErrorsOutput{value, } => value, + } + } + } + + impl Debug + for GetErrorsOutput { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for GetErrorsOutput { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + GetErrorsOutput::GetErrorsOutput{value, } => { + write!(_formatter, "simple.errors.internaldafny.types.GetErrorsOutput.GetErrorsOutput(")?; + ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Eq + for GetErrorsOutput {} + + impl Hash + for GetErrorsOutput { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + GetErrorsOutput::GetErrorsOutput{value, } => { + ::std::hash::Hash::hash(value, _state) + }, + } + } + } + + impl Default + for GetErrorsOutput { + fn default() -> GetErrorsOutput { + GetErrorsOutput::GetErrorsOutput { + value: ::std::default::Default::default() + } + } + } + + impl AsRef + for &GetErrorsOutput { + fn as_ref(&self) -> Self { + self + } + } + + pub struct ISimpleErrorsClientCallHistory {} + + impl ISimpleErrorsClientCallHistory { + pub fn _allocate_object() -> ::dafny_runtime::Object { + ::dafny_runtime::allocate_object::() + } + } + + impl UpcastObject + for crate::simple::errors::internaldafny::types::ISimpleErrorsClientCallHistory { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); + } + + pub trait ISimpleErrorsClient: ::std::any::Any + ::dafny_runtime::UpcastObject { + fn AlwaysError(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; + fn AlwaysMultipleErrors(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; + fn AlwaysNativeError(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; + } + + #[derive(PartialEq, Clone)] + pub enum SimpleErrorsConfig { + SimpleErrorsConfig {} + } + + impl SimpleErrorsConfig {} + + impl Debug + for SimpleErrorsConfig { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for SimpleErrorsConfig { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + SimpleErrorsConfig::SimpleErrorsConfig{} => { + write!(_formatter, "simple.errors.internaldafny.types.SimpleErrorsConfig.SimpleErrorsConfig")?; + Ok(()) + }, + } + } + } + + impl SimpleErrorsConfig { + pub fn _AllSingletonConstructors() -> ::dafny_runtime::SequenceIter<::std::rc::Rc> { + ::dafny_runtime::seq![::std::rc::Rc::new(SimpleErrorsConfig::SimpleErrorsConfig {})].iter() + } + } + + impl Eq + for SimpleErrorsConfig {} + + impl Hash + for SimpleErrorsConfig { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + SimpleErrorsConfig::SimpleErrorsConfig{} => { + + }, + } + } + } + + impl Default + for SimpleErrorsConfig { + fn default() -> SimpleErrorsConfig { + SimpleErrorsConfig::SimpleErrorsConfig {} + } + } + + impl AsRef + for &SimpleErrorsConfig { + fn as_ref(&self) -> Self { + self + } + } + + #[derive(PartialEq, Clone)] + pub enum Error { + SimpleErrorsException { + message: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> + }, + CollectionOfErrors { + list: ::dafny_runtime::Sequence<::std::rc::Rc>, + message: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> + }, + Opaque { + obj: ::dafny_runtime::Object + } + } + + impl Error { + pub fn message(&self) -> &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { + match self { + Error::SimpleErrorsException{message, } => message, + Error::CollectionOfErrors{list, message, } => message, + Error::Opaque{obj, } => panic!("field does not exist on this variant"), + } + } + pub fn list(&self) -> &::dafny_runtime::Sequence<::std::rc::Rc> { + match self { + Error::SimpleErrorsException{message, } => panic!("field does not exist on this variant"), + Error::CollectionOfErrors{list, message, } => list, + Error::Opaque{obj, } => panic!("field does not exist on this variant"), + } + } + pub fn obj(&self) -> &::dafny_runtime::Object { + match self { + Error::SimpleErrorsException{message, } => panic!("field does not exist on this variant"), + Error::CollectionOfErrors{list, message, } => panic!("field does not exist on this variant"), + Error::Opaque{obj, } => obj, + } + } + } + + impl Debug + for Error { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for Error { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + Error::SimpleErrorsException{message, } => { + write!(_formatter, "simple.errors.internaldafny.types.Error.SimpleErrorsException(")?; + ::dafny_runtime::DafnyPrint::fmt_print(message, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + Error::CollectionOfErrors{list, message, } => { + write!(_formatter, "simple.errors.internaldafny.types.Error.CollectionOfErrors(")?; + ::dafny_runtime::DafnyPrint::fmt_print(list, _formatter, false)?; + write!(_formatter, ", ")?; + ::dafny_runtime::DafnyPrint::fmt_print(message, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + Error::Opaque{obj, } => { + write!(_formatter, "simple.errors.internaldafny.types.Error.Opaque(")?; + ::dafny_runtime::DafnyPrint::fmt_print(obj, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Eq + for Error {} + + impl Hash + for Error { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + Error::SimpleErrorsException{message, } => { + ::std::hash::Hash::hash(message, _state) + }, + Error::CollectionOfErrors{list, message, } => { + ::std::hash::Hash::hash(list, _state); + ::std::hash::Hash::hash(message, _state) + }, + Error::Opaque{obj, } => { + ::std::hash::Hash::hash(obj, _state) + }, + } + } + } + + impl Default + for Error { + fn default() -> Error { + Error::SimpleErrorsException { + message: ::std::default::Default::default() + } + } + } + + impl AsRef + for &Error { + fn as_ref(&self) -> Self { + self + } + } + + pub type OpaqueError = ::std::rc::Rc; + } + } + } +} +pub mod r#_SimpleErrorsImpl_Compile { + pub use ::std::fmt::Debug; + pub use ::dafny_runtime::DafnyPrint; + pub use ::std::cmp::Eq; + pub use ::std::hash::Hash; + pub use ::std::default::Default; + pub use ::std::convert::AsRef; + pub use ::dafny_runtime::UpcastObject; + pub use ::std::any::Any; + + pub struct _default {} + + impl _default { + pub fn AlwaysError(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { + panic!("Halt") + }; + let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::errors::internaldafny::types::Error::SimpleErrorsException { + message: input.value().value().clone() + }); + output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Failure { + error: res.clone() + })); + return output.read(); + } + pub fn AlwaysMultipleErrors(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { + panic!("Halt") + }; + let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::errors::internaldafny::types::Error::CollectionOfErrors { + list: ::dafny_runtime::seq![::std::rc::Rc::new(crate::simple::errors::internaldafny::types::Error::SimpleErrorsException { + message: input.value().value().clone() + })], + message: ::dafny_runtime::string_utf16_of("Something") + }); + output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Failure { + error: res.clone() + })); + return output.read(); + } + pub fn AlwaysNativeError(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + let mut opaqueObject = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object>::new(); + let mut _nw1: ::dafny_runtime::Object = crate::r#_SimpleErrorsImpl_Compile::SomeOpaqueGeneratedTypeForTesting::_allocate_object(); + crate::r#_SimpleErrorsImpl_Compile::SomeOpaqueGeneratedTypeForTesting::_ctor(&_nw1); + opaqueObject = ::dafny_runtime::MaybePlacebo::from(_nw1.clone()); + let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::errors::internaldafny::types::Error::Opaque { + obj: ::dafny_runtime::upcast_object::()(opaqueObject.read()) + }); + output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Failure { + error: res.clone() + })); + return output.read(); + } + } + + #[derive(PartialEq, Clone)] + pub enum Config { + Config {} + } + + impl Config {} + + impl Debug + for Config { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for Config { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + Config::Config{} => { + write!(_formatter, "SimpleErrorsImpl_Compile.Config.Config")?; + Ok(()) + }, + } + } + } + + impl Config { + pub fn _AllSingletonConstructors() -> ::dafny_runtime::SequenceIter<::std::rc::Rc> { + ::dafny_runtime::seq![::std::rc::Rc::new(Config::Config {})].iter() + } + } + + impl Eq + for Config {} + + impl Hash + for Config { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + Config::Config{} => { + + }, + } + } + } + + impl Default + for Config { + fn default() -> Config { + Config::Config {} + } + } + + impl AsRef + for &Config { + fn as_ref(&self) -> Self { + self + } + } + + pub struct SomeOpaqueGeneratedTypeForTesting {} + + impl SomeOpaqueGeneratedTypeForTesting { + pub fn _allocate_object() -> ::dafny_runtime::Object { + ::dafny_runtime::allocate_object::() + } + pub fn _ctor(this: &::dafny_runtime::Object) -> () { + return (); + } + } + + impl UpcastObject + for SomeOpaqueGeneratedTypeForTesting { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); + } +} +pub mod r#_StandardLibrary_Compile { + pub struct _default {} + + impl _default { + pub fn Join<_T: ::dafny_runtime::DafnyType>(ss: &::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>, joiner: &::dafny_runtime::Sequence<_T>) -> ::dafny_runtime::Sequence<_T> { + let mut _accumulator: ::dafny_runtime::Sequence<_T> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>; + let mut _r0 = ss.clone(); + let mut _r1 = joiner.clone(); + 'TAIL_CALL_START: loop { + let ss = _r0; + let joiner = _r1; + if ss.cardinality() == ::dafny_runtime::int!(1) { + return _accumulator.concat(&ss.get(&::dafny_runtime::int!(0))); + } else { + _accumulator = _accumulator.concat(&ss.get(&::dafny_runtime::int!(0)).concat(&joiner)); + let mut _in0: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ss.drop(&::dafny_runtime::int!(1)); + let mut _in1: ::dafny_runtime::Sequence<_T> = joiner.clone(); + _r0 = _in0.clone(); + _r1 = _in1.clone(); + continue 'TAIL_CALL_START; + } + } + } + pub fn Split<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> { + let mut _accumulator: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>; + let mut _r0 = s.clone(); + let mut _r1 = delim.clone(); + 'TAIL_CALL_START: loop { + let s = _r0; + let delim = _r1; + let mut i: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(&s, &delim, &::dafny_runtime::int!(0)); + if matches!((&i).as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { + _accumulator = _accumulator.concat(&::dafny_runtime::seq![s.take(i.value())]); + let mut _in2: ::dafny_runtime::Sequence<_T> = s.drop(&(i.value().clone() + ::dafny_runtime::int!(1))); + let mut _in3: _T = delim.clone(); + _r0 = _in2.clone(); + _r1 = _in3.clone(); + continue 'TAIL_CALL_START; + } else { + return _accumulator.concat(&::dafny_runtime::seq![s.clone()]); + } + } + } + pub fn SplitOnce<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> (::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>) { + let mut i: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(s, delim, &::dafny_runtime::int!(0)); + ( + s.take(i.value()), + s.drop(&(i.value().clone() + ::dafny_runtime::int!(1))) + ) + } + pub fn r#_SplitOnce_q<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> ::std::rc::Rc, ::dafny_runtime::Sequence<_T>)>> { + let mut valueOrError0: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(s, delim, &::dafny_runtime::int!(0)); + if valueOrError0.IsFailure() { + valueOrError0.PropagateFailure::<(::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>)>() + } else { + let mut i: ::dafny_runtime::_System::nat = valueOrError0.Extract(); + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<(::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>)>::Some { + value: ( + s.take(&i), + s.drop(&(i.clone() + ::dafny_runtime::int!(1))) + ) + }) + } + } + pub fn FindIndexMatching<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, c: &_T, i: &::dafny_runtime::_System::nat) -> ::std::rc::Rc> { + crate::r#_StandardLibrary_Compile::_default::FindIndex::<_T>(s, { + let c: _T = c.clone(); + &({ + let mut c = c.clone(); + ::std::rc::Rc::new(move |x: &_T| -> bool{ + x.clone() == c.clone() + }) + }) + }, i) + } + pub fn FindIndex<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>, f: &::std::rc::Rc bool>, i: &::dafny_runtime::_System::nat) -> ::std::rc::Rc> { + let mut _r0 = s.clone(); + let mut _r1 = f.clone(); + let mut _r2 = i.clone(); + 'TAIL_CALL_START: loop { + let s = _r0; + let f = _r1; + let i = _r2; + if i.clone() == s.cardinality() { + return ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::_System::nat>::None {}); + } else { + if (&f)(&s.get(&i)) { + return ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::_System::nat>::Some { + value: i.clone() + }); + } else { + let mut _in4: ::dafny_runtime::Sequence<_T> = s.clone(); + let mut _in5: ::std::rc::Rc bool> = f.clone(); + let mut _in6: ::dafny_runtime::DafnyInt = i.clone() + ::dafny_runtime::int!(1); + _r0 = _in4.clone(); + _r1 = _in5.clone(); + _r2 = _in6.clone(); + continue 'TAIL_CALL_START; + } + } + } + } + pub fn Filter<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>, f: &::std::rc::Rc bool>) -> ::dafny_runtime::Sequence<_T> { + let mut _accumulator: ::dafny_runtime::Sequence<_T> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>; + let mut _r0 = s.clone(); + let mut _r1 = f.clone(); + 'TAIL_CALL_START: loop { + let s = _r0; + let f = _r1; + if s.cardinality() == ::dafny_runtime::int!(0) { + return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>)); + } else { + if (&f)(&s.get(&::dafny_runtime::int!(0))) { + _accumulator = _accumulator.concat(&::dafny_runtime::seq![s.get(&::dafny_runtime::int!(0))]); + let mut _in7: ::dafny_runtime::Sequence<_T> = s.drop(&::dafny_runtime::int!(1)); + let mut _in8: ::std::rc::Rc bool> = f.clone(); + _r0 = _in7.clone(); + _r1 = _in8.clone(); + continue 'TAIL_CALL_START; + } else { + let mut _in9: ::dafny_runtime::Sequence<_T> = s.drop(&::dafny_runtime::int!(1)); + let mut _in10: ::std::rc::Rc bool> = f.clone(); + _r0 = _in9.clone(); + _r1 = _in10.clone(); + continue 'TAIL_CALL_START; + } + } + } + } + pub fn Min(a: &::dafny_runtime::DafnyInt, b: &::dafny_runtime::DafnyInt) -> ::dafny_runtime::DafnyInt { + if a.clone() < b.clone() { + a.clone() + } else { + b.clone() + } + } + pub fn Fill<_T: ::dafny_runtime::DafnyType>(value: &_T, n: &::dafny_runtime::_System::nat) -> ::dafny_runtime::Sequence<_T> { + { + let _initializer = { + let value: _T = value.clone(); + { + let mut value = value.clone(); + ::std::rc::Rc::new(move |_v0: &::dafny_runtime::DafnyInt| -> _T{ + value.clone() + }) + } + }; + ::dafny_runtime::integer_range(::dafny_runtime::Zero::zero(), n.clone()).map(|i| _initializer(&i)).collect::<::dafny_runtime::Sequence<_>>() + } + } + pub fn SeqToArray<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> ::dafny_runtime::Object<[_T]> { + let mut a = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object<[_T]>>::new(); + let mut _init0: ::std::rc::Rc _T> = { + let s: ::dafny_runtime::Sequence<_T> = s.clone(); + { + let mut s = s.clone(); + ::std::rc::Rc::new(move |i: &::dafny_runtime::DafnyInt| -> _T{ + s.get(i) + }) + } + }; + let mut _nw2: ::dafny_runtime::Object<[::std::mem::MaybeUninit<_T>]> = ::dafny_runtime::array::placebos_usize_object::<_T>(::dafny_runtime::DafnyUsize::into_usize(s.cardinality())); + for r#__i0_0 in ::dafny_runtime::integer_range(0, ::dafny_runtime::rd!(_nw2.clone()).len()) { + { + let __idx0 = ::dafny_runtime::DafnyUsize::into_usize(r#__i0_0.clone()); + ::dafny_runtime::md!(_nw2)[__idx0] = ::std::mem::MaybeUninit::new((&_init0)(&::dafny_runtime::int!(r#__i0_0.clone()))); + } + } + a = ::dafny_runtime::MaybePlacebo::from(::dafny_runtime::array::construct_object(_nw2.clone())); + return a.read(); + } + pub fn LexicographicLessOrEqual<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, b: &::dafny_runtime::Sequence<_T>, less: &::std::rc::Rc bool>) -> bool { + ::dafny_runtime::integer_range(::dafny_runtime::int!(0), a.cardinality() + ::dafny_runtime::int!(1)).any(({ + let mut a = a.clone(); + let mut b = b.clone(); + let mut less = less.clone(); + ::std::rc::Rc::new(move |r#__exists_var_0: ::dafny_runtime::DafnyInt| -> bool{ + let mut k: ::dafny_runtime::DafnyInt = r#__exists_var_0.clone(); + ::dafny_runtime::int!(0) <= k.clone() && k.clone() <= a.cardinality() && crate::r#_StandardLibrary_Compile::_default::LexicographicLessOrEqualAux::<_T>(&a, &b, &less, &k) + }) + }).as_ref()) + } + pub fn LexicographicLessOrEqualAux<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, b: &::dafny_runtime::Sequence<_T>, less: &::std::rc::Rc bool>, lengthOfCommonPrefix: &::dafny_runtime::_System::nat) -> bool { + lengthOfCommonPrefix.clone() <= b.cardinality() && ::dafny_runtime::integer_range(::dafny_runtime::int!(0), lengthOfCommonPrefix.clone()).all(({ + let mut lengthOfCommonPrefix = lengthOfCommonPrefix.clone(); + let mut a = a.clone(); + let mut b = b.clone(); + ::std::rc::Rc::new(move |r#__forall_var_0: ::dafny_runtime::DafnyInt| -> bool{ + let mut i: ::dafny_runtime::DafnyInt = r#__forall_var_0.clone(); + !(::dafny_runtime::int!(0) <= i.clone() && i.clone() < lengthOfCommonPrefix.clone()) || a.get(&i) == b.get(&i) + }) + }).as_ref()) && (lengthOfCommonPrefix.clone() == a.cardinality() || lengthOfCommonPrefix.clone() < b.cardinality() && less(&a.get(lengthOfCommonPrefix), &b.get(lengthOfCommonPrefix))) + } + pub fn SetToOrderedSequence<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Set<::dafny_runtime::Sequence<_T>>, less: &::std::rc::Rc bool>) -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> { + let mut _accumulator: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>; + let mut _r0 = s.clone(); + let mut _r1 = less.clone(); + 'TAIL_CALL_START: loop { + let s = _r0; + let less = _r1; + if s.clone() == ::dafny_runtime::set!{} { + return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>)); + } else { + return (&({ + let mut s = s.clone(); + let mut less = less.clone(); + ::std::rc::Rc::new(move |r#__let_dummy_0: &::dafny_runtime::DafnyInt| -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>{ + let mut a = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Sequence<_T>>::new(); + 'label_goto__ASSIGN_SUCH_THAT_0: loop { + for r#__assign_such_that_0 in (&s).iter().cloned() { + a = ::dafny_runtime::MaybePlacebo::from(r#__assign_such_that_0.clone()); + if s.contains(&a.read()) && crate::r#_StandardLibrary_Compile::_default::IsMinimum::<_T>(&a.read(), &s, &less) { + break 'label_goto__ASSIGN_SUCH_THAT_0; + } + } + panic!("Halt"); + break; + }; + ::dafny_runtime::seq![a.read()].concat(&crate::r#_StandardLibrary_Compile::_default::SetToOrderedSequence::<_T>(&s.subtract(&::dafny_runtime::set!{a.read()}), &less)) + }) + }))(&::dafny_runtime::int!(0)); + } + } + } + pub fn IsMinimum<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, s: &::dafny_runtime::Set<::dafny_runtime::Sequence<_T>>, less: &::std::rc::Rc bool>) -> bool { + s.contains(a) && s.iter().all(({ + let mut a = a.clone(); + let mut s = s.clone(); + let mut less = less.clone(); + ::std::rc::Rc::new(move |r#__forall_var_1: &::dafny_runtime::Sequence<_T>| -> bool{ + let mut z: ::dafny_runtime::Sequence<_T> = r#__forall_var_1.clone(); + !s.contains(&z) || crate::r#_StandardLibrary_Compile::_default::LexicographicLessOrEqual::<_T>(&a, &z, &less) + }) + }).as_ref()) + } + } + + pub mod r#_UInt_Compile { + pub use ::std::default::Default; + pub use ::dafny_runtime::DafnyPrint; + + pub struct _default {} + + impl _default { + pub fn UInt8Less(a: u8, b: u8) -> bool { + a < b + } + pub fn HasUint16Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { + s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT16_LIMIT() + } + pub fn HasUint32Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { + s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT32_LIMIT() + } + pub fn HasUint64Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { + s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT64_LIMIT() + } + pub fn UInt16ToSeq(x: u16) -> ::dafny_runtime::Sequence { + let mut b0: u8 = (x / 256) as u8; + let mut b1: u8 = (x % 256) as u8; + ::dafny_runtime::seq![b0, b1] + } + pub fn SeqToUInt16(s: &::dafny_runtime::Sequence) -> u16 { + let mut x0: u16 = s.get(&::dafny_runtime::int!(0)) as u16 * 256; + x0 + s.get(&::dafny_runtime::int!(1)) as u16 + } + pub fn UInt32ToSeq(x: u32) -> ::dafny_runtime::Sequence { + let mut b0: u8 = (x / 16777216) as u8; + let mut x0: u32 = x - b0 as u32 * 16777216; + let mut b1: u8 = (x0 / 65536) as u8; + let mut x1: u32 = x0 - b1 as u32 * 65536; + let mut b2: u8 = (x1 / 256) as u8; + let mut b3: u8 = (x1 % 256) as u8; + ::dafny_runtime::seq![b0, b1, b2, b3] + } + pub fn SeqToUInt32(s: &::dafny_runtime::Sequence) -> u32 { + let mut x0: u32 = s.get(&::dafny_runtime::int!(0)) as u32 * 16777216; + let mut x1: u32 = x0 + s.get(&::dafny_runtime::int!(1)) as u32 * 65536; + let mut x2: u32 = x1 + s.get(&::dafny_runtime::int!(2)) as u32 * 256; + x2 + s.get(&::dafny_runtime::int!(3)) as u32 + } + pub fn UInt64ToSeq(x: u64) -> ::dafny_runtime::Sequence { + let mut b0: u8 = (x / 72057594037927936) as u8; + let mut x0: u64 = x - b0 as u64 * 72057594037927936; + let mut b1: u8 = (x0 / 281474976710656) as u8; + let mut x1: u64 = x0 - b1 as u64 * 281474976710656; + let mut b2: u8 = (x1 / 1099511627776) as u8; + let mut x2: u64 = x1 - b2 as u64 * 1099511627776; + let mut b3: u8 = (x2 / 4294967296) as u8; + let mut x3: u64 = x2 - b3 as u64 * 4294967296; + let mut b4: u8 = (x3 / 16777216) as u8; + let mut x4: u64 = x3 - b4 as u64 * 16777216; + let mut b5: u8 = (x4 / 65536) as u8; + let mut x5: u64 = x4 - b5 as u64 * 65536; + let mut b6: u8 = (x5 / 256) as u8; + let mut b7: u8 = (x5 % 256) as u8; + ::dafny_runtime::seq![b0, b1, b2, b3, b4, b5, b6, b7] + } + pub fn SeqToUInt64(s: &::dafny_runtime::Sequence) -> u64 { + let mut x0: u64 = s.get(&::dafny_runtime::int!(0)) as u64 * 72057594037927936; + let mut x1: u64 = x0 + s.get(&::dafny_runtime::int!(1)) as u64 * 281474976710656; + let mut x2: u64 = x1 + s.get(&::dafny_runtime::int!(2)) as u64 * 1099511627776; + let mut x3: u64 = x2 + s.get(&::dafny_runtime::int!(3)) as u64 * 4294967296; + let mut x4: u64 = x3 + s.get(&::dafny_runtime::int!(4)) as u64 * 16777216; + let mut x5: u64 = x4 + s.get(&::dafny_runtime::int!(5)) as u64 * 65536; + let mut x6: u64 = x5 + s.get(&::dafny_runtime::int!(6)) as u64 * 256; + let mut x: u64 = x6 + s.get(&::dafny_runtime::int!(7)) as u64; + x + } + pub fn UINT16_LIMIT() -> ::dafny_runtime::DafnyInt { + ::dafny_runtime::int!(b"65536") + } + pub fn UINT32_LIMIT() -> ::dafny_runtime::DafnyInt { + ::dafny_runtime::int!(b"4294967296") + } + pub fn UINT64_LIMIT() -> ::dafny_runtime::DafnyInt { + ::dafny_runtime::int!(b"18446744073709551616") + } + pub fn INT32_MAX_LIMIT() -> ::dafny_runtime::DafnyInt { + ::dafny_runtime::int!(b"2147483648") + } + pub fn INT64_MAX_LIMIT() -> ::dafny_runtime::DafnyInt { + ::dafny_runtime::int!(b"9223372036854775808") + } + } + + #[derive(Clone, PartialEq)] + #[repr(transparent)] + pub struct uint8(pub u8); + + impl uint8 { + pub fn is(_source: u8) -> bool { + return true; + } + } + + impl Default + for uint8 { + fn default() -> Self { + uint8(::std::default::Default::default()) + } + } + + impl DafnyPrint + for uint8 { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) + } + } + + impl ::std::ops::Deref + for uint8 { + type Target = u8; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + #[derive(Clone, PartialEq)] + #[repr(transparent)] + pub struct uint16(pub u16); + + impl uint16 { + pub fn is(_source: u16) -> bool { + return true; + } + } + + impl Default + for uint16 { + fn default() -> Self { + uint16(::std::default::Default::default()) + } + } + + impl DafnyPrint + for uint16 { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) + } + } + + impl ::std::ops::Deref + for uint16 { + type Target = u16; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + #[derive(Clone, PartialEq)] + #[repr(transparent)] + pub struct uint32(pub u32); + + impl uint32 { + pub fn is(_source: u32) -> bool { + return true; + } + } + + impl Default + for uint32 { + fn default() -> Self { + uint32(::std::default::Default::default()) + } + } + + impl DafnyPrint + for uint32 { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) + } + } + + impl ::std::ops::Deref + for uint32 { + type Target = u32; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + #[derive(Clone, PartialEq)] + #[repr(transparent)] + pub struct uint64(pub u64); + + impl uint64 { + pub fn is(_source: u64) -> bool { + return true; + } + } + + impl Default + for uint64 { + fn default() -> Self { + uint64(::std::default::Default::default()) + } + } + + impl DafnyPrint + for uint64 { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) + } + } + + impl ::std::ops::Deref + for uint64 { + type Target = u64; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + #[derive(Clone, PartialEq)] + #[repr(transparent)] + pub struct int32(pub i32); + + impl int32 { + pub fn is(_source: i32) -> bool { + return true; + } + } + + impl Default + for int32 { + fn default() -> Self { + int32(::std::default::Default::default()) + } + } + + impl DafnyPrint + for int32 { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) + } + } + + impl ::std::ops::Deref + for int32 { + type Target = i32; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + #[derive(Clone, PartialEq)] + #[repr(transparent)] + pub struct int64(pub i64); + + impl int64 { + pub fn is(_source: i64) -> bool { + return true; + } + } + + impl Default + for int64 { + fn default() -> Self { + int64(::std::default::Default::default()) + } + } + + impl DafnyPrint + for int64 { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) + } + } + + impl ::std::ops::Deref + for int64 { + type Target = i64; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + #[derive(Clone, PartialEq)] + #[repr(transparent)] + pub struct posInt64(pub u64); + + impl posInt64 { + pub fn is(_source: u64) -> bool { + let mut x: ::dafny_runtime::DafnyInt = ::std::convert::Into::<::dafny_runtime::DafnyInt>::into(_source.clone()); + return ::dafny_runtime::int!(0) < x.clone() && x.clone() < ::dafny_runtime::int!(b"9223372036854775808"); + } + } + + impl Default + for posInt64 { + fn default() -> Self { + posInt64(1) + } + } + + impl DafnyPrint + for posInt64 { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) + } + } + + impl ::std::ops::Deref + for posInt64 { + type Target = u64; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + pub type seq16 = ::dafny_runtime::Sequence; + + pub type seq32 = ::dafny_runtime::Sequence; + + pub type seq64 = ::dafny_runtime::Sequence; + } +} +pub mod r#_StandardLibraryInterop_Compile { + pub use ::dafny_runtime::UpcastObject; + pub use ::std::any::Any; + + pub struct WrappersInterop {} + + impl WrappersInterop { + pub fn _allocate_object() -> ::dafny_runtime::Object { + ::dafny_runtime::allocate_object::() + } + pub fn CreateStringSome(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Some { + value: s.clone() + }) + } + pub fn CreateStringNone() -> ::std::rc::Rc>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::None {}) + } + pub fn CreateBooleanSome(b: bool) -> ::std::rc::Rc> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::Some { + value: b + }) + } + pub fn CreateBooleanNone() -> ::std::rc::Rc> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::None {}) + } + } + + impl UpcastObject + for WrappersInterop { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); + } +} +pub mod UTF8 { + pub struct _default {} + + impl _default { + pub fn CreateEncodeSuccess(bytes: &crate::UTF8::ValidUTF8Bytes) -> ::std::rc::Rc>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Success { + value: bytes.clone() + }) + } + pub fn CreateEncodeFailure(error: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Failure { + error: error.clone() + }) + } + pub fn CreateDecodeSuccess(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: s.clone() + }) + } + pub fn CreateDecodeFailure(error: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: error.clone() + }) + } + pub fn IsASCIIString(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> bool { + let mut _hresult: bool = ::default(); + let mut _hi0: ::dafny_runtime::DafnyInt = s.cardinality(); + for i in ::dafny_runtime::integer_range(::dafny_runtime::int!(0), _hi0.clone()) { + if !(::dafny_runtime::int!(s.get(&i).0) < ::dafny_runtime::int!(128)) { + _hresult = false; + return _hresult; + } + } + _hresult = true; + return _hresult; + } + pub fn EncodeAscii(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> crate::UTF8::ValidUTF8Bytes { + let mut _accumulator: crate::UTF8::ValidUTF8Bytes = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence; + let mut _r0 = s.clone(); + 'TAIL_CALL_START: loop { + let s = _r0; + if s.cardinality() == ::dafny_runtime::int!(0) { + return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence)); + } else { + let mut x: ::dafny_runtime::Sequence = ::dafny_runtime::seq![s.get(&::dafny_runtime::int!(0)).0 as u8]; + _accumulator = _accumulator.concat(&x); + let mut _in11: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> = s.drop(&::dafny_runtime::int!(1)); + _r0 = _in11.clone(); + continue 'TAIL_CALL_START; + } + } + } + pub fn Uses1Byte(s: &::dafny_runtime::Sequence) -> bool { + 0 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 127 + } + pub fn Uses2Bytes(s: &::dafny_runtime::Sequence) -> bool { + 194 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 223 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) + } + pub fn Uses3Bytes(s: &::dafny_runtime::Sequence) -> bool { + s.get(&::dafny_runtime::int!(0)) == 224 && (160 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || 225 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 236 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || s.get(&::dafny_runtime::int!(0)) == 237 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 159) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || 238 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 239 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) + } + pub fn Uses4Bytes(s: &::dafny_runtime::Sequence) -> bool { + s.get(&::dafny_runtime::int!(0)) == 240 && (144 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) || 241 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 243 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) || s.get(&::dafny_runtime::int!(0)) == 244 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 143) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) + } + pub fn ValidUTF8Range(a: &::dafny_runtime::Sequence, lo: &::dafny_runtime::_System::nat, hi: &::dafny_runtime::_System::nat) -> bool { + let mut _r0 = a.clone(); + let mut _r1 = lo.clone(); + let mut _r2 = hi.clone(); + 'TAIL_CALL_START: loop { + let a = _r0; + let lo = _r1; + let hi = _r2; + if lo.clone() == hi.clone() { + return true; + } else { + let mut r: ::dafny_runtime::Sequence = a.slice(&lo, &hi); + if crate::UTF8::_default::Uses1Byte(&r) { + let mut _in12: ::dafny_runtime::Sequence = a.clone(); + let mut _in13: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(1); + let mut _in14: ::dafny_runtime::_System::nat = hi.clone(); + _r0 = _in12.clone(); + _r1 = _in13.clone(); + _r2 = _in14.clone(); + continue 'TAIL_CALL_START; + } else { + if ::dafny_runtime::int!(2) <= r.cardinality() && crate::UTF8::_default::Uses2Bytes(&r) { + let mut _in15: ::dafny_runtime::Sequence = a.clone(); + let mut _in16: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(2); + let mut _in17: ::dafny_runtime::_System::nat = hi.clone(); + _r0 = _in15.clone(); + _r1 = _in16.clone(); + _r2 = _in17.clone(); + continue 'TAIL_CALL_START; + } else { + if ::dafny_runtime::int!(3) <= r.cardinality() && crate::UTF8::_default::Uses3Bytes(&r) { + let mut _in18: ::dafny_runtime::Sequence = a.clone(); + let mut _in19: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(3); + let mut _in20: ::dafny_runtime::_System::nat = hi.clone(); + _r0 = _in18.clone(); + _r1 = _in19.clone(); + _r2 = _in20.clone(); + continue 'TAIL_CALL_START; + } else { + if ::dafny_runtime::int!(4) <= r.cardinality() && crate::UTF8::_default::Uses4Bytes(&r) { + let mut _in21: ::dafny_runtime::Sequence = a.clone(); + let mut _in22: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(4); + let mut _in23: ::dafny_runtime::_System::nat = hi.clone(); + _r0 = _in21.clone(); + _r1 = _in22.clone(); + _r2 = _in23.clone(); + continue 'TAIL_CALL_START; + } else { + return false; + } + } + } + } + } + } + } + pub fn ValidUTF8Seq(s: &::dafny_runtime::Sequence) -> bool { + crate::UTF8::_default::ValidUTF8Range(s, &::dafny_runtime::int!(0), &s.cardinality()) + } + } + + pub type ValidUTF8Bytes = ::dafny_runtime::Sequence; + + pub fn r#__init_ValidUTF8Bytes() -> ::dafny_runtime::Sequence { + ::dafny_runtime::seq![] as ::dafny_runtime::Sequence + } +} +pub mod r#_Wrappers_Compile { + pub use ::std::fmt::Debug; + pub use ::dafny_runtime::DafnyPrint; + pub use ::std::cmp::Eq; + pub use ::std::hash::Hash; + pub use ::std::default::Default; + pub use ::std::convert::AsRef; + + pub struct _default {} + + impl _default { + pub fn Need<_E: ::dafny_runtime::DafnyType>(condition: bool, error: &_E) -> ::std::rc::Rc> { + if condition { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Outcome::<_E>::Pass {}) + } else { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Outcome::<_E>::Fail { + error: error.clone() + }) + } + } + } + + #[derive(PartialEq, Clone)] + pub enum Option { + None {}, + Some { + value: T + } + } + + impl Option { + pub fn ToResult(self: &::std::rc::Rc) -> ::std::rc::Rc>> { + let mut _source0: ::std::rc::Rc> = self.clone(); + if matches!((&_source0).as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::string_utf16_of("Option is None") + }) + } else { + let mut r#___mcc_h0: T = _source0.value().clone(); + let mut v: T = r#___mcc_h0.clone(); + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Success { + value: v.clone() + }) + } + } + pub fn UnwrapOr(self: &::std::rc::Rc, default: &T) -> T { + let mut _source1: ::std::rc::Rc> = self.clone(); + if matches!((&_source1).as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) { + default.clone() + } else { + let mut r#___mcc_h0: T = _source1.value().clone(); + let mut v: T = r#___mcc_h0.clone(); + v.clone() + } + } + pub fn IsFailure(self: &::std::rc::Rc) -> bool { + matches!(self.as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) + } + pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<_U>::None {}) + } + pub fn Extract(self: &::std::rc::Rc) -> T { + self.value().clone() + } + pub fn value(&self) -> &T { + match self { + Option::None{} => panic!("field does not exist on this variant"), + Option::Some{value, } => value, + } + } + } + + impl Debug + for Option { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for Option { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + Option::None{} => { + write!(_formatter, "Wrappers_Compile.Option.None")?; + Ok(()) + }, + Option::Some{value, } => { + write!(_formatter, "Wrappers_Compile.Option.Some(")?; + ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Option { + pub fn coerce(f_0: ::std::rc::Rc r#__T0 + 'static>) -> ::std::rc::Rc) -> Option> { + ::std::rc::Rc::new(move |this: Self| -> Option{ + match this { + Option::None{} => { + Option::None {} + }, + Option::Some{value, } => { + Option::Some { + value: f_0.clone()(value) + } + }, + } + }) + } + } + + impl Eq + for Option {} + + impl Hash + for Option { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + Option::None{} => { + + }, + Option::Some{value, } => { + ::std::hash::Hash::hash(value, _state) + }, + } + } + } + + impl Default + for Option { + fn default() -> Option { + Option::None {} + } + } + + impl AsRef> + for &Option { + fn as_ref(&self) -> Self { + self + } + } + + #[derive(PartialEq, Clone)] + pub enum Result { + Success { + value: T + }, + Failure { + error: R + } + } + + impl Result { + pub fn ToOption(self: &::std::rc::Rc) -> ::std::rc::Rc> { + let mut _source2: ::std::rc::Rc> = self.clone(); + if matches!((&_source2).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { + let mut r#___mcc_h0: T = _source2.value().clone(); + let mut s: T = r#___mcc_h0.clone(); + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::Some { + value: s.clone() + }) + } else { + let mut r#___mcc_h1: R = _source2.error().clone(); + let mut e: R = r#___mcc_h1.clone(); + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::None {}) + } + } + pub fn UnwrapOr(self: &::std::rc::Rc, default: &T) -> T { + let mut _source3: ::std::rc::Rc> = self.clone(); + if matches!((&_source3).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { + let mut r#___mcc_h0: T = _source3.value().clone(); + let mut s: T = r#___mcc_h0.clone(); + s.clone() + } else { + let mut r#___mcc_h1: R = _source3.error().clone(); + let mut e: R = r#___mcc_h1.clone(); + default.clone() + } + } + pub fn IsFailure(self: &::std::rc::Rc) -> bool { + matches!(self.as_ref(), crate::r#_Wrappers_Compile::Result::Failure{ .. }) + } + pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<_U, R>::Failure { + error: self.error().clone() + }) + } + pub fn MapFailure<_NewR: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc, reWrap: &::std::rc::Rc _NewR>) -> ::std::rc::Rc> { + let mut _source4: ::std::rc::Rc> = self.clone(); + if matches!((&_source4).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { + let mut r#___mcc_h0: T = _source4.value().clone(); + let mut s: T = r#___mcc_h0.clone(); + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::::Success { + value: s.clone() + }) + } else { + let mut r#___mcc_h1: R = _source4.error().clone(); + let mut e: R = r#___mcc_h1.clone(); + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::::Failure { + error: reWrap(&e) + }) + } + } + pub fn Extract(self: &::std::rc::Rc) -> T { + self.value().clone() + } + pub fn value(&self) -> &T { + match self { + Result::Success{value, } => value, + Result::Failure{error, } => panic!("field does not exist on this variant"), + } + } + pub fn error(&self) -> &R { + match self { + Result::Success{value, } => panic!("field does not exist on this variant"), + Result::Failure{error, } => error, + } + } + } + + impl Debug + for Result { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for Result { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + Result::Success{value, } => { + write!(_formatter, "Wrappers_Compile.Result.Success(")?; + ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + Result::Failure{error, } => { + write!(_formatter, "Wrappers_Compile.Result.Failure(")?; + ::dafny_runtime::DafnyPrint::fmt_print(error, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Result { + pub fn coerce(f_0: ::std::rc::Rc r#__T0 + 'static>, f_1: ::std::rc::Rc r#__T1 + 'static>) -> ::std::rc::Rc) -> Result> { + ::std::rc::Rc::new(move |this: Self| -> Result{ + match this { + Result::Success{value, } => { + Result::Success { + value: f_0.clone()(value) + } + }, + Result::Failure{error, } => { + Result::Failure { + error: f_1.clone()(error) + } + }, + } + }) + } + } + + impl Eq + for Result {} + + impl Hash + for Result { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + Result::Success{value, } => { + ::std::hash::Hash::hash(value, _state) + }, + Result::Failure{error, } => { + ::std::hash::Hash::hash(error, _state) + }, + } + } + } + + impl Default + for Result { + fn default() -> Result { + Result::Success { + value: ::std::default::Default::default() + } + } + } + + impl AsRef> + for &Result { + fn as_ref(&self) -> Self { + self + } + } + + #[derive(PartialEq, Clone)] + pub enum Outcome { + Pass {}, + Fail { + error: E + } + } + + impl Outcome { + pub fn IsFailure(self: &::std::rc::Rc) -> bool { + matches!(self.as_ref(), crate::r#_Wrappers_Compile::Outcome::Fail{ .. }) + } + pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<_U, E>::Failure { + error: self.error().clone() + }) + } + pub fn error(&self) -> &E { + match self { + Outcome::Pass{} => panic!("field does not exist on this variant"), + Outcome::Fail{error, } => error, + } + } + } + + impl Debug + for Outcome { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for Outcome { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + Outcome::Pass{} => { + write!(_formatter, "Wrappers_Compile.Outcome.Pass")?; + Ok(()) + }, + Outcome::Fail{error, } => { + write!(_formatter, "Wrappers_Compile.Outcome.Fail(")?; + ::dafny_runtime::DafnyPrint::fmt_print(error, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Eq + for Outcome {} + + impl Hash + for Outcome { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + Outcome::Pass{} => { + + }, + Outcome::Fail{error, } => { + ::std::hash::Hash::hash(error, _state) + }, + } + } + } + + impl Default + for Outcome { + fn default() -> Outcome { + Outcome::Pass {} + } + } + + impl AsRef> + for &Outcome { + fn as_ref(&self) -> Self { + self + } + } +} \ No newline at end of file diff --git a/TestModels/Errors/runtimes/rust/src/standard_library_externs.rs b/TestModels/Errors/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/Errors/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/LanguageSpecificLogic/runtimes/rust/src/standard_library_externs.rs b/TestModels/LanguageSpecificLogic/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/LanguageSpecificLogic/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/Refinement/runtimes/rust/src/standard_library_externs.rs b/TestModels/Refinement/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/Refinement/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/Resource/runtimes/rust/src/standard_library_externs.rs b/TestModels/Resource/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/Resource/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/Makefile b/TestModels/SimpleTypes/SimpleBlob/Makefile index f27fa454f0..cb013bd311 100644 --- a/TestModels/SimpleTypes/SimpleBlob/Makefile +++ b/TestModels/SimpleTypes/SimpleBlob/Makefile @@ -3,9 +3,8 @@ CORES=2 -TRANSPILE_TESTS_IN_RUST=1 - ENABLE_EXTERN_PROCESSING=1 +RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/Cargo.toml index 743b97c036..7db289b458 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/Cargo.toml @@ -5,19 +5,13 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html -[features] -wrapped-client = [] - [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies] -simple_blob = { path = ".", features = ["wrapped-client"] } - -[dependencies.tokio] +[dev-dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client.rs index 71235fc03b..0e7fbefea4 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -14,10 +13,9 @@ impl Client { pub fn from_conf( conf: crate::types::simple_blob_config::SimpleBlobConfig, ) -> Result { - let inner = - crate::simple::types::blob::internaldafny::_default::SimpleBlob( - &crate::conversions::simple_blob_config::_simple_blob_config::to_dafny(conf), - ); + let inner = crate::simple::types::blob::internaldafny::_default::SimpleBlob( + &crate::conversions::simple_blob_config::_simple_blob_config::to_dafny(conf), + ); if matches!( inner.as_ref(), crate::_Wrappers_Compile::Result::Failure { .. } @@ -30,11 +28,11 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), }) } } mod get_blob; -mod get_blob_known_value_test; +mod get_blob_known_value; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob.rs index 4247bbc32d..c09128d419 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob.rs @@ -1,13 +1,11 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { /// Constructs a fluent builder for the [`GetBlob`](crate::operation::get_blob::builders::GetBlobFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_blob::builders::GetBlobFluentBuilder::value) / [`set_value(Option<::aws_smithy_types::Blob>)`](crate::operation::get_blob::builders::GetBlobFluentBuilder::set_value): (undocumented)
+ /// - [`value(impl Into<::dafny_runtime::Sequence>)`](crate::operation::get_blob::builders::GetBlobFluentBuilder::value) / [`set_value(Option<::dafny_runtime::Sequence>)`](crate::operation::get_blob::builders::GetBlobFluentBuilder::set_value):(undocumented)
/// - On success, responds with [`GetBlobOutput`](crate::operation::get_blob::GetBlobOutput) with field(s): - /// - [`value(Option<::aws_smithy_types::Blob>)`](crate::operation::get_blob::GetBlobOutput::value): (undocumented) + /// - [`value(Option)`](crate::operation::get_blob::GetBlobOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_blob::GetBlobError) pub fn get_blob(&self) -> crate::operation::get_blob::builders::GetBlobFluentBuilder { crate::operation::get_blob::builders::GetBlobFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value.rs new file mode 100644 index 0000000000..a8831d2421 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value.rs @@ -0,0 +1,17 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +impl super::Client { + /// Constructs a fluent builder for the [`GetBlob`](crate::operation::get_blob_known_value::builders::GetBlobFluentBuilder) operation. + /// + /// - The fluent builder is configurable: + /// - [`value(impl Into<::dafny_runtime::Sequence>)`](crate::operation::get_blob_known_value::builders::GetBlobFluentBuilder::value) / [`set_value(Option<::dafny_runtime::Sequence>)`](crate::operation::get_blob_known_value::builders::GetBlobFluentBuilder::set_value):(undocumented)
+ /// - On success, responds with [`GetBlobOutput`](crate::operation::get_blob_known_value::GetBlobOutput) with field(s): + /// - [`value(Option)`](crate::operation::get_blob_known_value::GetBlobOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_blob_known_value::GetBlobError) + pub fn get_blob_known_value( + &self, + ) -> crate::operation::get_blob_known_value::builders::GetBlobKnownValueFluentBuilder { + crate::operation::get_blob_known_value::builders::GetBlobKnownValueFluentBuilder::new( + self.clone(), + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value_test.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value_test.rs deleted file mode 100644 index eec5e197f0..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value_test.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -impl super::Client { - /// Constructs a fluent builder for the [`GetBlobKnownValueTest`](crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder) operation. - /// - /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder::value) / [`set_value(Option<::aws_smithy_types::Blob>)`](crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder::set_value): (undocumented)
- /// - On success, responds with [`GetBlobOutput`](crate::operation::get_blob_known_value_test::GetBlobOutput) with field(s): - /// - [`value(Option<::aws_smithy_types::Blob>)`](crate::operation::get_blob_known_value_test::GetBlobOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError) - pub fn get_blob_known_value_test(&self) -> crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder { - crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder::new(self.clone()) - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions.rs index cf1c199d5b..1cd4ad224e 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions.rs @@ -1,10 +1,6 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod error; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub mod get_blob; - pub mod get_blob; +pub mod get_blob_known_value; - pub mod get_blob_known_value_test; - - pub mod simple_blob_config; +pub mod simple_blob_config; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/error.rs deleted file mode 100644 index 6d52bba84a..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/error.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. - /// Wraps up an arbitrary Rust Error value as a Dafny Error -pub fn to_opaque_error(value: E) -> - ::std::rc::Rc -{ - let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( - ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), - )); - ::std::rc::Rc::new( - crate::r#simple::types::blob::internaldafny::types::Error::Opaque { - obj: error_obj, - }, - ) -} - -/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure -pub fn to_opaque_error_result(value: E) -> - ::std::rc::Rc< - crate::_Wrappers_Compile::Result< - T, - ::std::rc::Rc - > - > -{ - ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: to_opaque_error(value), - }, - ) -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob.rs index d38674b069..43479fd3c9 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] @@ -8,9 +7,14 @@ pub fn to_dafny_error( value: crate::operation::get_blob::GetBlobError, ) -> ::std::rc::Rc { match value { - crate::operation::get_blob::GetBlobError::Unhandled(unhandled) => - ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) - } + crate::operation::get_blob::GetBlobError::Unhandled(unhandled) => ::std::rc::Rc::new( + crate::r#simple::types::blob::internaldafny::types::Error::Opaque { + obj: ::dafny_runtime::upcast_object()( + ::dafny_runtime::object::new(unhandled), + ), + }, + ), + } } #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_input.rs index d37000fe2b..4e91b06d53 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_input.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_input.rs @@ -1,24 +1,42 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_blob::GetBlobInput, -) -> ::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::GetBlobInput, ->{ +) -> ::std::rc::Rc +{ + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { + value: ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&v, |x| *x), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobInput::GetBlobInput { - value: crate::standard_library_conversions::oblob_to_dafny(&value.value), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::blob::internaldafny::types::GetBlobInput, >, ) -> crate::operation::get_blob::GetBlobInput { - crate::operation::get_blob::GetBlobInput::builder() - .set_value(crate::standard_library_conversions::oblob_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + ::std::rc::Rc::try_unwrap(dafny_value.value().Extract().to_array()) + .unwrap_or_else(|rc| (*rc).clone()), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + + crate::operation::get_blob::GetBlobInput { value } } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_output.rs index a36a0e65c7..e9770da2c5 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_output.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_output.rs @@ -1,24 +1,43 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_blob::GetBlobOutput, -) -> ::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, ->{ +) -> ::std::rc::Rc +{ + let dafny_value = match value.value { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&b, |e| *e), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobOutput::GetBlobOutput { - value: crate::standard_library_conversions::oblob_to_dafny(&value.value), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, >, ) -> crate::operation::get_blob::GetBlobOutput { - crate::operation::get_blob::GetBlobOutput::builder() - .set_value(crate::standard_library_conversions::oblob_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( + &dafny_value.value().Extract(), + |e| *e, + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_blob::GetBlobOutput { value } } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value.rs new file mode 100644 index 0000000000..50a67357d0 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value.rs @@ -0,0 +1,39 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +use std::any::Any; + +#[allow(dead_code)] +pub fn to_dafny_error( + value: crate::operation::get_blob_known_value::GetBlobKnownValueError, +) -> ::std::rc::Rc { + match value { + crate::operation::get_blob_known_value::GetBlobKnownValueError::Unhandled(unhandled) => { + ::std::rc::Rc::new( + crate::r#simple::types::blob::internaldafny::types::Error::Opaque { + obj: ::dafny_runtime::upcast_object()( + ::dafny_runtime::object::new(unhandled), + ), + }, + ) + } + } +} + +#[allow(dead_code)] +pub fn from_dafny_error( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::Error, + >, +) -> crate::operation::get_blob_known_value::GetBlobKnownValueError { + // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error + if matches!(&dafny_value.as_ref(), crate::r#simple::types::blob::internaldafny::types::Error::CollectionOfErrors { .. }) { + let error_message = "TODO: can't get message yet"; + crate::operation::get_blob_known_value::GetBlobKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) + } else { + crate::operation::get_blob_known_value::GetBlobKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) + } +} + +pub mod _get_blob_known_value_input; + +pub mod _get_blob_known_value_output; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_input.rs new file mode 100644 index 0000000000..1e939e99a8 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_input.rs @@ -0,0 +1,41 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_blob_known_value::GetBlobKnownValueInput, +) -> ::std::rc::Rc +{ + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { + value: ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&v, |x| *x), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobInput::GetBlobInput { + value: ::std::rc::Rc::new(dafny_value) + }) +} + +#[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobInput, + >, +) -> crate::operation::get_blob_known_value::GetBlobKnownValueInput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + ::std::rc::Rc::try_unwrap(dafny_value.value().Extract().to_array()) + .unwrap_or_else(|rc| (*rc).clone()), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_blob_known_value::GetBlobKnownValueInput { value } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_output.rs new file mode 100644 index 0000000000..19cf635501 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_output.rs @@ -0,0 +1,43 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_blob_known_value::GetBlobKnownValueOutput, +) -> ::std::rc::Rc +{ + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { + value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&v, |e| *e), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobOutput::GetBlobOutput { + value: ::std::rc::Rc::new(dafny_value) + }) +} + +#[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, + >, +) -> crate::operation::get_blob_known_value::GetBlobKnownValueOutput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( + &dafny_value.value().Extract(), + |e| *e, + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_blob_known_value::GetBlobKnownValueOutput { value } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test.rs deleted file mode 100644 index 7ff941094b..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test.rs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use std::any::Any; - -#[allow(dead_code)] -pub fn to_dafny_error( - value: crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError, -) -> ::std::rc::Rc { - match value { - crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError::Unhandled(unhandled) => - ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) - } -} - -#[allow(dead_code)] -pub fn from_dafny_error( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::Error, - >, -) -> crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError { - // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error - if matches!(&dafny_value.as_ref(), crate::r#simple::types::blob::internaldafny::types::Error::CollectionOfErrors { .. }) { - let error_message = "TODO: can't get message yet"; - crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) - } else { - crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) - } -} - -pub mod _get_blob_known_value_test_input; - -pub mod _get_blob_known_value_test_output; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_input.rs deleted file mode 100644 index 49d2466ee7..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_input.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_blob_known_value_test::GetBlobInput, -) -> ::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::GetBlobInput, ->{ - ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobInput::GetBlobInput { - value: crate::standard_library_conversions::oblob_to_dafny(&value.value), - }) -} - #[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::GetBlobInput, - >, -) -> crate::operation::get_blob_known_value_test::GetBlobInput { - crate::operation::get_blob_known_value_test::GetBlobInput::builder() - .set_value(crate::standard_library_conversions::oblob_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_output.rs deleted file mode 100644 index 499929ee0a..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_output.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_blob_known_value_test::GetBlobOutput, -) -> ::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, ->{ - ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobOutput::GetBlobOutput { - value: crate::standard_library_conversions::oblob_to_dafny(&value.value), - }) -} - #[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, - >, -) -> crate::operation::get_blob_known_value_test::GetBlobOutput { - crate::operation::get_blob_known_value_test::GetBlobOutput::builder() - .set_value(crate::standard_library_conversions::oblob_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config.rs index 7852c4ae19..89599c3f8c 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config.rs @@ -1,4 +1,3 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + pub mod _simple_blob_config; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config/_simple_blob_config.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config/_simple_blob_config.rs index a9e1abdffe..d0a4cd5c44 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config/_simple_blob_config.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config/_simple_blob_config.rs @@ -1,13 +1,10 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_blob_config::SimpleBlobConfig, -) -> ::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::SimpleBlobConfig, -> { +) -> ::std::rc::Rc +{ ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::SimpleBlobConfig::SimpleBlobConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error.rs index 4cddaa7c39..ec89cbecc9 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error/sealed_unhandled.rs index eae8007292..cce22d1cfd 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,10 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use std::any::Any; - -use dafny_runtime::UpcastObject; - +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -27,6 +21,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl UpcastObject for Unhandled { +impl ::dafny_runtime::UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/lib.rs new file mode 100644 index 0000000000..3938142e1c --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/lib.rs @@ -0,0 +1,19 @@ +#![allow(deprecated)] + +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +pub mod client; +pub mod types; + +/// Common errors and error handling utilities. +pub mod error; + +/// All operations that this crate can perform. +pub mod operation; + +mod conversions; + +pub mod implementation_from_dafny; + +pub use client::Client; +pub use types::simple_blob_config::SimpleBlobConfig; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation.rs index 64ee269b55..a72267eda2 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation.rs @@ -1,8 +1,7 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + /// Types for the `GetBlob` operation. pub mod get_blob; -/// Types for the `GetBlobKnownValueTest` operation. -pub mod get_blob_known_value_test; +/// Types for the `GetBlobKnownValue` operation. +pub mod get_blob_known_value; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob.rs index 037e8b83af..2c923f1aa7 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetBlob`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -18,17 +16,14 @@ impl GetBlob { crate::operation::get_blob::GetBlobError, > { let inner_input = crate::conversions::get_blob::_get_blob_input::to_dafny(input); - let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetBlob(&inner_input); + let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetBlob(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - Ok( - crate::conversions::get_blob::_get_blob_output::from_dafny( - inner_result.value().clone(), - ), - ) + Ok(crate::conversions::get_blob::_get_blob_output::from_dafny( + inner_result.value().clone(), + )) } else { Err(crate::conversions::get_blob::from_dafny_error( inner_result.error().clone(), @@ -139,9 +134,9 @@ pub use crate::operation::get_blob::_get_blob_output::GetBlobOutput; pub use crate::operation::get_blob::_get_blob_input::GetBlobInput; -pub(crate) mod _get_blob_output; +mod _get_blob_input; -pub(crate) mod _get_blob_input; +mod _get_blob_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_input.rs index 335f1e1a36..6a0d554b13 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_input.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_input.rs @@ -1,18 +1,16 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetBlobInput { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::aws_smithy_types::Blob>, + pub value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, } impl GetBlobInput { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::Blob> { - self.value.clone() -} + pub fn value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { + self.value.as_ref() + } } impl GetBlobInput { /// Creates a new builder-style object to manufacture [`GetBlobInput`](crate::operation::operation::GetBlobInput). @@ -27,23 +25,29 @@ impl GetBlobInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetBlobInputBuilder { - pub(crate) value: ::std::option::Option<::aws_smithy_types::Blob>, + pub(crate) value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, } impl GetBlobInputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { - &self.value -} + pub fn value( + mut self, + input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { + self.value.as_ref() + } /// Consumes the builder and constructs a [`GetBlobInput`](crate::operation::operation::GetBlobInput). pub fn build( self, @@ -51,8 +55,6 @@ pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { crate::operation::get_blob::GetBlobInput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_blob::GetBlobInput { - value: self.value, - }) + ::std::result::Result::Ok(crate::operation::get_blob::GetBlobInput { value: self.value }) } } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_output.rs index 7de15870c4..b071eb836e 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_output.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_output.rs @@ -1,19 +1,19 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetBlobOutput { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::aws_smithy_types::Blob>, + pub value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, } + impl GetBlobOutput { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::Blob> { - self.value.clone() -} + pub fn value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { + self.value.as_ref() + } } + impl GetBlobOutput { /// Creates a new builder-style object to manufacture [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). pub fn builder() -> crate::operation::get_blob::builders::GetBlobOutputBuilder { @@ -27,23 +27,33 @@ impl GetBlobOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetBlobOutputBuilder { - pub(crate) value: ::std::option::Option<::aws_smithy_types::Blob>, + pub(crate) value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, } + impl GetBlobOutputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { - &self.value -} + pub fn value( + mut self, + input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, + ) -> Self { + self.value = input; + self + } + + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { + self.value.as_ref() + } + /// Consumes the builder and constructs a [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). pub fn build( self, @@ -51,8 +61,6 @@ pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { crate::operation::get_blob::GetBlobOutput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_blob::GetBlobOutput { - value: self.value, - }) + ::std::result::Result::Ok(crate::operation::get_blob::GetBlobOutput { value: self.value }) } } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/builders.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/builders.rs index 7fd6ca61e8..bedb57b108 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/builders.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/builders.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use crate::operation::get_blob::_get_blob_output::GetBlobOutputBuilder; pub use crate::operation::get_blob::_get_blob_input::GetBlobInputBuilder; @@ -24,7 +22,7 @@ impl GetBlobInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetBlobFluentBuilder { client: crate::client::Client, - pub(crate) inner: crate::operation::get_blob::builders::GetBlobInputBuilder, + inner: crate::operation::get_blob::builders::GetBlobInputBuilder, } impl GetBlobFluentBuilder { /// Creates a new `GetBlob`. @@ -58,17 +56,23 @@ impl GetBlobFluentBuilder { } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { - self.inner.get_value() -} + pub fn value( + mut self, + input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, + ) -> Self { + self.inner = self.inner.value(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, + ) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value.rs similarity index 67% rename from TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test.rs rename to TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value.rs index 32709dd754..ee1819d4fd 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value.rs @@ -1,46 +1,44 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -/// Orchestration and serialization glue logic for `GetBlobKnownValueTest`. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +/// Orchestration and serialization glue logic for `GetBlobKnownValue`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] -pub struct GetBlobKnownValueTest; -impl GetBlobKnownValueTest { - /// Creates a new `GetBlobKnownValueTest` +pub struct GetBlobKnownValue; +impl GetBlobKnownValue { + /// Creates a new `GetBlobKnownValue` pub fn new() -> Self { Self } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_blob_known_value_test::GetBlobInput, + input: crate::operation::get_blob_known_value::GetBlobKnownValueInput, ) -> ::std::result::Result< - crate::operation::get_blob_known_value_test::GetBlobOutput, - crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError, + crate::operation::get_blob_known_value::GetBlobKnownValueOutput, + crate::operation::get_blob_known_value::GetBlobKnownValueError, > { - let inner_input = crate::conversions::get_blob_known_value_test::_get_blob_known_value_test_input::to_dafny(input); - let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetBlobKnownValueTest(&inner_input); + let inner_input = + crate::conversions::get_blob_known_value::_get_blob_known_value_input::to_dafny(input); + let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetBlob(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { Ok( - crate::conversions::get_blob_known_value_test::_get_blob_known_value_test_output::from_dafny( + crate::conversions::get_blob_known_value::_get_blob_known_value_output::from_dafny( inner_result.value().clone(), ), ) } else { - Err(crate::conversions::get_blob_known_value_test::from_dafny_error( + Err(crate::conversions::get_blob_known_value::from_dafny_error( inner_result.error().clone(), )) } } } -/// Error type for the `GetBlobKnownValueTest` operation. +/// Error type for the `GetBlobKnownValue` operation. #[non_exhaustive] #[derive(::std::fmt::Debug)] -pub enum GetBlobKnownValueTestError { +pub enum GetBlobKnownValueError { /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ @@ -48,12 +46,12 @@ pub enum GetBlobKnownValueTestError { \    `err if err.code() == Some(\"SpecificExceptionCode\") => { /* handle the error */ }` \ - See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetBlobKnownValueTestError) for what information is available for the error." + See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetBlobKnownValueError) for what information is available for the error." )] Unhandled(crate::error::sealed_unhandled::Unhandled), } -impl GetBlobKnownValueTestError { - /// Creates the `GetBlobKnownValueTestError::Unhandled` variant from any error type. +impl GetBlobKnownValueError { + /// Creates the `GetBlobKnownValueError::Unhandled` variant from any error type. pub fn unhandled( err: impl ::std::convert::Into< ::std::boxed::Box< @@ -67,7 +65,7 @@ impl GetBlobKnownValueTestError { }) } - /// Creates the `GetBlobKnownValueTestError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). + /// Creates the `GetBlobKnownValueError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). pub fn generic(err: ::aws_smithy_types::error::ErrorMetadata) -> Self { Self::Unhandled(crate::error::sealed_unhandled::Unhandled { source: err.clone().into(), @@ -84,14 +82,14 @@ impl GetBlobKnownValueTestError { } } } -impl ::std::error::Error for GetBlobKnownValueTestError { +impl ::std::error::Error for GetBlobKnownValueError { fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> { match self { Self::Unhandled(_inner) => ::std::option::Option::Some(&*_inner.source), } } } -impl ::std::fmt::Display for GetBlobKnownValueTestError { +impl ::std::fmt::Display for GetBlobKnownValueError { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self { Self::Unhandled(_inner) => { @@ -106,7 +104,7 @@ impl ::std::fmt::Display for GetBlobKnownValueTestError { } } } -impl ::aws_smithy_types::retry::ProvideErrorKind for GetBlobKnownValueTestError { +impl ::aws_smithy_types::retry::ProvideErrorKind for GetBlobKnownValueError { fn code(&self) -> ::std::option::Option<&str> { ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self) } @@ -114,14 +112,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetBlobKnownValueTestError ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetBlobKnownValueTestError { +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetBlobKnownValueError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetBlobKnownValueTestError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetBlobKnownValueError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -135,13 +133,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetBlobK } } -pub use crate::operation::get_blob_known_value_test::_get_blob_output::GetBlobOutput; +pub use crate::operation::get_blob_known_value::_get_blob_known_value_output::GetBlobKnownValueOutput; -pub use crate::operation::get_blob_known_value_test::_get_blob_input::GetBlobInput; +pub use crate::operation::get_blob_known_value::_get_blob_known_value_input::GetBlobKnownValueInput; -pub(crate) mod _get_blob_output; +mod _get_blob_known_value_input; -pub(crate) mod _get_blob_input; +mod _get_blob_known_value_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_input.rs new file mode 100644 index 0000000000..be28c19c10 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_input.rs @@ -0,0 +1,63 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetBlobKnownValueInput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, +} +impl GetBlobKnownValueInput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { + self.value.as_ref() + } +} +impl GetBlobKnownValueInput { + /// Creates a new builder-style object to manufacture [`GetBlobKnownValueInput`](crate::operation::operation::GetBlobKnownValueInput). + pub fn builder( + ) -> crate::operation::get_blob_known_value::builders::GetBlobKnownValueInputBuilder { + crate::operation::get_blob_known_value::builders::GetBlobKnownValueInputBuilder::default() + } +} + +/// A builder for [`GetBlobKnownValueInput`](crate::operation::operation::GetBlobKnownValueInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetBlobKnownValueInputBuilder { + pub(crate) value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, +} +impl GetBlobKnownValueInputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::vec::Vec<::std::primitive::u8>> { + &self.value + } + /// Consumes the builder and constructs a [`GetBlobKnownValueInput`](crate::operation::operation::GetBlobKnownValueInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_blob_known_value::GetBlobKnownValueInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_blob_known_value::GetBlobKnownValueInput { value: self.value }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_output.rs new file mode 100644 index 0000000000..794b83ce46 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_output.rs @@ -0,0 +1,63 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetBlobKnownValueOutput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, +} +impl GetBlobKnownValueOutput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { + self.value.as_ref() + } +} +impl GetBlobKnownValueOutput { + /// Creates a new builder-style object to manufacture [`GetBlobKnownValueOutput`](crate::operation::operation::GetBlobKnownValueOutput). + pub fn builder( + ) -> crate::operation::get_blob_known_value::builders::GetBlobKnownValueOutputBuilder { + crate::operation::get_blob_known_value::builders::GetBlobKnownValueOutputBuilder::default() + } +} + +/// A builder for [`GetBlobKnownValueOutput`](crate::operation::operation::GetBlobKnownValueOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetBlobKnownValueOutputBuilder { + pub(crate) value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, +} +impl GetBlobKnownValueOutputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::vec::Vec<::std::primitive::u8>> { + &self.value + } + /// Consumes the builder and constructs a [`GetBlobKnownValueOutput`](crate::operation::operation::GetBlobKnownValueOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_blob_known_value::GetBlobKnownValueOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_blob_known_value::GetBlobKnownValueOutput { value: self.value }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/builders.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/builders.rs new file mode 100644 index 0000000000..274bb3f376 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/builders.rs @@ -0,0 +1,80 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub use crate::operation::get_blob_known_value::_get_blob_known_value_output::GetBlobKnownValueOutputBuilder; + +pub use crate::operation::get_blob_known_value::_get_blob_known_value_input::GetBlobKnownValueInputBuilder; + +impl GetBlobKnownValueInputBuilder { + /// Sends a request with this input using the given client. + pub async fn send_with( + self, + client: &crate::Client, + ) -> ::std::result::Result< + crate::operation::get_blob_known_value::GetBlobKnownValueOutput, + crate::operation::get_blob_known_value::GetBlobKnownValueError, + > { + let mut fluent_builder = client.get_blob_known_value(); + fluent_builder.inner = self; + fluent_builder.send().await + } +} +/// Fluent builder constructing a request to `GetBlobKnownValue`. +/// +#[derive(::std::clone::Clone, ::std::fmt::Debug)] +pub struct GetBlobKnownValueFluentBuilder { + client: crate::client::Client, + inner: crate::operation::get_blob_known_value::builders::GetBlobKnownValueInputBuilder, +} +impl GetBlobKnownValueFluentBuilder { + /// Creates a new `GetBlobKnownValue`. + pub(crate) fn new(client: crate::client::Client) -> Self { + Self { + client, + inner: ::std::default::Default::default(), + } + } + /// Access the GetBlobKnownValue as a reference. + pub fn as_input( + &self, + ) -> &crate::operation::get_blob_known_value::builders::GetBlobKnownValueInputBuilder { + &self.inner + } + /// Sends the request and returns the response. + pub async fn send( + self, + ) -> ::std::result::Result< + crate::operation::get_blob_known_value::GetBlobKnownValueOutput, + crate::operation::get_blob_known_value::GetBlobKnownValueError, + > { + let input = self + .inner + .build() + // Using unhandled since GetBlob doesn't declare any validation, + // and smithy-rs seems to not generate a ValidationError case unless there is + // (but isn't that a backwards compatibility problem for output structures?) + // Vanilla smithy-rs uses SdkError::construction_failure, + // but we aren't using SdkError. + .map_err(crate::operation::get_blob_known_value::GetBlobKnownValueError::unhandled)?; + crate::operation::get_blob_known_value::GetBlobKnownValue::send(&self.client, input).await + } + + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, + ) -> Self { + self.inner = self.inner.value(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, + ) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::vec::Vec<::std::primitive::u8>> { + self.inner.get_value() + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_input.rs deleted file mode 100644 index 9eb9a55b98..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_input.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetBlobInput { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::aws_smithy_types::Blob>, -} -impl GetBlobInput { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::Blob> { - self.value.clone() -} -} -impl GetBlobInput { - /// Creates a new builder-style object to manufacture [`GetBlobInput`](crate::operation::operation::GetBlobInput). - pub fn builder() -> crate::operation::get_blob_known_value_test::builders::GetBlobInputBuilder { - crate::operation::get_blob_known_value_test::builders::GetBlobInputBuilder::default() - } -} - -/// A builder for [`GetBlobInput`](crate::operation::operation::GetBlobInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetBlobInputBuilder { - pub(crate) value: ::std::option::Option<::aws_smithy_types::Blob>, -} -impl GetBlobInputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { - &self.value -} - /// Consumes the builder and constructs a [`GetBlobInput`](crate::operation::operation::GetBlobInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_blob_known_value_test::GetBlobInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_blob_known_value_test::GetBlobInput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_output.rs deleted file mode 100644 index 81cb83d89b..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_output.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetBlobOutput { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::aws_smithy_types::Blob>, -} -impl GetBlobOutput { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::Blob> { - self.value.clone() -} -} -impl GetBlobOutput { - /// Creates a new builder-style object to manufacture [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). - pub fn builder() -> crate::operation::get_blob_known_value_test::builders::GetBlobOutputBuilder { - crate::operation::get_blob_known_value_test::builders::GetBlobOutputBuilder::default() - } -} - -/// A builder for [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetBlobOutputBuilder { - pub(crate) value: ::std::option::Option<::aws_smithy_types::Blob>, -} -impl GetBlobOutputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { - &self.value -} - /// Consumes the builder and constructs a [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_blob_known_value_test::GetBlobOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_blob_known_value_test::GetBlobOutput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/builders.rs deleted file mode 100644 index b7ef06d065..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/builders.rs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub use crate::operation::get_blob_known_value_test::_get_blob_output::GetBlobOutputBuilder; - -pub use crate::operation::get_blob_known_value_test::_get_blob_input::GetBlobInputBuilder; - -impl GetBlobInputBuilder { - /// Sends a request with this input using the given client. - pub async fn send_with( - self, - client: &crate::Client, - ) -> ::std::result::Result< - crate::operation::get_blob_known_value_test::GetBlobOutput, - crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError, - > { - let mut fluent_builder = client.get_blob_known_value_test(); - fluent_builder.inner = self; - fluent_builder.send().await - } -} -/// Fluent builder constructing a request to `GetBlobKnownValueTest`. -/// -#[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct GetBlobKnownValueTestFluentBuilder { - client: crate::client::Client, - pub(crate) inner: crate::operation::get_blob_known_value_test::builders::GetBlobInputBuilder, -} -impl GetBlobKnownValueTestFluentBuilder { - /// Creates a new `GetBlobKnownValueTest`. - pub(crate) fn new(client: crate::client::Client) -> Self { - Self { - client, - inner: ::std::default::Default::default(), - } - } - /// Access the GetBlobKnownValueTest as a reference. - pub fn as_input(&self) -> &crate::operation::get_blob_known_value_test::builders::GetBlobInputBuilder { - &self.inner - } - /// Sends the request and returns the response. - pub async fn send( - self, - ) -> ::std::result::Result< - crate::operation::get_blob_known_value_test::GetBlobOutput, - crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError, - > { - let input = self - .inner - .build() - // Using unhandled since GetBlobKnownValueTest doesn't declare any validation, - // and smithy-rs seems to not generate a ValidationError case unless there is - // (but isn't that a backwards compatibility problem for output structures?) - // Vanilla smithy-rs uses SdkError::construction_failure, - // but we aren't using SdkError. - .map_err(crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError::unhandled)?; - crate::operation::get_blob_known_value_test::GetBlobKnownValueTest::send(&self.client, input).await - } - - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { - self.inner.get_value() -} -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_conversions.rs index 6bf8297d8a..3a51134c6e 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_conversions.rs @@ -1,266 +1,246 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + >, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny( - input: &Option, -) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny( + input: &::aws_smithy_types::Blob, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny( + input: ::dafny_runtime::Sequence, +) -> ::aws_smithy_types::Blob { + + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()) + .unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x, - ) +pub fn double_to_dafny( + input: f64, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny( + input: &::dafny_runtime::Sequence, +) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: &::aws_smithy_types::DateTime, + input: ::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &input.to_string(), - ) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, -> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc>> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input, - ); - ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) - .unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); + ::aws_smithy_types::DateTime::from_str( + &s, + aws_smithy_types::date_time::Format::DateTime, + ).unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::DateTime> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None {} => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None { } => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { - value: converter(&value), - }), - None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), - } + match input { + Some(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::Some { + value: converter(&value) + } + ), + None => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::None {} + ), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value), - }), - Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error), - }), - } -} + match input { + Ok(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value) + } + ), + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error) + } + ), + } +} \ No newline at end of file diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types.rs index ce57ffa44f..1dca219a01 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types.rs @@ -1,5 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + /// Types for the `SimpleBlobConfig` pub mod simple_blob_config; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types/simple_blob_config.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types/simple_blob_config.rs index 8386df9739..0709ccb7ee 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types/simple_blob_config.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types/simple_blob_config.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleBlobConfig {} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped.rs deleted file mode 100644 index 5c03253bfb..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod client; - -impl crate::r#simple::types::blob::internaldafny::wrapped::_default { - pub fn WrappedSimpleBlob(config: &::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::SimpleBlobConfig, - >) -> ::std::rc::Rc, - ::std::rc::Rc - >>{ - crate::wrapped::client::Client::from_conf(config) - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped/client.rs deleted file mode 100644 index 1cfbbbb813..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped/client.rs +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use tokio::runtime::Runtime; - -pub struct Client { - wrapped: crate::client::Client, - - /// A `current_thread` runtime for executing operations on the - /// asynchronous client in a blocking manner. - rt: Runtime -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::blob::internaldafny::types::ISimpleTypesBlobClient); -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); -} - -impl Client { - pub fn from_conf(config: &::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::SimpleBlobConfig, - >) -> -::std::rc::Rc, - ::std::rc::Rc ->> { - let rt_result = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build(); - let rt = match rt_result { - Ok(x) => x, - Err(error) => return crate::conversions::error::to_opaque_error_result(error), - }; - let result = crate::client::Client::from_conf( - crate::conversions::simple_blob_config::_simple_blob_config::from_dafny( - config.clone(), - ), - ); - match result { - Ok(client) => { - let wrap = crate::wrapped::client::Client { - wrapped: client, - rt - }; - std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) - } - ) - }, - Err(error) => crate::conversions::error::to_opaque_error_result(error) - } - } -} - -impl crate::r#simple::types::blob::internaldafny::types::ISimpleTypesBlobClient for Client { - fn GetBlob( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::GetBlobInput, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_blob::_get_blob_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_blob::GetBlob::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_blob::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_blob::_get_blob_output::to_dafny(client), - }, - ), - } - } - - fn GetBlobKnownValueTest( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::GetBlobInput, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_blob_known_value_test::_get_blob_known_value_test_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_blob_known_value_test::GetBlobKnownValueTest::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_blob_known_value_test::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_blob_known_value_test::_get_blob_known_value_test_output::to_dafny(client), - }, - ), - } - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/tests/simple_blob_test.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/tests/simple_blob_test.rs index b9c9ed9970..bf6ce9675d 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/tests/simple_blob_test.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/tests/simple_blob_test.rs @@ -32,11 +32,11 @@ use simple_blob::*; */ #[tokio::test] async fn test_get_blob() { - let s = aws_smithy_types::Blob::new(vec![0x0, 0x1, 0x2]); + let s = vec![0x0, 0x1, 0x2]; let result = client().get_blob().value(s.clone()).send().await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, s); + assert_eq!(value, &s); } /* @@ -64,15 +64,15 @@ async fn test_get_blob() { #[tokio::test] async fn test_get_known_value() { - let s = aws_smithy_types::Blob::new(vec![0x0, 0x2, 0x4]); + let s = vec![0x0, 0x2, 0x4]; let result = client() - .get_blob_known_value_test() + .get_blob_known_value() .value(s.clone()) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, s); + assert_eq!(value, &s); } pub fn client() -> Client { diff --git a/TestModels/SimpleTypes/SimpleBoolean/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleBoolean/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/SimpleTypes/SimpleBoolean/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/SimpleTypes/SimpleDouble/Makefile b/TestModels/SimpleTypes/SimpleDouble/Makefile index 2fc8ca1be2..032b8a16ae 100644 --- a/TestModels/SimpleTypes/SimpleDouble/Makefile +++ b/TestModels/SimpleTypes/SimpleDouble/Makefile @@ -3,9 +3,8 @@ CORES=2 -TRANSPILE_TESTS_IN_RUST=1 - ENABLE_EXTERN_PROCESSING=1 +RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/Cargo.toml index 0135a1e231..3bb72ebe2d 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/Cargo.toml @@ -5,19 +5,13 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html -[features] -wrapped-client = [] - [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies] -simple_double = { path = ".", features = ["wrapped-client"] } - -[dependencies.tokio] +[dev-dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client.rs index a858580317..5827083463 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -30,7 +29,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), }) } } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client/get_double.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client/get_double.rs index a41fdf754f..db3ce635ea 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client/get_double.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client/get_double.rs @@ -1,13 +1,11 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { /// Constructs a fluent builder for the [`GetDouble`](crate::operation::get_double::builders::GetDoubleFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_double::builders::GetDoubleFluentBuilder::value) / [`set_value(Option<::std::primitive::f64>)`](crate::operation::get_double::builders::GetDoubleFluentBuilder::set_value): (undocumented)
+ /// - [`value(f64)`](crate::operation::get_double::builders::GetDoubleFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_double::builders::GetDoubleFluentBuilder::set_value):(undocumented)
/// - On success, responds with [`GetDoubleOutput`](crate::operation::get_double::GetDoubleOutput) with field(s): - /// - [`value(Option<::std::primitive::f64>)`](crate::operation::get_double::GetDoubleOutput::value): (undocumented) + /// - [`value(Option)`](crate::operation::get_double::GetDoubleOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_double::GetDoubleError) pub fn get_double(&self) -> crate::operation::get_double::builders::GetDoubleFluentBuilder { crate::operation::get_double::builders::GetDoubleFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions.rs index f861ad1749..08430ee335 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions.rs @@ -1,8 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod error; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub mod get_double; - pub mod get_double; - - pub mod simple_double_config; +pub mod simple_double_config; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/error.rs deleted file mode 100644 index 1003d3aed9..0000000000 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/error.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. - /// Wraps up an arbitrary Rust Error value as a Dafny Error -pub fn to_opaque_error(value: E) -> - ::std::rc::Rc -{ - let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( - ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), - )); - ::std::rc::Rc::new( - crate::r#simple::types::smithydouble::internaldafny::types::Error::Opaque { - obj: error_obj, - }, - ) -} - -/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure -pub fn to_opaque_error_result(value: E) -> - ::std::rc::Rc< - crate::_Wrappers_Compile::Result< - T, - ::std::rc::Rc - > - > -{ - ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: to_opaque_error(value), - }, - ) -} diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double.rs index e886c559a7..45f3afc17c 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double.rs @@ -1,12 +1,12 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_double::GetDoubleError, -) -> ::std::rc::Rc { +) -> ::std::rc::Rc +{ match value { crate::operation::get_double::GetDoubleError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithydouble::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_input.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_input.rs index a0b6588355..1a6a82f8ef 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_input.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_input.rs @@ -1,24 +1,47 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_double::GetDoubleInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleInput, ->{ +> { + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { + value: ::dafny_runtime::Sequence::ArraySequence { + values: std::rc::Rc::new(f64::to_be_bytes(v).to_vec()), + }, + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleInput::GetDoubleInput { - value: crate::standard_library_conversions::odouble_to_dafny(&value.value), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleInput, >, ) -> crate::operation::get_double::GetDoubleInput { - crate::operation::get_double::GetDoubleInput::builder() - .set_value(crate::standard_library_conversions::odouble_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + let my_vec = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( + &dafny_value.value().Extract(), + |x| *x, + ); + Some(f64::from_be_bytes( + my_vec.try_into().expect("Error converting Sequence to f64"), + )) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_double::GetDoubleInput { value } } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_output.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_output.rs index 6607d6788e..5dcd0eb48a 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_output.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_output.rs @@ -1,24 +1,47 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_double::GetDoubleOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleOutput, ->{ +> { + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { + value: ::dafny_runtime::Sequence::ArraySequence { + values: std::rc::Rc::new(f64::to_be_bytes(v).to_vec()), + }, + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleOutput::GetDoubleOutput { - value: crate::standard_library_conversions::odouble_to_dafny(&value.value), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleOutput, >, ) -> crate::operation::get_double::GetDoubleOutput { - crate::operation::get_double::GetDoubleOutput::builder() - .set_value(crate::standard_library_conversions::odouble_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + let my_vec = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( + &dafny_value.value().Extract(), + |x| *x, + ); + Some(f64::from_be_bytes( + my_vec.try_into().expect("Error converting Sequence to f64"), + )) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_double::GetDoubleOutput { value } } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config.rs index 4289c31fa4..52a68a7b0e 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config.rs @@ -1,4 +1,3 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + pub mod _simple_double_config; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config/_simple_double_config.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config/_simple_double_config.rs index 4dd5aa6c03..f726f08b6d 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config/_simple_double_config.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config/_simple_double_config.rs @@ -1,12 +1,10 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_double_config::SimpleDoubleConfig, ) -> ::std::rc::Rc< - crate::r#simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig, + crate::simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig, > { ::std::rc::Rc::new(crate::r#simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig::SimpleDoubleConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error.rs index 4cddaa7c39..ec89cbecc9 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error/sealed_unhandled.rs index eae8007292..cce22d1cfd 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,10 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use std::any::Any; - -use dafny_runtime::UpcastObject; - +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -27,6 +21,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl UpcastObject for Unhandled { +impl ::dafny_runtime::UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/lib.rs new file mode 100644 index 0000000000..94379fc047 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/lib.rs @@ -0,0 +1,19 @@ +#![allow(deprecated)] + +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +pub mod client; +pub mod types; + +/// Common errors and error handling utilities. +pub mod error; + +/// All operations that this crate can perform. +pub mod operation; + +mod conversions; + +pub mod implementation_from_dafny; + +pub use client::Client; +pub use types::simple_double_config::SimpleDoubleConfig; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation.rs index 3b489e6c92..134175f816 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation.rs @@ -1,5 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + /// Types for the `GetDouble` operation. pub mod get_double; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double.rs index 38c65eb849..8b6d980d91 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetDouble`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -139,9 +137,9 @@ pub use crate::operation::get_double::_get_double_output::GetDoubleOutput; pub use crate::operation::get_double::_get_double_input::GetDoubleInput; -pub(crate) mod _get_double_output; +mod _get_double_input; -pub(crate) mod _get_double_input; +mod _get_double_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_input.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_input.rs index 598b2c0b07..af1cc4102d 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_input.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_input.rs @@ -1,18 +1,16 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetDoubleInput { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::primitive::f64>, + pub value: ::std::option::Option, } impl GetDoubleInput { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::primitive::f64> { - self.value -} + pub fn value(&self) -> ::std::option::Option<&f64> { + self.value.as_ref() + } } impl GetDoubleInput { /// Creates a new builder-style object to manufacture [`GetDoubleInput`](crate::operation::operation::GetDoubleInput). @@ -27,23 +25,23 @@ impl GetDoubleInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetDoubleInputBuilder { - pub(crate) value: ::std::option::Option<::std::primitive::f64>, + pub(crate) value: ::std::option::Option, } impl GetDoubleInputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::f64>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::f64>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::f64> { - &self.value -} + pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + &self.value + } /// Consumes the builder and constructs a [`GetDoubleInput`](crate::operation::operation::GetDoubleInput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_output.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_output.rs index 20305255c7..bf850acd35 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_output.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_output.rs @@ -1,19 +1,19 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetDoubleOutput { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::primitive::f64>, + pub value: ::std::option::Option, } + impl GetDoubleOutput { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::primitive::f64> { - self.value -} + pub fn value(&self) -> ::std::option::Option { + self.value + } } + impl GetDoubleOutput { /// Creates a new builder-style object to manufacture [`GetDoubleOutput`](crate::operation::operation::GetDoubleOutput). pub fn builder() -> crate::operation::get_double::builders::GetDoubleOutputBuilder { @@ -27,23 +27,27 @@ impl GetDoubleOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetDoubleOutputBuilder { - pub(crate) value: ::std::option::Option<::std::primitive::f64>, + pub(crate) value: ::std::option::Option, } + impl GetDoubleOutputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::f64>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::f64>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::f64> { - &self.value -} + pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self + } + + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetDoubleOutput`](crate::operation::operation::GetDoubleOutput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/builders.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/builders.rs index dd6f7e015f..ed9fd9a40b 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/builders.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/builders.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use crate::operation::get_double::_get_double_output::GetDoubleOutputBuilder; pub use crate::operation::get_double::_get_double_input::GetDoubleInputBuilder; @@ -24,7 +22,7 @@ impl GetDoubleInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetDoubleFluentBuilder { client: crate::client::Client, - pub(crate) inner: crate::operation::get_double::builders::GetDoubleInputBuilder, + inner: crate::operation::get_double::builders::GetDoubleInputBuilder, } impl GetDoubleFluentBuilder { /// Creates a new `GetDouble`. @@ -58,17 +56,17 @@ impl GetDoubleFluentBuilder { } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::f64>) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::f64>) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::f64> { - self.inner.get_value() -} + pub fn value(mut self, input: f64) -> Self { + self.inner = self.inner.value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_conversions.rs index 6bf8297d8a..3a51134c6e 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_conversions.rs @@ -1,266 +1,246 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + >, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny( - input: &Option, -) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny( + input: &::aws_smithy_types::Blob, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny( + input: ::dafny_runtime::Sequence, +) -> ::aws_smithy_types::Blob { + + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()) + .unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x, - ) +pub fn double_to_dafny( + input: f64, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny( + input: &::dafny_runtime::Sequence, +) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: &::aws_smithy_types::DateTime, + input: ::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &input.to_string(), - ) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, -> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc>> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input, - ); - ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) - .unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); + ::aws_smithy_types::DateTime::from_str( + &s, + aws_smithy_types::date_time::Format::DateTime, + ).unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::DateTime> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None {} => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None { } => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { - value: converter(&value), - }), - None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), - } + match input { + Some(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::Some { + value: converter(&value) + } + ), + None => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::None {} + ), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value), - }), - Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error), - }), - } -} + match input { + Ok(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value) + } + ), + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error) + } + ), + } +} \ No newline at end of file diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types.rs index 3154f39ef3..92447294d0 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types.rs @@ -1,5 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + /// Types for the `SimpleDoubleConfig` pub mod simple_double_config; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types/simple_double_config.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types/simple_double_config.rs index 46db0da2e6..b776656296 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types/simple_double_config.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types/simple_double_config.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleDoubleConfig {} diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped.rs deleted file mode 100644 index 2b7522dd24..0000000000 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod client; - -impl crate::r#simple::types::smithydouble::internaldafny::wrapped::_default { - pub fn WrappedSimpleDouble(config: &::std::rc::Rc< - crate::r#simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig, - >) -> ::std::rc::Rc, - ::std::rc::Rc - >>{ - crate::wrapped::client::Client::from_conf(config) - } -} diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped/client.rs deleted file mode 100644 index 281878c6a9..0000000000 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped/client.rs +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use tokio::runtime::Runtime; - -pub struct Client { - wrapped: crate::client::Client, - - /// A `current_thread` runtime for executing operations on the - /// asynchronous client in a blocking manner. - rt: Runtime -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::smithydouble::internaldafny::types::ISimpleTypesDoubleClient); -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); -} - -impl Client { - pub fn from_conf(config: &::std::rc::Rc< - crate::r#simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig, - >) -> -::std::rc::Rc, - ::std::rc::Rc ->> { - let rt_result = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build(); - let rt = match rt_result { - Ok(x) => x, - Err(error) => return crate::conversions::error::to_opaque_error_result(error), - }; - let result = crate::client::Client::from_conf( - crate::conversions::simple_double_config::_simple_double_config::from_dafny( - config.clone(), - ), - ); - match result { - Ok(client) => { - let wrap = crate::wrapped::client::Client { - wrapped: client, - rt - }; - std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) - } - ) - }, - Err(error) => crate::conversions::error::to_opaque_error_result(error) - } - } -} - -impl crate::r#simple::types::smithydouble::internaldafny::types::ISimpleTypesDoubleClient for Client { - fn GetDouble( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleInput, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleOutput, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_double::_get_double_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_double::GetDouble::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_double::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_double::_get_double_output::to_dafny(client), - }, - ), - } - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/Makefile b/TestModels/SimpleTypes/SimpleEnum/Makefile index 01aa866e43..62c78e49de 100644 --- a/TestModels/SimpleTypes/SimpleEnum/Makefile +++ b/TestModels/SimpleTypes/SimpleEnum/Makefile @@ -3,9 +3,8 @@ CORES=2 -TRANSPILE_TESTS_IN_RUST=1 - ENABLE_EXTERN_PROCESSING=1 +RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/Cargo.toml index fb5b567bbf..a3026b8a68 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/Cargo.toml @@ -5,19 +5,13 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html -[features] -wrapped-client = [] - [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies] -simple_enum = { path = ".", features = ["wrapped-client"] } - -[dependencies.tokio] +[dev-dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client.rs index 3357e68544..9649346b6f 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -30,7 +29,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), }) } } @@ -38,7 +37,5 @@ impl Client { mod get_enum; mod get_enum_first_known_value_test; - mod get_enum_second_known_value_test; - mod get_enum_third_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum.rs index 1f8ad39bc1..f0c395251e 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum.rs @@ -1,13 +1,11 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { /// Constructs a fluent builder for the [`GetEnum`](crate::operation::get_enum::builders::GetEnumFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_enum::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum::builders::GetEnumFluentBuilder::set_value): (undocumented)
+ /// - [`value(SimpleEnumShape)`](crate::operation::get_enum::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum::builders::GetEnumFluentBuilder::set_value):(undocumented)
/// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum::GetEnumOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_enum::GetEnumOutput::value): (undocumented) + /// - [`value(Option)`](crate::operation::get_enum::GetEnumOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_enum::GetEnumError) pub fn get_enum(&self) -> crate::operation::get_enum::builders::GetEnumFluentBuilder { crate::operation::get_enum::builders::GetEnumFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_first_known_value_test.rs index fe5b423fa2..a169931d82 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_first_known_value_test.rs @@ -1,15 +1,18 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { - /// Constructs a fluent builder for the [`GetEnumFirstKnownValueTest`](crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnum`](crate::operation::get_enum_first_known_value::builders::GetEnumFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder::set_value): (undocumented)
- /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_first_known_value_test::GetEnumOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_first_known_value_test::GetEnumOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError) - pub fn get_enum_first_known_value_test(&self) -> crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder { - crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder::new(self.clone()) + /// - [`value(SimpleEnumShape)`](crate::operation::get_enum_first_known_value::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_first_known_value::builders::GetEnumFluentBuilder::set_value):(undocumented)
+ /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_first_known_value::GetEnumOutput) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_first_known_value::GetEnumOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_first_known_value::GetEnumError) + pub fn get_enum_first_known_value_test( + &self, + ) -> crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder + { + crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder::new( + self.clone(), + ) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_second_known_value_test.rs index 4e9a16e551..8e4ec068d2 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_second_known_value_test.rs @@ -1,15 +1,18 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { - /// Constructs a fluent builder for the [`GetEnumSecondKnownValueTest`](crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnum`](crate::operation::get_enum_second_known_value::builders::GetEnumFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder::set_value): (undocumented)
- /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_second_known_value_test::GetEnumOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_second_known_value_test::GetEnumOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError) - pub fn get_enum_second_known_value_test(&self) -> crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder { - crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder::new(self.clone()) + /// - [`value(SimpleEnumShape)`](crate::operation::get_enum_second_known_value::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_second_known_value::builders::GetEnumFluentBuilder::set_value):(undocumented)
+ /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_second_known_value::GetEnumOutput) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_second_known_value::GetEnumOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_second_known_value::GetEnumError) + pub fn get_enum_second_known_value_test( + &self, + ) -> crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder + { + crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder::new( + self.clone(), + ) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_third_known_value_test.rs index 01060bfee7..47bdeb2fd5 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_third_known_value_test.rs @@ -1,15 +1,18 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { - /// Constructs a fluent builder for the [`GetEnumThirdKnownValueTest`](crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnum`](crate::operation::get_enum_third_known_value::builders::GetEnumFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder::set_value): (undocumented)
- /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_third_known_value_test::GetEnumOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_third_known_value_test::GetEnumOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError) - pub fn get_enum_third_known_value_test(&self) -> crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder { - crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder::new(self.clone()) + /// - [`value(SimpleEnumShape)`](crate::operation::get_enum_third_known_value::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_third_known_value::builders::GetEnumFluentBuilder::set_value):(undocumented)
+ /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_third_known_value::GetEnumOutput) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_third_known_value::GetEnumOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_third_known_value::GetEnumError) + pub fn get_enum_third_known_value_test( + &self, + ) -> crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder + { + crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder::new( + self.clone(), + ) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions.rs index 23444400ba..7361ee56f3 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions.rs @@ -1,16 +1,9 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod error; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub mod get_enum; - pub mod get_enum; +pub mod get_enum_first_known_value_test; +pub mod get_enum_second_known_value_test; +pub mod get_enum_third_known_value_test; - pub mod get_enum_first_known_value_test; - - pub mod get_enum_second_known_value_test; - - pub mod get_enum_third_known_value_test; - - pub mod simple_enum_config; - - pub mod simple_enum_shape; +pub mod simple_enum_config; +pub mod simple_enum_shape; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/error.rs deleted file mode 100644 index b16869c834..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/error.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. - /// Wraps up an arbitrary Rust Error value as a Dafny Error -pub fn to_opaque_error(value: E) -> - ::std::rc::Rc -{ - let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( - ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), - )); - ::std::rc::Rc::new( - crate::r#simple::types::smithyenum::internaldafny::types::Error::Opaque { - obj: error_obj, - }, - ) -} - -/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure -pub fn to_opaque_error_result(value: E) -> - ::std::rc::Rc< - crate::_Wrappers_Compile::Result< - T, - ::std::rc::Rc - > - > -{ - ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: to_opaque_error(value), - }, - ) -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum.rs index 6d75d851f5..ef493d1195 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_input.rs index 6d65b89526..3bbf16021f 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_input.rs @@ -1,34 +1,45 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_enum::GetEnumInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, ->{ +> { + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&v), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput::GetEnumInput { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, >, ) -> crate::operation::get_enum::GetEnumInput { - crate::operation::get_enum::GetEnumInput::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum::GetEnumInput { value } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_output.rs index 8511c2d0ba..1ae04378cc 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_output.rs @@ -1,34 +1,45 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_enum::GetEnumOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, ->{ +> { + let dafny_value = match value.value { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&b), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput::GetEnumOutput { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, >, ) -> crate::operation::get_enum::GetEnumOutput { - crate::operation::get_enum::GetEnumOutput::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum::GetEnumOutput { value } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test.rs index 51b4ad7bd9..5e3e946f36 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs index bd024fe5c6..453989647e 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs @@ -1,34 +1,45 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_first_known_value_test::GetEnumInput, + value: crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, ->{ +> { + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&v), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput::GetEnumInput { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, >, -) -> crate::operation::get_enum_first_known_value_test::GetEnumInput { - crate::operation::get_enum_first_known_value_test::GetEnumInput::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() +) -> crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput { value } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs index 0b94ed08ad..c31403c9c8 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs @@ -1,34 +1,45 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_first_known_value_test::GetEnumOutput, + value: crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, ->{ +> { + let dafny_value = match value.value { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&b), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput::GetEnumOutput { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, >, -) -> crate::operation::get_enum_first_known_value_test::GetEnumOutput { - crate::operation::get_enum_first_known_value_test::GetEnumOutput::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() +) -> crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput { value } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test.rs index 37724a3683..afa0c42cd6 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs index 0124095fbf..c73d8a6308 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs @@ -1,34 +1,45 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_second_known_value_test::GetEnumInput, + value: crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, ->{ +> { + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&v), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput::GetEnumInput { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, >, -) -> crate::operation::get_enum_second_known_value_test::GetEnumInput { - crate::operation::get_enum_second_known_value_test::GetEnumInput::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() +) -> crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput { value } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs index 6f9b39a9ab..fbb2809ed3 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs @@ -1,34 +1,45 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_second_known_value_test::GetEnumOutput, + value: crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, ->{ +> { + let dafny_value = match value.value { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&b), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput::GetEnumOutput { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, >, -) -> crate::operation::get_enum_second_known_value_test::GetEnumOutput { - crate::operation::get_enum_second_known_value_test::GetEnumOutput::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() +) -> crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput { value } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test.rs index 8860c8548a..b3d8d1186e 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs index bf7ce0415c..73c9d9b6f0 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs @@ -1,34 +1,45 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_third_known_value_test::GetEnumInput, + value: crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, ->{ +> { + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&v), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput::GetEnumInput { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, >, -) -> crate::operation::get_enum_third_known_value_test::GetEnumInput { - crate::operation::get_enum_third_known_value_test::GetEnumInput::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() +) -> crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput { value } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs index 0199b60a8e..aafc1403e6 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs @@ -1,34 +1,45 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_third_known_value_test::GetEnumOutput, + value: crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, ->{ +> { + let dafny_value = match value.value { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&b), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput::GetEnumOutput { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, >, -) -> crate::operation::get_enum_third_known_value_test::GetEnumOutput { - crate::operation::get_enum_third_known_value_test::GetEnumOutput::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() +) -> crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput { value } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config.rs index 6b6b7d9e31..973679ee23 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config.rs @@ -1,4 +1,3 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + pub mod _simple_enum_config; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config/_simple_enum_config.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config/_simple_enum_config.rs index 3fcaeb06a4..a1e48e7f0e 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config/_simple_enum_config.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config/_simple_enum_config.rs @@ -1,12 +1,10 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_enum_config::SimpleEnumConfig, ) -> ::std::rc::Rc< - crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumConfig, + crate::simple::types::smithyenum::internaldafny::types::SimpleEnumConfig, > { ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumConfig::SimpleEnumConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape.rs index 994d63ed8a..f531b5531f 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape.rs @@ -1,25 +1,3 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(dead_code)] +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub fn to_dafny( - value: crate::types::SimpleEnumShape, -) -> ::std::rc::Rc{ - ::std::rc::Rc::new(match value { - crate::types::SimpleEnumShape::First => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::FIRST {}, -crate::types::SimpleEnumShape::Second => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::SECOND {}, -crate::types::SimpleEnumShape::Third => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::THIRD {}, - _ => panic!("Unknown enum variant: {}", value), - }) -} - #[allow(dead_code)] -pub fn from_dafny( - dafny_value: &crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape, -) -> crate::types::SimpleEnumShape { - match dafny_value { - crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::FIRST {} => crate::types::SimpleEnumShape::First, -crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::SECOND {} => crate::types::SimpleEnumShape::Second, -crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::THIRD {} => crate::types::SimpleEnumShape::Third, - } -} +pub mod _simple_enum_shape; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape/_simple_enum_shape.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape/_simple_enum_shape.rs new file mode 100644 index 0000000000..8519605a7c --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape/_simple_enum_shape.rs @@ -0,0 +1,23 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(dead_code)] + +pub fn to_dafny( + value: &crate::types::simple_enum_shape::SimpleEnumShape, +) -> crate::simple::types::smithyenum::internaldafny::types::SimpleEnumShape { + match value { + crate::types::simple_enum_shape::SimpleEnumShape::FIRST => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::FIRST {}, + crate::types::simple_enum_shape::SimpleEnumShape::SECOND => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::SECOND {}, + crate::types::simple_enum_shape::SimpleEnumShape::THIRD => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::THIRD {}, + } +} + +#[allow(dead_code)] +pub fn from_dafny( + dafny_value: &crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape, +) -> crate::types::simple_enum_shape::SimpleEnumShape { + match dafny_value { + crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::FIRST {} => crate::types::simple_enum_shape::SimpleEnumShape::FIRST, + crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::SECOND {} => crate::types::simple_enum_shape::SimpleEnumShape::SECOND, + crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::THIRD {} => crate::types::simple_enum_shape::SimpleEnumShape::THIRD, + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error.rs index 4cddaa7c39..ec89cbecc9 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error/sealed_unhandled.rs index eae8007292..cce22d1cfd 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,10 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use std::any::Any; - -use dafny_runtime::UpcastObject; - +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -27,6 +21,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl UpcastObject for Unhandled { +impl ::dafny_runtime::UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/lib.rs new file mode 100644 index 0000000000..f914e7ba96 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/lib.rs @@ -0,0 +1,19 @@ +#![allow(deprecated)] + +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +pub mod client; +pub mod types; + +/// Common errors and error handling utilities. +pub mod error; + +/// All operations that this crate can perform. +pub mod operation; + +mod conversions; + +pub mod implementation_from_dafny; + +pub use client::Client; +pub use types::simple_enum_config::SimpleEnumConfig; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation.rs index febf44fb04..560af2715d 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation.rs @@ -1,14 +1,9 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + /// Types for the `GetEnum` operation. pub mod get_enum; -/// Types for the `GetEnumFirstKnownValueTest` operation. +/// Types for the `GetEnumKnownValue` operation. pub mod get_enum_first_known_value_test; - -/// Types for the `GetEnumSecondKnownValueTest` operation. pub mod get_enum_second_known_value_test; - -/// Types for the `GetEnumThirdKnownValueTest` operation. pub mod get_enum_third_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum.rs index 58f7c64109..d75b5ac448 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetEnum`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -18,17 +16,14 @@ impl GetEnum { crate::operation::get_enum::GetEnumError, > { let inner_input = crate::conversions::get_enum::_get_enum_input::to_dafny(input); - let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); + let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - Ok( - crate::conversions::get_enum::_get_enum_output::from_dafny( - inner_result.value().clone(), - ), - ) + Ok(crate::conversions::get_enum::_get_enum_output::from_dafny( + inner_result.value().clone(), + )) } else { Err(crate::conversions::get_enum::from_dafny_error( inner_result.error().clone(), @@ -139,9 +134,9 @@ pub use crate::operation::get_enum::_get_enum_output::GetEnumOutput; pub use crate::operation::get_enum::_get_enum_input::GetEnumInput; -pub(crate) mod _get_enum_output; +mod _get_enum_input; -pub(crate) mod _get_enum_input; +mod _get_enum_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_input.rs index 5308a7b969..37b1f16c17 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_input.rs @@ -1,18 +1,19 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetEnumInput { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, + pub value: ::std::option::Option, } impl GetEnumInput { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} + pub fn message( + &self, + ) -> ::std::option::Option<&crate::types::simple_enum_shape::SimpleEnumShape> { + self.value.as_ref() + } } impl GetEnumInput { /// Creates a new builder-style object to manufacture [`GetEnumInput`](crate::operation::operation::GetEnumInput). @@ -27,23 +28,31 @@ impl GetEnumInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetEnumInputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option, } impl GetEnumInputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } /// Consumes the builder and constructs a [`GetEnumInput`](crate::operation::operation::GetEnumInput). pub fn build( self, @@ -51,8 +60,6 @@ pub fn get_value(&self) -> &::std::option::Option crate::operation::get_enum::GetEnumInput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_enum::GetEnumInput { - value: self.value, - }) + ::std::result::Result::Ok(crate::operation::get_enum::GetEnumInput { value: self.value }) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_output.rs index 7a05b95d39..9675cc2c25 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_output.rs @@ -1,19 +1,20 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetEnumOutput { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, + pub value: ::std::option::Option, } + impl GetEnumOutput { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} + pub fn value(&self) -> ::std::option::Option { + self.value + } } + impl GetEnumOutput { /// Creates a new builder-style object to manufacture [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). pub fn builder() -> crate::operation::get_enum::builders::GetEnumOutputBuilder { @@ -27,23 +28,35 @@ impl GetEnumOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetEnumOutputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option, } + impl GetEnumOutputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). pub fn build( self, @@ -51,8 +64,6 @@ pub fn get_value(&self) -> &::std::option::Option crate::operation::get_enum::GetEnumOutput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_enum::GetEnumOutput { - value: self.value, - }) + ::std::result::Result::Ok(crate::operation::get_enum::GetEnumOutput { value: self.value }) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/builders.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/builders.rs index 34ee4503e4..11e371c133 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/builders.rs @@ -1,9 +1,6 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub use crate::operation::get_enum::_get_enum_output::GetEnumOutputBuilder; - +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use crate::operation::get_enum::_get_enum_input::GetEnumInputBuilder; +pub use crate::operation::get_enum::_get_enum_output::GetEnumOutputBuilder; impl GetEnumInputBuilder { /// Sends a request with this input using the given client. @@ -24,7 +21,7 @@ impl GetEnumInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumFluentBuilder { client: crate::client::Client, - pub(crate) inner: crate::operation::get_enum::builders::GetEnumInputBuilder, + inner: crate::operation::get_enum::builders::GetEnumInputBuilder, } impl GetEnumFluentBuilder { /// Creates a new `GetEnum`. @@ -58,17 +55,22 @@ impl GetEnumFluentBuilder { } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() -} + pub fn value(mut self, input: crate::types::simple_enum_shape::SimpleEnumShape) -> Self { + self.inner = self.inner.value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test.rs index 43bf7cd236..106ec1702c 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetEnumFirstKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -12,14 +10,14 @@ impl GetEnumFirstKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_first_known_value_test::GetEnumInput, + input: crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput, ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumOutput, + crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError, > { - let inner_input = crate::conversions::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::to_dafny(input); - let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumFirstKnownValueTest(&inner_input); + let inner_input = + crate::conversions::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::to_dafny(input); + let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -30,9 +28,11 @@ impl GetEnumFirstKnownValueTest { ), ) } else { - Err(crate::conversions::get_enum_first_known_value_test::from_dafny_error( - inner_result.error().clone(), - )) + Err( + crate::conversions::get_enum_first_known_value_test::from_dafny_error( + inner_result.error().clone(), + ), + ) } } } @@ -41,7 +41,7 @@ impl GetEnumFirstKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumFirstKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unfirst_known error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -121,7 +121,9 @@ impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumFirstK } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumFirstKnownValueTestError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError + for GetEnumFirstKnownValueTestError +{ fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -135,13 +137,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumF } } -pub use crate::operation::get_enum_first_known_value_test::_get_enum_output::GetEnumOutput; +pub use crate::operation::get_enum_first_known_value_test::_get_enum_first_known_value_test_output::GetEnumFirstKnownValueTestOutput; -pub use crate::operation::get_enum_first_known_value_test::_get_enum_input::GetEnumInput; +pub use crate::operation::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::GetEnumFirstKnownValueTestInput; -pub(crate) mod _get_enum_output; +mod _get_enum_first_known_value_test_input; -pub(crate) mod _get_enum_input; +mod _get_enum_first_known_value_test_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs new file mode 100644 index 0000000000..866727550e --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs @@ -0,0 +1,69 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumFirstKnownValueTestInput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetEnumFirstKnownValueTestInput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option { + self.value + } +} +impl GetEnumFirstKnownValueTestInput { + /// Creates a new builder-style object to manufacture [`GetEnumFirstKnownValueTestInput`](crate::operation::operation::GetEnumFirstKnownValueTestInput). + pub fn builder( + ) -> crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestInputBuilder + { + crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestInputBuilder::default() + } +} + +/// A builder for [`GetEnumFirstKnownValueTestInput`](crate::operation::operation::GetEnumFirstKnownValueTestInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumFirstKnownValueTestInputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumFirstKnownValueTestInputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetEnumFirstKnownValueTestInput`](crate::operation::operation::GetEnumFirstKnownValueTestInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs new file mode 100644 index 0000000000..65154c9626 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs @@ -0,0 +1,69 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumFirstKnownValueTestOutput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetEnumFirstKnownValueTestOutput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option { + self.value + } +} +impl GetEnumFirstKnownValueTestOutput { + /// Creates a new builder-style object to manufacture [`GetEnumFirstKnownValueTestOutput`](crate::operation::operation::GetEnumFirstKnownValueTestOutput). + pub fn builder( + ) -> crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestOutputBuilder + { + crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestOutputBuilder::default() + } +} + +/// A builder for [`GetEnumFirstKnownValueTestOutput`](crate::operation::operation::GetEnumFirstKnownValueTestOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumFirstKnownValueTestOutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumFirstKnownValueTestOutputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetEnumFirstKnownValueTestOutput`](crate::operation::operation::GetEnumFirstKnownValueTestOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_input.rs deleted file mode 100644 index 9ebdf0a653..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_input.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumInput { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, -} -impl GetEnumInput { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} -} -impl GetEnumInput { - /// Creates a new builder-style object to manufacture [`GetEnumInput`](crate::operation::operation::GetEnumInput). - pub fn builder() -> crate::operation::get_enum_first_known_value_test::builders::GetEnumInputBuilder { - crate::operation::get_enum_first_known_value_test::builders::GetEnumInputBuilder::default() - } -} - -/// A builder for [`GetEnumInput`](crate::operation::operation::GetEnumInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumInputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} - /// Consumes the builder and constructs a [`GetEnumInput`](crate::operation::operation::GetEnumInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_enum_first_known_value_test::GetEnumInput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_output.rs deleted file mode 100644 index 78d1bf2081..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_output.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumOutput { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, -} -impl GetEnumOutput { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} -} -impl GetEnumOutput { - /// Creates a new builder-style object to manufacture [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). - pub fn builder() -> crate::operation::get_enum_first_known_value_test::builders::GetEnumOutputBuilder { - crate::operation::get_enum_first_known_value_test::builders::GetEnumOutputBuilder::default() - } -} - -/// A builder for [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumOutputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} - /// Consumes the builder and constructs a [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_enum_first_known_value_test::GetEnumOutput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/builders.rs index 4da9155d3b..ca84c9774f 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/builders.rs @@ -1,17 +1,14 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub use crate::operation::get_enum_first_known_value_test::_get_enum_output::GetEnumOutputBuilder; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub use crate::operation::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::GetEnumFirstKnownValueTestInputBuilder; +pub use crate::operation::get_enum_first_known_value_test::_get_enum_first_known_value_test_output::GetEnumFirstKnownValueTestOutputBuilder; -pub use crate::operation::get_enum_first_known_value_test::_get_enum_input::GetEnumInputBuilder; - -impl GetEnumInputBuilder { +impl GetEnumFirstKnownValueTestInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumOutput, + crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError, > { let mut fluent_builder = client.get_enum_first_known_value_test(); @@ -24,7 +21,8 @@ impl GetEnumInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumFirstKnownValueTestFluentBuilder { client: crate::client::Client, - pub(crate) inner: crate::operation::get_enum_first_known_value_test::builders::GetEnumInputBuilder, + inner: + crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestInputBuilder, } impl GetEnumFirstKnownValueTestFluentBuilder { /// Creates a new `GetEnumFirstKnownValueTest`. @@ -35,40 +33,52 @@ impl GetEnumFirstKnownValueTestFluentBuilder { } } /// Access the GetEnumFirstKnownValueTest as a reference. - pub fn as_input(&self) -> &crate::operation::get_enum_first_known_value_test::builders::GetEnumInputBuilder { + pub fn as_input( + &self, + ) -> &crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestInputBuilder + { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumOutput, + crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnumFirstKnownValueTest doesn't declare any validation, + // Using unhandled since GetEnum doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError::unhandled)?; - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTest::send(&self.client, input).await + crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTest::send( + &self.client, + input, + ) + .await } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() -} + pub fn value(mut self, input: crate::types::simple_enum_shape::SimpleEnumShape) -> Self { + self.inner = self.inner.value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test.rs index af28939f9c..b59e0ce569 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetEnumSecondKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -12,14 +10,14 @@ impl GetEnumSecondKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_second_known_value_test::GetEnumInput, + input: crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput, ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumOutput, + crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError, > { - let inner_input = crate::conversions::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::to_dafny(input); - let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumSecondKnownValueTest(&inner_input); + let inner_input = + crate::conversions::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::to_dafny(input); + let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -30,9 +28,11 @@ impl GetEnumSecondKnownValueTest { ), ) } else { - Err(crate::conversions::get_enum_second_known_value_test::from_dafny_error( - inner_result.error().clone(), - )) + Err( + crate::conversions::get_enum_second_known_value_test::from_dafny_error( + inner_result.error().clone(), + ), + ) } } } @@ -41,7 +41,7 @@ impl GetEnumSecondKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumSecondKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unsecond_known error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -114,14 +114,18 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetEnumSecondKnownValueTest ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumSecondKnownValueTestError { +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata + for GetEnumSecondKnownValueTestError +{ fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumSecondKnownValueTestError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError + for GetEnumSecondKnownValueTestError +{ fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -135,13 +139,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumS } } -pub use crate::operation::get_enum_second_known_value_test::_get_enum_output::GetEnumOutput; +pub use crate::operation::get_enum_second_known_value_test::_get_enum_second_known_value_test_output::GetEnumSecondKnownValueTestOutput; -pub use crate::operation::get_enum_second_known_value_test::_get_enum_input::GetEnumInput; +pub use crate::operation::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::GetEnumSecondKnownValueTestInput; -pub(crate) mod _get_enum_output; +mod _get_enum_second_known_value_test_input; -pub(crate) mod _get_enum_input; +mod _get_enum_second_known_value_test_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_input.rs deleted file mode 100644 index 494cb01579..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_input.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumInput { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, -} -impl GetEnumInput { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} -} -impl GetEnumInput { - /// Creates a new builder-style object to manufacture [`GetEnumInput`](crate::operation::operation::GetEnumInput). - pub fn builder() -> crate::operation::get_enum_second_known_value_test::builders::GetEnumInputBuilder { - crate::operation::get_enum_second_known_value_test::builders::GetEnumInputBuilder::default() - } -} - -/// A builder for [`GetEnumInput`](crate::operation::operation::GetEnumInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumInputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} - /// Consumes the builder and constructs a [`GetEnumInput`](crate::operation::operation::GetEnumInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_enum_second_known_value_test::GetEnumInput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_output.rs deleted file mode 100644 index 355865e935..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_output.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumOutput { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, -} -impl GetEnumOutput { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} -} -impl GetEnumOutput { - /// Creates a new builder-style object to manufacture [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). - pub fn builder() -> crate::operation::get_enum_second_known_value_test::builders::GetEnumOutputBuilder { - crate::operation::get_enum_second_known_value_test::builders::GetEnumOutputBuilder::default() - } -} - -/// A builder for [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumOutputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} - /// Consumes the builder and constructs a [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_enum_second_known_value_test::GetEnumOutput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs new file mode 100644 index 0000000000..3fb03429b0 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs @@ -0,0 +1,69 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumSecondKnownValueTestInput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetEnumSecondKnownValueTestInput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option { + self.value + } +} +impl GetEnumSecondKnownValueTestInput { + /// Creates a new builder-style object to manufacture [`GetEnumSecondKnownValueTestInput`](crate::operation::operation::GetEnumSecondKnownValueTestInput). + pub fn builder( + ) -> crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestInputBuilder + { + crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestInputBuilder::default() + } +} + +/// A builder for [`GetEnumSecondKnownValueTestInput`](crate::operation::operation::GetEnumSecondKnownValueTestInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumSecondKnownValueTestInputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumSecondKnownValueTestInputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetEnumSecondKnownValueTestInput`](crate::operation::operation::GetEnumSecondKnownValueTestInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs new file mode 100644 index 0000000000..6937025052 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs @@ -0,0 +1,69 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumSecondKnownValueTestOutput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetEnumSecondKnownValueTestOutput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option { + self.value + } +} +impl GetEnumSecondKnownValueTestOutput { + /// Creates a new builder-style object to manufacture [`GetEnumSecondKnownValueTestOutput`](crate::operation::operation::GetEnumSecondKnownValueTestOutput). + pub fn builder( + ) -> crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestOutputBuilder + { + crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestOutputBuilder::default() + } +} + +/// A builder for [`GetEnumSecondKnownValueTestOutput`](crate::operation::operation::GetEnumSecondKnownValueTestOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumSecondKnownValueTestOutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumSecondKnownValueTestOutputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetEnumSecondKnownValueTestOutput`](crate::operation::operation::GetEnumSecondKnownValueTestOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/builders.rs index 1d0afa3fc5..e54348b361 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/builders.rs @@ -1,17 +1,14 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub use crate::operation::get_enum_second_known_value_test::_get_enum_output::GetEnumOutputBuilder; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub use crate::operation::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::GetEnumSecondKnownValueTestInputBuilder; +pub use crate::operation::get_enum_second_known_value_test::_get_enum_second_known_value_test_output::GetEnumSecondKnownValueTestOutputBuilder; -pub use crate::operation::get_enum_second_known_value_test::_get_enum_input::GetEnumInputBuilder; - -impl GetEnumInputBuilder { +impl GetEnumSecondKnownValueTestInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumOutput, + crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError, > { let mut fluent_builder = client.get_enum_second_known_value_test(); @@ -24,7 +21,7 @@ impl GetEnumInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumSecondKnownValueTestFluentBuilder { client: crate::client::Client, - pub(crate) inner: crate::operation::get_enum_second_known_value_test::builders::GetEnumInputBuilder, + inner: crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestInputBuilder, } impl GetEnumSecondKnownValueTestFluentBuilder { /// Creates a new `GetEnumSecondKnownValueTest`. @@ -35,40 +32,52 @@ impl GetEnumSecondKnownValueTestFluentBuilder { } } /// Access the GetEnumSecondKnownValueTest as a reference. - pub fn as_input(&self) -> &crate::operation::get_enum_second_known_value_test::builders::GetEnumInputBuilder { + pub fn as_input( + &self, + ) -> &crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestInputBuilder + { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumOutput, + crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnumSecondKnownValueTest doesn't declare any validation, + // Using unhandled since GetEnum doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError::unhandled)?; - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTest::send(&self.client, input).await + crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTest::send( + &self.client, + input, + ) + .await } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() -} + pub fn value(mut self, input: crate::types::simple_enum_shape::SimpleEnumShape) -> Self { + self.inner = self.inner.value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test.rs index 0b3f627823..d5def6ff29 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetEnumThirdKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -12,14 +10,14 @@ impl GetEnumThirdKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_third_known_value_test::GetEnumInput, + input: crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput, ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumOutput, + crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError, > { - let inner_input = crate::conversions::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::to_dafny(input); - let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumThirdKnownValueTest(&inner_input); + let inner_input = + crate::conversions::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::to_dafny(input); + let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -30,9 +28,11 @@ impl GetEnumThirdKnownValueTest { ), ) } else { - Err(crate::conversions::get_enum_third_known_value_test::from_dafny_error( - inner_result.error().clone(), - )) + Err( + crate::conversions::get_enum_third_known_value_test::from_dafny_error( + inner_result.error().clone(), + ), + ) } } } @@ -41,7 +41,7 @@ impl GetEnumThirdKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumThirdKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unthird_known error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -121,7 +121,9 @@ impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumThirdK } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumThirdKnownValueTestError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError + for GetEnumThirdKnownValueTestError +{ fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -135,13 +137,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumT } } -pub use crate::operation::get_enum_third_known_value_test::_get_enum_output::GetEnumOutput; +pub use crate::operation::get_enum_third_known_value_test::_get_enum_third_known_value_test_output::GetEnumThirdKnownValueTestOutput; -pub use crate::operation::get_enum_third_known_value_test::_get_enum_input::GetEnumInput; +pub use crate::operation::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::GetEnumThirdKnownValueTestInput; -pub(crate) mod _get_enum_output; +mod _get_enum_third_known_value_test_input; -pub(crate) mod _get_enum_input; +mod _get_enum_third_known_value_test_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_input.rs deleted file mode 100644 index 5529bb5f1d..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_input.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumInput { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, -} -impl GetEnumInput { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} -} -impl GetEnumInput { - /// Creates a new builder-style object to manufacture [`GetEnumInput`](crate::operation::operation::GetEnumInput). - pub fn builder() -> crate::operation::get_enum_third_known_value_test::builders::GetEnumInputBuilder { - crate::operation::get_enum_third_known_value_test::builders::GetEnumInputBuilder::default() - } -} - -/// A builder for [`GetEnumInput`](crate::operation::operation::GetEnumInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumInputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} - /// Consumes the builder and constructs a [`GetEnumInput`](crate::operation::operation::GetEnumInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_enum_third_known_value_test::GetEnumInput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_output.rs deleted file mode 100644 index 87d794f537..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_output.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumOutput { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, -} -impl GetEnumOutput { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} -} -impl GetEnumOutput { - /// Creates a new builder-style object to manufacture [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). - pub fn builder() -> crate::operation::get_enum_third_known_value_test::builders::GetEnumOutputBuilder { - crate::operation::get_enum_third_known_value_test::builders::GetEnumOutputBuilder::default() - } -} - -/// A builder for [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumOutputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} - /// Consumes the builder and constructs a [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_enum_third_known_value_test::GetEnumOutput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs new file mode 100644 index 0000000000..275d472c06 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs @@ -0,0 +1,68 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumThirdKnownValueTestInput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetEnumThirdKnownValueTestInput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option { + self.value + } +} +impl GetEnumThirdKnownValueTestInput { + /// Creates a new builder-style object to manufacture [`GetEnumThirdKnownValueTestInput`](crate::operation::operation::GetEnumThirdKnownValueTestInput). + pub fn builder( + ) -> crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestInputBuilder + { + crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestInputBuilder::default() + } +} + +/// A builder for [`GetEnumThirdKnownValueTestInput`](crate::operation::operation::GetEnumThirdKnownValueTestInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumThirdKnownValueTestInputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumThirdKnownValueTestInputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetEnumThirdKnownValueTestInput`](crate::operation::operation::GetEnumThirdKnownValueTestInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs new file mode 100644 index 0000000000..e1d498d3e5 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs @@ -0,0 +1,69 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumThirdKnownValueTestOutput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetEnumThirdKnownValueTestOutput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option { + self.value + } +} +impl GetEnumThirdKnownValueTestOutput { + /// Creates a new builder-style object to manufacture [`GetEnumThirdKnownValueTestOutput`](crate::operation::operation::GetEnumThirdKnownValueTestOutput). + pub fn builder( + ) -> crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestOutputBuilder + { + crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestOutputBuilder::default() + } +} + +/// A builder for [`GetEnumThirdKnownValueTestOutput`](crate::operation::operation::GetEnumThirdKnownValueTestOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumThirdKnownValueTestOutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumThirdKnownValueTestOutputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetEnumThirdKnownValueTestOutput`](crate::operation::operation::GetEnumThirdKnownValueTestOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/builders.rs index f51c94119c..db835240b0 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/builders.rs @@ -1,17 +1,14 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub use crate::operation::get_enum_third_known_value_test::_get_enum_output::GetEnumOutputBuilder; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub use crate::operation::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::GetEnumThirdKnownValueTestInputBuilder; +pub use crate::operation::get_enum_third_known_value_test::_get_enum_third_known_value_test_output::GetEnumThirdKnownValueTestOutputBuilder; -pub use crate::operation::get_enum_third_known_value_test::_get_enum_input::GetEnumInputBuilder; - -impl GetEnumInputBuilder { +impl GetEnumThirdKnownValueTestInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumOutput, + crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError, > { let mut fluent_builder = client.get_enum_third_known_value_test(); @@ -24,7 +21,8 @@ impl GetEnumInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumThirdKnownValueTestFluentBuilder { client: crate::client::Client, - pub(crate) inner: crate::operation::get_enum_third_known_value_test::builders::GetEnumInputBuilder, + inner: + crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestInputBuilder, } impl GetEnumThirdKnownValueTestFluentBuilder { /// Creates a new `GetEnumThirdKnownValueTest`. @@ -35,40 +33,52 @@ impl GetEnumThirdKnownValueTestFluentBuilder { } } /// Access the GetEnumThirdKnownValueTest as a reference. - pub fn as_input(&self) -> &crate::operation::get_enum_third_known_value_test::builders::GetEnumInputBuilder { + pub fn as_input( + &self, + ) -> &crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestInputBuilder + { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumOutput, + crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnumThirdKnownValueTest doesn't declare any validation, + // Using unhandled since GetEnum doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError::unhandled)?; - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTest::send(&self.client, input).await + crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTest::send( + &self.client, + input, + ) + .await } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() -} + pub fn value(mut self, input: crate::types::simple_enum_shape::SimpleEnumShape) -> Self { + self.inner = self.inner.value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_conversions.rs index 6bf8297d8a..3a51134c6e 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_conversions.rs @@ -1,266 +1,246 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + >, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny( - input: &Option, -) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny( + input: &::aws_smithy_types::Blob, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny( + input: ::dafny_runtime::Sequence, +) -> ::aws_smithy_types::Blob { + + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()) + .unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x, - ) +pub fn double_to_dafny( + input: f64, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny( + input: &::dafny_runtime::Sequence, +) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: &::aws_smithy_types::DateTime, + input: ::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &input.to_string(), - ) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, -> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc>> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input, - ); - ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) - .unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); + ::aws_smithy_types::DateTime::from_str( + &s, + aws_smithy_types::date_time::Format::DateTime, + ).unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::DateTime> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None {} => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None { } => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { - value: converter(&value), - }), - None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), - } + match input { + Some(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::Some { + value: converter(&value) + } + ), + None => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::None {} + ), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value), - }), - Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error), - }), - } -} + match input { + Ok(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value) + } + ), + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error) + } + ), + } +} \ No newline at end of file diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types.rs index 0f9d2788bd..de39101208 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types.rs @@ -1,8 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -/// Types for the `SimpleEnumConfig` -pub mod simple_enum_config; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -mod _simple_enum_shape; -pub use crate::types::_simple_enum_shape::SimpleEnumShape; +/// Types for the `SimpleIntegerConfig` +pub mod simple_enum_config; +pub mod simple_enum_shape; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/_simple_enum_shape.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/_simple_enum_shape.rs deleted file mode 100644 index fd2b3fdce2..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/_simple_enum_shape.rs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[derive(Debug, PartialEq, Copy, Clone)] -pub enum SimpleEnumShape { - First, -Second, -Third, -} - -impl ::std::fmt::Display for SimpleEnumShape { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - match self { - SimpleEnumShape::First => write!(f, "FIRST"), -SimpleEnumShape::Second => write!(f, "SECOND"), -SimpleEnumShape::Third => write!(f, "THIRD"), - } - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_config.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_config.rs index 7fd6368cb2..fd3ea0e14c 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_config.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_config.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleEnumConfig {} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_shape.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_shape.rs new file mode 100644 index 0000000000..dba3140596 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_shape.rs @@ -0,0 +1,6 @@ +#[derive(Debug, PartialEq, Copy, Clone)] +pub enum SimpleEnumShape { + FIRST, + SECOND, + THIRD, +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped.rs deleted file mode 100644 index fe5929068a..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod client; - -impl crate::r#simple::types::smithyenum::internaldafny::wrapped::_default { - pub fn WrappedSimpleEnum(config: &::std::rc::Rc< - crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumConfig, - >) -> ::std::rc::Rc, - ::std::rc::Rc - >>{ - crate::wrapped::client::Client::from_conf(config) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped/client.rs deleted file mode 100644 index d35f39e8c1..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped/client.rs +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use tokio::runtime::Runtime; - -pub struct Client { - wrapped: crate::client::Client, - - /// A `current_thread` runtime for executing operations on the - /// asynchronous client in a blocking manner. - rt: Runtime -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::smithyenum::internaldafny::types::ISimpleTypesEnumClient); -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); -} - -impl Client { - pub fn from_conf(config: &::std::rc::Rc< - crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumConfig, - >) -> -::std::rc::Rc, - ::std::rc::Rc ->> { - let rt_result = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build(); - let rt = match rt_result { - Ok(x) => x, - Err(error) => return crate::conversions::error::to_opaque_error_result(error), - }; - let result = crate::client::Client::from_conf( - crate::conversions::simple_enum_config::_simple_enum_config::from_dafny( - config.clone(), - ), - ); - match result { - Ok(client) => { - let wrap = crate::wrapped::client::Client { - wrapped: client, - rt - }; - std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) - } - ) - }, - Err(error) => crate::conversions::error::to_opaque_error_result(error) - } - } -} - -impl crate::r#simple::types::smithyenum::internaldafny::types::ISimpleTypesEnumClient for Client { - fn GetEnum( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_enum::_get_enum_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_enum::GetEnum::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_enum::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_enum::_get_enum_output::to_dafny(client), - }, - ), - } - } - - fn GetEnumFirstKnownValueTest( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTest::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_enum_first_known_value_test::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_enum_first_known_value_test::_get_enum_first_known_value_test_output::to_dafny(client), - }, - ), - } - } - - fn GetEnumSecondKnownValueTest( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTest::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_enum_second_known_value_test::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_enum_second_known_value_test::_get_enum_second_known_value_test_output::to_dafny(client), - }, - ), - } - } - - fn GetEnumThirdKnownValueTest( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTest::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_enum_third_known_value_test::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_enum_third_known_value_test::_get_enum_third_known_value_test_output::to_dafny(client), - }, - ), - } - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/tests/simple_enum_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/tests/simple_enum_test.rs index 0e8259e737..8e53533ea3 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/tests/simple_enum_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/tests/simple_enum_test.rs @@ -1,48 +1,48 @@ -use simple_enum::types::SimpleEnumShape::*; +use simple_enum::types::simple_enum_shape::SimpleEnumShape::*; use simple_enum::*; #[tokio::test] async fn test_get_enum() { - let result = client().get_enum().value(Second).send().await; + let result = client().get_enum().value(SECOND).send().await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, Second); + assert_eq!(value, SECOND); } #[tokio::test] async fn test_get_first_known_value() { let result = client() .get_enum_first_known_value_test() - .value(First) + .value(FIRST) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, First); + assert_eq!(value, FIRST); } #[tokio::test] async fn test_get_second_known_value() { let result = client() .get_enum_second_known_value_test() - .value(Second) + .value(SECOND) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, Second); + assert_eq!(value, SECOND); } #[tokio::test] async fn test_get_third_known_value() { let result = client() .get_enum_third_known_value_test() - .value(Third) + .value(THIRD) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, Third); + assert_eq!(value, THIRD); } pub fn client() -> Client { diff --git a/TestModels/SimpleTypes/SimpleEnumV2/Makefile b/TestModels/SimpleTypes/SimpleEnumV2/Makefile index 1cd07bb145..51615d0785 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/Makefile +++ b/TestModels/SimpleTypes/SimpleEnumV2/Makefile @@ -3,9 +3,8 @@ CORES=2 -TRANSPILE_TESTS_IN_RUST=1 - ENABLE_EXTERN_PROCESSING=1 +RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/Cargo.toml index 291c1fd915..dbaad13bfd 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/Cargo.toml @@ -5,19 +5,13 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html -[features] -wrapped-client = [] - [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies] -simple_enum_v2 = { path = ".", features = ["wrapped-client"] } - -[dependencies.tokio] +[dev-dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client.rs index 83490767ce..f7bbdbfacb 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -30,7 +29,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), }) } } @@ -38,7 +37,5 @@ impl Client { mod get_enum_v2; mod get_enum_v2_first_known_value_test; - mod get_enum_v2_second_known_value_test; - mod get_enum_v2_third_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2.rs index 7cc559b930..c9a688bd85 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2.rs @@ -1,13 +1,11 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { /// Constructs a fluent builder for the [`GetEnumV2`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::set_value): (undocumented)
+ /// - [`value(SimpleEnumV2Shape)`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::set_value):(undocumented)
/// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2::GetEnumV2Output) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_v2::GetEnumV2Output::value): (undocumented) + /// - [`value(Option)`](crate::operation::get_enum_v2::GetEnumV2Output::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2::GetEnumV2Error) pub fn get_enum_v2(&self) -> crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder { crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_first_known_value_test.rs index 896b404709..ebde767b2c 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_first_known_value_test.rs @@ -1,15 +1,18 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { - /// Constructs a fluent builder for the [`GetEnumV2FirstKnownValueTest`](crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumV2`](crate::operation::get_enum_v2_first_known_value::builders::GetEnumV2FluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder::set_value): (undocumented)
- /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError) - pub fn get_enum_v2_first_known_value_test(&self) -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder { - crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder::new(self.clone()) + /// - [`value(SimpleEnumV2Shape)`](crate::operation::get_enum_v2_first_known_value::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_first_known_value::builders::GetEnumV2FluentBuilder::set_value):(undocumented)
+ /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_first_known_value::GetEnumV2Output) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_v2_first_known_value::GetEnumV2Output::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_first_known_value::GetEnumV2Error) + pub fn get_enum_v2_first_known_value_test( + &self, + ) -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder + { + crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder::new( + self.clone(), + ) } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_second_known_value_test.rs index 3bbcda3c1f..f4981c29d3 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_second_known_value_test.rs @@ -1,15 +1,18 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { - /// Constructs a fluent builder for the [`GetEnumV2SecondKnownValueTest`](crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumV2`](crate::operation::get_enum_v2_second_known_value::builders::GetEnumV2FluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder::set_value): (undocumented)
- /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError) - pub fn get_enum_v2_second_known_value_test(&self) -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder { - crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder::new(self.clone()) + /// - [`value(SimpleEnumV2Shape)`](crate::operation::get_enum_v2_second_known_value::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_second_known_value::builders::GetEnumV2FluentBuilder::set_value):(undocumented)
+ /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_second_known_value::GetEnumV2Output) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_v2_second_known_value::GetEnumV2Output::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_second_known_value::GetEnumV2Error) + pub fn get_enum_v2_second_known_value_test( + &self, + ) -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder + { + crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder::new( + self.clone(), + ) } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_third_known_value_test.rs index c37fe8c75e..afc875f376 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_third_known_value_test.rs @@ -1,15 +1,18 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { - /// Constructs a fluent builder for the [`GetEnumV2ThirdKnownValueTest`](crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumV2`](crate::operation::get_enum_v2_third_known_value::builders::GetEnumV2FluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder::set_value): (undocumented)
- /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError) - pub fn get_enum_v2_third_known_value_test(&self) -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder { - crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder::new(self.clone()) + /// - [`value(SimpleEnumV2Shape)`](crate::operation::get_enum_v2_third_known_value::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_third_known_value::builders::GetEnumV2FluentBuilder::set_value):(undocumented)
+ /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_third_known_value::GetEnumV2Output) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_v2_third_known_value::GetEnumV2Output::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_third_known_value::GetEnumV2Error) + pub fn get_enum_v2_third_known_value_test( + &self, + ) -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder + { + crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder::new( + self.clone(), + ) } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions.rs index ae84ee4f2d..323761ef25 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions.rs @@ -1,16 +1,9 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod error; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub mod get_enum_v2; - pub mod get_enum_v2; +pub mod get_enum_v2_first_known_value_test; +pub mod get_enum_v2_second_known_value_test; +pub mod get_enum_v2_third_known_value_test; - pub mod get_enum_v2_first_known_value_test; - - pub mod get_enum_v2_second_known_value_test; - - pub mod get_enum_v2_third_known_value_test; - - pub mod simple_enum_v2_config; - - pub mod simple_enum_v2_shape; +pub mod simple_enum_v2_config; +pub mod simple_enum_v2_shape; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/error.rs deleted file mode 100644 index fd8f69459c..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/error.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. - /// Wraps up an arbitrary Rust Error value as a Dafny Error -pub fn to_opaque_error(value: E) -> - ::std::rc::Rc -{ - let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( - ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), - )); - ::std::rc::Rc::new( - crate::r#simple::types::enumv2::internaldafny::types::Error::Opaque { - obj: error_obj, - }, - ) -} - -/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure -pub fn to_opaque_error_result(value: E) -> - ::std::rc::Rc< - crate::_Wrappers_Compile::Result< - T, - ::std::rc::Rc - > - > -{ - ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: to_opaque_error(value), - }, - ) -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2.rs index b6ad1638f4..e9b9909b5d 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] @@ -8,9 +7,14 @@ pub fn to_dafny_error( value: crate::operation::get_enum_v2::GetEnumV2Error, ) -> ::std::rc::Rc { match value { - crate::operation::get_enum_v2::GetEnumV2Error::Unhandled(unhandled) => - ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) - } + crate::operation::get_enum_v2::GetEnumV2Error::Unhandled(unhandled) => ::std::rc::Rc::new( + crate::r#simple::types::enumv2::internaldafny::types::Error::Opaque { + obj: ::dafny_runtime::upcast_object()( + ::dafny_runtime::object::new(unhandled), + ), + }, + ), + } } #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_input.rs index 00959d1e89..236bf35509 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_input.rs @@ -1,34 +1,45 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_enum_v2::GetEnumV2Input, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, ->{ +> { + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&v), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input::GetEnumV2Input { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, >, ) -> crate::operation::get_enum_v2::GetEnumV2Input { - crate::operation::get_enum_v2::GetEnumV2Input::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_v2_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum_v2::GetEnumV2Input { value } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_output.rs index 08130c3e9b..84d950d915 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_output.rs @@ -1,34 +1,45 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_enum_v2::GetEnumV2Output, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, ->{ +> { + let dafny_value = match value.value { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&b), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output::GetEnumV2Output { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, >, ) -> crate::operation::get_enum_v2::GetEnumV2Output { - crate::operation::get_enum_v2::GetEnumV2Output::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_v2_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum_v2::GetEnumV2Output { value } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test.rs index e7bfe032d6..9e85094466 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs index 96fe41e22f..043d693333 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs @@ -1,34 +1,47 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input, + value: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, ->{ +> { + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&v), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input::GetEnumV2Input { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, >, -) -> crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input { - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_v2_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() +) -> crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput { + value, + } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs index 268a2afa6b..7378e11786 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs @@ -1,34 +1,47 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, + value: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, ->{ +> { + let dafny_value = match value.value { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&b), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output::GetEnumV2Output { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, >, -) -> crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output { - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_v2_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() +) -> crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput { + value, + } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test.rs index e64c315050..b6de63fad1 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs index 74e95d15a7..a7a40bf49c 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs @@ -1,34 +1,47 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input, + value: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, ->{ +> { + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&v), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input::GetEnumV2Input { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, >, -) -> crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input { - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_v2_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() +) -> crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput { + value, + } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs index 0b68410110..07bec26645 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs @@ -1,34 +1,47 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, + value: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, ->{ +> { + let dafny_value = match value.value { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&b), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output::GetEnumV2Output { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, >, -) -> crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output { - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_v2_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() +) -> crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput { + value, + } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test.rs index d190f09074..a1ddd7dab5 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs index 1b60f1e579..8adc054b04 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs @@ -1,34 +1,47 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input, + value: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, ->{ +> { + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&v), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input::GetEnumV2Input { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, >, -) -> crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input { - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_v2_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() +) -> crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput { + value, + } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs index ca7d68c38a..1607c8003e 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs @@ -1,34 +1,47 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, + value: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, ->{ +> { + let dafny_value = match value.value { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: ::std::rc::Rc::new( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&b), + ), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output::GetEnumV2Output { - value: ::std::rc::Rc::new(match &value.value { - Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, - None => crate::_Wrappers_Compile::Option::None { } -}) -, - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, >, -) -> crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output { - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output::builder() - .set_value(match &**dafny_value.value() { - crate::r#_Wrappers_Compile::Option::Some { value } => Some( - crate::conversions::simple_enum_v2_shape::from_dafny(value) - ), - _ => None, -} -) - .build() - .unwrap() +) -> crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( + &*dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput { + value, + } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config.rs index e280adea26..3eaacd610f 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config.rs @@ -1,4 +1,3 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + pub mod _simple_enum_v2_config; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config/_simple_enum_v2_config.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config/_simple_enum_v2_config.rs index 005e3ea6e6..f0a6804513 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config/_simple_enum_v2_config.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config/_simple_enum_v2_config.rs @@ -1,12 +1,10 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_enum_v2_config::SimpleEnumV2Config, ) -> ::std::rc::Rc< - crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Config, + crate::simple::types::enumv2::internaldafny::types::SimpleEnumV2Config, > { ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Config::SimpleEnumV2Config {}) } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape.rs index d2e61a3673..b4f4a50f80 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape.rs @@ -1,25 +1,3 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(dead_code)] +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub fn to_dafny( - value: crate::types::SimpleEnumV2Shape, -) -> ::std::rc::Rc{ - ::std::rc::Rc::new(match value { - crate::types::SimpleEnumV2Shape::First => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::FIRST {}, -crate::types::SimpleEnumV2Shape::Second => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::SECOND {}, -crate::types::SimpleEnumV2Shape::Third => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::THIRD {}, - _ => panic!("Unknown enum variant: {}", value), - }) -} - #[allow(dead_code)] -pub fn from_dafny( - dafny_value: &crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape, -) -> crate::types::SimpleEnumV2Shape { - match dafny_value { - crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::FIRST {} => crate::types::SimpleEnumV2Shape::First, -crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::SECOND {} => crate::types::SimpleEnumV2Shape::Second, -crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::THIRD {} => crate::types::SimpleEnumV2Shape::Third, - } -} +pub mod _simple_enum_v2_shape; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape/_simple_enum_v2_shape.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape/_simple_enum_v2_shape.rs new file mode 100644 index 0000000000..d48a6337b0 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape/_simple_enum_v2_shape.rs @@ -0,0 +1,23 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(dead_code)] + +pub fn to_dafny( + value: &crate::types::simple_enum_v2_shape::SimpleEnumV2Shape, +) -> crate::simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape { + match value { + crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::FIRST => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::FIRST {}, + crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::SECOND => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::SECOND {}, + crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::THIRD => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::THIRD {}, + } +} + +#[allow(dead_code)] +pub fn from_dafny( + dafny_value: &crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape, +) -> crate::types::simple_enum_v2_shape::SimpleEnumV2Shape { + match dafny_value { + crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::FIRST {} => crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::FIRST, + crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::SECOND {} => crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::SECOND, + crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::THIRD {} => crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::THIRD, + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error.rs index 4cddaa7c39..ec89cbecc9 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error/sealed_unhandled.rs index eae8007292..cce22d1cfd 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,10 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use std::any::Any; - -use dafny_runtime::UpcastObject; - +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -27,6 +21,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl UpcastObject for Unhandled { +impl ::dafny_runtime::UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/lib.rs new file mode 100644 index 0000000000..fcb015ba30 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/lib.rs @@ -0,0 +1,19 @@ +#![allow(deprecated)] + +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +pub mod client; +pub mod types; + +/// Common errors and error handling utilities. +pub mod error; + +/// All operations that this crate can perform. +pub mod operation; + +mod conversions; + +pub mod implementation_from_dafny; + +pub use client::Client; +pub use types::simple_enum_v2_config::SimpleEnumV2Config; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation.rs index a4dc395b89..565298a1a7 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation.rs @@ -1,14 +1,9 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + /// Types for the `GetEnumV2` operation. pub mod get_enum_v2; -/// Types for the `GetEnumV2FirstKnownValueTest` operation. +/// Types for the `GetEnumV2KnownValue` operation. pub mod get_enum_v2_first_known_value_test; - -/// Types for the `GetEnumV2SecondKnownValueTest` operation. pub mod get_enum_v2_second_known_value_test; - -/// Types for the `GetEnumV2ThirdKnownValueTest` operation. pub mod get_enum_v2_third_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2.rs index d35d560f15..f556fbe3ec 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetEnumV2`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -139,9 +137,9 @@ pub use crate::operation::get_enum_v2::_get_enum_v2_output::GetEnumV2Output; pub use crate::operation::get_enum_v2::_get_enum_v2_input::GetEnumV2Input; -pub(crate) mod _get_enum_v2_output; +mod _get_enum_v2_input; -pub(crate) mod _get_enum_v2_input; +mod _get_enum_v2_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_input.rs index dfb86df68c..a842022680 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_input.rs @@ -1,18 +1,19 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetEnumV2Input { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, + pub value: ::std::option::Option, } impl GetEnumV2Input { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} + pub fn message( + &self, + ) -> ::std::option::Option<&crate::types::simple_enum_v2_shape::SimpleEnumV2Shape> { + self.value.as_ref() + } } impl GetEnumV2Input { /// Creates a new builder-style object to manufacture [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). @@ -27,23 +28,31 @@ impl GetEnumV2Input { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetEnumV2InputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option, } impl GetEnumV2InputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } /// Consumes the builder and constructs a [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_output.rs index 3037a73e7d..002769f657 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_output.rs @@ -1,19 +1,22 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetEnumV2Output { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, + pub value: ::std::option::Option, } + impl GetEnumV2Output { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} + pub fn value( + &self, + ) -> ::std::option::Option { + self.value + } } + impl GetEnumV2Output { /// Creates a new builder-style object to manufacture [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). pub fn builder() -> crate::operation::get_enum_v2::builders::GetEnumV2OutputBuilder { @@ -27,23 +30,35 @@ impl GetEnumV2Output { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetEnumV2OutputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option, } + impl GetEnumV2OutputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/builders.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/builders.rs index 89b6e6ef12..e742b3d97c 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/builders.rs @@ -1,9 +1,6 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub use crate::operation::get_enum_v2::_get_enum_v2_output::GetEnumV2OutputBuilder; - +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use crate::operation::get_enum_v2::_get_enum_v2_input::GetEnumV2InputBuilder; +pub use crate::operation::get_enum_v2::_get_enum_v2_output::GetEnumV2OutputBuilder; impl GetEnumV2InputBuilder { /// Sends a request with this input using the given client. @@ -24,7 +21,7 @@ impl GetEnumV2InputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumV2FluentBuilder { client: crate::client::Client, - pub(crate) inner: crate::operation::get_enum_v2::builders::GetEnumV2InputBuilder, + inner: crate::operation::get_enum_v2::builders::GetEnumV2InputBuilder, } impl GetEnumV2FluentBuilder { /// Creates a new `GetEnumV2`. @@ -58,17 +55,22 @@ impl GetEnumV2FluentBuilder { } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() -} + pub fn value(mut self, input: crate::types::simple_enum_v2_shape::SimpleEnumV2Shape) -> Self { + self.inner = self.inner.value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test.rs index eae709de44..57c67e00bc 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetEnumV2FirstKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -12,14 +10,15 @@ impl GetEnumV2FirstKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input, + input: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput, ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError, > { - let inner_input = crate::conversions::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::to_dafny(input); + let inner_input = + crate::conversions::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::to_dafny(input); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2FirstKnownValueTest(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -30,9 +29,11 @@ impl GetEnumV2FirstKnownValueTest { ), ) } else { - Err(crate::conversions::get_enum_v2_first_known_value_test::from_dafny_error( - inner_result.error().clone(), - )) + Err( + crate::conversions::get_enum_v2_first_known_value_test::from_dafny_error( + inner_result.error().clone(), + ), + ) } } } @@ -41,7 +42,7 @@ impl GetEnumV2FirstKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumV2FirstKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unfirst_known error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -114,14 +115,18 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetEnumV2FirstKnownValueTes ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumV2FirstKnownValueTestError { +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata + for GetEnumV2FirstKnownValueTestError +{ fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumV2FirstKnownValueTestError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError + for GetEnumV2FirstKnownValueTestError +{ fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -135,13 +140,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumV } } -pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_output::GetEnumV2Output; +pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_output::GetEnumV2FirstKnownValueTestOutput; -pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_input::GetEnumV2Input; +pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::GetEnumV2FirstKnownValueTestInput; -pub(crate) mod _get_enum_v2_output; +mod _get_enum_v2_first_known_value_test_input; -pub(crate) mod _get_enum_v2_input; +mod _get_enum_v2_first_known_value_test_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs new file mode 100644 index 0000000000..a367fd776e --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs @@ -0,0 +1,71 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2FirstKnownValueTestInput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetEnumV2FirstKnownValueTestInput { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + &self, + ) -> ::std::option::Option { + self.value + } +} +impl GetEnumV2FirstKnownValueTestInput { + /// Creates a new builder-style object to manufacture [`GetEnumV2FirstKnownValueTestInput`](crate::operation::operation::GetEnumV2FirstKnownValueTestInput). + pub fn builder( + ) -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestInputBuilder + { + crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestInputBuilder::default() + } +} + +/// A builder for [`GetEnumV2FirstKnownValueTestInput`](crate::operation::operation::GetEnumV2FirstKnownValueTestInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2FirstKnownValueTestInputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2FirstKnownValueTestInputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetEnumV2FirstKnownValueTestInput`](crate::operation::operation::GetEnumV2FirstKnownValueTestInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs new file mode 100644 index 0000000000..f665704ab0 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs @@ -0,0 +1,71 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2FirstKnownValueTestOutput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetEnumV2FirstKnownValueTestOutput { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + &self, + ) -> ::std::option::Option { + self.value + } +} +impl GetEnumV2FirstKnownValueTestOutput { + /// Creates a new builder-style object to manufacture [`GetEnumV2FirstKnownValueTestOutput`](crate::operation::operation::GetEnumV2FirstKnownValueTestOutput). + pub fn builder( + ) -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestOutputBuilder + { + crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestOutputBuilder::default() + } +} + +/// A builder for [`GetEnumV2FirstKnownValueTestOutput`](crate::operation::operation::GetEnumV2FirstKnownValueTestOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2FirstKnownValueTestOutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2FirstKnownValueTestOutputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetEnumV2FirstKnownValueTestOutput`](crate::operation::operation::GetEnumV2FirstKnownValueTestOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_input.rs deleted file mode 100644 index fab2d07d14..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_input.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2Input { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, -} -impl GetEnumV2Input { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} -} -impl GetEnumV2Input { - /// Creates a new builder-style object to manufacture [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). - pub fn builder() -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2InputBuilder { - crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2InputBuilder::default() - } -} - -/// A builder for [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2InputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2InputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} - /// Consumes the builder and constructs a [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_output.rs deleted file mode 100644 index ee11f4792d..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_output.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2Output { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, -} -impl GetEnumV2Output { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} -} -impl GetEnumV2Output { - /// Creates a new builder-style object to manufacture [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). - pub fn builder() -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2OutputBuilder { - crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2OutputBuilder::default() - } -} - -/// A builder for [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2OutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2OutputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} - /// Consumes the builder and constructs a [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/builders.rs index 548fdeb7d2..c88ff6efee 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/builders.rs @@ -1,17 +1,14 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_output::GetEnumV2OutputBuilder; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::GetEnumV2FirstKnownValueTestInputBuilder; +pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_output::GetEnumV2FirstKnownValueTestOutputBuilder; -pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_input::GetEnumV2InputBuilder; - -impl GetEnumV2InputBuilder { +impl GetEnumV2FirstKnownValueTestInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError, > { let mut fluent_builder = client.get_enum_v2_first_known_value_test(); @@ -24,7 +21,8 @@ impl GetEnumV2InputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumV2FirstKnownValueTestFluentBuilder { client: crate::client::Client, - pub(crate) inner: crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2InputBuilder, + inner: + crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestInputBuilder, } impl GetEnumV2FirstKnownValueTestFluentBuilder { /// Creates a new `GetEnumV2FirstKnownValueTest`. @@ -35,40 +33,52 @@ impl GetEnumV2FirstKnownValueTestFluentBuilder { } } /// Access the GetEnumV2FirstKnownValueTest as a reference. - pub fn as_input(&self) -> &crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2InputBuilder { + pub fn as_input( + &self, + ) -> &crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestInputBuilder + { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnumV2FirstKnownValueTest doesn't declare any validation, + // Using unhandled since GetEnumV2 doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError::unhandled)?; - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTest::send(&self.client, input).await + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTest::send( + &self.client, + input, + ) + .await } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() -} + pub fn value(mut self, input: crate::types::simple_enum_v2_shape::SimpleEnumV2Shape) -> Self { + self.inner = self.inner.value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test.rs index 915d3dd2c7..9fecf26d24 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetEnumV2SecondKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -12,14 +10,15 @@ impl GetEnumV2SecondKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input, + input: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput, ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError, > { - let inner_input = crate::conversions::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::to_dafny(input); + let inner_input = + crate::conversions::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::to_dafny(input); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2SecondKnownValueTest(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -30,9 +29,11 @@ impl GetEnumV2SecondKnownValueTest { ), ) } else { - Err(crate::conversions::get_enum_v2_second_known_value_test::from_dafny_error( - inner_result.error().clone(), - )) + Err( + crate::conversions::get_enum_v2_second_known_value_test::from_dafny_error( + inner_result.error().clone(), + ), + ) } } } @@ -41,7 +42,7 @@ impl GetEnumV2SecondKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumV2SecondKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unsecond_known error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -114,14 +115,18 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetEnumV2SecondKnownValueTe ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumV2SecondKnownValueTestError { +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata + for GetEnumV2SecondKnownValueTestError +{ fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumV2SecondKnownValueTestError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError + for GetEnumV2SecondKnownValueTestError +{ fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -135,13 +140,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumV } } -pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_output::GetEnumV2Output; +pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_output::GetEnumV2SecondKnownValueTestOutput; -pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_input::GetEnumV2Input; +pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::GetEnumV2SecondKnownValueTestInput; -pub(crate) mod _get_enum_v2_output; +mod _get_enum_v2_second_known_value_test_input; -pub(crate) mod _get_enum_v2_input; +mod _get_enum_v2_second_known_value_test_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_input.rs deleted file mode 100644 index 925024a036..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_input.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2Input { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, -} -impl GetEnumV2Input { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} -} -impl GetEnumV2Input { - /// Creates a new builder-style object to manufacture [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). - pub fn builder() -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2InputBuilder { - crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2InputBuilder::default() - } -} - -/// A builder for [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2InputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2InputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} - /// Consumes the builder and constructs a [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_output.rs deleted file mode 100644 index 2e6fc555ed..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_output.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2Output { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, -} -impl GetEnumV2Output { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} -} -impl GetEnumV2Output { - /// Creates a new builder-style object to manufacture [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). - pub fn builder() -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2OutputBuilder { - crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2OutputBuilder::default() - } -} - -/// A builder for [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2OutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2OutputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} - /// Consumes the builder and constructs a [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs new file mode 100644 index 0000000000..d13dfd188e --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs @@ -0,0 +1,71 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2SecondKnownValueTestInput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetEnumV2SecondKnownValueTestInput { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + &self, + ) -> ::std::option::Option { + self.value + } +} +impl GetEnumV2SecondKnownValueTestInput { + /// Creates a new builder-style object to manufacture [`GetEnumV2SecondKnownValueTestInput`](crate::operation::operation::GetEnumV2SecondKnownValueTestInput). + pub fn builder( + ) -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestInputBuilder + { + crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestInputBuilder::default() + } +} + +/// A builder for [`GetEnumV2SecondKnownValueTestInput`](crate::operation::operation::GetEnumV2SecondKnownValueTestInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2SecondKnownValueTestInputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2SecondKnownValueTestInputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetEnumV2SecondKnownValueTestInput`](crate::operation::operation::GetEnumV2SecondKnownValueTestInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs new file mode 100644 index 0000000000..39218e3ad0 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs @@ -0,0 +1,71 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2SecondKnownValueTestOutput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetEnumV2SecondKnownValueTestOutput { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + &self, + ) -> ::std::option::Option { + self.value + } +} +impl GetEnumV2SecondKnownValueTestOutput { + /// Creates a new builder-style object to manufacture [`GetEnumV2SecondKnownValueTestOutput`](crate::operation::operation::GetEnumV2SecondKnownValueTestOutput). + pub fn builder( + ) -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestOutputBuilder + { + crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestOutputBuilder::default() + } +} + +/// A builder for [`GetEnumV2SecondKnownValueTestOutput`](crate::operation::operation::GetEnumV2SecondKnownValueTestOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2SecondKnownValueTestOutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2SecondKnownValueTestOutputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetEnumV2SecondKnownValueTestOutput`](crate::operation::operation::GetEnumV2SecondKnownValueTestOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/builders.rs index 13b3676202..5137b217e9 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/builders.rs @@ -1,17 +1,14 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_output::GetEnumV2OutputBuilder; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::GetEnumV2SecondKnownValueTestInputBuilder; +pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_output::GetEnumV2SecondKnownValueTestOutputBuilder; -pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_input::GetEnumV2InputBuilder; - -impl GetEnumV2InputBuilder { +impl GetEnumV2SecondKnownValueTestInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError, > { let mut fluent_builder = client.get_enum_v2_second_known_value_test(); @@ -24,7 +21,7 @@ impl GetEnumV2InputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumV2SecondKnownValueTestFluentBuilder { client: crate::client::Client, - pub(crate) inner: crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2InputBuilder, + inner: crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestInputBuilder, } impl GetEnumV2SecondKnownValueTestFluentBuilder { /// Creates a new `GetEnumV2SecondKnownValueTest`. @@ -35,40 +32,52 @@ impl GetEnumV2SecondKnownValueTestFluentBuilder { } } /// Access the GetEnumV2SecondKnownValueTest as a reference. - pub fn as_input(&self) -> &crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2InputBuilder { + pub fn as_input( + &self, + ) -> &crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestInputBuilder + { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnumV2SecondKnownValueTest doesn't declare any validation, + // Using unhandled since GetEnumV2 doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError::unhandled)?; - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTest::send(&self.client, input).await + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTest::send( + &self.client, + input, + ) + .await } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() -} + pub fn value(mut self, input: crate::types::simple_enum_v2_shape::SimpleEnumV2Shape) -> Self { + self.inner = self.inner.value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test.rs index 188442ad28..bf5efb30b6 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetEnumV2ThirdKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -12,14 +10,15 @@ impl GetEnumV2ThirdKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input, + input: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput, ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError, > { - let inner_input = crate::conversions::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::to_dafny(input); + let inner_input = + crate::conversions::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::to_dafny(input); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2ThirdKnownValueTest(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -30,9 +29,11 @@ impl GetEnumV2ThirdKnownValueTest { ), ) } else { - Err(crate::conversions::get_enum_v2_third_known_value_test::from_dafny_error( - inner_result.error().clone(), - )) + Err( + crate::conversions::get_enum_v2_third_known_value_test::from_dafny_error( + inner_result.error().clone(), + ), + ) } } } @@ -41,7 +42,7 @@ impl GetEnumV2ThirdKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumV2ThirdKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unthird_known error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -114,14 +115,18 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetEnumV2ThirdKnownValueTes ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumV2ThirdKnownValueTestError { +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata + for GetEnumV2ThirdKnownValueTestError +{ fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumV2ThirdKnownValueTestError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError + for GetEnumV2ThirdKnownValueTestError +{ fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -135,13 +140,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumV } } -pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_output::GetEnumV2Output; +pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_output::GetEnumV2ThirdKnownValueTestOutput; -pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_input::GetEnumV2Input; +pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::GetEnumV2ThirdKnownValueTestInput; -pub(crate) mod _get_enum_v2_output; +mod _get_enum_v2_third_known_value_test_input; -pub(crate) mod _get_enum_v2_input; +mod _get_enum_v2_third_known_value_test_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_input.rs deleted file mode 100644 index cdfce6ed40..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_input.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2Input { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, -} -impl GetEnumV2Input { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} -} -impl GetEnumV2Input { - /// Creates a new builder-style object to manufacture [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). - pub fn builder() -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2InputBuilder { - crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2InputBuilder::default() - } -} - -/// A builder for [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2InputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2InputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} - /// Consumes the builder and constructs a [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_output.rs deleted file mode 100644 index 1799bb2d27..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_output.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2Output { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option, -} -impl GetEnumV2Output { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option { - self.value.clone() -} -} -impl GetEnumV2Output { - /// Creates a new builder-style object to manufacture [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). - pub fn builder() -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2OutputBuilder { - crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2OutputBuilder::default() - } -} - -/// A builder for [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2OutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2OutputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - &self.value -} - /// Consumes the builder and constructs a [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs new file mode 100644 index 0000000000..573fb3c14b --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs @@ -0,0 +1,70 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2ThirdKnownValueTestInput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetEnumV2ThirdKnownValueTestInput { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + &self, + ) -> ::std::option::Option { + self.value + } +} +impl GetEnumV2ThirdKnownValueTestInput { + /// Creates a new builder-style object to manufacture [`GetEnumV2ThirdKnownValueTestInput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestInput). + pub fn builder( + ) -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestInputBuilder + { + crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestInputBuilder::default() + } +} + +/// A builder for [`GetEnumV2ThirdKnownValueTestInput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2ThirdKnownValueTestInputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2ThirdKnownValueTestInputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetEnumV2ThirdKnownValueTestInput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs new file mode 100644 index 0000000000..588e636c9c --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs @@ -0,0 +1,71 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2ThirdKnownValueTestOutput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetEnumV2ThirdKnownValueTestOutput { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + &self, + ) -> ::std::option::Option { + self.value + } +} +impl GetEnumV2ThirdKnownValueTestOutput { + /// Creates a new builder-style object to manufacture [`GetEnumV2ThirdKnownValueTestOutput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestOutput). + pub fn builder( + ) -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestOutputBuilder + { + crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestOutputBuilder::default() + } +} + +/// A builder for [`GetEnumV2ThirdKnownValueTestOutput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2ThirdKnownValueTestOutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2ThirdKnownValueTestOutputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value( + mut self, + input: impl ::std::convert::Into, + ) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetEnumV2ThirdKnownValueTestOutput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/builders.rs index 84838695de..f1bbbe0581 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/builders.rs @@ -1,17 +1,14 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_output::GetEnumV2OutputBuilder; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::GetEnumV2ThirdKnownValueTestInputBuilder; +pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_output::GetEnumV2ThirdKnownValueTestOutputBuilder; -pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_input::GetEnumV2InputBuilder; - -impl GetEnumV2InputBuilder { +impl GetEnumV2ThirdKnownValueTestInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError, > { let mut fluent_builder = client.get_enum_v2_third_known_value_test(); @@ -24,7 +21,8 @@ impl GetEnumV2InputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumV2ThirdKnownValueTestFluentBuilder { client: crate::client::Client, - pub(crate) inner: crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2InputBuilder, + inner: + crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestInputBuilder, } impl GetEnumV2ThirdKnownValueTestFluentBuilder { /// Creates a new `GetEnumV2ThirdKnownValueTest`. @@ -35,40 +33,52 @@ impl GetEnumV2ThirdKnownValueTestFluentBuilder { } } /// Access the GetEnumV2ThirdKnownValueTest as a reference. - pub fn as_input(&self) -> &crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2InputBuilder { + pub fn as_input( + &self, + ) -> &crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestInputBuilder + { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnumV2ThirdKnownValueTest doesn't declare any validation, + // Using unhandled since GetEnumV2 doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError::unhandled)?; - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTest::send(&self.client, input).await + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTest::send( + &self.client, + input, + ) + .await } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() -} + pub fn value(mut self, input: crate::types::simple_enum_v2_shape::SimpleEnumV2Shape) -> Self { + self.inner = self.inner.value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value( + mut self, + input: ::std::option::Option, + ) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value( + &self, + ) -> &::std::option::Option { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_conversions.rs index 6bf8297d8a..3a51134c6e 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_conversions.rs @@ -1,266 +1,246 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + >, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny( - input: &Option, -) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny( + input: &::aws_smithy_types::Blob, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny( + input: ::dafny_runtime::Sequence, +) -> ::aws_smithy_types::Blob { + + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()) + .unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x, - ) +pub fn double_to_dafny( + input: f64, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny( + input: &::dafny_runtime::Sequence, +) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: &::aws_smithy_types::DateTime, + input: ::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &input.to_string(), - ) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, -> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc>> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input, - ); - ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) - .unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); + ::aws_smithy_types::DateTime::from_str( + &s, + aws_smithy_types::date_time::Format::DateTime, + ).unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::DateTime> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None {} => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None { } => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { - value: converter(&value), - }), - None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), - } + match input { + Some(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::Some { + value: converter(&value) + } + ), + None => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::None {} + ), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value), - }), - Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error), - }), - } -} + match input { + Ok(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value) + } + ), + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error) + } + ), + } +} \ No newline at end of file diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types.rs index bd9720ed21..951f1e5c4a 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types.rs @@ -1,8 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -/// Types for the `SimpleEnumV2Config` -pub mod simple_enum_v2_config; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -mod _simple_enum_v2_shape; -pub use crate::types::_simple_enum_v2_shape::SimpleEnumV2Shape; +/// Types for the `SimpleIntegerConfig` +pub mod simple_enum_v2_config; +pub mod simple_enum_v2_shape; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/_simple_enum_v2_shape.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/_simple_enum_v2_shape.rs deleted file mode 100644 index 6747128c1b..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/_simple_enum_v2_shape.rs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[derive(Debug, PartialEq, Copy, Clone)] -pub enum SimpleEnumV2Shape { - First, -Second, -Third, -} - -impl ::std::fmt::Display for SimpleEnumV2Shape { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - match self { - SimpleEnumV2Shape::First => write!(f, "FIRST"), -SimpleEnumV2Shape::Second => write!(f, "SECOND"), -SimpleEnumV2Shape::Third => write!(f, "THIRD"), - } - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_config.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_config.rs index d03031da87..37b2d81ac2 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_config.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_config.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleEnumV2Config {} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_shape.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_shape.rs new file mode 100644 index 0000000000..b1eb347281 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_shape.rs @@ -0,0 +1,6 @@ +#[derive(Debug, PartialEq, Copy, Clone)] +pub enum SimpleEnumV2Shape { + FIRST, + SECOND, + THIRD, +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped.rs deleted file mode 100644 index 4bcdd7d0f8..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod client; - -impl crate::r#simple::types::enumv2::internaldafny::wrapped::_default { - pub fn WrappedSimpleEnumV2(config: &::std::rc::Rc< - crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Config, - >) -> ::std::rc::Rc, - ::std::rc::Rc - >>{ - crate::wrapped::client::Client::from_conf(config) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped/client.rs deleted file mode 100644 index 5beee2ab3f..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped/client.rs +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use tokio::runtime::Runtime; - -pub struct Client { - wrapped: crate::client::Client, - - /// A `current_thread` runtime for executing operations on the - /// asynchronous client in a blocking manner. - rt: Runtime -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::enumv2::internaldafny::types::ISimpleTypesEnumV2Client); -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); -} - -impl Client { - pub fn from_conf(config: &::std::rc::Rc< - crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Config, - >) -> -::std::rc::Rc, - ::std::rc::Rc ->> { - let rt_result = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build(); - let rt = match rt_result { - Ok(x) => x, - Err(error) => return crate::conversions::error::to_opaque_error_result(error), - }; - let result = crate::client::Client::from_conf( - crate::conversions::simple_enum_v2_config::_simple_enum_v2_config::from_dafny( - config.clone(), - ), - ); - match result { - Ok(client) => { - let wrap = crate::wrapped::client::Client { - wrapped: client, - rt - }; - std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) - } - ) - }, - Err(error) => crate::conversions::error::to_opaque_error_result(error) - } - } -} - -impl crate::r#simple::types::enumv2::internaldafny::types::ISimpleTypesEnumV2Client for Client { - fn GetEnumV2( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_enum_v2::_get_enum_v2_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_enum_v2::GetEnumV2::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_enum_v2::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_enum_v2::_get_enum_v2_output::to_dafny(client), - }, - ), - } - } - - fn GetEnumV2FirstKnownValueTest( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTest::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_enum_v2_first_known_value_test::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_output::to_dafny(client), - }, - ), - } - } - - fn GetEnumV2SecondKnownValueTest( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTest::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_enum_v2_second_known_value_test::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_output::to_dafny(client), - }, - ), - } - } - - fn GetEnumV2ThirdKnownValueTest( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTest::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_enum_v2_third_known_value_test::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_output::to_dafny(client), - }, - ), - } - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/tests/simple_enum_v2_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/tests/simple_enum_v2_test.rs index 4ce5192c09..ddf89e15e4 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/tests/simple_enum_v2_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/tests/simple_enum_v2_test.rs @@ -1,48 +1,48 @@ -use simple_enum_v2::types::SimpleEnumV2Shape::*; +use simple_enum_v2::types::simple_enum_v2_shape::SimpleEnumV2Shape::*; use simple_enum_v2::*; #[tokio::test] async fn test_get_enum() { - let result = client().get_enum_v2().value(Second).send().await; + let result = client().get_enum_v2().value(SECOND).send().await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, Second); + assert_eq!(value, SECOND); } #[tokio::test] async fn test_get_first_known_value() { let result = client() .get_enum_v2_first_known_value_test() - .value(First) + .value(FIRST) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, First); + assert_eq!(value, FIRST); } #[tokio::test] async fn test_get_second_known_value() { let result = client() .get_enum_v2_second_known_value_test() - .value(Second) + .value(SECOND) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, Second); + assert_eq!(value, SECOND); } #[tokio::test] async fn test_get_third_known_value() { let result = client() .get_enum_v2_third_known_value_test() - .value(Third) + .value(THIRD) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, Third); + assert_eq!(value, THIRD); } pub fn client() -> Client { diff --git a/TestModels/SimpleTypes/SimpleInteger/Makefile b/TestModels/SimpleTypes/SimpleInteger/Makefile index 3f522f1305..bd4715b6cd 100644 --- a/TestModels/SimpleTypes/SimpleInteger/Makefile +++ b/TestModels/SimpleTypes/SimpleInteger/Makefile @@ -3,9 +3,8 @@ CORES=2 -TRANSPILE_TESTS_IN_RUST=1 - ENABLE_EXTERN_PROCESSING=1 +RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/Cargo.toml index 3ef7587f62..d14ad003b2 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/Cargo.toml @@ -5,19 +5,13 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html -[features] -wrapped-client = [] - [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies] -simple_integer = { path = ".", features = ["wrapped-client"] } - -[dependencies.tokio] +[dev-dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client.rs index 077a869866..a82eefe997 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -30,11 +29,11 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), }) } } mod get_integer; -mod get_integer_known_value_test; +mod get_integer_known_value; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer.rs index 11767e3f95..ac241528f2 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer.rs @@ -1,13 +1,11 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { /// Constructs a fluent builder for the [`GetInteger`](crate::operation::get_integer::builders::GetIntegerFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_integer::builders::GetIntegerFluentBuilder::value) / [`set_value(Option<::std::primitive::i32>)`](crate::operation::get_integer::builders::GetIntegerFluentBuilder::set_value): (undocumented)
+ /// - [`value(i32)`](crate::operation::get_integer::builders::GetIntegerFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_integer::builders::GetIntegerFluentBuilder::set_value):(undocumented)
/// - On success, responds with [`GetIntegerOutput`](crate::operation::get_integer::GetIntegerOutput) with field(s): - /// - [`value(Option<::std::primitive::i32>)`](crate::operation::get_integer::GetIntegerOutput::value): (undocumented) + /// - [`value(Option)`](crate::operation::get_integer::GetIntegerOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_integer::GetIntegerError) pub fn get_integer(&self) -> crate::operation::get_integer::builders::GetIntegerFluentBuilder { crate::operation::get_integer::builders::GetIntegerFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value.rs new file mode 100644 index 0000000000..82695c20fe --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value.rs @@ -0,0 +1,18 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +impl super::Client { + /// Constructs a fluent builder for the [`GetInteger`](crate::operation::get_integer_known_value::builders::GetIntegerFluentBuilder) operation. + /// + /// - The fluent builder is configurable: + /// - [`value(i32)`](crate::operation::get_integer_known_value::builders::GetIntegerFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_integer_known_value::builders::GetIntegerFluentBuilder::set_value):(undocumented)
+ /// - On success, responds with [`GetIntegerOutput`](crate::operation::get_integer_known_value::GetIntegerOutput) with field(s): + /// - [`value(Option)`](crate::operation::get_integer_known_value::GetIntegerOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_integer_known_value::GetIntegerError) + pub fn get_integer_known_value( + &self, + ) -> crate::operation::get_integer_known_value::builders::GetIntegerKnownValueFluentBuilder + { + crate::operation::get_integer_known_value::builders::GetIntegerKnownValueFluentBuilder::new( + self.clone(), + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value_test.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value_test.rs deleted file mode 100644 index 7612ae9e55..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value_test.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -impl super::Client { - /// Constructs a fluent builder for the [`GetIntegerKnownValueTest`](crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder) operation. - /// - /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder::value) / [`set_value(Option<::std::primitive::i32>)`](crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder::set_value): (undocumented)
- /// - On success, responds with [`GetIntegerOutput`](crate::operation::get_integer_known_value_test::GetIntegerOutput) with field(s): - /// - [`value(Option<::std::primitive::i32>)`](crate::operation::get_integer_known_value_test::GetIntegerOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError) - pub fn get_integer_known_value_test(&self) -> crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder { - crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder::new(self.clone()) - } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions.rs index 0af6bf6b95..9d397cd054 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions.rs @@ -1,10 +1,6 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod error; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub mod get_integer; - pub mod get_integer; +pub mod get_integer_known_value; - pub mod get_integer_known_value_test; - - pub mod simple_integer_config; +pub mod simple_integer_config; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/error.rs deleted file mode 100644 index 77c44d4372..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/error.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. - /// Wraps up an arbitrary Rust Error value as a Dafny Error -pub fn to_opaque_error(value: E) -> - ::std::rc::Rc -{ - let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( - ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), - )); - ::std::rc::Rc::new( - crate::r#simple::types::integer::internaldafny::types::Error::Opaque { - obj: error_obj, - }, - ) -} - -/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure -pub fn to_opaque_error_result(value: E) -> - ::std::rc::Rc< - crate::_Wrappers_Compile::Result< - T, - ::std::rc::Rc - > - > -{ - ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: to_opaque_error(value), - }, - ) -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer.rs index 465334c3ec..3637ac26fa 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_input.rs index 03797dbbe0..9b5403e088 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_input.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_input.rs @@ -1,24 +1,37 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_integer::GetIntegerInput, ) -> ::std::rc::Rc< crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, ->{ +> { + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { value: v }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerInput::GetIntegerInput { - value: crate::standard_library_conversions::oint_to_dafny(value.value), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, >, ) -> crate::operation::get_integer::GetIntegerInput { - crate::operation::get_integer::GetIntegerInput::builder() - .set_value(crate::standard_library_conversions::oint_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(dafny_value.value().Extract()) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_integer::GetIntegerInput { value } } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_output.rs index 9b8946b2ba..0883177221 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_output.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_output.rs @@ -1,24 +1,37 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_integer::GetIntegerOutput, ) -> ::std::rc::Rc< crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, ->{ +> { + let dafny_value = match value.value { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput::GetIntegerOutput { - value: crate::standard_library_conversions::oint_to_dafny(value.value), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, >, ) -> crate::operation::get_integer::GetIntegerOutput { - crate::operation::get_integer::GetIntegerOutput::builder() - .set_value(crate::standard_library_conversions::oint_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(dafny_value.value().Extract()) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_integer::GetIntegerOutput { value } } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value.rs new file mode 100644 index 0000000000..15c6b7c8b2 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value.rs @@ -0,0 +1,32 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +use std::any::Any; + +#[allow(dead_code)] +pub fn to_dafny_error( + value: crate::operation::get_integer_known_value::GetIntegerKnownValueError, +) -> ::std::rc::Rc { + match value { + crate::operation::get_integer_known_value::GetIntegerKnownValueError::Unhandled(unhandled) => + ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) + } +} + +#[allow(dead_code)] +pub fn from_dafny_error( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::Error, + >, +) -> crate::operation::get_integer_known_value::GetIntegerKnownValueError { + // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error + if matches!(&dafny_value.as_ref(), crate::r#simple::types::integer::internaldafny::types::Error::CollectionOfErrors { .. }) { + let error_message = "TODO: can't get message yet"; + crate::operation::get_integer_known_value::GetIntegerKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) + } else { + crate::operation::get_integer_known_value::GetIntegerKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) + } +} + +pub mod _get_integer_known_value_input; + +pub mod _get_integer_known_value_output; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_input.rs new file mode 100644 index 0000000000..40db6820d4 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_input.rs @@ -0,0 +1,37 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_integer_known_value::GetIntegerKnownValueInput, +) -> ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, +> { + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { value: v }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerInput::GetIntegerInput { + value: ::std::rc::Rc::new(dafny_value) + }) +} + +#[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, + >, +) -> crate::operation::get_integer_known_value::GetIntegerKnownValueInput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(dafny_value.value().Extract()) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_integer_known_value::GetIntegerKnownValueInput { value } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_output.rs new file mode 100644 index 0000000000..c122e6bee4 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_output.rs @@ -0,0 +1,37 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, +) -> ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, +> { + let dafny_value = match value.value { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput::GetIntegerOutput { + value: ::std::rc::Rc::new(dafny_value) + }) +} + +#[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, + >, +) -> crate::operation::get_integer_known_value::GetIntegerKnownValueOutput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(dafny_value.value().Extract()) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_integer_known_value::GetIntegerKnownValueOutput { value } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test.rs deleted file mode 100644 index 553b0b3725..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test.rs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use std::any::Any; - -#[allow(dead_code)] -pub fn to_dafny_error( - value: crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError, -) -> ::std::rc::Rc { - match value { - crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError::Unhandled(unhandled) => - ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) - } -} - -#[allow(dead_code)] -pub fn from_dafny_error( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::Error, - >, -) -> crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError { - // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error - if matches!(&dafny_value.as_ref(), crate::r#simple::types::integer::internaldafny::types::Error::CollectionOfErrors { .. }) { - let error_message = "TODO: can't get message yet"; - crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) - } else { - crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) - } -} - -pub mod _get_integer_known_value_test_input; - -pub mod _get_integer_known_value_test_output; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_input.rs deleted file mode 100644 index 0b004b785b..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_input.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_integer_known_value_test::GetIntegerInput, -) -> ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, ->{ - ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerInput::GetIntegerInput { - value: crate::standard_library_conversions::oint_to_dafny(value.value), - }) -} - #[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, - >, -) -> crate::operation::get_integer_known_value_test::GetIntegerInput { - crate::operation::get_integer_known_value_test::GetIntegerInput::builder() - .set_value(crate::standard_library_conversions::oint_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_output.rs deleted file mode 100644 index 19f8b437b6..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_output.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_integer_known_value_test::GetIntegerOutput, -) -> ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, ->{ - ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput::GetIntegerOutput { - value: crate::standard_library_conversions::oint_to_dafny(value.value), - }) -} - #[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, - >, -) -> crate::operation::get_integer_known_value_test::GetIntegerOutput { - crate::operation::get_integer_known_value_test::GetIntegerOutput::builder() - .set_value(crate::standard_library_conversions::oint_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config.rs index f25f66bfec..f3cdb7384b 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config.rs @@ -1,4 +1,3 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + pub mod _simple_integer_config; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config/_simple_integer_config.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config/_simple_integer_config.rs index a712be2fba..360d19898b 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config/_simple_integer_config.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config/_simple_integer_config.rs @@ -1,12 +1,10 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_integer_config::SimpleIntegerConfig, ) -> ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::SimpleIntegerConfig, + crate::simple::types::integer::internaldafny::types::SimpleIntegerConfig, > { ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::SimpleIntegerConfig::SimpleIntegerConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error.rs index 4cddaa7c39..ec89cbecc9 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error/sealed_unhandled.rs index eae8007292..cce22d1cfd 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,10 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use std::any::Any; - -use dafny_runtime::UpcastObject; - +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -27,6 +21,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl UpcastObject for Unhandled { +impl ::dafny_runtime::UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/lib.rs new file mode 100644 index 0000000000..e427bffab8 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/lib.rs @@ -0,0 +1,19 @@ +#![allow(deprecated)] + +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +pub mod client; +pub mod types; + +/// Common errors and error handling utilities. +pub mod error; + +/// All operations that this crate can perform. +pub mod operation; + +mod conversions; + +pub mod implementation_from_dafny; + +pub use client::Client; +pub use types::simple_integer_config::SimpleIntegerConfig; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation.rs index 94588bbdb2..faaa994cb8 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation.rs @@ -1,8 +1,7 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + /// Types for the `GetInteger` operation. pub mod get_integer; -/// Types for the `GetIntegerKnownValueTest` operation. -pub mod get_integer_known_value_test; +/// Types for the `GetIntegerKnownValue` operation. +pub mod get_integer_known_value; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer.rs index 1887a2158b..3cb49535a7 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetInteger`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -139,9 +137,9 @@ pub use crate::operation::get_integer::_get_integer_output::GetIntegerOutput; pub use crate::operation::get_integer::_get_integer_input::GetIntegerInput; -pub(crate) mod _get_integer_output; +mod _get_integer_input; -pub(crate) mod _get_integer_input; +mod _get_integer_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_input.rs index ae911475a7..ab0c63e080 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_input.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_input.rs @@ -1,18 +1,16 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetIntegerInput { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::primitive::i32>, + pub value: ::std::option::Option, } impl GetIntegerInput { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::primitive::i32> { - self.value -} + pub fn value(&self) -> ::std::option::Option<&i32> { + self.value.as_ref() + } } impl GetIntegerInput { /// Creates a new builder-style object to manufacture [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). @@ -27,23 +25,23 @@ impl GetIntegerInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetIntegerInputBuilder { - pub(crate) value: ::std::option::Option<::std::primitive::i32>, + pub(crate) value: ::std::option::Option, } impl GetIntegerInputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { - &self.value -} + pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + &self.value + } /// Consumes the builder and constructs a [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_output.rs index 354b4fb6af..49ae58c834 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_output.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_output.rs @@ -1,19 +1,19 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetIntegerOutput { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::primitive::i32>, + pub value: ::std::option::Option, } + impl GetIntegerOutput { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::primitive::i32> { - self.value -} + pub fn value(&self) -> ::std::option::Option { + self.value + } } + impl GetIntegerOutput { /// Creates a new builder-style object to manufacture [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). pub fn builder() -> crate::operation::get_integer::builders::GetIntegerOutputBuilder { @@ -27,23 +27,27 @@ impl GetIntegerOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetIntegerOutputBuilder { - pub(crate) value: ::std::option::Option<::std::primitive::i32>, + pub(crate) value: ::std::option::Option, } + impl GetIntegerOutputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { - &self.value -} + pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self + } + + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/builders.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/builders.rs index f96df4a71d..74d985a93a 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/builders.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/builders.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use crate::operation::get_integer::_get_integer_output::GetIntegerOutputBuilder; pub use crate::operation::get_integer::_get_integer_input::GetIntegerInputBuilder; @@ -23,8 +21,8 @@ impl GetIntegerInputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetIntegerFluentBuilder { - client: crate::client::Client, - pub(crate) inner: crate::operation::get_integer::builders::GetIntegerInputBuilder, + client: crate::Client, + inner: crate::operation::get_integer::builders::GetIntegerInputBuilder, } impl GetIntegerFluentBuilder { /// Creates a new `GetInteger`. @@ -58,17 +56,17 @@ impl GetIntegerFluentBuilder { } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { - self.inner.get_value() -} + pub fn value(mut self, input: i32) -> Self { + self.inner = self.inner.value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value.rs similarity index 67% rename from TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test.rs rename to TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value.rs index 0a0f7a5080..06e0fa0cb4 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value.rs @@ -1,46 +1,49 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -/// Orchestration and serialization glue logic for `GetIntegerKnownValueTest`. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +/// Orchestration and serialization glue logic for `GetIntegerKnownValue`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] -pub struct GetIntegerKnownValueTest; -impl GetIntegerKnownValueTest { - /// Creates a new `GetIntegerKnownValueTest` +pub struct GetIntegerKnownValue; +impl GetIntegerKnownValue { + /// Creates a new `GetIntegerKnownValue` pub fn new() -> Self { Self } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_integer_known_value_test::GetIntegerInput, + input: crate::operation::get_integer_known_value::GetIntegerKnownValueInput, ) -> ::std::result::Result< - crate::operation::get_integer_known_value_test::GetIntegerOutput, - crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError, + crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, + crate::operation::get_integer_known_value::GetIntegerKnownValueError, > { - let inner_input = crate::conversions::get_integer_known_value_test::_get_integer_known_value_test_input::to_dafny(input); + let inner_input = + crate::conversions::get_integer_known_value::_get_integer_known_value_input::to_dafny( + input, + ); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetIntegerKnownValueTest(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetInteger(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { Ok( - crate::conversions::get_integer_known_value_test::_get_integer_known_value_test_output::from_dafny( + crate::conversions::get_integer_known_value::_get_integer_known_value_output::from_dafny( inner_result.value().clone(), ), ) } else { - Err(crate::conversions::get_integer_known_value_test::from_dafny_error( - inner_result.error().clone(), - )) + Err( + crate::conversions::get_integer_known_value::from_dafny_error( + inner_result.error().clone(), + ), + ) } } } -/// Error type for the `GetIntegerKnownValueTest` operation. +/// Error type for the `GetIntegerKnownValue` operation. #[non_exhaustive] #[derive(::std::fmt::Debug)] -pub enum GetIntegerKnownValueTestError { +pub enum GetIntegerKnownValueError { /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ @@ -48,12 +51,12 @@ pub enum GetIntegerKnownValueTestError { \    `err if err.code() == Some(\"SpecificExceptionCode\") => { /* handle the error */ }` \ - See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetIntegerKnownValueTestError) for what information is available for the error." + See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetIntegerKnownValueError) for what information is available for the error." )] Unhandled(crate::error::sealed_unhandled::Unhandled), } -impl GetIntegerKnownValueTestError { - /// Creates the `GetIntegerKnownValueTestError::Unhandled` variant from any error type. +impl GetIntegerKnownValueError { + /// Creates the `GetIntegerKnownValueError::Unhandled` variant from any error type. pub fn unhandled( err: impl ::std::convert::Into< ::std::boxed::Box< @@ -67,7 +70,7 @@ impl GetIntegerKnownValueTestError { }) } - /// Creates the `GetIntegerKnownValueTestError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). + /// Creates the `GetIntegerKnownValueError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). pub fn generic(err: ::aws_smithy_types::error::ErrorMetadata) -> Self { Self::Unhandled(crate::error::sealed_unhandled::Unhandled { source: err.clone().into(), @@ -84,14 +87,14 @@ impl GetIntegerKnownValueTestError { } } } -impl ::std::error::Error for GetIntegerKnownValueTestError { +impl ::std::error::Error for GetIntegerKnownValueError { fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> { match self { Self::Unhandled(_inner) => ::std::option::Option::Some(&*_inner.source), } } } -impl ::std::fmt::Display for GetIntegerKnownValueTestError { +impl ::std::fmt::Display for GetIntegerKnownValueError { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self { Self::Unhandled(_inner) => { @@ -106,7 +109,7 @@ impl ::std::fmt::Display for GetIntegerKnownValueTestError { } } } -impl ::aws_smithy_types::retry::ProvideErrorKind for GetIntegerKnownValueTestError { +impl ::aws_smithy_types::retry::ProvideErrorKind for GetIntegerKnownValueError { fn code(&self) -> ::std::option::Option<&str> { ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self) } @@ -114,14 +117,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetIntegerKnownValueTestErr ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetIntegerKnownValueTestError { +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetIntegerKnownValueError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetIntegerKnownValueTestError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetIntegerKnownValueError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -135,13 +138,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetInteg } } -pub use crate::operation::get_integer_known_value_test::_get_integer_output::GetIntegerOutput; +pub use crate::operation::get_integer_known_value::_get_integer_known_value_output::GetIntegerKnownValueOutput; -pub use crate::operation::get_integer_known_value_test::_get_integer_input::GetIntegerInput; +pub use crate::operation::get_integer_known_value::_get_integer_known_value_input::GetIntegerKnownValueInput; -pub(crate) mod _get_integer_output; +mod _get_integer_known_value_input; -pub(crate) mod _get_integer_input; +mod _get_integer_known_value_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_input.rs new file mode 100644 index 0000000000..83a4b82918 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_input.rs @@ -0,0 +1,59 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetIntegerKnownValueInput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetIntegerKnownValueInput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option { + self.value + } +} +impl GetIntegerKnownValueInput { + /// Creates a new builder-style object to manufacture [`GetIntegerKnownValueInput`](crate::operation::operation::GetIntegerKnownValueInput). + pub fn builder( + ) -> crate::operation::get_integer_known_value::builders::GetIntegerKnownValueInputBuilder { + crate::operation::get_integer_known_value::builders::GetIntegerKnownValueInputBuilder::default() + } +} + +/// A builder for [`GetIntegerKnownValueInput`](crate::operation::operation::GetIntegerKnownValueInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetIntegerKnownValueInputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetIntegerKnownValueInputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetIntegerKnownValueInput`](crate::operation::operation::GetIntegerKnownValueInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_integer_known_value::GetIntegerKnownValueInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_integer_known_value::GetIntegerKnownValueInput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_output.rs new file mode 100644 index 0000000000..f80e3163bf --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_output.rs @@ -0,0 +1,60 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetIntegerKnownValueOutput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetIntegerKnownValueOutput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option { + self.value + } +} +impl GetIntegerKnownValueOutput { + /// Creates a new builder-style object to manufacture [`GetIntegerKnownValueOutput`](crate::operation::operation::GetIntegerKnownValueOutput). + pub fn builder( + ) -> crate::operation::get_integer_known_value::builders::GetIntegerKnownValueOutputBuilder + { + crate::operation::get_integer_known_value::builders::GetIntegerKnownValueOutputBuilder::default() + } +} + +/// A builder for [`GetIntegerKnownValueOutput`](crate::operation::operation::GetIntegerKnownValueOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetIntegerKnownValueOutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetIntegerKnownValueOutputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetIntegerKnownValueOutput`](crate::operation::operation::GetIntegerKnownValueOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_integer_known_value::GetIntegerKnownValueOutput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/builders.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/builders.rs new file mode 100644 index 0000000000..9cfc99ee3a --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/builders.rs @@ -0,0 +1,78 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub use crate::operation::get_integer_known_value::_get_integer_known_value_output::GetIntegerKnownValueOutputBuilder; + +pub use crate::operation::get_integer_known_value::_get_integer_known_value_input::GetIntegerKnownValueInputBuilder; + +impl GetIntegerKnownValueInputBuilder { + /// Sends a request with this input using the given client. + pub async fn send_with( + self, + client: &crate::Client, + ) -> ::std::result::Result< + crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, + crate::operation::get_integer_known_value::GetIntegerKnownValueError, + > { + let mut fluent_builder = client.get_integer_known_value(); + fluent_builder.inner = self; + fluent_builder.send().await + } +} +/// Fluent builder constructing a request to `GetIntegerKnownValue`. +/// +#[derive(::std::clone::Clone, ::std::fmt::Debug)] +pub struct GetIntegerKnownValueFluentBuilder { + client: crate::client::Client, + inner: crate::operation::get_integer_known_value::builders::GetIntegerKnownValueInputBuilder, +} +impl GetIntegerKnownValueFluentBuilder { + /// Creates a new `GetIntegerKnownValue`. + pub(crate) fn new(client: crate::client::Client) -> Self { + Self { + client, + inner: ::std::default::Default::default(), + } + } + /// Access the GetIntegerKnownValue as a reference. + pub fn as_input( + &self, + ) -> &crate::operation::get_integer_known_value::builders::GetIntegerKnownValueInputBuilder + { + &self.inner + } + /// Sends the request and returns the response. + pub async fn send( + self, + ) -> ::std::result::Result< + crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, + crate::operation::get_integer_known_value::GetIntegerKnownValueError, + > { + let input = self + .inner + .build() + // Using unhandled since GetInteger doesn't declare any validation, + // and smithy-rs seems to not generate a ValidationError case unless there is + // (but isn't that a backwards compatibility problem for output structures?) + // Vanilla smithy-rs uses SdkError::construction_failure, + // but we aren't using SdkError. + .map_err( + crate::operation::get_integer_known_value::GetIntegerKnownValueError::unhandled, + )?; + crate::operation::get_integer_known_value::GetIntegerKnownValue::send(&self.client, input) + .await + } + + #[allow(missing_docs)] // documentation missing in model + pub fn value(mut self, input: i32) -> Self { + self.inner = self.inner.value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_input.rs deleted file mode 100644 index 43e834f3de..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_input.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetIntegerInput { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::primitive::i32>, -} -impl GetIntegerInput { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::primitive::i32> { - self.value -} -} -impl GetIntegerInput { - /// Creates a new builder-style object to manufacture [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). - pub fn builder() -> crate::operation::get_integer_known_value_test::builders::GetIntegerInputBuilder { - crate::operation::get_integer_known_value_test::builders::GetIntegerInputBuilder::default() - } -} - -/// A builder for [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetIntegerInputBuilder { - pub(crate) value: ::std::option::Option<::std::primitive::i32>, -} -impl GetIntegerInputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { - &self.value -} - /// Consumes the builder and constructs a [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_integer_known_value_test::GetIntegerInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_integer_known_value_test::GetIntegerInput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_output.rs deleted file mode 100644 index c1c00f46eb..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_output.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetIntegerOutput { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::primitive::i32>, -} -impl GetIntegerOutput { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::primitive::i32> { - self.value -} -} -impl GetIntegerOutput { - /// Creates a new builder-style object to manufacture [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). - pub fn builder() -> crate::operation::get_integer_known_value_test::builders::GetIntegerOutputBuilder { - crate::operation::get_integer_known_value_test::builders::GetIntegerOutputBuilder::default() - } -} - -/// A builder for [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetIntegerOutputBuilder { - pub(crate) value: ::std::option::Option<::std::primitive::i32>, -} -impl GetIntegerOutputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { - &self.value -} - /// Consumes the builder and constructs a [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_integer_known_value_test::GetIntegerOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_integer_known_value_test::GetIntegerOutput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/builders.rs deleted file mode 100644 index a7554ca939..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/builders.rs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub use crate::operation::get_integer_known_value_test::_get_integer_output::GetIntegerOutputBuilder; - -pub use crate::operation::get_integer_known_value_test::_get_integer_input::GetIntegerInputBuilder; - -impl GetIntegerInputBuilder { - /// Sends a request with this input using the given client. - pub async fn send_with( - self, - client: &crate::Client, - ) -> ::std::result::Result< - crate::operation::get_integer_known_value_test::GetIntegerOutput, - crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError, - > { - let mut fluent_builder = client.get_integer_known_value_test(); - fluent_builder.inner = self; - fluent_builder.send().await - } -} -/// Fluent builder constructing a request to `GetIntegerKnownValueTest`. -/// -#[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct GetIntegerKnownValueTestFluentBuilder { - client: crate::client::Client, - pub(crate) inner: crate::operation::get_integer_known_value_test::builders::GetIntegerInputBuilder, -} -impl GetIntegerKnownValueTestFluentBuilder { - /// Creates a new `GetIntegerKnownValueTest`. - pub(crate) fn new(client: crate::client::Client) -> Self { - Self { - client, - inner: ::std::default::Default::default(), - } - } - /// Access the GetIntegerKnownValueTest as a reference. - pub fn as_input(&self) -> &crate::operation::get_integer_known_value_test::builders::GetIntegerInputBuilder { - &self.inner - } - /// Sends the request and returns the response. - pub async fn send( - self, - ) -> ::std::result::Result< - crate::operation::get_integer_known_value_test::GetIntegerOutput, - crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError, - > { - let input = self - .inner - .build() - // Using unhandled since GetIntegerKnownValueTest doesn't declare any validation, - // and smithy-rs seems to not generate a ValidationError case unless there is - // (but isn't that a backwards compatibility problem for output structures?) - // Vanilla smithy-rs uses SdkError::construction_failure, - // but we aren't using SdkError. - .map_err(crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError::unhandled)?; - crate::operation::get_integer_known_value_test::GetIntegerKnownValueTest::send(&self.client, input).await - } - - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { - self.inner.get_value() -} -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_conversions.rs index 6bf8297d8a..3a51134c6e 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_conversions.rs @@ -1,266 +1,246 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + >, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny( - input: &Option, -) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny( + input: &::aws_smithy_types::Blob, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny( + input: ::dafny_runtime::Sequence, +) -> ::aws_smithy_types::Blob { + + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()) + .unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x, - ) +pub fn double_to_dafny( + input: f64, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny( + input: &::dafny_runtime::Sequence, +) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: &::aws_smithy_types::DateTime, + input: ::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &input.to_string(), - ) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, -> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc>> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input, - ); - ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) - .unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); + ::aws_smithy_types::DateTime::from_str( + &s, + aws_smithy_types::date_time::Format::DateTime, + ).unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::DateTime> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None {} => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None { } => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { - value: converter(&value), - }), - None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), - } + match input { + Some(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::Some { + value: converter(&value) + } + ), + None => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::None {} + ), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value), - }), - Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error), - }), - } -} + match input { + Ok(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value) + } + ), + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error) + } + ), + } +} \ No newline at end of file diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types.rs index 646cdced26..0ab755433a 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types.rs @@ -1,5 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + /// Types for the `SimpleIntegerConfig` pub mod simple_integer_config; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types/simple_integer_config.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types/simple_integer_config.rs index 4851f5748c..15a5df4737 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types/simple_integer_config.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types/simple_integer_config.rs @@ -1,8 +1,9 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + #[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct SimpleIntegerConfig {} +pub struct SimpleIntegerConfig { + // XXX : ::std::option::Option +} impl SimpleIntegerConfig { pub fn builder() -> SimpleIntegerConfigBuilder { @@ -11,12 +12,17 @@ impl SimpleIntegerConfig { } #[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct SimpleIntegerConfigBuilder {} +pub struct SimpleIntegerConfigBuilder { + // XXX : ::std::option::Option +} impl SimpleIntegerConfigBuilder { /// Creates a new `SimpleIntegerConfigBuilder`. pub(crate) fn new() -> Self { - Self {} + Self { + // XXX = ::std::option::Option::None + // somewhere get default values for things? + } } pub fn build( self, @@ -24,4 +30,19 @@ impl SimpleIntegerConfigBuilder { { ::std::result::Result::Ok(SimpleIntegerConfig {}) } + /* + pub fn XXX(mut self, input: impl ::std::convert::Into) -> Self { + self.XXX = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_XXX(mut self, input: ::std::option::Option) -> Self { + self.XXX = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_XXX(&self) -> &::std::option::Option { + &self.XXX + } + */ } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped.rs deleted file mode 100644 index 77a3cb4cd4..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod client; - -impl crate::r#simple::types::integer::internaldafny::wrapped::_default { - pub fn WrappedSimpleInteger(config: &::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::SimpleIntegerConfig, - >) -> ::std::rc::Rc, - ::std::rc::Rc - >>{ - crate::wrapped::client::Client::from_conf(config) - } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped/client.rs deleted file mode 100644 index 2df771a408..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped/client.rs +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use tokio::runtime::Runtime; - -pub struct Client { - wrapped: crate::client::Client, - - /// A `current_thread` runtime for executing operations on the - /// asynchronous client in a blocking manner. - rt: Runtime -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::integer::internaldafny::types::ISimpleTypesIntegerClient); -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); -} - -impl Client { - pub fn from_conf(config: &::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::SimpleIntegerConfig, - >) -> -::std::rc::Rc, - ::std::rc::Rc ->> { - let rt_result = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build(); - let rt = match rt_result { - Ok(x) => x, - Err(error) => return crate::conversions::error::to_opaque_error_result(error), - }; - let result = crate::client::Client::from_conf( - crate::conversions::simple_integer_config::_simple_integer_config::from_dafny( - config.clone(), - ), - ); - match result { - Ok(client) => { - let wrap = crate::wrapped::client::Client { - wrapped: client, - rt - }; - std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) - } - ) - }, - Err(error) => crate::conversions::error::to_opaque_error_result(error) - } - } -} - -impl crate::r#simple::types::integer::internaldafny::types::ISimpleTypesIntegerClient for Client { - fn GetInteger( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_integer::_get_integer_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_integer::GetInteger::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_integer::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_integer::_get_integer_output::to_dafny(client), - }, - ), - } - } - - fn GetIntegerKnownValueTest( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_integer_known_value_test::_get_integer_known_value_test_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_integer_known_value_test::GetIntegerKnownValueTest::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_integer_known_value_test::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_integer_known_value_test::_get_integer_known_value_test_output::to_dafny(client), - }, - ), - } - } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/tests/simple_integer_test.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/tests/simple_integer_test.rs index a48b2d5df6..432eb5450c 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/tests/simple_integer_test.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/tests/simple_integer_test.rs @@ -10,7 +10,7 @@ async fn test_get_integer() { #[tokio::test] async fn test_get_known_value() { - let result = client().get_integer_known_value_test().value(20).send().await; + let result = client().get_integer_known_value().value(20).send().await; let output = result.unwrap(); let value = output.value().unwrap(); assert_eq!(value, 20); diff --git a/TestModels/SimpleTypes/SimpleLong/Makefile b/TestModels/SimpleTypes/SimpleLong/Makefile index 30f5ebd1a4..ff21e566bb 100644 --- a/TestModels/SimpleTypes/SimpleLong/Makefile +++ b/TestModels/SimpleTypes/SimpleLong/Makefile @@ -3,9 +3,8 @@ CORES=2 -TRANSPILE_TESTS_IN_RUST=1 - ENABLE_EXTERN_PROCESSING=1 +RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/Cargo.toml index 9c0ced7f0a..6fa3747d29 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/Cargo.toml @@ -5,19 +5,13 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html -[features] -wrapped-client = [] - [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies] -simple_long = { path = ".", features = ["wrapped-client"] } - -[dependencies.tokio] +[dev-dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client.rs index 6ec9bcc3e4..0529ead1f9 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -30,11 +29,11 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), }) } } mod get_long; -mod get_long_known_value_test; +mod get_long_known_value; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long.rs index d420786f93..acd51ffb21 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long.rs @@ -1,13 +1,11 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { /// Constructs a fluent builder for the [`GetLong`](crate::operation::get_long::builders::GetLongFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_long::builders::GetLongFluentBuilder::value) / [`set_value(Option<::std::primitive::i64>)`](crate::operation::get_long::builders::GetLongFluentBuilder::set_value): (undocumented)
+ /// - [`value(i64)`](crate::operation::get_long::builders::GetLongFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_long::builders::GetLongFluentBuilder::set_value):(undocumented)
/// - On success, responds with [`GetLongOutput`](crate::operation::get_long::GetLongOutput) with field(s): - /// - [`value(Option<::std::primitive::i64>)`](crate::operation::get_long::GetLongOutput::value): (undocumented) + /// - [`value(Option)`](crate::operation::get_long::GetLongOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_long::GetLongError) pub fn get_long(&self) -> crate::operation::get_long::builders::GetLongFluentBuilder { crate::operation::get_long::builders::GetLongFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value.rs new file mode 100644 index 0000000000..197e3f5bef --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value.rs @@ -0,0 +1,17 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +impl super::Client { + /// Constructs a fluent builder for the [`GetLong`](crate::operation::get_long_known_value::builders::GetLongFluentBuilder) operation. + /// + /// - The fluent builder is configurable: + /// - [`value(i64)`](crate::operation::get_long_known_value::builders::GetLongFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_long_known_value::builders::GetLongFluentBuilder::set_value):(undocumented)
+ /// - On success, responds with [`GetLongOutput`](crate::operation::get_long_known_value::GetLongOutput) with field(s): + /// - [`value(Option)`](crate::operation::get_long_known_value::GetLongOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_long_known_value::GetLongError) + pub fn get_long_known_value( + &self, + ) -> crate::operation::get_long_known_value::builders::GetLongKnownValueFluentBuilder { + crate::operation::get_long_known_value::builders::GetLongKnownValueFluentBuilder::new( + self.clone(), + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value_test.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value_test.rs deleted file mode 100644 index d0cc474cc5..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value_test.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -impl super::Client { - /// Constructs a fluent builder for the [`GetLongKnownValueTest`](crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder) operation. - /// - /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder::value) / [`set_value(Option<::std::primitive::i64>)`](crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder::set_value): (undocumented)
- /// - On success, responds with [`GetLongOutput`](crate::operation::get_long_known_value_test::GetLongOutput) with field(s): - /// - [`value(Option<::std::primitive::i64>)`](crate::operation::get_long_known_value_test::GetLongOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_long_known_value_test::GetLongKnownValueTestError) - pub fn get_long_known_value_test(&self) -> crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder { - crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder::new(self.clone()) - } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions.rs index a0cb33c551..4ff5bcbc92 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions.rs @@ -1,10 +1,6 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod error; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub mod get_long; - pub mod get_long; +pub mod get_long_known_value; - pub mod get_long_known_value_test; - - pub mod simple_long_config; +pub mod simple_long_config; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/error.rs deleted file mode 100644 index 4d0aeedd1a..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/error.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. - /// Wraps up an arbitrary Rust Error value as a Dafny Error -pub fn to_opaque_error(value: E) -> - ::std::rc::Rc -{ - let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( - ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), - )); - ::std::rc::Rc::new( - crate::r#simple::types::smithylong::internaldafny::types::Error::Opaque { - obj: error_obj, - }, - ) -} - -/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure -pub fn to_opaque_error_result(value: E) -> - ::std::rc::Rc< - crate::_Wrappers_Compile::Result< - T, - ::std::rc::Rc - > - > -{ - ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: to_opaque_error(value), - }, - ) -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long.rs index 210e9a6d0d..59558ca19b 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_input.rs index 9b4211a3da..8392959724 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_input.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_input.rs @@ -1,24 +1,37 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_long::GetLongInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, ->{ +> { + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { value: v }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongInput::GetLongInput { - value: crate::standard_library_conversions::olong_to_dafny(&value.value), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, >, ) -> crate::operation::get_long::GetLongInput { - crate::operation::get_long::GetLongInput::builder() - .set_value(crate::standard_library_conversions::olong_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(dafny_value.value().Extract()) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_long::GetLongInput { value } } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_output.rs index 4bbf353650..68ff34defe 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_output.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_output.rs @@ -1,24 +1,37 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_long::GetLongOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, ->{ +> { + let dafny_value = match value.value { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput::GetLongOutput { - value: crate::standard_library_conversions::olong_to_dafny(&value.value), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, >, ) -> crate::operation::get_long::GetLongOutput { - crate::operation::get_long::GetLongOutput::builder() - .set_value(crate::standard_library_conversions::olong_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(dafny_value.value().Extract()) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_long::GetLongOutput { value } } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value.rs new file mode 100644 index 0000000000..f4c90a3a2b --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value.rs @@ -0,0 +1,32 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +use std::any::Any; + +#[allow(dead_code)] +pub fn to_dafny_error( + value: crate::operation::get_long_known_value::GetLongKnownValueError, +) -> ::std::rc::Rc { + match value { + crate::operation::get_long_known_value::GetLongKnownValueError::Unhandled(unhandled) => + ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) + } +} + +#[allow(dead_code)] +pub fn from_dafny_error( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::Error, + >, +) -> crate::operation::get_long_known_value::GetLongKnownValueError { + // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error + if matches!(&dafny_value.as_ref(), crate::r#simple::types::smithylong::internaldafny::types::Error::CollectionOfErrors { .. }) { + let error_message = "TODO: can't get message yet"; + crate::operation::get_long_known_value::GetLongKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) + } else { + crate::operation::get_long_known_value::GetLongKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) + } +} + +pub mod _get_long_known_value_input; + +pub mod _get_long_known_value_output; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_input.rs new file mode 100644 index 0000000000..aae399058f --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_input.rs @@ -0,0 +1,37 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_long_known_value::GetLongKnownValueInput, +) -> ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, +> { + let dafny_value = match value.value { + Some(v) => crate::_Wrappers_Compile::Option::Some { value: v }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongInput::GetLongInput { + value: ::std::rc::Rc::new(dafny_value) + }) +} + +#[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, + >, +) -> crate::operation::get_long_known_value::GetLongKnownValueInput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(dafny_value.value().Extract()) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_long_known_value::GetLongKnownValueInput { value } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_output.rs new file mode 100644 index 0000000000..bdc927aae1 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_output.rs @@ -0,0 +1,37 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_long_known_value::GetLongKnownValueOutput, +) -> ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, +> { + let dafny_value = match value.value { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput::GetLongOutput { + value: ::std::rc::Rc::new(dafny_value) + }) +} + +#[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, + >, +) -> crate::operation::get_long_known_value::GetLongKnownValueOutput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(dafny_value.value().Extract()) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_long_known_value::GetLongKnownValueOutput { value } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test.rs deleted file mode 100644 index 5550a2e767..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test.rs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use std::any::Any; - -#[allow(dead_code)] -pub fn to_dafny_error( - value: crate::operation::get_long_known_value_test::GetLongKnownValueTestError, -) -> ::std::rc::Rc { - match value { - crate::operation::get_long_known_value_test::GetLongKnownValueTestError::Unhandled(unhandled) => - ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) - } -} - -#[allow(dead_code)] -pub fn from_dafny_error( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::Error, - >, -) -> crate::operation::get_long_known_value_test::GetLongKnownValueTestError { - // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error - if matches!(&dafny_value.as_ref(), crate::r#simple::types::smithylong::internaldafny::types::Error::CollectionOfErrors { .. }) { - let error_message = "TODO: can't get message yet"; - crate::operation::get_long_known_value_test::GetLongKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) - } else { - crate::operation::get_long_known_value_test::GetLongKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) - } -} - -pub mod _get_long_known_value_test_input; - -pub mod _get_long_known_value_test_output; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_input.rs deleted file mode 100644 index 67c44ec3c3..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_input.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_long_known_value_test::GetLongInput, -) -> ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, ->{ - ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongInput::GetLongInput { - value: crate::standard_library_conversions::olong_to_dafny(&value.value), - }) -} - #[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, - >, -) -> crate::operation::get_long_known_value_test::GetLongInput { - crate::operation::get_long_known_value_test::GetLongInput::builder() - .set_value(crate::standard_library_conversions::olong_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_output.rs deleted file mode 100644 index 859142fbf6..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_output.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_long_known_value_test::GetLongOutput, -) -> ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, ->{ - ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput::GetLongOutput { - value: crate::standard_library_conversions::olong_to_dafny(&value.value), - }) -} - #[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, - >, -) -> crate::operation::get_long_known_value_test::GetLongOutput { - crate::operation::get_long_known_value_test::GetLongOutput::builder() - .set_value(crate::standard_library_conversions::olong_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config.rs index 644ecd05da..129c7eb442 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config.rs @@ -1,4 +1,3 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + pub mod _simple_long_config; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config/_simple_long_config.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config/_simple_long_config.rs index 1371539ba8..4bb610c4d2 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config/_simple_long_config.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config/_simple_long_config.rs @@ -1,12 +1,10 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_long_config::SimpleLongConfig, ) -> ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::SimpleLongConfig, + crate::simple::types::smithylong::internaldafny::types::SimpleLongConfig, > { ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::SimpleLongConfig::SimpleLongConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error.rs index 4cddaa7c39..ec89cbecc9 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error/sealed_unhandled.rs index eae8007292..cce22d1cfd 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,10 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use std::any::Any; - -use dafny_runtime::UpcastObject; - +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -27,6 +21,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl UpcastObject for Unhandled { +impl ::dafny_runtime::UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/lib.rs new file mode 100644 index 0000000000..1248f58305 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/lib.rs @@ -0,0 +1,19 @@ +#![allow(deprecated)] + +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +pub mod client; +pub mod types; + +/// Common errors and error handling utilities. +pub mod error; + +/// All operations that this crate can perform. +pub mod operation; + +mod conversions; + +pub mod implementation_from_dafny; + +pub use client::Client; +pub use types::simple_long_config::SimpleLongConfig; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation.rs index 4584907aea..9378720071 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation.rs @@ -1,8 +1,7 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + /// Types for the `GetLong` operation. pub mod get_long; -/// Types for the `GetLongKnownValueTest` operation. -pub mod get_long_known_value_test; +/// Types for the `GetLongKnownValue` operation. +pub mod get_long_known_value; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long.rs index a7387cce96..44259e5ba4 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetLong`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -18,17 +16,14 @@ impl GetLong { crate::operation::get_long::GetLongError, > { let inner_input = crate::conversions::get_long::_get_long_input::to_dafny(input); - let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetLong(&inner_input); + let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetLong(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - Ok( - crate::conversions::get_long::_get_long_output::from_dafny( - inner_result.value().clone(), - ), - ) + Ok(crate::conversions::get_long::_get_long_output::from_dafny( + inner_result.value().clone(), + )) } else { Err(crate::conversions::get_long::from_dafny_error( inner_result.error().clone(), @@ -139,9 +134,9 @@ pub use crate::operation::get_long::_get_long_output::GetLongOutput; pub use crate::operation::get_long::_get_long_input::GetLongInput; -pub(crate) mod _get_long_output; +mod _get_long_input; -pub(crate) mod _get_long_input; +mod _get_long_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_input.rs index 0f9e90cd9c..cf4ca97a0f 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_input.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_input.rs @@ -1,18 +1,16 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetLongInput { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::primitive::i64>, + pub value: ::std::option::Option, } impl GetLongInput { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::primitive::i64> { - self.value -} + pub fn value(&self) -> ::std::option::Option<&i64> { + self.value.as_ref() + } } impl GetLongInput { /// Creates a new builder-style object to manufacture [`GetLongInput`](crate::operation::operation::GetLongInput). @@ -27,23 +25,23 @@ impl GetLongInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetLongInputBuilder { - pub(crate) value: ::std::option::Option<::std::primitive::i64>, + pub(crate) value: ::std::option::Option, } impl GetLongInputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { - &self.value -} + pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + &self.value + } /// Consumes the builder and constructs a [`GetLongInput`](crate::operation::operation::GetLongInput). pub fn build( self, @@ -51,8 +49,6 @@ pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { crate::operation::get_long::GetLongInput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_long::GetLongInput { - value: self.value, - }) + ::std::result::Result::Ok(crate::operation::get_long::GetLongInput { value: self.value }) } } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_output.rs index 86950e84ce..5a2814c686 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_output.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_output.rs @@ -1,19 +1,19 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetLongOutput { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::primitive::i64>, + pub value: ::std::option::Option, } + impl GetLongOutput { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::primitive::i64> { - self.value -} + pub fn value(&self) -> ::std::option::Option { + self.value + } } + impl GetLongOutput { /// Creates a new builder-style object to manufacture [`GetLongOutput`](crate::operation::operation::GetLongOutput). pub fn builder() -> crate::operation::get_long::builders::GetLongOutputBuilder { @@ -27,23 +27,27 @@ impl GetLongOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetLongOutputBuilder { - pub(crate) value: ::std::option::Option<::std::primitive::i64>, + pub(crate) value: ::std::option::Option, } + impl GetLongOutputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { - &self.value -} + pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self + } + + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetLongOutput`](crate::operation::operation::GetLongOutput). pub fn build( self, @@ -51,8 +55,6 @@ pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { crate::operation::get_long::GetLongOutput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_long::GetLongOutput { - value: self.value, - }) + ::std::result::Result::Ok(crate::operation::get_long::GetLongOutput { value: self.value }) } } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/builders.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/builders.rs index 5cdbbd256e..cf89d6b34d 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/builders.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/builders.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use crate::operation::get_long::_get_long_output::GetLongOutputBuilder; pub use crate::operation::get_long::_get_long_input::GetLongInputBuilder; @@ -24,7 +22,7 @@ impl GetLongInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetLongFluentBuilder { client: crate::client::Client, - pub(crate) inner: crate::operation::get_long::builders::GetLongInputBuilder, + inner: crate::operation::get_long::builders::GetLongInputBuilder, } impl GetLongFluentBuilder { /// Creates a new `GetLong`. @@ -58,17 +56,17 @@ impl GetLongFluentBuilder { } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { - self.inner.get_value() -} + pub fn value(mut self, input: i64) -> Self { + self.inner = self.inner.value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value.rs similarity index 67% rename from TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test.rs rename to TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value.rs index ce1f24b47b..b434182d0d 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value.rs @@ -1,46 +1,44 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -/// Orchestration and serialization glue logic for `GetLongKnownValueTest`. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +/// Orchestration and serialization glue logic for `GetLongKnownValue`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] -pub struct GetLongKnownValueTest; -impl GetLongKnownValueTest { - /// Creates a new `GetLongKnownValueTest` +pub struct GetLongKnownValue; +impl GetLongKnownValue { + /// Creates a new `GetLongKnownValue` pub fn new() -> Self { Self } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_long_known_value_test::GetLongInput, + input: crate::operation::get_long_known_value::GetLongKnownValueInput, ) -> ::std::result::Result< - crate::operation::get_long_known_value_test::GetLongOutput, - crate::operation::get_long_known_value_test::GetLongKnownValueTestError, + crate::operation::get_long_known_value::GetLongKnownValueOutput, + crate::operation::get_long_known_value::GetLongKnownValueError, > { - let inner_input = crate::conversions::get_long_known_value_test::_get_long_known_value_test_input::to_dafny(input); - let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetLongKnownValueTest(&inner_input); + let inner_input = + crate::conversions::get_long_known_value::_get_long_known_value_input::to_dafny(input); + let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetLong(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { Ok( - crate::conversions::get_long_known_value_test::_get_long_known_value_test_output::from_dafny( + crate::conversions::get_long_known_value::_get_long_known_value_output::from_dafny( inner_result.value().clone(), ), ) } else { - Err(crate::conversions::get_long_known_value_test::from_dafny_error( + Err(crate::conversions::get_long_known_value::from_dafny_error( inner_result.error().clone(), )) } } } -/// Error type for the `GetLongKnownValueTest` operation. +/// Error type for the `GetLongKnownValue` operation. #[non_exhaustive] #[derive(::std::fmt::Debug)] -pub enum GetLongKnownValueTestError { +pub enum GetLongKnownValueError { /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ @@ -48,12 +46,12 @@ pub enum GetLongKnownValueTestError { \    `err if err.code() == Some(\"SpecificExceptionCode\") => { /* handle the error */ }` \ - See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetLongKnownValueTestError) for what information is available for the error." + See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetLongKnownValueError) for what information is available for the error." )] Unhandled(crate::error::sealed_unhandled::Unhandled), } -impl GetLongKnownValueTestError { - /// Creates the `GetLongKnownValueTestError::Unhandled` variant from any error type. +impl GetLongKnownValueError { + /// Creates the `GetLongKnownValueError::Unhandled` variant from any error type. pub fn unhandled( err: impl ::std::convert::Into< ::std::boxed::Box< @@ -67,7 +65,7 @@ impl GetLongKnownValueTestError { }) } - /// Creates the `GetLongKnownValueTestError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). + /// Creates the `GetLongKnownValueError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). pub fn generic(err: ::aws_smithy_types::error::ErrorMetadata) -> Self { Self::Unhandled(crate::error::sealed_unhandled::Unhandled { source: err.clone().into(), @@ -84,14 +82,14 @@ impl GetLongKnownValueTestError { } } } -impl ::std::error::Error for GetLongKnownValueTestError { +impl ::std::error::Error for GetLongKnownValueError { fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> { match self { Self::Unhandled(_inner) => ::std::option::Option::Some(&*_inner.source), } } } -impl ::std::fmt::Display for GetLongKnownValueTestError { +impl ::std::fmt::Display for GetLongKnownValueError { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self { Self::Unhandled(_inner) => { @@ -106,7 +104,7 @@ impl ::std::fmt::Display for GetLongKnownValueTestError { } } } -impl ::aws_smithy_types::retry::ProvideErrorKind for GetLongKnownValueTestError { +impl ::aws_smithy_types::retry::ProvideErrorKind for GetLongKnownValueError { fn code(&self) -> ::std::option::Option<&str> { ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self) } @@ -114,14 +112,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetLongKnownValueTestError ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetLongKnownValueTestError { +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetLongKnownValueError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetLongKnownValueTestError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetLongKnownValueError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -135,13 +133,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetLongK } } -pub use crate::operation::get_long_known_value_test::_get_long_output::GetLongOutput; +pub use crate::operation::get_long_known_value::_get_long_known_value_output::GetLongKnownValueOutput; -pub use crate::operation::get_long_known_value_test::_get_long_input::GetLongInput; +pub use crate::operation::get_long_known_value::_get_long_known_value_input::GetLongKnownValueInput; -pub(crate) mod _get_long_output; +mod _get_long_known_value_input; -pub(crate) mod _get_long_input; +mod _get_long_known_value_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_input.rs new file mode 100644 index 0000000000..b1b4d3bece --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_input.rs @@ -0,0 +1,57 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetLongKnownValueInput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetLongKnownValueInput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option { + self.value + } +} +impl GetLongKnownValueInput { + /// Creates a new builder-style object to manufacture [`GetLongKnownValueInput`](crate::operation::operation::GetLongKnownValueInput). + pub fn builder( + ) -> crate::operation::get_long_known_value::builders::GetLongKnownValueInputBuilder { + crate::operation::get_long_known_value::builders::GetLongKnownValueInputBuilder::default() + } +} + +/// A builder for [`GetLongKnownValueInput`](crate::operation::operation::GetLongKnownValueInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetLongKnownValueInputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetLongKnownValueInputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetLongKnownValueInput`](crate::operation::operation::GetLongKnownValueInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_long_known_value::GetLongKnownValueInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_long_known_value::GetLongKnownValueInput { value: self.value }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_output.rs new file mode 100644 index 0000000000..b18b9c89a4 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_output.rs @@ -0,0 +1,57 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetLongKnownValueOutput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option, +} +impl GetLongKnownValueOutput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option { + self.value + } +} +impl GetLongKnownValueOutput { + /// Creates a new builder-style object to manufacture [`GetLongKnownValueOutput`](crate::operation::operation::GetLongKnownValueOutput). + pub fn builder( + ) -> crate::operation::get_long_known_value::builders::GetLongKnownValueOutputBuilder { + crate::operation::get_long_known_value::builders::GetLongKnownValueOutputBuilder::default() + } +} + +/// A builder for [`GetLongKnownValueOutput`](crate::operation::operation::GetLongKnownValueOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetLongKnownValueOutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetLongKnownValueOutputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + &self.value + } + /// Consumes the builder and constructs a [`GetLongKnownValueOutput`](crate::operation::operation::GetLongKnownValueOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_long_known_value::GetLongKnownValueOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_long_known_value::GetLongKnownValueOutput { value: self.value }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/builders.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/builders.rs new file mode 100644 index 0000000000..46a4de5e36 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/builders.rs @@ -0,0 +1,74 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub use crate::operation::get_long_known_value::_get_long_known_value_output::GetLongKnownValueOutputBuilder; + +pub use crate::operation::get_long_known_value::_get_long_known_value_input::GetLongKnownValueInputBuilder; + +impl GetLongKnownValueInputBuilder { + /// Sends a request with this input using the given client. + pub async fn send_with( + self, + client: &crate::Client, + ) -> ::std::result::Result< + crate::operation::get_long_known_value::GetLongKnownValueOutput, + crate::operation::get_long_known_value::GetLongKnownValueError, + > { + let mut fluent_builder = client.get_long_known_value(); + fluent_builder.inner = self; + fluent_builder.send().await + } +} +/// Fluent builder constructing a request to `GetLongKnownValue`. +/// +#[derive(::std::clone::Clone, ::std::fmt::Debug)] +pub struct GetLongKnownValueFluentBuilder { + client: crate::client::Client, + inner: crate::operation::get_long_known_value::builders::GetLongKnownValueInputBuilder, +} +impl GetLongKnownValueFluentBuilder { + /// Creates a new `GetLongKnownValue`. + pub(crate) fn new(client: crate::client::Client) -> Self { + Self { + client, + inner: ::std::default::Default::default(), + } + } + /// Access the GetLongKnownValue as a reference. + pub fn as_input( + &self, + ) -> &crate::operation::get_long_known_value::builders::GetLongKnownValueInputBuilder { + &self.inner + } + /// Sends the request and returns the response. + pub async fn send( + self, + ) -> ::std::result::Result< + crate::operation::get_long_known_value::GetLongKnownValueOutput, + crate::operation::get_long_known_value::GetLongKnownValueError, + > { + let input = self + .inner + .build() + // Using unhandled since GetLong doesn't declare any validation, + // and smithy-rs seems to not generate a ValidationError case unless there is + // (but isn't that a backwards compatibility problem for output structures?) + // Vanilla smithy-rs uses SdkError::construction_failure, + // but we aren't using SdkError. + .map_err(crate::operation::get_long_known_value::GetLongKnownValueError::unhandled)?; + crate::operation::get_long_known_value::GetLongKnownValue::send(&self.client, input).await + } + + #[allow(missing_docs)] // documentation missing in model + pub fn value(mut self, input: i64) -> Self { + self.inner = self.inner.value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_input.rs deleted file mode 100644 index 3549b72552..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_input.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetLongInput { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::primitive::i64>, -} -impl GetLongInput { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::primitive::i64> { - self.value -} -} -impl GetLongInput { - /// Creates a new builder-style object to manufacture [`GetLongInput`](crate::operation::operation::GetLongInput). - pub fn builder() -> crate::operation::get_long_known_value_test::builders::GetLongInputBuilder { - crate::operation::get_long_known_value_test::builders::GetLongInputBuilder::default() - } -} - -/// A builder for [`GetLongInput`](crate::operation::operation::GetLongInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetLongInputBuilder { - pub(crate) value: ::std::option::Option<::std::primitive::i64>, -} -impl GetLongInputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { - &self.value -} - /// Consumes the builder and constructs a [`GetLongInput`](crate::operation::operation::GetLongInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_long_known_value_test::GetLongInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_long_known_value_test::GetLongInput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_output.rs deleted file mode 100644 index 60d05a1481..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_output.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetLongOutput { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::primitive::i64>, -} -impl GetLongOutput { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::primitive::i64> { - self.value -} -} -impl GetLongOutput { - /// Creates a new builder-style object to manufacture [`GetLongOutput`](crate::operation::operation::GetLongOutput). - pub fn builder() -> crate::operation::get_long_known_value_test::builders::GetLongOutputBuilder { - crate::operation::get_long_known_value_test::builders::GetLongOutputBuilder::default() - } -} - -/// A builder for [`GetLongOutput`](crate::operation::operation::GetLongOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetLongOutputBuilder { - pub(crate) value: ::std::option::Option<::std::primitive::i64>, -} -impl GetLongOutputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { - &self.value -} - /// Consumes the builder and constructs a [`GetLongOutput`](crate::operation::operation::GetLongOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_long_known_value_test::GetLongOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_long_known_value_test::GetLongOutput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/builders.rs deleted file mode 100644 index a79b8a361b..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/builders.rs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub use crate::operation::get_long_known_value_test::_get_long_output::GetLongOutputBuilder; - -pub use crate::operation::get_long_known_value_test::_get_long_input::GetLongInputBuilder; - -impl GetLongInputBuilder { - /// Sends a request with this input using the given client. - pub async fn send_with( - self, - client: &crate::Client, - ) -> ::std::result::Result< - crate::operation::get_long_known_value_test::GetLongOutput, - crate::operation::get_long_known_value_test::GetLongKnownValueTestError, - > { - let mut fluent_builder = client.get_long_known_value_test(); - fluent_builder.inner = self; - fluent_builder.send().await - } -} -/// Fluent builder constructing a request to `GetLongKnownValueTest`. -/// -#[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct GetLongKnownValueTestFluentBuilder { - client: crate::client::Client, - pub(crate) inner: crate::operation::get_long_known_value_test::builders::GetLongInputBuilder, -} -impl GetLongKnownValueTestFluentBuilder { - /// Creates a new `GetLongKnownValueTest`. - pub(crate) fn new(client: crate::client::Client) -> Self { - Self { - client, - inner: ::std::default::Default::default(), - } - } - /// Access the GetLongKnownValueTest as a reference. - pub fn as_input(&self) -> &crate::operation::get_long_known_value_test::builders::GetLongInputBuilder { - &self.inner - } - /// Sends the request and returns the response. - pub async fn send( - self, - ) -> ::std::result::Result< - crate::operation::get_long_known_value_test::GetLongOutput, - crate::operation::get_long_known_value_test::GetLongKnownValueTestError, - > { - let input = self - .inner - .build() - // Using unhandled since GetLongKnownValueTest doesn't declare any validation, - // and smithy-rs seems to not generate a ValidationError case unless there is - // (but isn't that a backwards compatibility problem for output structures?) - // Vanilla smithy-rs uses SdkError::construction_failure, - // but we aren't using SdkError. - .map_err(crate::operation::get_long_known_value_test::GetLongKnownValueTestError::unhandled)?; - crate::operation::get_long_known_value_test::GetLongKnownValueTest::send(&self.client, input).await - } - - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { - self.inner.get_value() -} -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_conversions.rs index 6bf8297d8a..3a51134c6e 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_conversions.rs @@ -1,266 +1,246 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + >, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny( - input: &Option, -) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny( + input: &::aws_smithy_types::Blob, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny( + input: ::dafny_runtime::Sequence, +) -> ::aws_smithy_types::Blob { + + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()) + .unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x, - ) +pub fn double_to_dafny( + input: f64, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny( + input: &::dafny_runtime::Sequence, +) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: &::aws_smithy_types::DateTime, + input: ::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &input.to_string(), - ) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, -> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc>> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input, - ); - ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) - .unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); + ::aws_smithy_types::DateTime::from_str( + &s, + aws_smithy_types::date_time::Format::DateTime, + ).unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::DateTime> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None {} => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None { } => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { - value: converter(&value), - }), - None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), - } + match input { + Some(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::Some { + value: converter(&value) + } + ), + None => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::None {} + ), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value), - }), - Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error), - }), - } -} + match input { + Ok(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value) + } + ), + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error) + } + ), + } +} \ No newline at end of file diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types.rs index d9223fcb30..f8ff6d665a 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types.rs @@ -1,5 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + /// Types for the `SimpleLongConfig` pub mod simple_long_config; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types/simple_long_config.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types/simple_long_config.rs index 5df8e1ebfc..7def54c032 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types/simple_long_config.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types/simple_long_config.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleLongConfig {} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped.rs deleted file mode 100644 index ef8910b03c..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod client; - -impl crate::r#simple::types::smithylong::internaldafny::wrapped::_default { - pub fn WrappedSimpleLong(config: &::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::SimpleLongConfig, - >) -> ::std::rc::Rc, - ::std::rc::Rc - >>{ - crate::wrapped::client::Client::from_conf(config) - } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped/client.rs deleted file mode 100644 index 5b4a2bf9c4..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped/client.rs +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use tokio::runtime::Runtime; - -pub struct Client { - wrapped: crate::client::Client, - - /// A `current_thread` runtime for executing operations on the - /// asynchronous client in a blocking manner. - rt: Runtime -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::smithylong::internaldafny::types::ISimpleTypesLongClient); -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); -} - -impl Client { - pub fn from_conf(config: &::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::SimpleLongConfig, - >) -> -::std::rc::Rc, - ::std::rc::Rc ->> { - let rt_result = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build(); - let rt = match rt_result { - Ok(x) => x, - Err(error) => return crate::conversions::error::to_opaque_error_result(error), - }; - let result = crate::client::Client::from_conf( - crate::conversions::simple_long_config::_simple_long_config::from_dafny( - config.clone(), - ), - ); - match result { - Ok(client) => { - let wrap = crate::wrapped::client::Client { - wrapped: client, - rt - }; - std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) - } - ) - }, - Err(error) => crate::conversions::error::to_opaque_error_result(error) - } - } -} - -impl crate::r#simple::types::smithylong::internaldafny::types::ISimpleTypesLongClient for Client { - fn GetLong( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_long::_get_long_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_long::GetLong::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_long::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_long::_get_long_output::to_dafny(client), - }, - ), - } - } - - fn GetLongKnownValueTest( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_long_known_value_test::_get_long_known_value_test_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_long_known_value_test::GetLongKnownValueTest::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_long_known_value_test::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_long_known_value_test::_get_long_known_value_test_output::to_dafny(client), - }, - ), - } - } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/tests/simple_long_test.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/tests/simple_long_test.rs index e48d52d5fd..d63548ae69 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/tests/simple_long_test.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/tests/simple_long_test.rs @@ -10,7 +10,7 @@ async fn test_get_long() { #[tokio::test] async fn test_get_known_value() { - let result = client().get_long_known_value_test().value(33i64).send().await; + let result = client().get_long_known_value().value(33i64).send().await; let output = result.unwrap(); let value = output.value().unwrap(); assert_eq!(value, 33i64); diff --git a/TestModels/SimpleTypes/SimpleString/Makefile b/TestModels/SimpleTypes/SimpleString/Makefile index 6ee0d9abff..e68e628e37 100644 --- a/TestModels/SimpleTypes/SimpleString/Makefile +++ b/TestModels/SimpleTypes/SimpleString/Makefile @@ -3,9 +3,8 @@ CORES=2 -TRANSPILE_TESTS_IN_RUST=1 - ENABLE_EXTERN_PROCESSING=1 +RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleString/runtimes/rust/Cargo.toml index 65ef7a3960..3f66bd6aa2 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/Cargo.toml @@ -5,21 +5,15 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html -[features] -wrapped-client = [] - [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies] -simple_string = { path = ".", features = ["wrapped-client"] } - -[dependencies.tokio] +[dev-dependencies.tokio] version = "1.26.0" features = ["full"] [lib] -path = "src/implementation_from_dafny.rs" +path = "src/implementation_from_dafny.rs" \ No newline at end of file diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client.rs index 88a144918b..2d5b76bf25 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -14,6 +13,8 @@ impl Client { pub fn from_conf( conf: crate::types::simple_string_config::SimpleStringConfig, ) -> Result { + // If this service had any configuration properties, + // they would need converting here too. let inner = crate::simple::types::smithystring::internaldafny::_default::SimpleString( &crate::conversions::simple_string_config::_simple_string_config::to_dafny(conf), @@ -30,7 +31,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), }) } } @@ -41,4 +42,4 @@ mod get_string_known_value; mod get_string_utf8; -mod get_string_utf8_known_value; +mod get_string_utf8_known_value; \ No newline at end of file diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string.rs index fe18db0b8c..da262534e9 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string.rs @@ -1,13 +1,11 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { /// Constructs a fluent builder for the [`GetString`](crate::operation::get_string::builders::GetStringFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_string::builders::GetStringFluentBuilder::value) / [`set_value(Option<::std::string::String>)`](crate::operation::get_string::builders::GetStringFluentBuilder::set_value): (undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_string::builders::GetStringFluentBuilder::name) / [`set_name(Option)`](crate::operation::get_string::builders::GetStringFluentBuilder::set_name):(undocumented)
/// - On success, responds with [`GetStringOutput`](crate::operation::get_string::GetStringOutput) with field(s): - /// - [`value(Option<::std::string::String>)`](crate::operation::get_string::GetStringOutput::value): (undocumented) + /// - [`value(Option)`](crate::operation::get_string::GetStringOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_string::GetStringError) pub fn get_string(&self) -> crate::operation::get_string::builders::GetStringFluentBuilder { crate::operation::get_string::builders::GetStringFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_known_value.rs index 6ddfcadaa5..8c13c6ad59 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_known_value.rs @@ -1,15 +1,17 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { /// Constructs a fluent builder for the [`GetStringKnownValue`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::value) / [`set_value(Option<::std::string::String>)`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::set_value): (undocumented)
- /// - On success, responds with [`GetStringOutput`](crate::operation::get_string_known_value::GetStringOutput) with field(s): - /// - [`value(Option<::std::string::String>)`](crate::operation::get_string_known_value::GetStringOutput::value): (undocumented) + /// - [`value(impl Into>)`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::name) / [`set_name(Option)`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::set_name):(undocumented)
+ /// - On success, responds with [`GetStringKnownValueOutput`](crate::operation::get_string_known_value::GetStringKnownValueOutput) with field(s): + /// - [`value(Option)`](crate::operation::get_string_known_value::GetStringKnownValueOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_string_known_value::GetStringKnownValueError) - pub fn get_string_known_value(&self) -> crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder { - crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::new(self.clone()) + pub fn get_string_known_value( + &self, + ) -> crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder { + crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::new( + self.clone(), + ) } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8.rs index 010a0547e6..3a487be091 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8.rs @@ -1,15 +1,15 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { /// Constructs a fluent builder for the [`GetStringUTF8`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::value) / [`set_value(Option<::std::string::String>)`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::set_value): (undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::name) / [`set_name(Option)`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::set_name):(undocumented)
/// - On success, responds with [`GetStringUTF8Output`](crate::operation::get_string_utf8::GetStringUTF8Output) with field(s): - /// - [`value(Option<::std::string::String>)`](crate::operation::get_string_utf8::GetStringUTF8Output::value): (undocumented) + /// - [`value(Option)`](crate::operation::get_string_utf8::GetStringUTF8Output::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_string_utf8::GetStringUTF8Error) - pub fn get_string_utf8(&self) -> crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder { + pub fn get_string_utf8( + &self, + ) -> crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder { crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8_known_value.rs index dab2fd15fb..205f24ff5f 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8_known_value.rs @@ -1,15 +1,15 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { /// Constructs a fluent builder for the [`GetStringUTF8KnownValue`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::value) / [`set_value(Option<::std::string::String>)`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::set_value): (undocumented)
- /// - On success, responds with [`GetStringUTF8Output`](crate::operation::get_string_utf8_known_value::GetStringUTF8Output) with field(s): - /// - [`value(Option<::std::string::String>)`](crate::operation::get_string_utf8_known_value::GetStringUTF8Output::value): (undocumented) + /// - [`value(impl Into>)`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::name) / [`set_name(Option)`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::set_name):(undocumented)
+ /// - On success, responds with [`GetStringUTF8KnownValueOutput`](crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput) with field(s): + /// - [`value(Option)`](crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError) - pub fn get_string_utf8_known_value(&self) -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder { + pub fn get_string_utf8_known_value( + &self, + ) -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder { crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions.rs index c994c2ec1b..e48982f580 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions.rs @@ -1,14 +1,10 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod error; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub mod get_string; - pub mod get_string; +pub mod get_string_known_value; - pub mod get_string_known_value; +pub mod get_string_utf8; - pub mod get_string_utf8; +pub mod get_string_utf8_known_value; - pub mod get_string_utf8_known_value; - - pub mod simple_string_config; +pub mod simple_string_config; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/error.rs deleted file mode 100644 index ec72eaf961..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/error.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. - /// Wraps up an arbitrary Rust Error value as a Dafny Error -pub fn to_opaque_error(value: E) -> - ::std::rc::Rc -{ - let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( - ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), - )); - ::std::rc::Rc::new( - crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { - obj: error_obj, - }, - ) -} - -/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure -pub fn to_opaque_error_result(value: E) -> - ::std::rc::Rc< - crate::_Wrappers_Compile::Result< - T, - ::std::rc::Rc - > - > -{ - ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: to_opaque_error(value), - }, - ) -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string.rs index 28eedb4163..4a11ce9324 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string.rs @@ -1,12 +1,12 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_string::GetStringError, -) -> ::std::rc::Rc { +) -> ::std::rc::Rc +{ match value { crate::operation::get_string::GetStringError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_input.rs index 504704b4f8..2b7ac1e68b 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_input.rs @@ -1,24 +1,43 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_string::GetStringInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, ->{ +> { + let dafny_value = match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { + value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringInput::GetStringInput { - value: crate::standard_library_conversions::ostring_to_dafny(&value.value), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, >, ) -> crate::operation::get_string::GetStringInput { - crate::operation::get_string::GetStringInput::builder() - .set_value(crate::standard_library_conversions::ostring_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_string::GetStringInput { value } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_output.rs index 9f993cd584..66cfd60615 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_output.rs @@ -1,24 +1,41 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_string::GetStringOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, ->{ +> { + let dafny_value = match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { + value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { - value: crate::standard_library_conversions::ostring_to_dafny(&value.value), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, - >, + dafny_value: ::std::rc::Rc, ) -> crate::operation::get_string::GetStringOutput { - crate::operation::get_string::GetStringOutput::builder() - .set_value(crate::standard_library_conversions::ostring_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_string::GetStringOutput { value } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value.rs index 9f4018f6fa..680fd6ad86 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value.rs @@ -1,12 +1,12 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_string_known_value::GetStringKnownValueError, -) -> ::std::rc::Rc { +) -> ::std::rc::Rc +{ match value { crate::operation::get_string_known_value::GetStringKnownValueError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_input.rs index cc34124d85..2a638911d9 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_input.rs @@ -1,24 +1,43 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_string_known_value::GetStringInput, + value: crate::operation::get_string_known_value::GetStringKnownValueInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, ->{ +> { + let dafny_value = match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { + value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringInput::GetStringInput { - value: crate::standard_library_conversions::ostring_to_dafny(&value.value), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, >, -) -> crate::operation::get_string_known_value::GetStringInput { - crate::operation::get_string_known_value::GetStringInput::builder() - .set_value(crate::standard_library_conversions::ostring_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() +) -> crate::operation::get_string_known_value::GetStringKnownValueInput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_string_known_value::GetStringKnownValueInput { value } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_output.rs index 1507eeb3f4..00f53c20bc 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_output.rs @@ -1,24 +1,41 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_string_known_value::GetStringOutput, + value: crate::operation::get_string_known_value::GetStringKnownValueOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, ->{ +> { + let dafny_value = match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { + value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { - value: crate::standard_library_conversions::ostring_to_dafny(&value.value), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, - >, -) -> crate::operation::get_string_known_value::GetStringOutput { - crate::operation::get_string_known_value::GetStringOutput::builder() - .set_value(crate::standard_library_conversions::ostring_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() + dafny_value: ::std::rc::Rc, +) -> crate::operation::get_string_known_value::GetStringKnownValueOutput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &dafny_value.value().Extract(), + ), + ) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_string_known_value::GetStringKnownValueOutput { value } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8.rs index 855e9697cd..1f3d581ec4 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8.rs @@ -1,12 +1,12 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_string_utf8::GetStringUTF8Error, -) -> ::std::rc::Rc { +) -> ::std::rc::Rc +{ match value { crate::operation::get_string_utf8::GetStringUTF8Error::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_input.rs index c70b83f7bf..c6b8fc2ae2 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_input.rs @@ -1,30 +1,43 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use core::str; + +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_string_utf8::GetStringUTF8Input, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, ->{ +> { + let dafny_value = match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { + value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input::GetStringUTF8Input { - value: ::std::rc::Rc::new(match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) }, - None => crate::_Wrappers_Compile::Option::None {}, -}), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, >, ) -> crate::operation::get_string_utf8::GetStringUTF8Input { - crate::operation::get_string_utf8::GetStringUTF8Input::builder() - .set_value(match dafny_value.value().as_ref() { - crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&dafny_value.value().Extract(), |b| *b)).unwrap()), - _ => ::std::option::Option::None, -}) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + let bytes = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( + &dafny_value.value().Extract(), |b| *b); + Some(String::from_utf8(bytes).unwrap()) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_string_utf8::GetStringUTF8Input { value } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_output.rs index be225b6181..1ceb81a53a 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_output.rs @@ -1,30 +1,39 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_string_utf8::GetStringUTF8Output, ) -> ::std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, ->{ - ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output::GetStringUTF8Output { - value: ::std::rc::Rc::new(match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) }, - None => crate::_Wrappers_Compile::Option::None {}, -}), - }) + crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, +> { + let dafny_value = match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { + value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, - >, + dafny_value: ::std::rc::Rc, ) -> crate::operation::get_string_utf8::GetStringUTF8Output { - crate::operation::get_string_utf8::GetStringUTF8Output::builder() - .set_value(match dafny_value.value().as_ref() { - crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&dafny_value.value().Extract(), |b| *b)).unwrap()), - _ => ::std::option::Option::None, -}) - .build() - .unwrap() + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + let bytes = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( + &dafny_value.value().Extract(), |b| *b); + Some(String::from_utf8(bytes).unwrap()) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_string_utf8::GetStringUTF8Output { value } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value.rs index 25e02541ce..f942e0b21e 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value.rs @@ -1,12 +1,12 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError, -) -> ::std::rc::Rc { +) -> ::std::rc::Rc +{ match value { crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs index 233ffd0804..97719cd80e 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs @@ -1,30 +1,43 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use core::str; + +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_string_utf8_known_value::GetStringUTF8Input, + value: crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, ->{ +> { + let dafny_value = match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { + value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input::GetStringUTF8Input { - value: ::std::rc::Rc::new(match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) }, - None => crate::_Wrappers_Compile::Option::None {}, -}), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, >, -) -> crate::operation::get_string_utf8_known_value::GetStringUTF8Input { - crate::operation::get_string_utf8_known_value::GetStringUTF8Input::builder() - .set_value(match dafny_value.value().as_ref() { - crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&dafny_value.value().Extract(), |b| *b)).unwrap()), - _ => ::std::option::Option::None, -}) - .build() - .unwrap() +) -> crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + let bytes = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( + &dafny_value.value().Extract(), |b| *b); + Some(String::from_utf8(bytes).unwrap()) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput { value } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs index 2aa9d94c0f..2f0ea07136 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs @@ -1,30 +1,39 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_string_utf8_known_value::GetStringUTF8Output, + value: crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, ) -> ::std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, ->{ - ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output::GetStringUTF8Output { - value: ::std::rc::Rc::new(match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) }, - None => crate::_Wrappers_Compile::Option::None {}, -}), - }) + crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, +> { + let dafny_value = match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { + value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, - >, -) -> crate::operation::get_string_utf8_known_value::GetStringUTF8Output { - crate::operation::get_string_utf8_known_value::GetStringUTF8Output::builder() - .set_value(match dafny_value.value().as_ref() { - crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&dafny_value.value().Extract(), |b| *b)).unwrap()), - _ => ::std::option::Option::None, -}) - .build() - .unwrap() + dafny_value: ::std::rc::Rc, +) -> crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput { + let value = if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + let bytes = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( + &dafny_value.value().Extract(), |b| *b); + Some(String::from_utf8(bytes).unwrap()) + } else if matches!( + dafny_value.value().as_ref(), + crate::_Wrappers_Compile::Option::None { .. } + ) { + None + } else { + panic!("Unreachable") + }; + crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput { value } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config.rs index d8734a9d1d..286313ae8b 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config.rs @@ -1,4 +1,3 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + pub mod _simple_string_config; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config/_simple_string_config.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config/_simple_string_config.rs index 71f90a271c..95d7da8d43 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config/_simple_string_config.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config/_simple_string_config.rs @@ -1,12 +1,10 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_string_config::SimpleStringConfig, ) -> ::std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::SimpleStringConfig, + crate::simple::types::smithystring::internaldafny::types::SimpleStringConfig, > { ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::SimpleStringConfig::SimpleStringConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error.rs index 4cddaa7c39..ec89cbecc9 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error/sealed_unhandled.rs index eae8007292..cce22d1cfd 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,10 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use std::any::Any; - -use dafny_runtime::UpcastObject; - +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -27,6 +21,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl UpcastObject for Unhandled { +impl ::dafny_runtime::UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/implementation_from_dafny.rs-e b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/implementation_from_dafny.rs-e new file mode 100644 index 0000000000..0c57116297 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/implementation_from_dafny.rs-e @@ -0,0 +1,1880 @@ +#![allow(warnings, unconditional_panic)] +#![allow(nonstandard_style)] + +pub mod _module { + +} +pub mod simple { + pub mod types { + pub mod smithystring { + pub mod internaldafny { + pub use ::dafny_runtime::UpcastObject; + pub use ::std::any::Any; + pub use crate::simple::types::smithystring::internaldafny::types::ISimpleTypesStringClient; + + pub struct _default {} + + impl _default { + pub fn DefaultSimpleStringConfig() -> ::std::rc::Rc { + ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::SimpleStringConfig::SimpleStringConfig {}) + } + pub fn SimpleString(config: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut res = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + let mut client = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object>::new(); + let mut _nw0: ::dafny_runtime::Object = crate::simple::types::smithystring::internaldafny::SimpleStringClient::_allocate_object(); + crate::simple::types::smithystring::internaldafny::SimpleStringClient::_ctor(&_nw0, &::std::rc::Rc::new(crate::r#_SimpleStringImpl_Compile::Config::Config {})); + client = ::dafny_runtime::MaybePlacebo::from(_nw0.clone()); + res = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Success { + value: client.read() + })); + return res.read(); + } + pub fn CreateSuccessOfClient(client: &::dafny_runtime::Object) -> ::std::rc::Rc, ::std::rc::Rc>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Success { + value: client.clone() + }) + } + pub fn CreateFailureOfError(error: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Failure { + error: error.clone() + }) + } + } + + pub struct SimpleStringClient { + pub r#__i_config: ::std::rc::Rc + } + + impl SimpleStringClient { + pub fn _allocate_object() -> ::dafny_runtime::Object { + ::dafny_runtime::allocate_object::() + } + pub fn _ctor(this: &::dafny_runtime::Object, config: &::std::rc::Rc) -> () { + let mut _set__i_config: bool = false; + ::dafny_runtime::update_field_uninit_object!(this.clone(), r#__i_config, _set__i_config, config.clone()); + return (); + } + pub fn config(&self) -> ::std::rc::Rc { + self.r#__i_config.clone() + } + } + + impl UpcastObject + for crate::simple::types::smithystring::internaldafny::SimpleStringClient { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); + } + + impl ISimpleTypesStringClient + for crate::simple::types::smithystring::internaldafny::SimpleStringClient { + fn GetString(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + let mut _out0 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + _out0 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleStringImpl_Compile::_default::GetString(&self.config().clone(), input)); + output = ::dafny_runtime::MaybePlacebo::from(_out0.read()); + return output.read(); + } + fn GetStringKnownValue(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + let mut _out1 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + _out1 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleStringImpl_Compile::_default::GetStringKnownValue(&self.config().clone(), input)); + output = ::dafny_runtime::MaybePlacebo::from(_out1.read()); + return output.read(); + } + fn GetStringUTF8(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + let mut _out2 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + _out2 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleStringImpl_Compile::_default::GetStringUTF8(&self.config().clone(), input)); + output = ::dafny_runtime::MaybePlacebo::from(_out2.read()); + return output.read(); + } + fn GetStringUTF8KnownValue(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + let mut _out3 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + _out3 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleStringImpl_Compile::_default::GetStringUTF8KnownValue(&self.config().clone(), input)); + output = ::dafny_runtime::MaybePlacebo::from(_out3.read()); + return output.read(); + } + } + + impl UpcastObject + for crate::simple::types::smithystring::internaldafny::SimpleStringClient { + ::dafny_runtime::UpcastObjectFn!(dyn crate::simple::types::smithystring::internaldafny::types::ISimpleTypesStringClient); + } + + pub mod types { + pub use ::std::fmt::Debug; + pub use ::dafny_runtime::DafnyPrint; + pub use ::std::cmp::Eq; + pub use ::std::hash::Hash; + pub use ::std::default::Default; + pub use ::std::convert::AsRef; + pub use ::dafny_runtime::UpcastObject; + pub use ::std::any::Any; + + #[derive(PartialEq, Clone)] + pub enum DafnyCallEvent { + DafnyCallEvent { + input: I, + output: O + } + } + + impl DafnyCallEvent { + pub fn input(&self) -> &I { + match self { + DafnyCallEvent::DafnyCallEvent{input, output, } => input, + } + } + pub fn output(&self) -> &O { + match self { + DafnyCallEvent::DafnyCallEvent{input, output, } => output, + } + } + } + + impl Debug + for DafnyCallEvent { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for DafnyCallEvent { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + DafnyCallEvent::DafnyCallEvent{input, output, } => { + write!(_formatter, "simple.types.smithystring.internaldafny.types.DafnyCallEvent.DafnyCallEvent(")?; + ::dafny_runtime::DafnyPrint::fmt_print(input, _formatter, false)?; + write!(_formatter, ", ")?; + ::dafny_runtime::DafnyPrint::fmt_print(output, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Eq + for DafnyCallEvent {} + + impl Hash + for DafnyCallEvent { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + DafnyCallEvent::DafnyCallEvent{input, output, } => { + ::std::hash::Hash::hash(input, _state); + ::std::hash::Hash::hash(output, _state) + }, + } + } + } + + impl Default + for DafnyCallEvent { + fn default() -> DafnyCallEvent { + DafnyCallEvent::DafnyCallEvent { + input: ::std::default::Default::default(), + output: ::std::default::Default::default() + } + } + } + + impl AsRef> + for &DafnyCallEvent { + fn as_ref(&self) -> Self { + self + } + } + + #[derive(PartialEq, Clone)] + pub enum GetStringInput { + GetStringInput { + value: ::std::rc::Rc>> + } + } + + impl GetStringInput { + pub fn value(&self) -> &::std::rc::Rc>> { + match self { + GetStringInput::GetStringInput{value, } => value, + } + } + } + + impl Debug + for GetStringInput { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for GetStringInput { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + GetStringInput::GetStringInput{value, } => { + write!(_formatter, "simple.types.smithystring.internaldafny.types.GetStringInput.GetStringInput(")?; + ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Eq + for GetStringInput {} + + impl Hash + for GetStringInput { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + GetStringInput::GetStringInput{value, } => { + ::std::hash::Hash::hash(value, _state) + }, + } + } + } + + impl Default + for GetStringInput { + fn default() -> GetStringInput { + GetStringInput::GetStringInput { + value: ::std::default::Default::default() + } + } + } + + impl AsRef + for &GetStringInput { + fn as_ref(&self) -> Self { + self + } + } + + #[derive(PartialEq, Clone)] + pub enum GetStringOutput { + GetStringOutput { + value: ::std::rc::Rc>> + } + } + + impl GetStringOutput { + pub fn value(&self) -> &::std::rc::Rc>> { + match self { + GetStringOutput::GetStringOutput{value, } => value, + } + } + } + + impl Debug + for GetStringOutput { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for GetStringOutput { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + GetStringOutput::GetStringOutput{value, } => { + write!(_formatter, "simple.types.smithystring.internaldafny.types.GetStringOutput.GetStringOutput(")?; + ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Eq + for GetStringOutput {} + + impl Hash + for GetStringOutput { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + GetStringOutput::GetStringOutput{value, } => { + ::std::hash::Hash::hash(value, _state) + }, + } + } + } + + impl Default + for GetStringOutput { + fn default() -> GetStringOutput { + GetStringOutput::GetStringOutput { + value: ::std::default::Default::default() + } + } + } + + impl AsRef + for &GetStringOutput { + fn as_ref(&self) -> Self { + self + } + } + + #[derive(PartialEq, Clone)] + pub enum GetStringUTF8Input { + GetStringUTF8Input { + value: ::std::rc::Rc> + } + } + + impl GetStringUTF8Input { + pub fn value(&self) -> &::std::rc::Rc> { + match self { + GetStringUTF8Input::GetStringUTF8Input{value, } => value, + } + } + } + + impl Debug + for GetStringUTF8Input { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for GetStringUTF8Input { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + GetStringUTF8Input::GetStringUTF8Input{value, } => { + write!(_formatter, "simple.types.smithystring.internaldafny.types.GetStringUTF8Input.GetStringUTF8Input(")?; + ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Eq + for GetStringUTF8Input {} + + impl Hash + for GetStringUTF8Input { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + GetStringUTF8Input::GetStringUTF8Input{value, } => { + ::std::hash::Hash::hash(value, _state) + }, + } + } + } + + impl Default + for GetStringUTF8Input { + fn default() -> GetStringUTF8Input { + GetStringUTF8Input::GetStringUTF8Input { + value: ::std::default::Default::default() + } + } + } + + impl AsRef + for &GetStringUTF8Input { + fn as_ref(&self) -> Self { + self + } + } + + #[derive(PartialEq, Clone)] + pub enum GetStringUTF8Output { + GetStringUTF8Output { + value: ::std::rc::Rc> + } + } + + impl GetStringUTF8Output { + pub fn value(&self) -> &::std::rc::Rc> { + match self { + GetStringUTF8Output::GetStringUTF8Output{value, } => value, + } + } + } + + impl Debug + for GetStringUTF8Output { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for GetStringUTF8Output { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + GetStringUTF8Output::GetStringUTF8Output{value, } => { + write!(_formatter, "simple.types.smithystring.internaldafny.types.GetStringUTF8Output.GetStringUTF8Output(")?; + ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Eq + for GetStringUTF8Output {} + + impl Hash + for GetStringUTF8Output { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + GetStringUTF8Output::GetStringUTF8Output{value, } => { + ::std::hash::Hash::hash(value, _state) + }, + } + } + } + + impl Default + for GetStringUTF8Output { + fn default() -> GetStringUTF8Output { + GetStringUTF8Output::GetStringUTF8Output { + value: ::std::default::Default::default() + } + } + } + + impl AsRef + for &GetStringUTF8Output { + fn as_ref(&self) -> Self { + self + } + } + + #[derive(PartialEq, Clone)] + pub enum SimpleStringConfig { + SimpleStringConfig {} + } + + impl SimpleStringConfig {} + + impl Debug + for SimpleStringConfig { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for SimpleStringConfig { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + SimpleStringConfig::SimpleStringConfig{} => { + write!(_formatter, "simple.types.smithystring.internaldafny.types.SimpleStringConfig.SimpleStringConfig")?; + Ok(()) + }, + } + } + } + + impl SimpleStringConfig { + pub fn _AllSingletonConstructors() -> ::dafny_runtime::SequenceIter<::std::rc::Rc> { + ::dafny_runtime::seq![::std::rc::Rc::new(SimpleStringConfig::SimpleStringConfig {})].iter() + } + } + + impl Eq + for SimpleStringConfig {} + + impl Hash + for SimpleStringConfig { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + SimpleStringConfig::SimpleStringConfig{} => { + + }, + } + } + } + + impl Default + for SimpleStringConfig { + fn default() -> SimpleStringConfig { + SimpleStringConfig::SimpleStringConfig {} + } + } + + impl AsRef + for &SimpleStringConfig { + fn as_ref(&self) -> Self { + self + } + } + + pub struct ISimpleTypesStringClientCallHistory {} + + impl ISimpleTypesStringClientCallHistory { + pub fn _allocate_object() -> ::dafny_runtime::Object { + ::dafny_runtime::allocate_object::() + } + } + + impl UpcastObject + for crate::simple::types::smithystring::internaldafny::types::ISimpleTypesStringClientCallHistory { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); + } + + pub trait ISimpleTypesStringClient: ::std::any::Any + ::dafny_runtime::UpcastObject { + fn GetString(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; + fn GetStringKnownValue(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; + fn GetStringUTF8(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; + fn GetStringUTF8KnownValue(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; + } + + #[derive(PartialEq, Clone)] + pub enum Error { + CollectionOfErrors { + list: ::dafny_runtime::Sequence<::std::rc::Rc>, + message: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> + }, + Opaque { + obj: ::dafny_runtime::Object + } + } + + impl Error { + pub fn list(&self) -> &::dafny_runtime::Sequence<::std::rc::Rc> { + match self { + Error::CollectionOfErrors{list, message, } => list, + Error::Opaque{obj, } => panic!("field does not exist on this variant"), + } + } + pub fn message(&self) -> &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { + match self { + Error::CollectionOfErrors{list, message, } => message, + Error::Opaque{obj, } => panic!("field does not exist on this variant"), + } + } + pub fn obj(&self) -> &::dafny_runtime::Object { + match self { + Error::CollectionOfErrors{list, message, } => panic!("field does not exist on this variant"), + Error::Opaque{obj, } => obj, + } + } + } + + impl Debug + for Error { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for Error { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + Error::CollectionOfErrors{list, message, } => { + write!(_formatter, "simple.types.smithystring.internaldafny.types.Error.CollectionOfErrors(")?; + ::dafny_runtime::DafnyPrint::fmt_print(list, _formatter, false)?; + write!(_formatter, ", ")?; + ::dafny_runtime::DafnyPrint::fmt_print(message, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + Error::Opaque{obj, } => { + write!(_formatter, "simple.types.smithystring.internaldafny.types.Error.Opaque(")?; + ::dafny_runtime::DafnyPrint::fmt_print(obj, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Eq + for Error {} + + impl Hash + for Error { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + Error::CollectionOfErrors{list, message, } => { + ::std::hash::Hash::hash(list, _state); + ::std::hash::Hash::hash(message, _state) + }, + Error::Opaque{obj, } => { + ::std::hash::Hash::hash(obj, _state) + }, + } + } + } + + impl Default + for Error { + fn default() -> Error { + Error::CollectionOfErrors { + list: ::std::default::Default::default(), + message: ::std::default::Default::default() + } + } + } + + impl AsRef + for &Error { + fn as_ref(&self) -> Self { + self + } + } + + pub type OpaqueError = ::std::rc::Rc; + } + } + } + } +} +pub mod r#_SimpleStringImpl_Compile { + pub use ::std::fmt::Debug; + pub use ::dafny_runtime::DafnyPrint; + pub use ::std::cmp::Eq; + pub use ::std::hash::Hash; + pub use ::std::default::Default; + pub use ::std::convert::AsRef; + + pub struct _default {} + + impl _default { + pub fn GetString(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { + value: input.value().clone() + }); + output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Success { + value: res.clone() + })); + return output.read(); + } + pub fn GetStringKnownValue(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { + panic!("Halt") + }; + let mut _e00: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> = input.value().value().clone(); + let mut _e10: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> = ::dafny_runtime::string_utf16_of("TEST_SIMPLE_STRING_KNOWN_VALUE"); + if !(_e00.clone() == _e10.clone()) { + print!("{}", ::dafny_runtime::DafnyPrintWrapper(&::dafny_runtime::string_utf16_of("Left:\n"))); + print!("{}", ::dafny_runtime::DafnyPrintWrapper(&_e00)); + print!("{}", ::dafny_runtime::DafnyPrintWrapper(&::dafny_runtime::string_utf16_of("Right:\n"))); + print!("{}", ::dafny_runtime::DafnyPrintWrapper(&_e10)); + panic!("Halt") + }; + let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { + value: input.value().clone() + }); + output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Success { + value: res.clone() + })); + return output.read(); + } + pub fn GetStringUTF8(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { + panic!("Halt") + }; + let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::GetStringUTF8Output::GetStringUTF8Output { + value: input.value().clone() + }); + output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Success { + value: res.clone() + })); + return output.read(); + } + pub fn GetStringUTF8KnownValue(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { + let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); + if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { + panic!("Halt") + }; + let mut expected: ::dafny_runtime::Sequence = ::dafny_runtime::seq![72, 101, 108, 108, 111]; + let mut _e01: crate::UTF8::ValidUTF8Bytes = input.value().value().clone(); + let mut _e11: ::dafny_runtime::Sequence = expected.clone(); + if !(_e01.clone() == _e11.clone()) { + print!("{}", ::dafny_runtime::DafnyPrintWrapper(&::dafny_runtime::string_utf16_of("Left:\n"))); + print!("{}", ::dafny_runtime::DafnyPrintWrapper(&_e01)); + print!("{}", ::dafny_runtime::DafnyPrintWrapper(&::dafny_runtime::string_utf16_of("Right:\n"))); + print!("{}", ::dafny_runtime::DafnyPrintWrapper(&_e11)); + panic!("Halt") + }; + let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::GetStringUTF8Output::GetStringUTF8Output { + value: input.value().clone() + }); + output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Success { + value: res.clone() + })); + return output.read(); + } + } + + #[derive(PartialEq, Clone)] + pub enum Config { + Config {} + } + + impl Config {} + + impl Debug + for Config { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for Config { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + Config::Config{} => { + write!(_formatter, "SimpleStringImpl_Compile.Config.Config")?; + Ok(()) + }, + } + } + } + + impl Config { + pub fn _AllSingletonConstructors() -> ::dafny_runtime::SequenceIter<::std::rc::Rc> { + ::dafny_runtime::seq![::std::rc::Rc::new(Config::Config {})].iter() + } + } + + impl Eq + for Config {} + + impl Hash + for Config { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + Config::Config{} => { + + }, + } + } + } + + impl Default + for Config { + fn default() -> Config { + Config::Config {} + } + } + + impl AsRef + for &Config { + fn as_ref(&self) -> Self { + self + } + } +} +pub mod r#_StandardLibrary_Compile { + pub struct _default {} + + impl _default { + pub fn Join<_T: ::dafny_runtime::DafnyType>(ss: &::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>, joiner: &::dafny_runtime::Sequence<_T>) -> ::dafny_runtime::Sequence<_T> { + let mut _accumulator: ::dafny_runtime::Sequence<_T> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>; + let mut _r0 = ss.clone(); + let mut _r1 = joiner.clone(); + 'TAIL_CALL_START: loop { + let ss = _r0; + let joiner = _r1; + if ss.cardinality() == ::dafny_runtime::int!(1) { + return _accumulator.concat(&ss.get(&::dafny_runtime::int!(0))); + } else { + _accumulator = _accumulator.concat(&ss.get(&::dafny_runtime::int!(0)).concat(&joiner)); + let mut _in0: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ss.drop(&::dafny_runtime::int!(1)); + let mut _in1: ::dafny_runtime::Sequence<_T> = joiner.clone(); + _r0 = _in0.clone(); + _r1 = _in1.clone(); + continue 'TAIL_CALL_START; + } + } + } + pub fn Split<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> { + let mut _accumulator: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>; + let mut _r0 = s.clone(); + let mut _r1 = delim.clone(); + 'TAIL_CALL_START: loop { + let s = _r0; + let delim = _r1; + let mut i: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(&s, &delim, &::dafny_runtime::int!(0)); + if matches!((&i).as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { + _accumulator = _accumulator.concat(&::dafny_runtime::seq![s.take(i.value())]); + let mut _in2: ::dafny_runtime::Sequence<_T> = s.drop(&(i.value().clone() + ::dafny_runtime::int!(1))); + let mut _in3: _T = delim.clone(); + _r0 = _in2.clone(); + _r1 = _in3.clone(); + continue 'TAIL_CALL_START; + } else { + return _accumulator.concat(&::dafny_runtime::seq![s.clone()]); + } + } + } + pub fn SplitOnce<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> (::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>) { + let mut i: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(s, delim, &::dafny_runtime::int!(0)); + ( + s.take(i.value()), + s.drop(&(i.value().clone() + ::dafny_runtime::int!(1))) + ) + } + pub fn r#_SplitOnce_q<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> ::std::rc::Rc, ::dafny_runtime::Sequence<_T>)>> { + let mut valueOrError0: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(s, delim, &::dafny_runtime::int!(0)); + if valueOrError0.IsFailure() { + valueOrError0.PropagateFailure::<(::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>)>() + } else { + let mut i: ::dafny_runtime::_System::nat = valueOrError0.Extract(); + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<(::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>)>::Some { + value: ( + s.take(&i), + s.drop(&(i.clone() + ::dafny_runtime::int!(1))) + ) + }) + } + } + pub fn FindIndexMatching<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, c: &_T, i: &::dafny_runtime::_System::nat) -> ::std::rc::Rc> { + crate::r#_StandardLibrary_Compile::_default::FindIndex::<_T>(s, { + let c: _T = c.clone(); + &({ + let mut c = c.clone(); + ::std::rc::Rc::new(move |x: &_T| -> bool{ + x.clone() == c.clone() + }) + }) + }, i) + } + pub fn FindIndex<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>, f: &::std::rc::Rc bool>, i: &::dafny_runtime::_System::nat) -> ::std::rc::Rc> { + let mut _r0 = s.clone(); + let mut _r1 = f.clone(); + let mut _r2 = i.clone(); + 'TAIL_CALL_START: loop { + let s = _r0; + let f = _r1; + let i = _r2; + if i.clone() == s.cardinality() { + return ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::_System::nat>::None {}); + } else { + if (&f)(&s.get(&i)) { + return ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::_System::nat>::Some { + value: i.clone() + }); + } else { + let mut _in4: ::dafny_runtime::Sequence<_T> = s.clone(); + let mut _in5: ::std::rc::Rc bool> = f.clone(); + let mut _in6: ::dafny_runtime::DafnyInt = i.clone() + ::dafny_runtime::int!(1); + _r0 = _in4.clone(); + _r1 = _in5.clone(); + _r2 = _in6.clone(); + continue 'TAIL_CALL_START; + } + } + } + } + pub fn Filter<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>, f: &::std::rc::Rc bool>) -> ::dafny_runtime::Sequence<_T> { + let mut _accumulator: ::dafny_runtime::Sequence<_T> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>; + let mut _r0 = s.clone(); + let mut _r1 = f.clone(); + 'TAIL_CALL_START: loop { + let s = _r0; + let f = _r1; + if s.cardinality() == ::dafny_runtime::int!(0) { + return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>)); + } else { + if (&f)(&s.get(&::dafny_runtime::int!(0))) { + _accumulator = _accumulator.concat(&::dafny_runtime::seq![s.get(&::dafny_runtime::int!(0))]); + let mut _in7: ::dafny_runtime::Sequence<_T> = s.drop(&::dafny_runtime::int!(1)); + let mut _in8: ::std::rc::Rc bool> = f.clone(); + _r0 = _in7.clone(); + _r1 = _in8.clone(); + continue 'TAIL_CALL_START; + } else { + let mut _in9: ::dafny_runtime::Sequence<_T> = s.drop(&::dafny_runtime::int!(1)); + let mut _in10: ::std::rc::Rc bool> = f.clone(); + _r0 = _in9.clone(); + _r1 = _in10.clone(); + continue 'TAIL_CALL_START; + } + } + } + } + pub fn Min(a: &::dafny_runtime::DafnyInt, b: &::dafny_runtime::DafnyInt) -> ::dafny_runtime::DafnyInt { + if a.clone() < b.clone() { + a.clone() + } else { + b.clone() + } + } + pub fn Fill<_T: ::dafny_runtime::DafnyType>(value: &_T, n: &::dafny_runtime::_System::nat) -> ::dafny_runtime::Sequence<_T> { + { + let _initializer = { + let value: _T = value.clone(); + { + let mut value = value.clone(); + ::std::rc::Rc::new(move |_v0: &::dafny_runtime::DafnyInt| -> _T{ + value.clone() + }) + } + }; + ::dafny_runtime::integer_range(::dafny_runtime::Zero::zero(), n.clone()).map(|i| _initializer(&i)).collect::<::dafny_runtime::Sequence<_>>() + } + } + pub fn SeqToArray<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> ::dafny_runtime::Object<[_T]> { + let mut a = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object<[_T]>>::new(); + let mut _init0: ::std::rc::Rc _T> = { + let s: ::dafny_runtime::Sequence<_T> = s.clone(); + { + let mut s = s.clone(); + ::std::rc::Rc::new(move |i: &::dafny_runtime::DafnyInt| -> _T{ + s.get(i) + }) + } + }; + let mut _nw1: ::dafny_runtime::Object<[::std::mem::MaybeUninit<_T>]> = ::dafny_runtime::array::placebos_usize_object::<_T>(::dafny_runtime::DafnyUsize::into_usize(s.cardinality())); + for r#__i0_0 in ::dafny_runtime::integer_range(0, ::dafny_runtime::rd!(_nw1.clone()).len()) { + { + let __idx0 = ::dafny_runtime::DafnyUsize::into_usize(r#__i0_0.clone()); + ::dafny_runtime::md!(_nw1)[__idx0] = ::std::mem::MaybeUninit::new((&_init0)(&::dafny_runtime::int!(r#__i0_0.clone()))); + } + } + a = ::dafny_runtime::MaybePlacebo::from(::dafny_runtime::array::construct_object(_nw1.clone())); + return a.read(); + } + pub fn LexicographicLessOrEqual<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, b: &::dafny_runtime::Sequence<_T>, less: &::std::rc::Rc bool>) -> bool { + ::dafny_runtime::integer_range(::dafny_runtime::int!(0), a.cardinality() + ::dafny_runtime::int!(1)).any(({ + let mut a = a.clone(); + let mut b = b.clone(); + let mut less = less.clone(); + ::std::rc::Rc::new(move |r#__exists_var_0: ::dafny_runtime::DafnyInt| -> bool{ + let mut k: ::dafny_runtime::DafnyInt = r#__exists_var_0.clone(); + ::dafny_runtime::int!(0) <= k.clone() && k.clone() <= a.cardinality() && crate::r#_StandardLibrary_Compile::_default::LexicographicLessOrEqualAux::<_T>(&a, &b, &less, &k) + }) + }).as_ref()) + } + pub fn LexicographicLessOrEqualAux<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, b: &::dafny_runtime::Sequence<_T>, less: &::std::rc::Rc bool>, lengthOfCommonPrefix: &::dafny_runtime::_System::nat) -> bool { + lengthOfCommonPrefix.clone() <= b.cardinality() && ::dafny_runtime::integer_range(::dafny_runtime::int!(0), lengthOfCommonPrefix.clone()).all(({ + let mut lengthOfCommonPrefix = lengthOfCommonPrefix.clone(); + let mut a = a.clone(); + let mut b = b.clone(); + ::std::rc::Rc::new(move |r#__forall_var_0: ::dafny_runtime::DafnyInt| -> bool{ + let mut i: ::dafny_runtime::DafnyInt = r#__forall_var_0.clone(); + !(::dafny_runtime::int!(0) <= i.clone() && i.clone() < lengthOfCommonPrefix.clone()) || a.get(&i) == b.get(&i) + }) + }).as_ref()) && (lengthOfCommonPrefix.clone() == a.cardinality() || lengthOfCommonPrefix.clone() < b.cardinality() && less(&a.get(lengthOfCommonPrefix), &b.get(lengthOfCommonPrefix))) + } + pub fn SetToOrderedSequence<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Set<::dafny_runtime::Sequence<_T>>, less: &::std::rc::Rc bool>) -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> { + let mut _accumulator: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>; + let mut _r0 = s.clone(); + let mut _r1 = less.clone(); + 'TAIL_CALL_START: loop { + let s = _r0; + let less = _r1; + if s.clone() == ::dafny_runtime::set!{} { + return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>)); + } else { + return (&({ + let mut s = s.clone(); + let mut less = less.clone(); + ::std::rc::Rc::new(move |r#__let_dummy_0: &::dafny_runtime::DafnyInt| -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>{ + let mut a = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Sequence<_T>>::new(); + 'label_goto__ASSIGN_SUCH_THAT_0: loop { + for r#__assign_such_that_0 in (&s).iter().cloned() { + a = ::dafny_runtime::MaybePlacebo::from(r#__assign_such_that_0.clone()); + if s.contains(&a.read()) && crate::r#_StandardLibrary_Compile::_default::IsMinimum::<_T>(&a.read(), &s, &less) { + break 'label_goto__ASSIGN_SUCH_THAT_0; + } + } + panic!("Halt"); + break; + }; + ::dafny_runtime::seq![a.read()].concat(&crate::r#_StandardLibrary_Compile::_default::SetToOrderedSequence::<_T>(&s.subtract(&::dafny_runtime::set!{a.read()}), &less)) + }) + }))(&::dafny_runtime::int!(0)); + } + } + } + pub fn IsMinimum<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, s: &::dafny_runtime::Set<::dafny_runtime::Sequence<_T>>, less: &::std::rc::Rc bool>) -> bool { + s.contains(a) && s.iter().all(({ + let mut a = a.clone(); + let mut s = s.clone(); + let mut less = less.clone(); + ::std::rc::Rc::new(move |r#__forall_var_1: &::dafny_runtime::Sequence<_T>| -> bool{ + let mut z: ::dafny_runtime::Sequence<_T> = r#__forall_var_1.clone(); + !s.contains(&z) || crate::r#_StandardLibrary_Compile::_default::LexicographicLessOrEqual::<_T>(&a, &z, &less) + }) + }).as_ref()) + } + } + + pub mod r#_UInt_Compile { + pub use ::std::default::Default; + pub use ::dafny_runtime::DafnyPrint; + + pub struct _default {} + + impl _default { + pub fn UInt8Less(a: u8, b: u8) -> bool { + a < b + } + pub fn HasUint16Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { + s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT16_LIMIT() + } + pub fn HasUint32Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { + s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT32_LIMIT() + } + pub fn HasUint64Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { + s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT64_LIMIT() + } + pub fn UInt16ToSeq(x: u16) -> ::dafny_runtime::Sequence { + let mut b0: u8 = (x / 256) as u8; + let mut b1: u8 = (x % 256) as u8; + ::dafny_runtime::seq![b0, b1] + } + pub fn SeqToUInt16(s: &::dafny_runtime::Sequence) -> u16 { + let mut x0: u16 = s.get(&::dafny_runtime::int!(0)) as u16 * 256; + x0 + s.get(&::dafny_runtime::int!(1)) as u16 + } + pub fn UInt32ToSeq(x: u32) -> ::dafny_runtime::Sequence { + let mut b0: u8 = (x / 16777216) as u8; + let mut x0: u32 = x - b0 as u32 * 16777216; + let mut b1: u8 = (x0 / 65536) as u8; + let mut x1: u32 = x0 - b1 as u32 * 65536; + let mut b2: u8 = (x1 / 256) as u8; + let mut b3: u8 = (x1 % 256) as u8; + ::dafny_runtime::seq![b0, b1, b2, b3] + } + pub fn SeqToUInt32(s: &::dafny_runtime::Sequence) -> u32 { + let mut x0: u32 = s.get(&::dafny_runtime::int!(0)) as u32 * 16777216; + let mut x1: u32 = x0 + s.get(&::dafny_runtime::int!(1)) as u32 * 65536; + let mut x2: u32 = x1 + s.get(&::dafny_runtime::int!(2)) as u32 * 256; + x2 + s.get(&::dafny_runtime::int!(3)) as u32 + } + pub fn UInt64ToSeq(x: u64) -> ::dafny_runtime::Sequence { + let mut b0: u8 = (x / 72057594037927936) as u8; + let mut x0: u64 = x - b0 as u64 * 72057594037927936; + let mut b1: u8 = (x0 / 281474976710656) as u8; + let mut x1: u64 = x0 - b1 as u64 * 281474976710656; + let mut b2: u8 = (x1 / 1099511627776) as u8; + let mut x2: u64 = x1 - b2 as u64 * 1099511627776; + let mut b3: u8 = (x2 / 4294967296) as u8; + let mut x3: u64 = x2 - b3 as u64 * 4294967296; + let mut b4: u8 = (x3 / 16777216) as u8; + let mut x4: u64 = x3 - b4 as u64 * 16777216; + let mut b5: u8 = (x4 / 65536) as u8; + let mut x5: u64 = x4 - b5 as u64 * 65536; + let mut b6: u8 = (x5 / 256) as u8; + let mut b7: u8 = (x5 % 256) as u8; + ::dafny_runtime::seq![b0, b1, b2, b3, b4, b5, b6, b7] + } + pub fn SeqToUInt64(s: &::dafny_runtime::Sequence) -> u64 { + let mut x0: u64 = s.get(&::dafny_runtime::int!(0)) as u64 * 72057594037927936; + let mut x1: u64 = x0 + s.get(&::dafny_runtime::int!(1)) as u64 * 281474976710656; + let mut x2: u64 = x1 + s.get(&::dafny_runtime::int!(2)) as u64 * 1099511627776; + let mut x3: u64 = x2 + s.get(&::dafny_runtime::int!(3)) as u64 * 4294967296; + let mut x4: u64 = x3 + s.get(&::dafny_runtime::int!(4)) as u64 * 16777216; + let mut x5: u64 = x4 + s.get(&::dafny_runtime::int!(5)) as u64 * 65536; + let mut x6: u64 = x5 + s.get(&::dafny_runtime::int!(6)) as u64 * 256; + let mut x: u64 = x6 + s.get(&::dafny_runtime::int!(7)) as u64; + x + } + pub fn UINT16_LIMIT() -> ::dafny_runtime::DafnyInt { + ::dafny_runtime::int!(b"65536") + } + pub fn UINT32_LIMIT() -> ::dafny_runtime::DafnyInt { + ::dafny_runtime::int!(b"4294967296") + } + pub fn UINT64_LIMIT() -> ::dafny_runtime::DafnyInt { + ::dafny_runtime::int!(b"18446744073709551616") + } + pub fn INT32_MAX_LIMIT() -> ::dafny_runtime::DafnyInt { + ::dafny_runtime::int!(b"2147483648") + } + pub fn INT64_MAX_LIMIT() -> ::dafny_runtime::DafnyInt { + ::dafny_runtime::int!(b"9223372036854775808") + } + } + + #[derive(Clone, PartialEq)] + #[repr(transparent)] + pub struct uint8(pub u8); + + impl uint8 { + pub fn is(_source: u8) -> bool { + return true; + } + } + + impl Default + for uint8 { + fn default() -> Self { + uint8(::std::default::Default::default()) + } + } + + impl DafnyPrint + for uint8 { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) + } + } + + impl ::std::ops::Deref + for uint8 { + type Target = u8; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + #[derive(Clone, PartialEq)] + #[repr(transparent)] + pub struct uint16(pub u16); + + impl uint16 { + pub fn is(_source: u16) -> bool { + return true; + } + } + + impl Default + for uint16 { + fn default() -> Self { + uint16(::std::default::Default::default()) + } + } + + impl DafnyPrint + for uint16 { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) + } + } + + impl ::std::ops::Deref + for uint16 { + type Target = u16; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + #[derive(Clone, PartialEq)] + #[repr(transparent)] + pub struct uint32(pub u32); + + impl uint32 { + pub fn is(_source: u32) -> bool { + return true; + } + } + + impl Default + for uint32 { + fn default() -> Self { + uint32(::std::default::Default::default()) + } + } + + impl DafnyPrint + for uint32 { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) + } + } + + impl ::std::ops::Deref + for uint32 { + type Target = u32; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + #[derive(Clone, PartialEq)] + #[repr(transparent)] + pub struct uint64(pub u64); + + impl uint64 { + pub fn is(_source: u64) -> bool { + return true; + } + } + + impl Default + for uint64 { + fn default() -> Self { + uint64(::std::default::Default::default()) + } + } + + impl DafnyPrint + for uint64 { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) + } + } + + impl ::std::ops::Deref + for uint64 { + type Target = u64; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + #[derive(Clone, PartialEq)] + #[repr(transparent)] + pub struct int32(pub i32); + + impl int32 { + pub fn is(_source: i32) -> bool { + return true; + } + } + + impl Default + for int32 { + fn default() -> Self { + int32(::std::default::Default::default()) + } + } + + impl DafnyPrint + for int32 { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) + } + } + + impl ::std::ops::Deref + for int32 { + type Target = i32; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + #[derive(Clone, PartialEq)] + #[repr(transparent)] + pub struct int64(pub i64); + + impl int64 { + pub fn is(_source: i64) -> bool { + return true; + } + } + + impl Default + for int64 { + fn default() -> Self { + int64(::std::default::Default::default()) + } + } + + impl DafnyPrint + for int64 { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) + } + } + + impl ::std::ops::Deref + for int64 { + type Target = i64; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + #[derive(Clone, PartialEq)] + #[repr(transparent)] + pub struct posInt64(pub u64); + + impl posInt64 { + pub fn is(_source: u64) -> bool { + let mut x: ::dafny_runtime::DafnyInt = ::std::convert::Into::<::dafny_runtime::DafnyInt>::into(_source.clone()); + return ::dafny_runtime::int!(0) < x.clone() && x.clone() < ::dafny_runtime::int!(b"9223372036854775808"); + } + } + + impl Default + for posInt64 { + fn default() -> Self { + posInt64(1) + } + } + + impl DafnyPrint + for posInt64 { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) + } + } + + impl ::std::ops::Deref + for posInt64 { + type Target = u64; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + pub type seq16 = ::dafny_runtime::Sequence; + + pub type seq32 = ::dafny_runtime::Sequence; + + pub type seq64 = ::dafny_runtime::Sequence; + } +} +pub mod r#_StandardLibraryInterop_Compile { + pub use ::dafny_runtime::UpcastObject; + pub use ::std::any::Any; + + pub struct WrappersInterop {} + + impl WrappersInterop { + pub fn _allocate_object() -> ::dafny_runtime::Object { + ::dafny_runtime::allocate_object::() + } + pub fn CreateStringSome(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Some { + value: s.clone() + }) + } + pub fn CreateStringNone() -> ::std::rc::Rc>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::None {}) + } + pub fn CreateBooleanSome(b: bool) -> ::std::rc::Rc> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::Some { + value: b + }) + } + pub fn CreateBooleanNone() -> ::std::rc::Rc> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::None {}) + } + } + + impl UpcastObject + for WrappersInterop { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); + } +} +pub mod UTF8 { + pub struct _default {} + + impl _default { + pub fn CreateEncodeSuccess(bytes: &crate::UTF8::ValidUTF8Bytes) -> ::std::rc::Rc>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Success { + value: bytes.clone() + }) + } + pub fn CreateEncodeFailure(error: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Failure { + error: error.clone() + }) + } + pub fn CreateDecodeSuccess(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: s.clone() + }) + } + pub fn CreateDecodeFailure(error: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: error.clone() + }) + } + pub fn IsASCIIString(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> bool { + let mut _hresult: bool = ::default(); + let mut _hi0: ::dafny_runtime::DafnyInt = s.cardinality(); + for i in ::dafny_runtime::integer_range(::dafny_runtime::int!(0), _hi0.clone()) { + if !(::dafny_runtime::int!(s.get(&i).0) < ::dafny_runtime::int!(128)) { + _hresult = false; + return _hresult; + } + } + _hresult = true; + return _hresult; + } + pub fn EncodeAscii(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> crate::UTF8::ValidUTF8Bytes { + let mut _accumulator: crate::UTF8::ValidUTF8Bytes = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence; + let mut _r0 = s.clone(); + 'TAIL_CALL_START: loop { + let s = _r0; + if s.cardinality() == ::dafny_runtime::int!(0) { + return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence)); + } else { + let mut x: ::dafny_runtime::Sequence = ::dafny_runtime::seq![s.get(&::dafny_runtime::int!(0)).0 as u8]; + _accumulator = _accumulator.concat(&x); + let mut _in11: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> = s.drop(&::dafny_runtime::int!(1)); + _r0 = _in11.clone(); + continue 'TAIL_CALL_START; + } + } + } + pub fn Uses1Byte(s: &::dafny_runtime::Sequence) -> bool { + 0 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 127 + } + pub fn Uses2Bytes(s: &::dafny_runtime::Sequence) -> bool { + 194 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 223 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) + } + pub fn Uses3Bytes(s: &::dafny_runtime::Sequence) -> bool { + s.get(&::dafny_runtime::int!(0)) == 224 && (160 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || 225 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 236 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || s.get(&::dafny_runtime::int!(0)) == 237 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 159) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || 238 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 239 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) + } + pub fn Uses4Bytes(s: &::dafny_runtime::Sequence) -> bool { + s.get(&::dafny_runtime::int!(0)) == 240 && (144 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) || 241 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 243 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) || s.get(&::dafny_runtime::int!(0)) == 244 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 143) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) + } + pub fn ValidUTF8Range(a: &::dafny_runtime::Sequence, lo: &::dafny_runtime::_System::nat, hi: &::dafny_runtime::_System::nat) -> bool { + let mut _r0 = a.clone(); + let mut _r1 = lo.clone(); + let mut _r2 = hi.clone(); + 'TAIL_CALL_START: loop { + let a = _r0; + let lo = _r1; + let hi = _r2; + if lo.clone() == hi.clone() { + return true; + } else { + let mut r: ::dafny_runtime::Sequence = a.slice(&lo, &hi); + if crate::UTF8::_default::Uses1Byte(&r) { + let mut _in12: ::dafny_runtime::Sequence = a.clone(); + let mut _in13: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(1); + let mut _in14: ::dafny_runtime::_System::nat = hi.clone(); + _r0 = _in12.clone(); + _r1 = _in13.clone(); + _r2 = _in14.clone(); + continue 'TAIL_CALL_START; + } else { + if ::dafny_runtime::int!(2) <= r.cardinality() && crate::UTF8::_default::Uses2Bytes(&r) { + let mut _in15: ::dafny_runtime::Sequence = a.clone(); + let mut _in16: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(2); + let mut _in17: ::dafny_runtime::_System::nat = hi.clone(); + _r0 = _in15.clone(); + _r1 = _in16.clone(); + _r2 = _in17.clone(); + continue 'TAIL_CALL_START; + } else { + if ::dafny_runtime::int!(3) <= r.cardinality() && crate::UTF8::_default::Uses3Bytes(&r) { + let mut _in18: ::dafny_runtime::Sequence = a.clone(); + let mut _in19: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(3); + let mut _in20: ::dafny_runtime::_System::nat = hi.clone(); + _r0 = _in18.clone(); + _r1 = _in19.clone(); + _r2 = _in20.clone(); + continue 'TAIL_CALL_START; + } else { + if ::dafny_runtime::int!(4) <= r.cardinality() && crate::UTF8::_default::Uses4Bytes(&r) { + let mut _in21: ::dafny_runtime::Sequence = a.clone(); + let mut _in22: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(4); + let mut _in23: ::dafny_runtime::_System::nat = hi.clone(); + _r0 = _in21.clone(); + _r1 = _in22.clone(); + _r2 = _in23.clone(); + continue 'TAIL_CALL_START; + } else { + return false; + } + } + } + } + } + } + } + pub fn ValidUTF8Seq(s: &::dafny_runtime::Sequence) -> bool { + crate::UTF8::_default::ValidUTF8Range(s, &::dafny_runtime::int!(0), &s.cardinality()) + } + } + + pub type ValidUTF8Bytes = ::dafny_runtime::Sequence; + + pub fn r#__init_ValidUTF8Bytes() -> ::dafny_runtime::Sequence { + ::dafny_runtime::seq![] as ::dafny_runtime::Sequence + } +} +pub mod r#_Wrappers_Compile { + pub use ::std::fmt::Debug; + pub use ::dafny_runtime::DafnyPrint; + pub use ::std::cmp::Eq; + pub use ::std::hash::Hash; + pub use ::std::default::Default; + pub use ::std::convert::AsRef; + + pub struct _default {} + + impl _default { + pub fn Need<_E: ::dafny_runtime::DafnyType>(condition: bool, error: &_E) -> ::std::rc::Rc> { + if condition { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Outcome::<_E>::Pass {}) + } else { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Outcome::<_E>::Fail { + error: error.clone() + }) + } + } + } + + #[derive(PartialEq, Clone)] + pub enum Option { + None {}, + Some { + value: T + } + } + + impl Option { + pub fn ToResult(self: &::std::rc::Rc) -> ::std::rc::Rc>> { + let mut _source0: ::std::rc::Rc> = self.clone(); + if matches!((&_source0).as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::string_utf16_of("Option is None") + }) + } else { + let mut r#___mcc_h0: T = _source0.value().clone(); + let mut v: T = r#___mcc_h0.clone(); + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Success { + value: v.clone() + }) + } + } + pub fn UnwrapOr(self: &::std::rc::Rc, default: &T) -> T { + let mut _source1: ::std::rc::Rc> = self.clone(); + if matches!((&_source1).as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) { + default.clone() + } else { + let mut r#___mcc_h0: T = _source1.value().clone(); + let mut v: T = r#___mcc_h0.clone(); + v.clone() + } + } + pub fn IsFailure(self: &::std::rc::Rc) -> bool { + matches!(self.as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) + } + pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<_U>::None {}) + } + pub fn Extract(self: &::std::rc::Rc) -> T { + self.value().clone() + } + pub fn value(&self) -> &T { + match self { + Option::None{} => panic!("field does not exist on this variant"), + Option::Some{value, } => value, + } + } + } + + impl Debug + for Option { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for Option { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + Option::None{} => { + write!(_formatter, "Wrappers_Compile.Option.None")?; + Ok(()) + }, + Option::Some{value, } => { + write!(_formatter, "Wrappers_Compile.Option.Some(")?; + ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Option { + pub fn coerce(f_0: ::std::rc::Rc r#__T0 + 'static>) -> ::std::rc::Rc) -> Option> { + ::std::rc::Rc::new(move |this: Self| -> Option{ + match this { + Option::None{} => { + Option::None {} + }, + Option::Some{value, } => { + Option::Some { + value: f_0.clone()(value) + } + }, + } + }) + } + } + + impl Eq + for Option {} + + impl Hash + for Option { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + Option::None{} => { + + }, + Option::Some{value, } => { + ::std::hash::Hash::hash(value, _state) + }, + } + } + } + + impl Default + for Option { + fn default() -> Option { + Option::None {} + } + } + + impl AsRef> + for &Option { + fn as_ref(&self) -> Self { + self + } + } + + #[derive(PartialEq, Clone)] + pub enum Result { + Success { + value: T + }, + Failure { + error: R + } + } + + impl Result { + pub fn ToOption(self: &::std::rc::Rc) -> ::std::rc::Rc> { + let mut _source2: ::std::rc::Rc> = self.clone(); + if matches!((&_source2).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { + let mut r#___mcc_h0: T = _source2.value().clone(); + let mut s: T = r#___mcc_h0.clone(); + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::Some { + value: s.clone() + }) + } else { + let mut r#___mcc_h1: R = _source2.error().clone(); + let mut e: R = r#___mcc_h1.clone(); + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::None {}) + } + } + pub fn UnwrapOr(self: &::std::rc::Rc, default: &T) -> T { + let mut _source3: ::std::rc::Rc> = self.clone(); + if matches!((&_source3).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { + let mut r#___mcc_h0: T = _source3.value().clone(); + let mut s: T = r#___mcc_h0.clone(); + s.clone() + } else { + let mut r#___mcc_h1: R = _source3.error().clone(); + let mut e: R = r#___mcc_h1.clone(); + default.clone() + } + } + pub fn IsFailure(self: &::std::rc::Rc) -> bool { + matches!(self.as_ref(), crate::r#_Wrappers_Compile::Result::Failure{ .. }) + } + pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<_U, R>::Failure { + error: self.error().clone() + }) + } + pub fn MapFailure<_NewR: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc, reWrap: &::std::rc::Rc _NewR>) -> ::std::rc::Rc> { + let mut _source4: ::std::rc::Rc> = self.clone(); + if matches!((&_source4).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { + let mut r#___mcc_h0: T = _source4.value().clone(); + let mut s: T = r#___mcc_h0.clone(); + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::::Success { + value: s.clone() + }) + } else { + let mut r#___mcc_h1: R = _source4.error().clone(); + let mut e: R = r#___mcc_h1.clone(); + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::::Failure { + error: reWrap(&e) + }) + } + } + pub fn Extract(self: &::std::rc::Rc) -> T { + self.value().clone() + } + pub fn value(&self) -> &T { + match self { + Result::Success{value, } => value, + Result::Failure{error, } => panic!("field does not exist on this variant"), + } + } + pub fn error(&self) -> &R { + match self { + Result::Success{value, } => panic!("field does not exist on this variant"), + Result::Failure{error, } => error, + } + } + } + + impl Debug + for Result { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for Result { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + Result::Success{value, } => { + write!(_formatter, "Wrappers_Compile.Result.Success(")?; + ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + Result::Failure{error, } => { + write!(_formatter, "Wrappers_Compile.Result.Failure(")?; + ::dafny_runtime::DafnyPrint::fmt_print(error, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Result { + pub fn coerce(f_0: ::std::rc::Rc r#__T0 + 'static>, f_1: ::std::rc::Rc r#__T1 + 'static>) -> ::std::rc::Rc) -> Result> { + ::std::rc::Rc::new(move |this: Self| -> Result{ + match this { + Result::Success{value, } => { + Result::Success { + value: f_0.clone()(value) + } + }, + Result::Failure{error, } => { + Result::Failure { + error: f_1.clone()(error) + } + }, + } + }) + } + } + + impl Eq + for Result {} + + impl Hash + for Result { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + Result::Success{value, } => { + ::std::hash::Hash::hash(value, _state) + }, + Result::Failure{error, } => { + ::std::hash::Hash::hash(error, _state) + }, + } + } + } + + impl Default + for Result { + fn default() -> Result { + Result::Success { + value: ::std::default::Default::default() + } + } + } + + impl AsRef> + for &Result { + fn as_ref(&self) -> Self { + self + } + } + + #[derive(PartialEq, Clone)] + pub enum Outcome { + Pass {}, + Fail { + error: E + } + } + + impl Outcome { + pub fn IsFailure(self: &::std::rc::Rc) -> bool { + matches!(self.as_ref(), crate::r#_Wrappers_Compile::Outcome::Fail{ .. }) + } + pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { + ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<_U, E>::Failure { + error: self.error().clone() + }) + } + pub fn error(&self) -> &E { + match self { + Outcome::Pass{} => panic!("field does not exist on this variant"), + Outcome::Fail{error, } => error, + } + } + } + + impl Debug + for Outcome { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) + } + } + + impl DafnyPrint + for Outcome { + fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { + match self { + Outcome::Pass{} => { + write!(_formatter, "Wrappers_Compile.Outcome.Pass")?; + Ok(()) + }, + Outcome::Fail{error, } => { + write!(_formatter, "Wrappers_Compile.Outcome.Fail(")?; + ::dafny_runtime::DafnyPrint::fmt_print(error, _formatter, false)?; + write!(_formatter, ")")?; + Ok(()) + }, + } + } + } + + impl Eq + for Outcome {} + + impl Hash + for Outcome { + fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { + match self { + Outcome::Pass{} => { + + }, + Outcome::Fail{error, } => { + ::std::hash::Hash::hash(error, _state) + }, + } + } + } + + impl Default + for Outcome { + fn default() -> Outcome { + Outcome::Pass {} + } + } + + impl AsRef> + for &Outcome { + fn as_ref(&self) -> Self { + self + } + } +} \ No newline at end of file diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/lib.rs new file mode 100644 index 0000000000..4315dacf41 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/lib.rs @@ -0,0 +1,17 @@ +#![allow(deprecated)] + +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +pub mod client; +pub mod types; + +/// Common errors and error handling utilities. +pub mod error; + +/// All operations that this crate can perform. +pub mod operation; + +mod conversions; + +pub use client::Client; +pub use types::simple_string_config::SimpleStringConfig; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation.rs index 1220a72598..11a6156789 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + /// Types for the `GetString` operation. pub mod get_string; @@ -12,3 +11,4 @@ pub mod get_string_utf8; /// Types for the `GetStringUTF8KnownValue` operation. pub mod get_string_utf8_known_value; + diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string.rs index 2ac87c12d5..813f2280e3 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetString`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -139,9 +137,9 @@ pub use crate::operation::get_string::_get_string_output::GetStringOutput; pub use crate::operation::get_string::_get_string_input::GetStringInput; -pub(crate) mod _get_string_output; +mod _get_string_input; -pub(crate) mod _get_string_input; +mod _get_string_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_input.rs index b775cb1bfa..9c0d47f5f2 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_input.rs @@ -1,18 +1,16 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetStringInput { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::string::String>, + pub value: ::std::option::Option<::std::string::String>, } impl GetStringInput { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::string::String> { - self.value.clone() -} + pub fn value(&self) -> ::std::option::Option<&str> { + self.value.as_deref() + } } impl GetStringInput { /// Creates a new builder-style object to manufacture [`GetStringInput`](crate::operation::operation::GetStringInput). @@ -31,19 +29,19 @@ pub struct GetStringInputBuilder { } impl GetStringInputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value -} + pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value + } /// Consumes the builder and constructs a [`GetStringInput`](crate::operation::operation::GetStringInput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_output.rs index 0f89443a9b..ab6b1fa3cd 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_output.rs @@ -1,18 +1,16 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetStringOutput { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::string::String>, + pub value: ::std::option::Option<::std::string::String>, } impl GetStringOutput { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::string::String> { - self.value.clone() -} + pub fn value(&self) -> ::std::option::Option<&str> { + self.value.as_deref() + } } impl GetStringOutput { /// Creates a new builder-style object to manufacture [`GetStringOutput`](crate::operation::operation::GetStringOutput). @@ -31,19 +29,19 @@ pub struct GetStringOutputBuilder { } impl GetStringOutputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value -} + pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value + } /// Consumes the builder and constructs a [`GetStringOutput`](crate::operation::operation::GetStringOutput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/builders.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/builders.rs index e0c6cd015e..ec32b2e2ce 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/builders.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/builders.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use crate::operation::get_string::_get_string_output::GetStringOutputBuilder; pub use crate::operation::get_string::_get_string_input::GetStringInputBuilder; @@ -23,12 +21,12 @@ impl GetStringInputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetStringFluentBuilder { - client: crate::client::Client, - pub(crate) inner: crate::operation::get_string::builders::GetStringInputBuilder, + client: crate::Client, + inner: crate::operation::get_string::builders::GetStringInputBuilder, } impl GetStringFluentBuilder { /// Creates a new `GetString`. - pub(crate) fn new(client: crate::client::Client) -> Self { + pub(crate) fn new(client: crate::Client) -> Self { Self { client, inner: ::std::default::Default::default(), @@ -58,17 +56,17 @@ impl GetStringFluentBuilder { } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - self.inner.get_value() -} + pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.inner = self.inner.value(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value.rs index 0d9960be0e..d6abc77c74 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetStringKnownValue`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -12,27 +10,28 @@ impl GetStringKnownValue { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_string_known_value::GetStringInput, + input: crate::operation::get_string_known_value::GetStringKnownValueInput, ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringOutput, + crate::operation::get_string_known_value::GetStringKnownValueOutput, crate::operation::get_string_known_value::GetStringKnownValueError, > { - let inner_input = crate::conversions::get_string_known_value::_get_string_known_value_input::to_dafny(input); + let inner_input = + crate::conversions::get_string_known_value::_get_string_known_value_input::to_dafny( + input, + ); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetStringKnownValue(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetString(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - Ok( - crate::conversions::get_string_known_value::_get_string_known_value_output::from_dafny( - inner_result.value().clone(), + Ok(crate::conversions::get_string_known_value::_get_string_known_value_output::from_dafny(inner_result.value().clone())) + } else { + Err( + crate::conversions::get_string_known_value::from_dafny_error( + inner_result.error().clone(), ), ) - } else { - Err(crate::conversions::get_string_known_value::from_dafny_error( - inner_result.error().clone(), - )) } } } @@ -135,13 +134,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetStrin } } -pub use crate::operation::get_string_known_value::_get_string_output::GetStringOutput; +pub use crate::operation::get_string_known_value::_get_string_known_value_output::GetStringKnownValueOutput; -pub use crate::operation::get_string_known_value::_get_string_input::GetStringInput; +pub use crate::operation::get_string_known_value::_get_string_known_value_input::GetStringKnownValueInput; -pub(crate) mod _get_string_output; +mod _get_string_known_value_input; -pub(crate) mod _get_string_input; +mod _get_string_known_value_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_input.rs deleted file mode 100644 index 2eedc4c6b9..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_input.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetStringInput { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::string::String>, -} -impl GetStringInput { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::string::String> { - self.value.clone() -} -} -impl GetStringInput { - /// Creates a new builder-style object to manufacture [`GetStringInput`](crate::operation::operation::GetStringInput). - pub fn builder() -> crate::operation::get_string_known_value::builders::GetStringInputBuilder { - crate::operation::get_string_known_value::builders::GetStringInputBuilder::default() - } -} - -/// A builder for [`GetStringInput`](crate::operation::operation::GetStringInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetStringInputBuilder { - pub(crate) value: ::std::option::Option<::std::string::String>, -} -impl GetStringInputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value -} - /// Consumes the builder and constructs a [`GetStringInput`](crate::operation::operation::GetStringInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_string_known_value::GetStringInput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_input.rs new file mode 100644 index 0000000000..b67c3effad --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_input.rs @@ -0,0 +1,60 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetStringKnownValueInput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option<::std::string::String>, +} +impl GetStringKnownValueInput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option<&str> { + self.value.as_deref() + } +} +impl GetStringKnownValueInput { + /// Creates a new builder-style object to manufacture [`GetStringKnownValueInput`](crate::operation::operation::GetStringKnownValueInput). + pub fn builder( + ) -> crate::operation::get_string_known_value::builders::GetStringKnownValueInputBuilder { + crate::operation::get_string_known_value::builders::GetStringKnownValueInputBuilder::default( + ) + } +} + +/// A builder for [`GetStringKnownValueInput`](crate::operation::operation::GetStringKnownValueInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetStringKnownValueInputBuilder { + pub(crate) value: ::std::option::Option<::std::string::String>, +} +impl GetStringKnownValueInputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value + } + /// Consumes the builder and constructs a [`GetStringKnownValueInput`](crate::operation::operation::GetStringKnownValueInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_string_known_value::GetStringKnownValueInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_string_known_value::GetStringKnownValueInput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_output.rs new file mode 100644 index 0000000000..291e692c5a --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_output.rs @@ -0,0 +1,59 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetStringKnownValueOutput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option<::std::string::String>, +} +impl GetStringKnownValueOutput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option<&str> { + self.value.as_deref() + } +} +impl GetStringKnownValueOutput { + /// Creates a new builder-style object to manufacture [`GetStringKnownValueOutput`](crate::operation::operation::GetStringKnownValueOutput). + pub fn builder( + ) -> crate::operation::get_string_known_value::builders::GetStringKnownValueOutputBuilder { + crate::operation::get_string_known_value::builders::GetStringKnownValueOutputBuilder::default() + } +} + +/// A builder for [`GetStringKnownValueOutput`](crate::operation::operation::GetStringKnownValueOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetStringKnownValueOutputBuilder { + pub(crate) value: ::std::option::Option<::std::string::String>, +} +impl GetStringKnownValueOutputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value + } + /// Consumes the builder and constructs a [`GetStringKnownValueOutput`](crate::operation::operation::GetStringKnownValueOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_string_known_value::GetStringKnownValueOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok( + crate::operation::get_string_known_value::GetStringKnownValueOutput { + value: self.value, + }, + ) + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_output.rs deleted file mode 100644 index dd7b2a2ebc..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_output.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetStringOutput { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::string::String>, -} -impl GetStringOutput { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::string::String> { - self.value.clone() -} -} -impl GetStringOutput { - /// Creates a new builder-style object to manufacture [`GetStringOutput`](crate::operation::operation::GetStringOutput). - pub fn builder() -> crate::operation::get_string_known_value::builders::GetStringOutputBuilder { - crate::operation::get_string_known_value::builders::GetStringOutputBuilder::default() - } -} - -/// A builder for [`GetStringOutput`](crate::operation::operation::GetStringOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetStringOutputBuilder { - pub(crate) value: ::std::option::Option<::std::string::String>, -} -impl GetStringOutputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value -} - /// Consumes the builder and constructs a [`GetStringOutput`](crate::operation::operation::GetStringOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_string_known_value::GetStringOutput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/builders.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/builders.rs index 0d379f9cad..82b4c7fb37 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/builders.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/builders.rs @@ -1,17 +1,15 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub use crate::operation::get_string_known_value::_get_string_output::GetStringOutputBuilder; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub use crate::operation::get_string_known_value::_get_string_known_value_output::GetStringKnownValueOutputBuilder; -pub use crate::operation::get_string_known_value::_get_string_input::GetStringInputBuilder; +pub use crate::operation::get_string_known_value::_get_string_known_value_input::GetStringKnownValueInputBuilder; -impl GetStringInputBuilder { +impl GetStringKnownValueInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringOutput, + crate::operation::get_string_known_value::GetStringKnownValueOutput, crate::operation::get_string_known_value::GetStringKnownValueError, > { let mut fluent_builder = client.get_string_known_value(); @@ -23,52 +21,57 @@ impl GetStringInputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetStringKnownValueFluentBuilder { - client: crate::client::Client, - pub(crate) inner: crate::operation::get_string_known_value::builders::GetStringInputBuilder, + client: crate::Client, + inner: crate::operation::get_string_known_value::builders::GetStringKnownValueInputBuilder, } impl GetStringKnownValueFluentBuilder { /// Creates a new `GetStringKnownValue`. - pub(crate) fn new(client: crate::client::Client) -> Self { + pub(crate) fn new(client: crate::Client) -> Self { Self { client, inner: ::std::default::Default::default(), } } /// Access the GetStringKnownValue as a reference. - pub fn as_input(&self) -> &crate::operation::get_string_known_value::builders::GetStringInputBuilder { + pub fn as_input( + &self, + ) -> &crate::operation::get_string_known_value::builders::GetStringKnownValueInputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringOutput, + crate::operation::get_string_known_value::GetStringKnownValueOutput, crate::operation::get_string_known_value::GetStringKnownValueError, > { let input = self .inner .build() - // Using unhandled since GetStringKnownValue doesn't declare any validation, + // Using unhandled since GetString doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. - .map_err(crate::operation::get_string_known_value::GetStringKnownValueError::unhandled)?; - crate::operation::get_string_known_value::GetStringKnownValue::send(&self.client, input).await + .map_err( + crate::operation::get_string_known_value::GetStringKnownValueError::unhandled, + )?; + crate::operation::get_string_known_value::GetStringKnownValue::send(&self.client, input) + .await } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - self.inner.get_value() -} + pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.inner = self.inner.value(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8.rs index d27e047855..966f215250 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetStringUTF8`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -17,7 +15,8 @@ impl GetStringUTF8 { crate::operation::get_string_utf8::GetStringUTF8Output, crate::operation::get_string_utf8::GetStringUTF8Error, > { - let inner_input = crate::conversions::get_string_utf8::_get_string_utf8_input::to_dafny(input); + let inner_input = + crate::conversions::get_string_utf8::_get_string_utf8_input::to_dafny(input); let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetStringUTF8(&inner_input); if matches!( @@ -139,9 +138,9 @@ pub use crate::operation::get_string_utf8::_get_string_utf8_output::GetStringUTF pub use crate::operation::get_string_utf8::_get_string_utf8_input::GetStringUTF8Input; -pub(crate) mod _get_string_utf8_output; +mod _get_string_utf8_input; -pub(crate) mod _get_string_utf8_input; +mod _get_string_utf8_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_input.rs index 8950b2a8c0..a448688ed3 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_input.rs @@ -1,18 +1,16 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetStringUTF8Input { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::string::String>, + pub value: ::std::option::Option<::std::string::String>, } impl GetStringUTF8Input { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::string::String> { - self.value.clone() -} + pub fn value(&self) -> ::std::option::Option<&str> { + self.value.as_deref() + } } impl GetStringUTF8Input { /// Creates a new builder-style object to manufacture [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). @@ -31,19 +29,19 @@ pub struct GetStringUTF8InputBuilder { } impl GetStringUTF8InputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value -} + pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value + } /// Consumes the builder and constructs a [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_output.rs index bb7220129d..2c8dca6a85 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_output.rs @@ -1,18 +1,16 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetStringUTF8Output { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::string::String>, + pub value: ::std::option::Option<::std::string::String>, } impl GetStringUTF8Output { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::string::String> { - self.value.clone() -} + pub fn value(&self) -> ::std::option::Option<&str> { + self.value.as_deref() + } } impl GetStringUTF8Output { /// Creates a new builder-style object to manufacture [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). @@ -31,19 +29,19 @@ pub struct GetStringUTF8OutputBuilder { } impl GetStringUTF8OutputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value -} + pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value + } /// Consumes the builder and constructs a [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/builders.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/builders.rs index 2291919ec3..26bf3d9e26 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/builders.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/builders.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use crate::operation::get_string_utf8::_get_string_utf8_output::GetStringUTF8OutputBuilder; pub use crate::operation::get_string_utf8::_get_string_utf8_input::GetStringUTF8InputBuilder; @@ -23,19 +21,21 @@ impl GetStringUTF8InputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetStringUTF8FluentBuilder { - client: crate::client::Client, - pub(crate) inner: crate::operation::get_string_utf8::builders::GetStringUTF8InputBuilder, + client: crate::Client, + inner: crate::operation::get_string_utf8::builders::GetStringUTF8InputBuilder, } impl GetStringUTF8FluentBuilder { /// Creates a new `GetStringUTF8`. - pub(crate) fn new(client: crate::client::Client) -> Self { + pub(crate) fn new(client: crate::Client) -> Self { Self { client, inner: ::std::default::Default::default(), } } /// Access the GetStringUTF8 as a reference. - pub fn as_input(&self) -> &crate::operation::get_string_utf8::builders::GetStringUTF8InputBuilder { + pub fn as_input( + &self, + ) -> &crate::operation::get_string_utf8::builders::GetStringUTF8InputBuilder { &self.inner } /// Sends the request and returns the response. @@ -48,7 +48,7 @@ impl GetStringUTF8FluentBuilder { let input = self .inner .build() - // Using unhandled since GetStringUTF8 doesn't declare any validation, + // Using unhandled since GetString doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, @@ -58,17 +58,17 @@ impl GetStringUTF8FluentBuilder { } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - self.inner.get_value() -} + pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.inner = self.inner.value(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value.rs index 47bb6d9ea5..16b06252a3 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetStringUTF8KnownValue`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -12,12 +10,13 @@ impl GetStringUTF8KnownValue { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_string_utf8_known_value::GetStringUTF8Input, + input: crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput, ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8Output, + crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError, > { - let inner_input = crate::conversions::get_string_utf8_known_value::_get_string_utf8_known_value_input::to_dafny(input); + let inner_input = + crate::conversions::get_string_utf8_known_value::_get_string_utf8_known_value_input::to_dafny(input); let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetStringUTF8KnownValue(&inner_input); if matches!( @@ -135,13 +134,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetStrin } } -pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_output::GetStringUTF8Output; +pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_known_value_output::GetStringUTF8KnownValueOutput; -pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_input::GetStringUTF8Input; +pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_known_value_input::GetStringUTF8KnownValueInput; -pub(crate) mod _get_string_utf8_output; +mod _get_string_utf8_known_value_input; -pub(crate) mod _get_string_utf8_input; +mod _get_string_utf8_known_value_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_input.rs deleted file mode 100644 index 6e21c111bd..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_input.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetStringUTF8Input { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::string::String>, -} -impl GetStringUTF8Input { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::string::String> { - self.value.clone() -} -} -impl GetStringUTF8Input { - /// Creates a new builder-style object to manufacture [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). - pub fn builder() -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8InputBuilder { - crate::operation::get_string_utf8_known_value::builders::GetStringUTF8InputBuilder::default() - } -} - -/// A builder for [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetStringUTF8InputBuilder { - pub(crate) value: ::std::option::Option<::std::string::String>, -} -impl GetStringUTF8InputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value -} - /// Consumes the builder and constructs a [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8Input, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_string_utf8_known_value::GetStringUTF8Input { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs new file mode 100644 index 0000000000..6b73af0d8f --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs @@ -0,0 +1,56 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetStringUTF8KnownValueInput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option<::std::string::String>, +} +impl GetStringUTF8KnownValueInput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option<&str> { + self.value.as_deref() + } +} +impl GetStringUTF8KnownValueInput { + /// Creates a new builder-style object to manufacture [`GetStringUTF8KnownValueInput`](crate::operation::operation::GetStringUTF8KnownValueInput). + pub fn builder() -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueInputBuilder { + crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueInputBuilder::default() + } +} + +/// A builder for [`GetStringUTF8KnownValueInput`](crate::operation::operation::GetStringUTF8KnownValueInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetStringUTF8KnownValueInputBuilder { + pub(crate) value: ::std::option::Option<::std::string::String>, +} +impl GetStringUTF8KnownValueInputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value + } + /// Consumes the builder and constructs a [`GetStringUTF8KnownValueInput`](crate::operation::operation::GetStringUTF8KnownValueInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs new file mode 100644 index 0000000000..8c77126081 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs @@ -0,0 +1,56 @@ +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetStringUTF8KnownValueOutput { + #[allow(missing_docs)] // documentation missing in model + pub value: ::std::option::Option<::std::string::String>, +} +impl GetStringUTF8KnownValueOutput { + #[allow(missing_docs)] // documentation missing in model + pub fn value(&self) -> ::std::option::Option<&str> { + self.value.as_deref() + } +} +impl GetStringUTF8KnownValueOutput { + /// Creates a new builder-style object to manufacture [`GetStringUTF8KnownValueOutput`](crate::operation::operation::GetStringUTF8KnownValueOutput). + pub fn builder() -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueOutputBuilder { + crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueOutputBuilder::default() + } +} + +/// A builder for [`GetStringUTF8KnownValueOutput`](crate::operation::operation::GetStringUTF8KnownValueOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetStringUTF8KnownValueOutputBuilder { + pub(crate) value: ::std::option::Option<::std::string::String>, +} +impl GetStringUTF8KnownValueOutputBuilder { + #[allow(missing_docs)] // documentation missing in model + pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value + } + /// Consumes the builder and constructs a [`GetStringUTF8KnownValueOutput`](crate::operation::operation::GetStringUTF8KnownValueOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_output.rs deleted file mode 100644 index f1dfb24b67..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_output.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetStringUTF8Output { - #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::std::string::String>, -} -impl GetStringUTF8Output { - #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::std::string::String> { - self.value.clone() -} -} -impl GetStringUTF8Output { - /// Creates a new builder-style object to manufacture [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). - pub fn builder() -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8OutputBuilder { - crate::operation::get_string_utf8_known_value::builders::GetStringUTF8OutputBuilder::default() - } -} - -/// A builder for [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetStringUTF8OutputBuilder { - pub(crate) value: ::std::option::Option<::std::string::String>, -} -impl GetStringUTF8OutputBuilder { - #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value -} - /// Consumes the builder and constructs a [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8Output, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_string_utf8_known_value::GetStringUTF8Output { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/builders.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/builders.rs index c6e957eee6..0b29a00e10 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/builders.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/builders.rs @@ -1,17 +1,15 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_output::GetStringUTF8OutputBuilder; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_known_value_output::GetStringUTF8KnownValueOutputBuilder; -pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_input::GetStringUTF8InputBuilder; +pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_known_value_input::GetStringUTF8KnownValueInputBuilder; -impl GetStringUTF8InputBuilder { +impl GetStringUTF8KnownValueInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8Output, + crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError, > { let mut fluent_builder = client.get_string_utf8_known_value(); @@ -23,32 +21,34 @@ impl GetStringUTF8InputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetStringUTF8KnownValueFluentBuilder { - client: crate::client::Client, - pub(crate) inner: crate::operation::get_string_utf8_known_value::builders::GetStringUTF8InputBuilder, + client: crate::Client, + inner: crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueInputBuilder, } impl GetStringUTF8KnownValueFluentBuilder { /// Creates a new `GetStringUTF8KnownValue`. - pub(crate) fn new(client: crate::client::Client) -> Self { + pub(crate) fn new(client: crate::Client) -> Self { Self { client, inner: ::std::default::Default::default(), } } /// Access the GetStringUTF8KnownValue as a reference. - pub fn as_input(&self) -> &crate::operation::get_string_utf8_known_value::builders::GetStringUTF8InputBuilder { + pub fn as_input( + &self, + ) -> &crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueInputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8Output, + crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError, > { let input = self .inner .build() - // Using unhandled since GetStringUTF8KnownValue doesn't declare any validation, + // Using unhandled since GetString doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, @@ -58,17 +58,17 @@ impl GetStringUTF8KnownValueFluentBuilder { } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - self.inner.get_value() -} + pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.inner = self.inner.value(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_conversions.rs index 6bf8297d8a..3a51134c6e 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_conversions.rs @@ -1,266 +1,246 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + >, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny( - input: &Option, -) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny( + input: &::aws_smithy_types::Blob, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny( + input: ::dafny_runtime::Sequence, +) -> ::aws_smithy_types::Blob { + + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()) + .unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x, - ) +pub fn double_to_dafny( + input: f64, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny( + input: &::dafny_runtime::Sequence, +) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: &::aws_smithy_types::DateTime, + input: ::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &input.to_string(), - ) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, -> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc>> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input, - ); - ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) - .unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); + ::aws_smithy_types::DateTime::from_str( + &s, + aws_smithy_types::date_time::Format::DateTime, + ).unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::DateTime> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None {} => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None { } => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { - value: converter(&value), - }), - None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), - } + match input { + Some(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::Some { + value: converter(&value) + } + ), + None => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::None {} + ), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value), - }), - Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error), - }), - } -} + match input { + Ok(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value) + } + ), + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error) + } + ), + } +} \ No newline at end of file diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types.rs index 9e117395c3..7ec7460923 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types.rs @@ -1,5 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + /// Types for the `SimpleStringConfig` pub mod simple_string_config; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types/simple_string_config.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types/simple_string_config.rs index 94d186d226..6b9ec61a06 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types/simple_string_config.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types/simple_string_config.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleStringConfig {} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped.rs deleted file mode 100644 index 4f32d02ae7..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod client; - -impl crate::r#simple::types::smithystring::internaldafny::wrapped::_default { - pub fn WrappedSimpleString(config: &::std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::SimpleStringConfig, - >) -> ::std::rc::Rc, - ::std::rc::Rc - >>{ - crate::wrapped::client::Client::from_conf(config) - } -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped/client.rs deleted file mode 100644 index f89535dd13..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped/client.rs +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use tokio::runtime::Runtime; - -pub struct Client { - wrapped: crate::client::Client, - - /// A `current_thread` runtime for executing operations on the - /// asynchronous client in a blocking manner. - rt: Runtime -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::smithystring::internaldafny::types::ISimpleTypesStringClient); -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); -} - -impl Client { - pub fn from_conf(config: &::std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::SimpleStringConfig, - >) -> -::std::rc::Rc, - ::std::rc::Rc ->> { - let rt_result = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build(); - let rt = match rt_result { - Ok(x) => x, - Err(error) => return crate::conversions::error::to_opaque_error_result(error), - }; - let result = crate::client::Client::from_conf( - crate::conversions::simple_string_config::_simple_string_config::from_dafny( - config.clone(), - ), - ); - match result { - Ok(client) => { - let wrap = crate::wrapped::client::Client { - wrapped: client, - rt - }; - std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) - } - ) - }, - Err(error) => crate::conversions::error::to_opaque_error_result(error) - } - } -} - -impl crate::r#simple::types::smithystring::internaldafny::types::ISimpleTypesStringClient for Client { - fn GetString( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_string::_get_string_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_string::GetString::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_string::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_string::_get_string_output::to_dafny(client), - }, - ), - } - } - - fn GetStringKnownValue( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_string_known_value::_get_string_known_value_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_string_known_value::GetStringKnownValue::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_string_known_value::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_string_known_value::_get_string_known_value_output::to_dafny(client), - }, - ), - } - } - - fn GetStringUTF8( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_string_utf8::_get_string_utf8_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_string_utf8::GetStringUTF8::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_string_utf8::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_string_utf8::_get_string_utf8_output::to_dafny(client), - }, - ), - } - } - - fn GetStringUTF8KnownValue( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_string_utf8_known_value::_get_string_utf8_known_value_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValue::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_string_utf8_known_value::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_string_utf8_known_value::_get_string_utf8_known_value_output::to_dafny(client), - }, - ), - } - } -} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/Makefile b/TestModels/SimpleTypes/SimpleTimestamp/Makefile index 55d0f10c8b..6575072c56 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/Makefile +++ b/TestModels/SimpleTypes/SimpleTimestamp/Makefile @@ -3,9 +3,8 @@ CORES=2 -TRANSPILE_TESTS_IN_RUST=1 - ENABLE_EXTERN_PROCESSING=1 +RUST_BENERATED=1 include ../../SharedMakefile.mk @@ -23,8 +22,10 @@ SMITHY_DEPS=dafny-dependencies/Model/traits.smithy # This project has no dependencies # DEPENDENT-MODELS:= + POLYMORPH_OPTIONS=--generate client-constructors,project-files + # Constants for languages that drop extern names (Python, Go) TYPES_FILE_PATH=Model/SimpleTypesTimestampTypes.dfy diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/Cargo.toml index de5d419467..94927ac487 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/Cargo.toml @@ -5,21 +5,14 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html -[features] -wrapped-client = [] - [dependencies] +dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} aws-smithy-runtime = { version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = { version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" -dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} [dev-dependencies] -simple_timestamp = { path = ".", features = ["wrapped-client"] } - -[dependencies.tokio] -version = "1.26.0" -features = ["full"] +tokio = { version = "1.26.0", features = ["full"] } [lib] path = "src/implementation_from_dafny.rs" diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client.rs index c87832fe22..1691812f17 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -30,7 +29,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), }) } } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client/get_timestamp.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client/get_timestamp.rs index e272f76759..9004f4f30c 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client/get_timestamp.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client/get_timestamp.rs @@ -1,15 +1,15 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. impl super::Client { /// Constructs a fluent builder for the [`GetTimestamp`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::value) / [`set_value(Option<::aws_smithy_types::DateTime>)`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::set_value): (undocumented)
+ /// - [`value(DateTime)`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::set_value):
required: **false**
(undocumented)
/// - On success, responds with [`GetTimestampOutput`](crate::operation::get_timestamp::GetTimestampOutput) with field(s): - /// - [`value(Option<::aws_smithy_types::DateTime>)`](crate::operation::get_timestamp::GetTimestampOutput::value): (undocumented) + /// - [`value(Option)`](crate::operation::get_timestamp::GetTimestampOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_timestamp::GetTimestampError) - pub fn get_timestamp(&self) -> crate::operation::get_timestamp::builders::GetTimestampFluentBuilder { + pub fn get_timestamp( + &self, + ) -> crate::operation::get_timestamp::builders::GetTimestampFluentBuilder { crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions.rs index 85c9ba3aa5..6c19c684d4 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions.rs @@ -1,8 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod error; +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +pub mod get_timestamp; - pub mod get_timestamp; - - pub mod simple_timestamp_config; +pub mod simple_timestamp_config; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/error.rs deleted file mode 100644 index 255fc97000..0000000000 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/error.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. - /// Wraps up an arbitrary Rust Error value as a Dafny Error -pub fn to_opaque_error(value: E) -> - ::std::rc::Rc -{ - let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( - ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), - )); - ::std::rc::Rc::new( - crate::r#simple::types::timestamp::internaldafny::types::Error::Opaque { - obj: error_obj, - }, - ) -} - -/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure -pub fn to_opaque_error_result(value: E) -> - ::std::rc::Rc< - crate::_Wrappers_Compile::Result< - T, - ::std::rc::Rc - > - > -{ - ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: to_opaque_error(value), - }, - ) -} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp.rs index e96799af63..64d9cf3a17 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp.rs @@ -1,12 +1,12 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_timestamp::GetTimestampError, -) -> ::std::rc::Rc { +) -> ::std::rc::Rc +{ match value { crate::operation::get_timestamp::GetTimestampError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::timestamp::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_input.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_input.rs index b42a091567..ec1fde893a 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_input.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_input.rs @@ -1,24 +1,39 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_timestamp::GetTimestampInput, ) -> ::std::rc::Rc< crate::r#simple::types::timestamp::internaldafny::types::GetTimestampInput, ->{ +> { + let dafny_value = match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s.to_string()) }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::timestamp::internaldafny::types::GetTimestampInput::GetTimestampInput { - value: crate::standard_library_conversions::otimestamp_to_dafny(&value.value), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::timestamp::internaldafny::types::GetTimestampInput, >, -) -> crate::operation::get_timestamp::GetTimestampInput { - crate::operation::get_timestamp::GetTimestampInput::builder() - .set_value(crate::standard_library_conversions::otimestamp_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() +) -> Result< + crate::operation::get_timestamp::GetTimestampInput, + aws_smithy_types::date_time::DateTimeParseError, +> { + let value = match dafny_value.value().as_ref() { + crate::_Wrappers_Compile::Option::None {} => None, + crate::_Wrappers_Compile::Option::Some { value } => { + let value = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&value); + let value = ::aws_smithy_types::DateTime::from_str( + &value, + aws_smithy_types::date_time::Format::DateTime, + )?; + Some(value) + } + }; + + Ok(crate::operation::get_timestamp::GetTimestampInput { value }) } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_output.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_output.rs index 09e9489bd3..958069da06 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_output.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_output.rs @@ -1,24 +1,39 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_timestamp::GetTimestampOutput, ) -> ::std::rc::Rc< crate::r#simple::types::timestamp::internaldafny::types::GetTimestampOutput, ->{ +> { + let dafny_value = match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s.to_string()) }, + None => crate::_Wrappers_Compile::Option::None {}, + }; ::std::rc::Rc::new(crate::r#simple::types::timestamp::internaldafny::types::GetTimestampOutput::GetTimestampOutput { - value: crate::standard_library_conversions::otimestamp_to_dafny(&value.value), - }) + value: ::std::rc::Rc::new(dafny_value) + }) } - #[allow(dead_code)] + +#[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::timestamp::internaldafny::types::GetTimestampOutput, >, -) -> crate::operation::get_timestamp::GetTimestampOutput { - crate::operation::get_timestamp::GetTimestampOutput::builder() - .set_value(crate::standard_library_conversions::otimestamp_from_dafny(dafny_value.value().clone())) - .build() - .unwrap() +) -> Result< + crate::operation::get_timestamp::GetTimestampOutput, + aws_smithy_types::date_time::DateTimeParseError, +> { + let value = match dafny_value.value().as_ref() { + crate::_Wrappers_Compile::Option::None {} => None, + crate::_Wrappers_Compile::Option::Some { value } => { + let value = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&value); + let value = ::aws_smithy_types::DateTime::from_str( + &value, + aws_smithy_types::date_time::Format::DateTime, + )?; + Some(value) + } + }; + + Ok(crate::operation::get_timestamp::GetTimestampOutput { value }) } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config.rs index f4c49447c2..3ab1449023 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config.rs @@ -1,4 +1,3 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + pub mod _simple_timestamp_config; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config/_simple_timestamp_config.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config/_simple_timestamp_config.rs index 65be65a356..7a6ad17f9b 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config/_simple_timestamp_config.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config/_simple_timestamp_config.rs @@ -1,13 +1,11 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_timestamp_config::SimpleTimestampConfig, ) -> ::std::rc::Rc< - crate::r#simple::types::timestamp::internaldafny::types::SimpleTimestampConfig, -> { + crate::simple::types::timestamp::internaldafny::types::SimpleTimestampConfig, +>{ ::std::rc::Rc::new(crate::r#simple::types::timestamp::internaldafny::types::SimpleTimestampConfig::SimpleTimestampConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error.rs index 4cddaa7c39..ec89cbecc9 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error/sealed_unhandled.rs index eae8007292..cce22d1cfd 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,10 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use std::any::Any; - -use dafny_runtime::UpcastObject; - +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -27,6 +21,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl UpcastObject for Unhandled { +impl ::dafny_runtime::UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/lib.rs new file mode 100644 index 0000000000..4e55b724cc --- /dev/null +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/lib.rs @@ -0,0 +1,19 @@ +#![allow(deprecated)] + +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + +pub mod client; +pub mod types; + +/// Common errors and error handling utilities. +pub mod error; + +/// All operations that this crate can perform. +pub mod operation; + +mod conversions; + +pub mod implementation_from_dafny; + +pub use client::Client; +pub use types::simple_timestamp_config::SimpleTimestampConfig; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation.rs index e1bae12748..14ae6ca55a 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation.rs @@ -1,5 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + /// Types for the `GetTimestamp` operation. pub mod get_timestamp; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp.rs index a393c9880c..27f406c721 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `GetTimestamp`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -24,11 +22,10 @@ impl GetTimestamp { inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - Ok( - crate::conversions::get_timestamp::_get_timestamp_output::from_dafny( - inner_result.value().clone(), - ), + crate::conversions::get_timestamp::_get_timestamp_output::from_dafny( + inner_result.value().clone(), ) + .map_err(crate::operation::get_timestamp::GetTimestampError::unhandled) } else { Err(crate::conversions::get_timestamp::from_dafny_error( inner_result.error().clone(), @@ -139,9 +136,9 @@ pub use crate::operation::get_timestamp::_get_timestamp_output::GetTimestampOutp pub use crate::operation::get_timestamp::_get_timestamp_input::GetTimestampInput; -pub(crate) mod _get_timestamp_output; +mod _get_timestamp_input; -pub(crate) mod _get_timestamp_input; +mod _get_timestamp_output; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_input.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_input.rs index 1155b34c91..acf259d313 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_input.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_input.rs @@ -1,27 +1,25 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetTimestampInput { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::aws_smithy_types::DateTime>, + pub value: ::std::option::Option<::aws_smithy_types::DateTime>, } impl GetTimestampInput { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::DateTime> { - self.value -} + pub fn value(&self) -> ::std::option::Option<&::aws_smithy_types::DateTime> { + self.value.as_ref() + } } impl GetTimestampInput { - /// Creates a new builder-style object to manufacture [`GetTimestampInput`](crate::operation::operation::GetTimestampInput). + /// Creates a new builder-style object to manufacture [`GetTimestampInput`](crate::operation::get_timestamp::GetTimestampInput). pub fn builder() -> crate::operation::get_timestamp::builders::GetTimestampInputBuilder { crate::operation::get_timestamp::builders::GetTimestampInputBuilder::default() } } -/// A builder for [`GetTimestampInput`](crate::operation::operation::GetTimestampInput). +/// A builder for [`GetTimestampInput`](crate::operation::get_timestamp::GetTimestampInput). #[non_exhaustive] #[derive( ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, @@ -31,20 +29,20 @@ pub struct GetTimestampInputBuilder { } impl GetTimestampInputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::DateTime>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { - &self.value -} - /// Consumes the builder and constructs a [`GetTimestampInput`](crate::operation::operation::GetTimestampInput). + pub fn value(mut self, input: ::aws_smithy_types::DateTime) -> Self { + self.value = ::std::option::Option::Some(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { + &self.value + } + /// Consumes the builder and constructs a [`GetTimestampInput`](crate::operation::get_timestamp::GetTimestampInput). pub fn build( self, ) -> ::std::result::Result< diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_output.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_output.rs index c4f3ab84e0..711324b3a8 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_output.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_output.rs @@ -1,27 +1,25 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetTimestampOutput { #[allow(missing_docs)] // documentation missing in model -pub value: ::std::option::Option<::aws_smithy_types::DateTime>, + pub value: ::std::option::Option<::aws_smithy_types::DateTime>, } impl GetTimestampOutput { #[allow(missing_docs)] // documentation missing in model -pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::DateTime> { - self.value -} + pub fn value(&self) -> ::std::option::Option<&::aws_smithy_types::DateTime> { + self.value.as_ref() + } } impl GetTimestampOutput { - /// Creates a new builder-style object to manufacture [`GetTimestampOutput`](crate::operation::operation::GetTimestampOutput). + /// Creates a new builder-style object to manufacture [`GetTimestampOutput`](crate::operation::get_timestamp::GetTimestampOutput). pub fn builder() -> crate::operation::get_timestamp::builders::GetTimestampOutputBuilder { crate::operation::get_timestamp::builders::GetTimestampOutputBuilder::default() } } -/// A builder for [`GetTimestampOutput`](crate::operation::operation::GetTimestampOutput). +/// A builder for [`GetTimestampOutput`](crate::operation::get_timestamp::GetTimestampOutput). #[non_exhaustive] #[derive( ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, @@ -31,28 +29,21 @@ pub struct GetTimestampOutputBuilder { } impl GetTimestampOutputBuilder { #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::DateTime>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { - self.value = input; - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { - &self.value -} - /// Consumes the builder and constructs a [`GetTimestampOutput`](crate::operation::operation::GetTimestampOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_timestamp::GetTimestampOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_timestamp::GetTimestampOutput { - value: self.value, - }) + pub fn value(mut self, input: ::aws_smithy_types::DateTime) -> Self { + self.value = ::std::option::Option::Some(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { + self.value = input; + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { + &self.value + } + /// Consumes the builder and constructs a [`GetTimestampOutput`](crate::operation::get_timestamp::GetTimestampOutput). + pub fn build(self) -> crate::operation::get_timestamp::GetTimestampOutput { + crate::operation::get_timestamp::GetTimestampOutput { value: self.value } } } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/builders.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/builders.rs index 4f9282db2a..6097f5dc0d 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/builders.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/builders.rs @@ -1,6 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use crate::operation::get_timestamp::_get_timestamp_output::GetTimestampOutputBuilder; pub use crate::operation::get_timestamp::_get_timestamp_input::GetTimestampInputBuilder; @@ -24,7 +22,7 @@ impl GetTimestampInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetTimestampFluentBuilder { client: crate::client::Client, - pub(crate) inner: crate::operation::get_timestamp::builders::GetTimestampInputBuilder, + inner: crate::operation::get_timestamp::builders::GetTimestampInputBuilder, } impl GetTimestampFluentBuilder { /// Creates a new `GetTimestamp`. @@ -58,17 +56,17 @@ impl GetTimestampFluentBuilder { } #[allow(missing_docs)] // documentation missing in model -pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::DateTime>) -> Self { - self.inner = self.inner.value(input.into()); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { - self.inner = self.inner.set_value(input); - self -} -#[allow(missing_docs)] // documentation missing in model -pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { - self.inner.get_value() -} + pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::DateTime>) -> Self { + self.inner = self.inner.value(input.into()); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { + self.inner = self.inner.set_value(input); + self + } + #[allow(missing_docs)] // documentation missing in model + pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { + self.inner.get_value() + } } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_conversions.rs index 6bf8297d8a..3a51134c6e 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_conversions.rs @@ -1,266 +1,246 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + >, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny( - input: &Option, -) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny( - input: ::std::rc::Rc>, -) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny( + input: &::aws_smithy_types::Blob, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny( + input: ::dafny_runtime::Sequence, +) -> ::aws_smithy_types::Blob { + + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()) + .unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x, - ) +pub fn double_to_dafny( + input: f64, +) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny( + input: &::dafny_runtime::Sequence, +) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: &::aws_smithy_types::DateTime, + input: ::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &input.to_string(), - ) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, -> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc>> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input, - ); - ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) - .unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); + ::aws_smithy_types::DateTime::from_str( + &s, + aws_smithy_types::date_time::Format::DateTime, + ).unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - >, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::DateTime> { - if matches!( - input.as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None {} => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None { } => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { - value: converter(&value), - }), - None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), - } + match input { + Some(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::Some { + value: converter(&value) + } + ), + None => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Option::None {} + ), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value), - }), - Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error), - }), - } -} + match input { + Ok(value) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value) + } + ), + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error) + } + ), + } +} \ No newline at end of file diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types.rs index 7eff17a000..b22d67ccbb 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types.rs @@ -1,5 +1,4 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + /// Types for the `SimpleTimestampConfig` pub mod simple_timestamp_config; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types/simple_timestamp_config.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types/simple_timestamp_config.rs index 678b4ac557..611191c990 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types/simple_timestamp_config.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types/simple_timestamp_config.rs @@ -1,6 +1,5 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. + #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleTimestampConfig {} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped.rs deleted file mode 100644 index cefeb4517d..0000000000 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -pub mod client; - -impl crate::r#simple::types::timestamp::internaldafny::wrapped::_default { - pub fn WrappedSimpleTimestamp(config: &::std::rc::Rc< - crate::r#simple::types::timestamp::internaldafny::types::SimpleTimestampConfig, - >) -> ::std::rc::Rc, - ::std::rc::Rc - >>{ - crate::wrapped::client::Client::from_conf(config) - } -} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped/client.rs deleted file mode 100644 index c33b27e948..0000000000 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped/client.rs +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -use tokio::runtime::Runtime; - -pub struct Client { - wrapped: crate::client::Client, - - /// A `current_thread` runtime for executing operations on the - /// asynchronous client in a blocking manner. - rt: Runtime -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::timestamp::internaldafny::types::ISimpleTypesTimestampClient); -} - -impl dafny_runtime::UpcastObject for Client { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); -} - -impl Client { - pub fn from_conf(config: &::std::rc::Rc< - crate::r#simple::types::timestamp::internaldafny::types::SimpleTimestampConfig, - >) -> -::std::rc::Rc, - ::std::rc::Rc ->> { - let rt_result = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build(); - let rt = match rt_result { - Ok(x) => x, - Err(error) => return crate::conversions::error::to_opaque_error_result(error), - }; - let result = crate::client::Client::from_conf( - crate::conversions::simple_timestamp_config::_simple_timestamp_config::from_dafny( - config.clone(), - ), - ); - match result { - Ok(client) => { - let wrap = crate::wrapped::client::Client { - wrapped: client, - rt - }; - std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) - } - ) - }, - Err(error) => crate::conversions::error::to_opaque_error_result(error) - } - } -} - -impl crate::r#simple::types::timestamp::internaldafny::types::ISimpleTypesTimestampClient for Client { - fn GetTimestamp( - &mut self, - input: &std::rc::Rc< - crate::r#simple::types::timestamp::internaldafny::types::GetTimestampInput, - >, - ) -> std::rc::Rc< - crate::r#_Wrappers_Compile::Result< - std::rc::Rc< - crate::r#simple::types::timestamp::internaldafny::types::GetTimestampOutput, - >, - std::rc::Rc, - >, - >{ - let inner_input = - crate::conversions::get_timestamp::_get_timestamp_input::from_dafny(input.clone()); - let result = self.rt.block_on(crate::operation::get_timestamp::GetTimestamp::send(&self.wrapped, inner_input)); - match result { - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: crate::conversions::get_timestamp::to_dafny_error(error), - }, - ), - Ok(client) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::get_timestamp::_get_timestamp_output::to_dafny(client), - }, - ), - } - } -} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/tests/simple_timestamp_test.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/tests/simple_timestamp_test.rs index f45eb0c6ee..b6b60a0483 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/tests/simple_timestamp_test.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/tests/simple_timestamp_test.rs @@ -28,7 +28,7 @@ async fn test_get_timestamp() { .unwrap(); let result = client().get_timestamp().value(ts).send().await.unwrap(); let value = result.value().unwrap(); - assert_eq!(value, ts); + assert_eq!(value, &ts); } pub fn client() -> Client { diff --git a/TestModels/SimpleTypes/SimpleTimestamp/src/WrappedSimpleTypesTimestampImpl.dfy b/TestModels/SimpleTypes/SimpleTimestamp/src/WrappedSimpleTypesTimestampImpl.dfy deleted file mode 100644 index ce9fc36dbc..0000000000 --- a/TestModels/SimpleTypes/SimpleTimestamp/src/WrappedSimpleTypesTimestampImpl.dfy +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -include "../Model/SimpleTypesTimestampTypesWrapped.dfy" - -module {:options "--function-syntax:4"} {:extern "simple.types.timestamp.internaldafny.wrapped"} WrappedSimpleTypesTimestampService refines WrappedAbstractSimpleTypesTimestampService { - import WrappedService = SimpleTimestamp - function WrappedDefaultSimpleTimestampConfig(): SimpleTimestampConfig { - SimpleTimestampConfig - } -} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/test/SimpleTimestampImplTest.dfy b/TestModels/SimpleTypes/SimpleTimestamp/test/SimpleTimestampImplTest.dfy index a30f145cd2..7cd928417e 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/test/SimpleTimestampImplTest.dfy +++ b/TestModels/SimpleTypes/SimpleTimestamp/test/SimpleTimestampImplTest.dfy @@ -12,7 +12,6 @@ module SimpleTimestampImplTest { var client :- expect SimpleTimestamp.SimpleTimestamp(); TestGetTimestamp(client); - TestGetTimestampNoMs(client); } method TestGetTimestamp(client: ISimpleTypesTimestampClient) @@ -20,26 +19,9 @@ module SimpleTimestampImplTest { modifies client.Modifies ensures client.ValidState() { - var dafnyTimestamp := "2024-06-11T12:34:56.789Z"; - var ret :- expect client.GetTimestamp(SimpleTimestamp.Types.GetTimestampInput(value := Some(dafnyTimestamp))); + var dafnyTimestamp := "2024-06-11T12:34:56"; + var ret :- expect client.GetTimestamp(SimpleTimestamp.Types.GetTimestampInput(value:= Some(dafnyTimestamp))); expect ret.value == Some(dafnyTimestamp); print ret; } - - method TestGetTimestampNoMs(client: ISimpleTypesTimestampClient) - requires client.ValidState() - modifies client.Modifies - ensures client.ValidState() - { - var dafnyTimestamp := "2024-06-11T12:34:56Z"; - var ret :- expect client.GetTimestamp(SimpleTimestamp.Types.GetTimestampInput(value := Some(dafnyTimestamp))); - expect ret.value.Some?; - var retTimestamp := ret.value.value; - - // It's okay if milliseconds are serialized, so only check for prefix - expect |retTimestamp| > 0; - expect retTimestamp[|retTimestamp| - 1] == 'Z'; - expect dafnyTimestamp[|dafnyTimestamp| - 1] <= retTimestamp[|retTimestamp| - 1]; - print ret; - } } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/test/WrappedSimpleTimestampTest.dfy b/TestModels/SimpleTypes/SimpleTimestamp/test/WrappedSimpleTimestampTest.dfy index d51eb599bc..3e741368ff 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/test/WrappedSimpleTimestampTest.dfy +++ b/TestModels/SimpleTypes/SimpleTimestamp/test/WrappedSimpleTimestampTest.dfy @@ -11,6 +11,5 @@ module WrappedSimpleTypesTimestampTest { var client :- expect WrappedSimpleTypesTimestampService.WrappedSimpleTimestamp(); SimpleTimestampImplTest.TestGetTimestamp(client); - SimpleTimestampImplTest.TestGetTimestampNoMs(client); } } diff --git a/TestModels/Union/runtimes/rust/src/standard_library_externs.rs b/TestModels/Union/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/Union/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/attribute_action.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/attribute_action.rs index 86959a17b6..3b4bb95a5e 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/attribute_action.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/attribute_action.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::AttributeAction, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::AttributeAction::Add => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::ADD {}, -aws_sdk_dynamodb::types::AttributeAction::Put => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::PUT {}, -aws_sdk_dynamodb::types::AttributeAction::Delete => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::DELETE {}, + aws_sdk_dynamodb::types::AttributeAction::Add => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::ADD {}, + aws_sdk_dynamodb::types::AttributeAction::Put => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::PUT {}, + aws_sdk_dynamodb::types::AttributeAction::Delete => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::DELETE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction, ) -> aws_sdk_dynamodb::types::AttributeAction { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::ADD {} => aws_sdk_dynamodb::types::AttributeAction::Add, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::PUT {} => aws_sdk_dynamodb::types::AttributeAction::Put, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::DELETE {} => aws_sdk_dynamodb::types::AttributeAction::Delete, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::ADD {} => aws_sdk_dynamodb::types::AttributeAction::Add, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::PUT {} => aws_sdk_dynamodb::types::AttributeAction::Put, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::DELETE {} => aws_sdk_dynamodb::types::AttributeAction::Delete, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/batch_statement_error_code_enum.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/batch_statement_error_code_enum.rs index fd53a818a3..93746fece8 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/batch_statement_error_code_enum.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/batch_statement_error_code_enum.rs @@ -7,17 +7,17 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed {}, -aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded {}, -aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::RequestLimitExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::RequestLimitExceeded {}, -aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ValidationError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ValidationError {}, -aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded {}, -aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::TransactionConflict => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::TransactionConflict {}, -aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ThrottlingError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ThrottlingError {}, -aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::InternalServerError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::InternalServerError {}, -aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ResourceNotFound => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ResourceNotFound {}, -aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::AccessDenied => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::AccessDenied {}, -aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::DuplicateItem => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::DuplicateItem {}, + aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed {}, + aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded {}, + aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::RequestLimitExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::RequestLimitExceeded {}, + aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ValidationError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ValidationError {}, + aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded {}, + aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::TransactionConflict => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::TransactionConflict {}, + aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ThrottlingError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ThrottlingError {}, + aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::InternalServerError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::InternalServerError {}, + aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ResourceNotFound => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ResourceNotFound {}, + aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::AccessDenied => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::AccessDenied {}, + aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::DuplicateItem => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::DuplicateItem {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -26,16 +26,16 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum, ) -> aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::RequestLimitExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::RequestLimitExceeded, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ValidationError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ValidationError, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::TransactionConflict {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::TransactionConflict, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ThrottlingError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ThrottlingError, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::InternalServerError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::InternalServerError, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ResourceNotFound {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ResourceNotFound, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::AccessDenied {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::AccessDenied, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::DuplicateItem {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::DuplicateItem, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::RequestLimitExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::RequestLimitExceeded, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ValidationError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ValidationError, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::TransactionConflict {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::TransactionConflict, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ThrottlingError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ThrottlingError, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::InternalServerError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::InternalServerError, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ResourceNotFound {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ResourceNotFound, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::AccessDenied {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::AccessDenied, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::DuplicateItem {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::DuplicateItem, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/billing_mode.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/billing_mode.rs index a29d5b3565..5304c2abc0 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/billing_mode.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/billing_mode.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::BillingMode, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::BillingMode::Provisioned => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PROVISIONED {}, -aws_sdk_dynamodb::types::BillingMode::PayPerRequest => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PAY_PER_REQUEST {}, + aws_sdk_dynamodb::types::BillingMode::Provisioned => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PROVISIONED {}, + aws_sdk_dynamodb::types::BillingMode::PayPerRequest => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PAY_PER_REQUEST {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode, ) -> aws_sdk_dynamodb::types::BillingMode { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PROVISIONED {} => aws_sdk_dynamodb::types::BillingMode::Provisioned, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PAY_PER_REQUEST {} => aws_sdk_dynamodb::types::BillingMode::PayPerRequest, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PROVISIONED {} => aws_sdk_dynamodb::types::BillingMode::Provisioned, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PAY_PER_REQUEST {} => aws_sdk_dynamodb::types::BillingMode::PayPerRequest, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/comparison_operator.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/comparison_operator.rs index a18dec568f..0c75159bda 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/comparison_operator.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/comparison_operator.rs @@ -7,19 +7,19 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ComparisonOperator, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ComparisonOperator::Eq => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::EQ {}, -aws_sdk_dynamodb::types::ComparisonOperator::Ne => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NE {}, -aws_sdk_dynamodb::types::ComparisonOperator::In => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::IN {}, -aws_sdk_dynamodb::types::ComparisonOperator::Le => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LE {}, -aws_sdk_dynamodb::types::ComparisonOperator::Lt => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LT {}, -aws_sdk_dynamodb::types::ComparisonOperator::Ge => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GE {}, -aws_sdk_dynamodb::types::ComparisonOperator::Gt => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GT {}, -aws_sdk_dynamodb::types::ComparisonOperator::Between => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BETWEEN {}, -aws_sdk_dynamodb::types::ComparisonOperator::NotNull => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_NULL {}, -aws_sdk_dynamodb::types::ComparisonOperator::Null => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NULL {}, -aws_sdk_dynamodb::types::ComparisonOperator::Contains => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::CONTAINS {}, -aws_sdk_dynamodb::types::ComparisonOperator::NotContains => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_CONTAINS {}, -aws_sdk_dynamodb::types::ComparisonOperator::BeginsWith => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BEGINS_WITH {}, + aws_sdk_dynamodb::types::ComparisonOperator::Eq => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::EQ {}, + aws_sdk_dynamodb::types::ComparisonOperator::Ne => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NE {}, + aws_sdk_dynamodb::types::ComparisonOperator::In => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::IN {}, + aws_sdk_dynamodb::types::ComparisonOperator::Le => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LE {}, + aws_sdk_dynamodb::types::ComparisonOperator::Lt => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LT {}, + aws_sdk_dynamodb::types::ComparisonOperator::Ge => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GE {}, + aws_sdk_dynamodb::types::ComparisonOperator::Gt => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GT {}, + aws_sdk_dynamodb::types::ComparisonOperator::Between => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BETWEEN {}, + aws_sdk_dynamodb::types::ComparisonOperator::NotNull => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_NULL {}, + aws_sdk_dynamodb::types::ComparisonOperator::Null => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NULL {}, + aws_sdk_dynamodb::types::ComparisonOperator::Contains => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::CONTAINS {}, + aws_sdk_dynamodb::types::ComparisonOperator::NotContains => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_CONTAINS {}, + aws_sdk_dynamodb::types::ComparisonOperator::BeginsWith => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BEGINS_WITH {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -28,18 +28,18 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator, ) -> aws_sdk_dynamodb::types::ComparisonOperator { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::EQ {} => aws_sdk_dynamodb::types::ComparisonOperator::Eq, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NE {} => aws_sdk_dynamodb::types::ComparisonOperator::Ne, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::IN {} => aws_sdk_dynamodb::types::ComparisonOperator::In, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LE {} => aws_sdk_dynamodb::types::ComparisonOperator::Le, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LT {} => aws_sdk_dynamodb::types::ComparisonOperator::Lt, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GE {} => aws_sdk_dynamodb::types::ComparisonOperator::Ge, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GT {} => aws_sdk_dynamodb::types::ComparisonOperator::Gt, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BETWEEN {} => aws_sdk_dynamodb::types::ComparisonOperator::Between, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_NULL {} => aws_sdk_dynamodb::types::ComparisonOperator::NotNull, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NULL {} => aws_sdk_dynamodb::types::ComparisonOperator::Null, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::CONTAINS {} => aws_sdk_dynamodb::types::ComparisonOperator::Contains, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_CONTAINS {} => aws_sdk_dynamodb::types::ComparisonOperator::NotContains, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BEGINS_WITH {} => aws_sdk_dynamodb::types::ComparisonOperator::BeginsWith, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::EQ {} => aws_sdk_dynamodb::types::ComparisonOperator::Eq, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NE {} => aws_sdk_dynamodb::types::ComparisonOperator::Ne, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::IN {} => aws_sdk_dynamodb::types::ComparisonOperator::In, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LE {} => aws_sdk_dynamodb::types::ComparisonOperator::Le, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LT {} => aws_sdk_dynamodb::types::ComparisonOperator::Lt, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GE {} => aws_sdk_dynamodb::types::ComparisonOperator::Ge, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GT {} => aws_sdk_dynamodb::types::ComparisonOperator::Gt, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BETWEEN {} => aws_sdk_dynamodb::types::ComparisonOperator::Between, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_NULL {} => aws_sdk_dynamodb::types::ComparisonOperator::NotNull, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NULL {} => aws_sdk_dynamodb::types::ComparisonOperator::Null, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::CONTAINS {} => aws_sdk_dynamodb::types::ComparisonOperator::Contains, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_CONTAINS {} => aws_sdk_dynamodb::types::ComparisonOperator::NotContains, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BEGINS_WITH {} => aws_sdk_dynamodb::types::ComparisonOperator::BeginsWith, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/conditional_operator.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/conditional_operator.rs index 216ac006fb..64208da483 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/conditional_operator.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/conditional_operator.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ConditionalOperator, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ConditionalOperator::And => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::AND {}, -aws_sdk_dynamodb::types::ConditionalOperator::Or => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::OR {}, + aws_sdk_dynamodb::types::ConditionalOperator::And => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::AND {}, + aws_sdk_dynamodb::types::ConditionalOperator::Or => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::OR {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator, ) -> aws_sdk_dynamodb::types::ConditionalOperator { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::AND {} => aws_sdk_dynamodb::types::ConditionalOperator::And, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::OR {} => aws_sdk_dynamodb::types::ConditionalOperator::Or, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::AND {} => aws_sdk_dynamodb::types::ConditionalOperator::And, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::OR {} => aws_sdk_dynamodb::types::ConditionalOperator::Or, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/index_status.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/index_status.rs index df88cdcb2c..cd99dab3d6 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/index_status.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/index_status.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::IndexStatus, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::IndexStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::CREATING {}, -aws_sdk_dynamodb::types::IndexStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::UPDATING {}, -aws_sdk_dynamodb::types::IndexStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::DELETING {}, -aws_sdk_dynamodb::types::IndexStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::ACTIVE {}, + aws_sdk_dynamodb::types::IndexStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::CREATING {}, + aws_sdk_dynamodb::types::IndexStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::UPDATING {}, + aws_sdk_dynamodb::types::IndexStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::DELETING {}, + aws_sdk_dynamodb::types::IndexStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::ACTIVE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus, ) -> aws_sdk_dynamodb::types::IndexStatus { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::CREATING {} => aws_sdk_dynamodb::types::IndexStatus::Creating, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::UPDATING {} => aws_sdk_dynamodb::types::IndexStatus::Updating, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::DELETING {} => aws_sdk_dynamodb::types::IndexStatus::Deleting, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::ACTIVE {} => aws_sdk_dynamodb::types::IndexStatus::Active, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::CREATING {} => aws_sdk_dynamodb::types::IndexStatus::Creating, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::UPDATING {} => aws_sdk_dynamodb::types::IndexStatus::Updating, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::DELETING {} => aws_sdk_dynamodb::types::IndexStatus::Deleting, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::ACTIVE {} => aws_sdk_dynamodb::types::IndexStatus::Active, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/key_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/key_type.rs index ea86df5b0e..0d5d59c569 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/key_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/key_type.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::KeyType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::KeyType::Hash => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::HASH {}, -aws_sdk_dynamodb::types::KeyType::Range => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::RANGE {}, + aws_sdk_dynamodb::types::KeyType::Hash => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::HASH {}, + aws_sdk_dynamodb::types::KeyType::Range => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::RANGE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType, ) -> aws_sdk_dynamodb::types::KeyType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::HASH {} => aws_sdk_dynamodb::types::KeyType::Hash, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::RANGE {} => aws_sdk_dynamodb::types::KeyType::Range, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::HASH {} => aws_sdk_dynamodb::types::KeyType::Hash, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::RANGE {} => aws_sdk_dynamodb::types::KeyType::Range, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/projection_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/projection_type.rs index 28b89124fa..d242c07d48 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/projection_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/projection_type.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ProjectionType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ProjectionType::All => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::ALL {}, -aws_sdk_dynamodb::types::ProjectionType::KeysOnly => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::KEYS_ONLY {}, -aws_sdk_dynamodb::types::ProjectionType::Include => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::INCLUDE {}, + aws_sdk_dynamodb::types::ProjectionType::All => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::ALL {}, + aws_sdk_dynamodb::types::ProjectionType::KeysOnly => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::KEYS_ONLY {}, + aws_sdk_dynamodb::types::ProjectionType::Include => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::INCLUDE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType, ) -> aws_sdk_dynamodb::types::ProjectionType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::ALL {} => aws_sdk_dynamodb::types::ProjectionType::All, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::KEYS_ONLY {} => aws_sdk_dynamodb::types::ProjectionType::KeysOnly, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::INCLUDE {} => aws_sdk_dynamodb::types::ProjectionType::Include, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::ALL {} => aws_sdk_dynamodb::types::ProjectionType::All, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::KEYS_ONLY {} => aws_sdk_dynamodb::types::ProjectionType::KeysOnly, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::INCLUDE {} => aws_sdk_dynamodb::types::ProjectionType::Include, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/replica_status.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/replica_status.rs index fd626473a6..11e2638d48 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/replica_status.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/replica_status.rs @@ -7,13 +7,13 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReplicaStatus, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReplicaStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATING {}, -aws_sdk_dynamodb::types::ReplicaStatus::CreationFailed => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATION_FAILED {}, -aws_sdk_dynamodb::types::ReplicaStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::UPDATING {}, -aws_sdk_dynamodb::types::ReplicaStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::DELETING {}, -aws_sdk_dynamodb::types::ReplicaStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::ACTIVE {}, -aws_sdk_dynamodb::types::ReplicaStatus::RegionDisabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::REGION_DISABLED {}, -aws_sdk_dynamodb::types::ReplicaStatus::InaccessibleEncryptionCredentials => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {}, + aws_sdk_dynamodb::types::ReplicaStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATING {}, + aws_sdk_dynamodb::types::ReplicaStatus::CreationFailed => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATION_FAILED {}, + aws_sdk_dynamodb::types::ReplicaStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::UPDATING {}, + aws_sdk_dynamodb::types::ReplicaStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::DELETING {}, + aws_sdk_dynamodb::types::ReplicaStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::ACTIVE {}, + aws_sdk_dynamodb::types::ReplicaStatus::RegionDisabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::REGION_DISABLED {}, + aws_sdk_dynamodb::types::ReplicaStatus::InaccessibleEncryptionCredentials => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -22,12 +22,12 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus, ) -> aws_sdk_dynamodb::types::ReplicaStatus { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATING {} => aws_sdk_dynamodb::types::ReplicaStatus::Creating, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATION_FAILED {} => aws_sdk_dynamodb::types::ReplicaStatus::CreationFailed, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::UPDATING {} => aws_sdk_dynamodb::types::ReplicaStatus::Updating, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::DELETING {} => aws_sdk_dynamodb::types::ReplicaStatus::Deleting, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::ACTIVE {} => aws_sdk_dynamodb::types::ReplicaStatus::Active, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::REGION_DISABLED {} => aws_sdk_dynamodb::types::ReplicaStatus::RegionDisabled, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {} => aws_sdk_dynamodb::types::ReplicaStatus::InaccessibleEncryptionCredentials, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATING {} => aws_sdk_dynamodb::types::ReplicaStatus::Creating, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATION_FAILED {} => aws_sdk_dynamodb::types::ReplicaStatus::CreationFailed, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::UPDATING {} => aws_sdk_dynamodb::types::ReplicaStatus::Updating, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::DELETING {} => aws_sdk_dynamodb::types::ReplicaStatus::Deleting, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::ACTIVE {} => aws_sdk_dynamodb::types::ReplicaStatus::Active, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::REGION_DISABLED {} => aws_sdk_dynamodb::types::ReplicaStatus::RegionDisabled, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {} => aws_sdk_dynamodb::types::ReplicaStatus::InaccessibleEncryptionCredentials, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_consumed_capacity.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_consumed_capacity.rs index b2526611f3..fbfeeb4e61 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_consumed_capacity.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_consumed_capacity.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReturnConsumedCapacity, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReturnConsumedCapacity::Indexes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::INDEXES {}, -aws_sdk_dynamodb::types::ReturnConsumedCapacity::Total => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::TOTAL {}, -aws_sdk_dynamodb::types::ReturnConsumedCapacity::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::NONE {}, + aws_sdk_dynamodb::types::ReturnConsumedCapacity::Indexes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::INDEXES {}, + aws_sdk_dynamodb::types::ReturnConsumedCapacity::Total => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::TOTAL {}, + aws_sdk_dynamodb::types::ReturnConsumedCapacity::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::NONE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity, ) -> aws_sdk_dynamodb::types::ReturnConsumedCapacity { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::INDEXES {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::Indexes, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::TOTAL {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::Total, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::NONE {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::None, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::INDEXES {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::Indexes, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::TOTAL {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::Total, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::NONE {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::None, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_item_collection_metrics.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_item_collection_metrics.rs index 6857387303..0896dc4cd3 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_item_collection_metrics.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_item_collection_metrics.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReturnItemCollectionMetrics, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::Size => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::SIZE {}, -aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::NONE {}, + aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::Size => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::SIZE {}, + aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::NONE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics, ) -> aws_sdk_dynamodb::types::ReturnItemCollectionMetrics { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::SIZE {} => aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::Size, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::NONE {} => aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::None, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::SIZE {} => aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::Size, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::NONE {} => aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::None, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_value.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_value.rs index df8085df33..21983ab80f 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_value.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_value.rs @@ -7,11 +7,11 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReturnValue, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReturnValue::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::NONE {}, -aws_sdk_dynamodb::types::ReturnValue::AllOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_OLD {}, -aws_sdk_dynamodb::types::ReturnValue::UpdatedOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_OLD {}, -aws_sdk_dynamodb::types::ReturnValue::AllNew => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_NEW {}, -aws_sdk_dynamodb::types::ReturnValue::UpdatedNew => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_NEW {}, + aws_sdk_dynamodb::types::ReturnValue::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::NONE {}, + aws_sdk_dynamodb::types::ReturnValue::AllOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_OLD {}, + aws_sdk_dynamodb::types::ReturnValue::UpdatedOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_OLD {}, + aws_sdk_dynamodb::types::ReturnValue::AllNew => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_NEW {}, + aws_sdk_dynamodb::types::ReturnValue::UpdatedNew => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_NEW {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -20,10 +20,10 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue, ) -> aws_sdk_dynamodb::types::ReturnValue { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::NONE {} => aws_sdk_dynamodb::types::ReturnValue::None, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_OLD {} => aws_sdk_dynamodb::types::ReturnValue::AllOld, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_OLD {} => aws_sdk_dynamodb::types::ReturnValue::UpdatedOld, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_NEW {} => aws_sdk_dynamodb::types::ReturnValue::AllNew, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_NEW {} => aws_sdk_dynamodb::types::ReturnValue::UpdatedNew, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::NONE {} => aws_sdk_dynamodb::types::ReturnValue::None, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_OLD {} => aws_sdk_dynamodb::types::ReturnValue::AllOld, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_OLD {} => aws_sdk_dynamodb::types::ReturnValue::UpdatedOld, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_NEW {} => aws_sdk_dynamodb::types::ReturnValue::AllNew, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_NEW {} => aws_sdk_dynamodb::types::ReturnValue::UpdatedNew, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_values_on_condition_check_failure.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_values_on_condition_check_failure.rs index 7d3380d942..b185462326 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_values_on_condition_check_failure.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_values_on_condition_check_failure.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::AllOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::ALL_OLD {}, -aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::NONE {}, + aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::AllOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::ALL_OLD {}, + aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::NONE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure, ) -> aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::ALL_OLD {} => aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::AllOld, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::NONE {} => aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::None, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::ALL_OLD {} => aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::AllOld, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::NONE {} => aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::None, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/scalar_attribute_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/scalar_attribute_type.rs index f921f603f0..7a16ac8159 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/scalar_attribute_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/scalar_attribute_type.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ScalarAttributeType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ScalarAttributeType::S => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::S {}, -aws_sdk_dynamodb::types::ScalarAttributeType::N => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::N {}, -aws_sdk_dynamodb::types::ScalarAttributeType::B => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::B {}, + aws_sdk_dynamodb::types::ScalarAttributeType::S => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::S {}, + aws_sdk_dynamodb::types::ScalarAttributeType::N => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::N {}, + aws_sdk_dynamodb::types::ScalarAttributeType::B => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::B {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType, ) -> aws_sdk_dynamodb::types::ScalarAttributeType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::S {} => aws_sdk_dynamodb::types::ScalarAttributeType::S, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::N {} => aws_sdk_dynamodb::types::ScalarAttributeType::N, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::B {} => aws_sdk_dynamodb::types::ScalarAttributeType::B, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::S {} => aws_sdk_dynamodb::types::ScalarAttributeType::S, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::N {} => aws_sdk_dynamodb::types::ScalarAttributeType::N, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::B {} => aws_sdk_dynamodb::types::ScalarAttributeType::B, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/select.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/select.rs index c52b7a634b..52afedb1c3 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/select.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/select.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::Select, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::Select::AllAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_ATTRIBUTES {}, -aws_sdk_dynamodb::types::Select::AllProjectedAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_PROJECTED_ATTRIBUTES {}, -aws_sdk_dynamodb::types::Select::SpecificAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::SPECIFIC_ATTRIBUTES {}, -aws_sdk_dynamodb::types::Select::Count => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::COUNT {}, + aws_sdk_dynamodb::types::Select::AllAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_ATTRIBUTES {}, + aws_sdk_dynamodb::types::Select::AllProjectedAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_PROJECTED_ATTRIBUTES {}, + aws_sdk_dynamodb::types::Select::SpecificAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::SPECIFIC_ATTRIBUTES {}, + aws_sdk_dynamodb::types::Select::Count => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::COUNT {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select, ) -> aws_sdk_dynamodb::types::Select { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::AllAttributes, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_PROJECTED_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::AllProjectedAttributes, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::SPECIFIC_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::SpecificAttributes, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::COUNT {} => aws_sdk_dynamodb::types::Select::Count, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::AllAttributes, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_PROJECTED_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::AllProjectedAttributes, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::SPECIFIC_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::SpecificAttributes, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::COUNT {} => aws_sdk_dynamodb::types::Select::Count, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_status.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_status.rs index a4f20bf1cf..fd0a2e7a4b 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_status.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_status.rs @@ -7,11 +7,11 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::SseStatus, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::SseStatus::Enabling => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLING {}, -aws_sdk_dynamodb::types::SseStatus::Enabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLED {}, -aws_sdk_dynamodb::types::SseStatus::Disabling => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLING {}, -aws_sdk_dynamodb::types::SseStatus::Disabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLED {}, -aws_sdk_dynamodb::types::SseStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::UPDATING {}, + aws_sdk_dynamodb::types::SseStatus::Enabling => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLING {}, + aws_sdk_dynamodb::types::SseStatus::Enabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLED {}, + aws_sdk_dynamodb::types::SseStatus::Disabling => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLING {}, + aws_sdk_dynamodb::types::SseStatus::Disabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLED {}, + aws_sdk_dynamodb::types::SseStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::UPDATING {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -20,10 +20,10 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus, ) -> aws_sdk_dynamodb::types::SseStatus { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLING {} => aws_sdk_dynamodb::types::SseStatus::Enabling, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLED {} => aws_sdk_dynamodb::types::SseStatus::Enabled, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLING {} => aws_sdk_dynamodb::types::SseStatus::Disabling, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLED {} => aws_sdk_dynamodb::types::SseStatus::Disabled, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::UPDATING {} => aws_sdk_dynamodb::types::SseStatus::Updating, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLING {} => aws_sdk_dynamodb::types::SseStatus::Enabling, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLED {} => aws_sdk_dynamodb::types::SseStatus::Enabled, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLING {} => aws_sdk_dynamodb::types::SseStatus::Disabling, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLED {} => aws_sdk_dynamodb::types::SseStatus::Disabled, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::UPDATING {} => aws_sdk_dynamodb::types::SseStatus::Updating, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_type.rs index 56f69062bc..6a6dfd122e 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_type.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::SseType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::SseType::Aes256 => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::AES256 {}, -aws_sdk_dynamodb::types::SseType::Kms => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::KMS {}, + aws_sdk_dynamodb::types::SseType::Aes256 => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::AES256 {}, + aws_sdk_dynamodb::types::SseType::Kms => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::KMS {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType, ) -> aws_sdk_dynamodb::types::SseType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::AES256 {} => aws_sdk_dynamodb::types::SseType::Aes256, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::KMS {} => aws_sdk_dynamodb::types::SseType::Kms, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::AES256 {} => aws_sdk_dynamodb::types::SseType::Aes256, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::KMS {} => aws_sdk_dynamodb::types::SseType::Kms, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/stream_view_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/stream_view_type.rs index 718b38e764..df3a0c2b7b 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/stream_view_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/stream_view_type.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::StreamViewType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::StreamViewType::NewImage => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_IMAGE {}, -aws_sdk_dynamodb::types::StreamViewType::OldImage => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::OLD_IMAGE {}, -aws_sdk_dynamodb::types::StreamViewType::NewAndOldImages => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_AND_OLD_IMAGES {}, -aws_sdk_dynamodb::types::StreamViewType::KeysOnly => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::KEYS_ONLY {}, + aws_sdk_dynamodb::types::StreamViewType::NewImage => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_IMAGE {}, + aws_sdk_dynamodb::types::StreamViewType::OldImage => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::OLD_IMAGE {}, + aws_sdk_dynamodb::types::StreamViewType::NewAndOldImages => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_AND_OLD_IMAGES {}, + aws_sdk_dynamodb::types::StreamViewType::KeysOnly => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::KEYS_ONLY {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType, ) -> aws_sdk_dynamodb::types::StreamViewType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_IMAGE {} => aws_sdk_dynamodb::types::StreamViewType::NewImage, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::OLD_IMAGE {} => aws_sdk_dynamodb::types::StreamViewType::OldImage, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_AND_OLD_IMAGES {} => aws_sdk_dynamodb::types::StreamViewType::NewAndOldImages, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::KEYS_ONLY {} => aws_sdk_dynamodb::types::StreamViewType::KeysOnly, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_IMAGE {} => aws_sdk_dynamodb::types::StreamViewType::NewImage, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::OLD_IMAGE {} => aws_sdk_dynamodb::types::StreamViewType::OldImage, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_AND_OLD_IMAGES {} => aws_sdk_dynamodb::types::StreamViewType::NewAndOldImages, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::KEYS_ONLY {} => aws_sdk_dynamodb::types::StreamViewType::KeysOnly, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_class.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_class.rs index f0a717fc91..dba3a71daa 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_class.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_class.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::TableClass, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::TableClass::Standard => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD {}, -aws_sdk_dynamodb::types::TableClass::StandardInfrequentAccess => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD_INFREQUENT_ACCESS {}, + aws_sdk_dynamodb::types::TableClass::Standard => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD {}, + aws_sdk_dynamodb::types::TableClass::StandardInfrequentAccess => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD_INFREQUENT_ACCESS {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass, ) -> aws_sdk_dynamodb::types::TableClass { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD {} => aws_sdk_dynamodb::types::TableClass::Standard, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD_INFREQUENT_ACCESS {} => aws_sdk_dynamodb::types::TableClass::StandardInfrequentAccess, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD {} => aws_sdk_dynamodb::types::TableClass::Standard, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD_INFREQUENT_ACCESS {} => aws_sdk_dynamodb::types::TableClass::StandardInfrequentAccess, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_status.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_status.rs index e996bc8805..444e0c5411 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_status.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_status.rs @@ -7,13 +7,13 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::TableStatus, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::TableStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::CREATING {}, -aws_sdk_dynamodb::types::TableStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::UPDATING {}, -aws_sdk_dynamodb::types::TableStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::DELETING {}, -aws_sdk_dynamodb::types::TableStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ACTIVE {}, -aws_sdk_dynamodb::types::TableStatus::InaccessibleEncryptionCredentials => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {}, -aws_sdk_dynamodb::types::TableStatus::Archiving => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVING {}, -aws_sdk_dynamodb::types::TableStatus::Archived => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVED {}, + aws_sdk_dynamodb::types::TableStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::CREATING {}, + aws_sdk_dynamodb::types::TableStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::UPDATING {}, + aws_sdk_dynamodb::types::TableStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::DELETING {}, + aws_sdk_dynamodb::types::TableStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ACTIVE {}, + aws_sdk_dynamodb::types::TableStatus::InaccessibleEncryptionCredentials => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {}, + aws_sdk_dynamodb::types::TableStatus::Archiving => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVING {}, + aws_sdk_dynamodb::types::TableStatus::Archived => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVED {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -22,12 +22,12 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus, ) -> aws_sdk_dynamodb::types::TableStatus { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::CREATING {} => aws_sdk_dynamodb::types::TableStatus::Creating, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::UPDATING {} => aws_sdk_dynamodb::types::TableStatus::Updating, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::DELETING {} => aws_sdk_dynamodb::types::TableStatus::Deleting, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ACTIVE {} => aws_sdk_dynamodb::types::TableStatus::Active, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {} => aws_sdk_dynamodb::types::TableStatus::InaccessibleEncryptionCredentials, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVING {} => aws_sdk_dynamodb::types::TableStatus::Archiving, -crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVED {} => aws_sdk_dynamodb::types::TableStatus::Archived, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::CREATING {} => aws_sdk_dynamodb::types::TableStatus::Creating, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::UPDATING {} => aws_sdk_dynamodb::types::TableStatus::Updating, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::DELETING {} => aws_sdk_dynamodb::types::TableStatus::Deleting, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ACTIVE {} => aws_sdk_dynamodb::types::TableStatus::Active, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {} => aws_sdk_dynamodb::types::TableStatus::InaccessibleEncryptionCredentials, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVING {} => aws_sdk_dynamodb::types::TableStatus::Archiving, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVED {} => aws_sdk_dynamodb::types::TableStatus::Archived, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/standard_library_externs.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/customer_master_key_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/customer_master_key_spec.rs index d00e07390b..3115f64a3a 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/customer_master_key_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/customer_master_key_spec.rs @@ -7,19 +7,19 @@ pub fn to_dafny( value: aws_sdk_kms::types::CustomerMasterKeySpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::CustomerMasterKeySpec::Rsa2048 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_2048 {}, -aws_sdk_kms::types::CustomerMasterKeySpec::Rsa3072 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_3072 {}, -aws_sdk_kms::types::CustomerMasterKeySpec::Rsa4096 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_4096 {}, -aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P256 {}, -aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P384 {}, -aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP521 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P521 {}, -aws_sdk_kms::types::CustomerMasterKeySpec::EccSecgP256K1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_SECG_P256K1 {}, -aws_sdk_kms::types::CustomerMasterKeySpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SYMMETRIC_DEFAULT {}, -aws_sdk_kms::types::CustomerMasterKeySpec::Hmac224 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_224 {}, -aws_sdk_kms::types::CustomerMasterKeySpec::Hmac256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_256 {}, -aws_sdk_kms::types::CustomerMasterKeySpec::Hmac384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_384 {}, -aws_sdk_kms::types::CustomerMasterKeySpec::Hmac512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_512 {}, -aws_sdk_kms::types::CustomerMasterKeySpec::Sm2 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SM2 {}, + aws_sdk_kms::types::CustomerMasterKeySpec::Rsa2048 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_2048 {}, + aws_sdk_kms::types::CustomerMasterKeySpec::Rsa3072 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_3072 {}, + aws_sdk_kms::types::CustomerMasterKeySpec::Rsa4096 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_4096 {}, + aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P256 {}, + aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P384 {}, + aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP521 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P521 {}, + aws_sdk_kms::types::CustomerMasterKeySpec::EccSecgP256K1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_SECG_P256K1 {}, + aws_sdk_kms::types::CustomerMasterKeySpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SYMMETRIC_DEFAULT {}, + aws_sdk_kms::types::CustomerMasterKeySpec::Hmac224 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_224 {}, + aws_sdk_kms::types::CustomerMasterKeySpec::Hmac256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_256 {}, + aws_sdk_kms::types::CustomerMasterKeySpec::Hmac384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_384 {}, + aws_sdk_kms::types::CustomerMasterKeySpec::Hmac512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_512 {}, + aws_sdk_kms::types::CustomerMasterKeySpec::Sm2 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SM2 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -28,18 +28,18 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec, ) -> aws_sdk_kms::types::CustomerMasterKeySpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_2048 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa2048, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_3072 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa3072, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_4096 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa4096, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P256 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP256, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P384 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP384, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P521 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP521, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_SECG_P256K1 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccSecgP256K1, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::CustomerMasterKeySpec::SymmetricDefault, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_224 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac224, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_256 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac256, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_384 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac384, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_512 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac512, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SM2 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Sm2, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_2048 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa2048, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_3072 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa3072, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_4096 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa4096, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P256 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP256, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P384 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP384, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P521 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP521, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_SECG_P256K1 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccSecgP256K1, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::CustomerMasterKeySpec::SymmetricDefault, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_224 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac224, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_256 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac256, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_384 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac384, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_512 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac512, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SM2 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Sm2, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/data_key_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/data_key_spec.rs index f26b83c132..aa96da51cb 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/data_key_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/data_key_spec.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_kms::types::DataKeySpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::DataKeySpec::Aes256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_256 {}, -aws_sdk_kms::types::DataKeySpec::Aes128 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_128 {}, + aws_sdk_kms::types::DataKeySpec::Aes256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_256 {}, + aws_sdk_kms::types::DataKeySpec::Aes128 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_128 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec, ) -> aws_sdk_kms::types::DataKeySpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_256 {} => aws_sdk_kms::types::DataKeySpec::Aes256, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_128 {} => aws_sdk_kms::types::DataKeySpec::Aes128, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_256 {} => aws_sdk_kms::types::DataKeySpec::Aes256, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_128 {} => aws_sdk_kms::types::DataKeySpec::Aes128, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/encryption_algorithm_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/encryption_algorithm_spec.rs index af802a8f42..8cc859bad9 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/encryption_algorithm_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/encryption_algorithm_spec.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_kms::types::EncryptionAlgorithmSpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::EncryptionAlgorithmSpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::SYMMETRIC_DEFAULT {}, -aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_1 {}, -aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_256 {}, + aws_sdk_kms::types::EncryptionAlgorithmSpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::SYMMETRIC_DEFAULT {}, + aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_1 {}, + aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_256 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec, ) -> aws_sdk_kms::types::EncryptionAlgorithmSpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::SymmetricDefault, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_1 {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha1, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_256 {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::SymmetricDefault, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_1 {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha1, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_256 {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_agreement_algorithm_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_agreement_algorithm_spec.rs index 1693266fff..ab964fd2f7 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_agreement_algorithm_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_agreement_algorithm_spec.rs @@ -7,7 +7,7 @@ pub fn to_dafny( value: aws_sdk_kms::types::KeyAgreementAlgorithmSpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::KeyAgreementAlgorithmSpec::Ecdh => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec::ECDH {}, + aws_sdk_kms::types::KeyAgreementAlgorithmSpec::Ecdh => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec::ECDH {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -16,6 +16,6 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec, ) -> aws_sdk_kms::types::KeyAgreementAlgorithmSpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec::ECDH {} => aws_sdk_kms::types::KeyAgreementAlgorithmSpec::Ecdh, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec::ECDH {} => aws_sdk_kms::types::KeyAgreementAlgorithmSpec::Ecdh, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_encryption_mechanism.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_encryption_mechanism.rs index 80c4b4d9b9..1dd9d0e9d8 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_encryption_mechanism.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_encryption_mechanism.rs @@ -7,7 +7,7 @@ pub fn to_dafny( value: aws_sdk_kms::types::KeyEncryptionMechanism, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::KeyEncryptionMechanism::RsaesOaepSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism::RSAES_OAEP_SHA_256 {}, + aws_sdk_kms::types::KeyEncryptionMechanism::RsaesOaepSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism::RSAES_OAEP_SHA_256 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -16,6 +16,6 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism, ) -> aws_sdk_kms::types::KeyEncryptionMechanism { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism::RSAES_OAEP_SHA_256 {} => aws_sdk_kms::types::KeyEncryptionMechanism::RsaesOaepSha256, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism::RSAES_OAEP_SHA_256 {} => aws_sdk_kms::types::KeyEncryptionMechanism::RsaesOaepSha256, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_spec.rs index 14c6136fc9..66ae3f0dc7 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_spec.rs @@ -7,19 +7,19 @@ pub fn to_dafny( value: aws_sdk_kms::types::KeySpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::KeySpec::Rsa2048 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_2048 {}, -aws_sdk_kms::types::KeySpec::Rsa3072 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_3072 {}, -aws_sdk_kms::types::KeySpec::Rsa4096 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_4096 {}, -aws_sdk_kms::types::KeySpec::EccNistP256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P256 {}, -aws_sdk_kms::types::KeySpec::EccNistP384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P384 {}, -aws_sdk_kms::types::KeySpec::EccNistP521 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P521 {}, -aws_sdk_kms::types::KeySpec::EccSecgP256K1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_SECG_P256K1 {}, -aws_sdk_kms::types::KeySpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SYMMETRIC_DEFAULT {}, -aws_sdk_kms::types::KeySpec::Hmac224 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_224 {}, -aws_sdk_kms::types::KeySpec::Hmac256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_256 {}, -aws_sdk_kms::types::KeySpec::Hmac384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_384 {}, -aws_sdk_kms::types::KeySpec::Hmac512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_512 {}, -aws_sdk_kms::types::KeySpec::Sm2 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SM2 {}, + aws_sdk_kms::types::KeySpec::Rsa2048 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_2048 {}, + aws_sdk_kms::types::KeySpec::Rsa3072 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_3072 {}, + aws_sdk_kms::types::KeySpec::Rsa4096 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_4096 {}, + aws_sdk_kms::types::KeySpec::EccNistP256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P256 {}, + aws_sdk_kms::types::KeySpec::EccNistP384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P384 {}, + aws_sdk_kms::types::KeySpec::EccNistP521 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P521 {}, + aws_sdk_kms::types::KeySpec::EccSecgP256K1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_SECG_P256K1 {}, + aws_sdk_kms::types::KeySpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SYMMETRIC_DEFAULT {}, + aws_sdk_kms::types::KeySpec::Hmac224 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_224 {}, + aws_sdk_kms::types::KeySpec::Hmac256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_256 {}, + aws_sdk_kms::types::KeySpec::Hmac384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_384 {}, + aws_sdk_kms::types::KeySpec::Hmac512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_512 {}, + aws_sdk_kms::types::KeySpec::Sm2 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SM2 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -28,18 +28,18 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec, ) -> aws_sdk_kms::types::KeySpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_2048 {} => aws_sdk_kms::types::KeySpec::Rsa2048, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_3072 {} => aws_sdk_kms::types::KeySpec::Rsa3072, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_4096 {} => aws_sdk_kms::types::KeySpec::Rsa4096, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P256 {} => aws_sdk_kms::types::KeySpec::EccNistP256, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P384 {} => aws_sdk_kms::types::KeySpec::EccNistP384, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P521 {} => aws_sdk_kms::types::KeySpec::EccNistP521, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_SECG_P256K1 {} => aws_sdk_kms::types::KeySpec::EccSecgP256K1, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::KeySpec::SymmetricDefault, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_224 {} => aws_sdk_kms::types::KeySpec::Hmac224, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_256 {} => aws_sdk_kms::types::KeySpec::Hmac256, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_384 {} => aws_sdk_kms::types::KeySpec::Hmac384, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_512 {} => aws_sdk_kms::types::KeySpec::Hmac512, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SM2 {} => aws_sdk_kms::types::KeySpec::Sm2, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_2048 {} => aws_sdk_kms::types::KeySpec::Rsa2048, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_3072 {} => aws_sdk_kms::types::KeySpec::Rsa3072, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_4096 {} => aws_sdk_kms::types::KeySpec::Rsa4096, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P256 {} => aws_sdk_kms::types::KeySpec::EccNistP256, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P384 {} => aws_sdk_kms::types::KeySpec::EccNistP384, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P521 {} => aws_sdk_kms::types::KeySpec::EccNistP521, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_SECG_P256K1 {} => aws_sdk_kms::types::KeySpec::EccSecgP256K1, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::KeySpec::SymmetricDefault, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_224 {} => aws_sdk_kms::types::KeySpec::Hmac224, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_256 {} => aws_sdk_kms::types::KeySpec::Hmac256, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_384 {} => aws_sdk_kms::types::KeySpec::Hmac384, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_512 {} => aws_sdk_kms::types::KeySpec::Hmac512, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SM2 {} => aws_sdk_kms::types::KeySpec::Sm2, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_usage_type.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_usage_type.rs index 8d2db6b3ca..fdf182c6dd 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_usage_type.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_usage_type.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_kms::types::KeyUsageType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::KeyUsageType::SignVerify => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::SIGN_VERIFY {}, -aws_sdk_kms::types::KeyUsageType::EncryptDecrypt => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::ENCRYPT_DECRYPT {}, -aws_sdk_kms::types::KeyUsageType::GenerateVerifyMac => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::GENERATE_VERIFY_MAC {}, -aws_sdk_kms::types::KeyUsageType::KeyAgreement => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::KEY_AGREEMENT {}, + aws_sdk_kms::types::KeyUsageType::SignVerify => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::SIGN_VERIFY {}, + aws_sdk_kms::types::KeyUsageType::EncryptDecrypt => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::ENCRYPT_DECRYPT {}, + aws_sdk_kms::types::KeyUsageType::GenerateVerifyMac => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::GENERATE_VERIFY_MAC {}, + aws_sdk_kms::types::KeyUsageType::KeyAgreement => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::KEY_AGREEMENT {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType, ) -> aws_sdk_kms::types::KeyUsageType { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::SIGN_VERIFY {} => aws_sdk_kms::types::KeyUsageType::SignVerify, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::ENCRYPT_DECRYPT {} => aws_sdk_kms::types::KeyUsageType::EncryptDecrypt, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::GENERATE_VERIFY_MAC {} => aws_sdk_kms::types::KeyUsageType::GenerateVerifyMac, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::KEY_AGREEMENT {} => aws_sdk_kms::types::KeyUsageType::KeyAgreement, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::SIGN_VERIFY {} => aws_sdk_kms::types::KeyUsageType::SignVerify, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::ENCRYPT_DECRYPT {} => aws_sdk_kms::types::KeyUsageType::EncryptDecrypt, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::GENERATE_VERIFY_MAC {} => aws_sdk_kms::types::KeyUsageType::GenerateVerifyMac, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::KEY_AGREEMENT {} => aws_sdk_kms::types::KeyUsageType::KeyAgreement, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/origin_type.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/origin_type.rs index 8878e10fa2..79b60c37bd 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/origin_type.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/origin_type.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_kms::types::OriginType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::OriginType::AwsKms => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_KMS {}, -aws_sdk_kms::types::OriginType::External => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL {}, -aws_sdk_kms::types::OriginType::AwsCloudhsm => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_CLOUDHSM {}, -aws_sdk_kms::types::OriginType::ExternalKeyStore => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL_KEY_STORE {}, + aws_sdk_kms::types::OriginType::AwsKms => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_KMS {}, + aws_sdk_kms::types::OriginType::External => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL {}, + aws_sdk_kms::types::OriginType::AwsCloudhsm => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_CLOUDHSM {}, + aws_sdk_kms::types::OriginType::ExternalKeyStore => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL_KEY_STORE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType, ) -> aws_sdk_kms::types::OriginType { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_KMS {} => aws_sdk_kms::types::OriginType::AwsKms, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL {} => aws_sdk_kms::types::OriginType::External, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_CLOUDHSM {} => aws_sdk_kms::types::OriginType::AwsCloudhsm, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL_KEY_STORE {} => aws_sdk_kms::types::OriginType::ExternalKeyStore, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_KMS {} => aws_sdk_kms::types::OriginType::AwsKms, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL {} => aws_sdk_kms::types::OriginType::External, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_CLOUDHSM {} => aws_sdk_kms::types::OriginType::AwsCloudhsm, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL_KEY_STORE {} => aws_sdk_kms::types::OriginType::ExternalKeyStore, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/signing_algorithm_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/signing_algorithm_spec.rs index 4fcc04f841..bc9cbeb90b 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/signing_algorithm_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/signing_algorithm_spec.rs @@ -7,16 +7,16 @@ pub fn to_dafny( value: aws_sdk_kms::types::SigningAlgorithmSpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_256 {}, -aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_384 {}, -aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_512 {}, -aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_256 {}, -aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_384 {}, -aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_512 {}, -aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_256 {}, -aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_384 {}, -aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_512 {}, -aws_sdk_kms::types::SigningAlgorithmSpec::Sm2Dsa => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::SM2DSA {}, + aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_256 {}, + aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_384 {}, + aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_512 {}, + aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_256 {}, + aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_384 {}, + aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_512 {}, + aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_256 {}, + aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_384 {}, + aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_512 {}, + aws_sdk_kms::types::SigningAlgorithmSpec::Sm2Dsa => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::SM2DSA {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -25,15 +25,15 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec, ) -> aws_sdk_kms::types::SigningAlgorithmSpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha256, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha384, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha512, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha256, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha384, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha512, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha256, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha384, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha512, -crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::SM2DSA {} => aws_sdk_kms::types::SigningAlgorithmSpec::Sm2Dsa, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha256, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha384, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha512, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha256, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha384, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha512, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha256, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha384, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha512, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::SM2DSA {} => aws_sdk_kms::types::SigningAlgorithmSpec::Sm2Dsa, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/standard_library_externs.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/codegen/smithy-dafny-codegen-cli/src/main/java/software/amazon/polymorph/CodegenCli.java b/codegen/smithy-dafny-codegen-cli/src/main/java/software/amazon/polymorph/CodegenCli.java index 4e12ab1308..253f589759 100644 --- a/codegen/smithy-dafny-codegen-cli/src/main/java/software/amazon/polymorph/CodegenCli.java +++ b/codegen/smithy-dafny-codegen-cli/src/main/java/software/amazon/polymorph/CodegenCli.java @@ -21,11 +21,13 @@ import org.apache.commons.cli.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + +import software.amazon.smithy.model.Model; +import software.amazon.smithy.model.loader.ModelAssembler; + import software.amazon.polymorph.CodegenEngine.TargetLanguage; import software.amazon.polymorph.smithydafny.DafnyVersion; import software.amazon.polymorph.smithyjava.generator.CodegenSubject.AwsSdkVersion; -import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.loader.ModelAssembler; import software.amazon.smithy.model.validation.ValidatedResult; import software.amazon.smithy.model.validation.ValidationEvent; @@ -233,12 +235,12 @@ private static Options getCliOptionsForBuild() { .build() ) .addOption( - Option - .builder() - .longOpt("output-go") - .desc(" output directory for generated Go files") - .hasArg() - .build() + Option + .builder() + .longOpt("output-go") + .desc(" output directory for generated Go files") + .hasArg() + .build() ) .addOption( Option @@ -352,7 +354,8 @@ private static Options getCliOptionsForBuild() { .valueSeparator(',') .build() ); - } + } + private static Options getCliOptionsForPatchAfterTranspile() { return new Options() @@ -554,8 +557,8 @@ static Optional parse(String[] args) throws ParseException { .ofNullable(commandLine.getOptionValue("output-dotnet")) .map(Paths::get); final Optional outputGoDir = Optional - .ofNullable(commandLine.getOptionValue("output-go")) - .map(Paths::get); + .ofNullable(commandLine.getOptionValue("output-go")) + .map(Paths::get); final Optional outputRustDir = Optional .ofNullable(commandLine.getOptionValue("output-rust")) .map(Paths::get); diff --git a/codegen/smithy-dafny-codegen-test/src/test/java/software/amazon/polymorph/smithygo/GoTestModels.java b/codegen/smithy-dafny-codegen-test/src/test/java/software/amazon/polymorph/smithygo/GoTestModels.java deleted file mode 100644 index 07bf4bce64..0000000000 --- a/codegen/smithy-dafny-codegen-test/src/test/java/software/amazon/polymorph/smithygo/GoTestModels.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package software.amazon.polymorph.smithygo; - -import java.nio.file.Path; -import java.util.HashSet; -import java.util.Set; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; -import software.amazon.polymorph.TestModelTest; - -class GoTestModels extends TestModelTest { - - private static final Set DISABLED_TESTS = new HashSet<>(); - - static { - DISABLED_TESTS.add("AggregateReferences"); - DISABLED_TESTS.add("LanguageSpecificLogic"); - DISABLED_TESTS.add("SimpleTypes/BigDecimal"); - DISABLED_TESTS.add("SimpleTypes/BigInteger"); - DISABLED_TESTS.add("SimpleTypes/SimpleByte"); - DISABLED_TESTS.add("SimpleTypes/SimpleFloat"); - DISABLED_TESTS.add("SimpleTypes/SimpleShort"); - DISABLED_TESTS.add("SimpleTypes/SimpleTimestamp"); - DISABLED_TESTS.add("aws-sdks/ddb-lite"); - DISABLED_TESTS.add("aws-sdks/glue"); - DISABLED_TESTS.add("aws-sdks/lakeformation"); - DISABLED_TESTS.add("aws-sdks/kms-lite"); - DISABLED_TESTS.add("aws-sdks/sqs"); - DISABLED_TESTS.add("aws-sdks/sqs-via-cli"); - } - - @ParameterizedTest - @MethodSource("discoverTestModels") - void testModelsForJava(String relativeTestModelPath) { - Assumptions.assumeFalse(DISABLED_TESTS.contains(relativeTestModelPath)); - - Path testModelPath = getTestModelPath(relativeTestModelPath); - make(testModelPath, "setup_prettier"); - make(testModelPath, "polymorph_dafny"); - make(testModelPath, "polymorph_go"); - make(testModelPath, "transpile_go"); - make(testModelPath, "test_go"); - } -} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java index e3a234f9f3..ccd4bec72d 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java @@ -43,7 +43,6 @@ import software.amazon.polymorph.smithydotnet.localServiceWrapper.LocalServiceWrappedConversionCodegen; import software.amazon.polymorph.smithydotnet.localServiceWrapper.LocalServiceWrappedShimCodegen; import software.amazon.polymorph.smithygo.awssdk.DafnyGoAwsSdkClientCodegenPlugin; -import software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceCodegenPlugin; import software.amazon.polymorph.smithyjava.generator.CodegenSubject.AwsSdkVersion; import software.amazon.polymorph.smithyjava.generator.awssdk.v1.JavaAwsSdkV1; import software.amazon.polymorph.smithyjava.generator.awssdk.v2.JavaAwsSdkV2; @@ -67,6 +66,7 @@ import software.amazon.smithy.model.node.ObjectNode; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.utils.IoUtils; +import software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceCodegenPlugin; import software.amazon.smithy.utils.Pair; public class CodegenEngine { @@ -246,7 +246,15 @@ private void generateDafny(final Path outputDir) { dafnyOtherGeneratedAspects(outputDir); - formatDafnyCode(outputDir); + LOGGER.info("Formatting Dafny code in {}", outputDir); + runCommand( + outputDir, + "dafny", + "format", + "--function-syntax:3", + "--unicode-char:false", + "." + ); handlePatching(TargetLanguage.DAFNY, outputDir); } @@ -307,29 +315,16 @@ private void dafnyOtherGeneratedAspects(final Path outputDir) { // Perhaps we can make a `smithy init` template for that instead? if (!generationAspects.isEmpty()) { - formatDafnyCode(outputDir.resolve("../src")); - } - } - - /** - * Formats the Dafny code in the given path using {@code dafny format}, - * but does not throw an exception if the command fails. - *

- * This enables generating interdependent Dafny files - * across multiple smithy-dafny-codegen invocations. - */ - private void formatDafnyCode(final Path path) { - LOGGER.info("Formatting Dafny code in {}", path); - final CommandResult formatResult = runCommand( - path, - "dafny", - "format", - "--function-syntax:3", - "--unicode-char:false", - "." - ); - if (formatResult.exitCode != 0) { - LOGGER.warn("Formatting failed:\n{}", formatResult.output); + Path srcDir = outputDir.resolve("../src"); + LOGGER.info("Formatting Dafny code in {}", srcDir); + runCommand( + srcDir, + "dafny", + "format", + "--function-syntax:3", + "--unicode-char:false", + "." + ); } } @@ -365,7 +360,7 @@ private void generateJava(final Path outputDir, final Path testOutputDir) { javaOtherGeneratedAspects(); LOGGER.info("Formatting Java code in {}", outputDir); - runCommandOrThrow( + runCommand( outputDir, "npm", "i", @@ -373,7 +368,7 @@ private void generateJava(final Path outputDir, final Path testOutputDir) { "prettier@3", "prettier-plugin-java@2.5" ); - runCommandOrThrow( + runCommand( outputDir, "npx", "prettier@3", @@ -549,7 +544,7 @@ private void generateDotnet(final Path outputDir) { .filter(path -> path.toFile().getName().endsWith(".csproj")) .map(Path::toString) ); - runCommandOrThrow(dotnetRoot, args.toArray(String[]::new)); + runCommand(dotnetRoot, args.toArray(String[]::new)); } catch (IOException e) { throw new RuntimeException(e); } @@ -726,17 +721,13 @@ private void generateRust(final Path outputDir) { generator.generate(outputDir); } - // TODO: These should be part of the StandardLibrary instead, + // TODO: This should be part of the StandardLibrary instead, // but since the Dafny Rust code generator doesn't yet support multiple crates, // we have to inline it instead. writeTemplatedFile( "runtimes/rust/src/standard_library_conversions.rs", Map.of() ); - writeTemplatedFile( - "runtimes/rust/src/standard_library_externs.rs", - Map.of() - ); handlePatching(TargetLanguage.RUST, outputDir); } @@ -774,14 +765,13 @@ private void handlePatching(TargetLanguage targetLanguage, Path outputDir) { ); Path outputDirRelative = libraryRoot.relativize(outputDir); // Need to ignore the exit code because diff will return 1 if there is a diff - String patchContent = runCommand( + String patchContent = runCommandIgnoringExitCode( libraryRoot, "git", "diff", "-R", outputDirRelative.toString() - ) - .output; + ); if (!patchContent.isBlank()) { IOUtils.writeToFile(patchContent, patchFile.toFile()); } @@ -797,13 +787,7 @@ private void handlePatching(TargetLanguage targetLanguage, Path outputDir) { if (dafnyVersion.compareTo(patchFilePair.getKey()) >= 0) { Path patchFile = patchFilePair.getValue(); LOGGER.info("Applying patch file {}", patchFile); - runCommandOrThrow( - libraryRoot, - "git", - "apply", - "-v", - patchFile.toString() - ); + runCommand(libraryRoot, "git", "apply", "-v", patchFile.toString()); return; } } @@ -815,36 +799,25 @@ private void handlePatching(TargetLanguage targetLanguage, Path outputDir) { private void generateGo() { if (libraryName.isEmpty()) { - throw new IllegalArgumentException("Go codegen requires a library name"); + throw new IllegalArgumentException("Python codegen requires a module name"); } - ObjectNode.Builder goSettingsBuilder = ObjectNode - .builder() - .withMember("service", serviceShape.getId().toString()) - .withMember("moduleName", libraryName.get()); + ObjectNode.Builder goSettingsBuilder = ObjectNode.builder() + .withMember("service", serviceShape.getId().toString()) + .withMember("moduleName", libraryName.get()); - final PluginContext pluginContext = PluginContext - .builder() - .model(model) - .fileManifest( - FileManifest.create(targetLangOutputDirs.get(TargetLanguage.GO)) - ) - .settings(goSettingsBuilder.build()) - .build(); + final PluginContext pluginContext = PluginContext.builder() + .model(model) + .fileManifest(FileManifest.create(targetLangOutputDirs.get(TargetLanguage.GO))) + .settings(goSettingsBuilder.build()) + .build(); - final Map smithyNamespaceToGoModuleNameMap = new HashMap<>( - dependencyLibraryNames - ); - smithyNamespaceToGoModuleNameMap.put( - serviceShape.getId().getNamespace(), - libraryName.get() - ); + final Map smithyNamespaceToGoModuleNameMap = new HashMap<>(dependencyLibraryNames); + smithyNamespaceToGoModuleNameMap.put(serviceShape.getId().getNamespace(), libraryName.get()); if (this.awsSdkStyle) { - new DafnyGoAwsSdkClientCodegenPlugin(smithyNamespaceToGoModuleNameMap) - .run(pluginContext); + new DafnyGoAwsSdkClientCodegenPlugin(smithyNamespaceToGoModuleNameMap).run(pluginContext); } else { - new DafnyLocalServiceCodegenPlugin(smithyNamespaceToGoModuleNameMap) - .run(pluginContext); + new DafnyLocalServiceCodegenPlugin(smithyNamespaceToGoModuleNameMap).run(pluginContext); } } @@ -968,10 +941,7 @@ private String extraDeclarationsForLocalService() { pub mod operation; mod conversions; - - /// Copied from StandardLibrary mod standard_library_conversions; - mod standard_library_externs; #[cfg(feature = "wrapped-client")] pub mod wrapped; @@ -989,34 +959,26 @@ private String extraDeclarationsForLocalService() { ); } - private record CommandResult(int exitCode, String output) {} - - /** - * Runs the given command and throws an exception if the exit code is nonzero. - */ - private String runCommandOrThrow(Path workingDir, String... args) { - final CommandResult result = runCommand(workingDir, args); - if (result.exitCode != 0) { - throw new RuntimeException( - "Command failed: " + List.of(args) + "\n" + result.output - ); - } - return result.output; - } - - /** - * Runs the given command. - */ - private CommandResult runCommand(Path workingDir, String... args) { - final List argsList = List.of(args); - final StringBuilder output = new StringBuilder(); - final int exitCode = IoUtils.runCommand( + private String runCommand(Path workingDir, String... args) { + List argsList = List.of(args); + StringBuilder output = new StringBuilder(); + int exitCode = IoUtils.runCommand( argsList, workingDir, output, Collections.emptyMap() ); - return new CommandResult(exitCode, output.toString()); + if (exitCode != 0) { + throw new RuntimeException("Command failed: " + argsList + "\n" + output); + } + return output.toString(); + } + + private String runCommandIgnoringExitCode(Path workingDir, String... args) { + List argsList = List.of(args); + StringBuilder output = new StringBuilder(); + IoUtils.runCommand(argsList, workingDir, output, Collections.emptyMap()); + return output.toString(); } private Path standardLibraryPath() { diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithydotnet/TypeConversionCodegen.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithydotnet/TypeConversionCodegen.java index 05494838e1..c955b48e2f 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithydotnet/TypeConversionCodegen.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithydotnet/TypeConversionCodegen.java @@ -114,7 +114,6 @@ public Map generate() { Stream.of(typeConverter.fromDafny, typeConverter.toDafny) ) ) - .prepend(conversionConstants()) .lineSeparated() .braced(); final TokenTree conversionClass = conversionClassBody @@ -123,16 +122,6 @@ public Map generate() { return Map.of(TYPE_CONVERSION_CLASS_PATH, conversionClass.prepend(prelude)); } - private static TokenTree conversionConstants() { - return TokenTree.of( - """ - private const string ISO8601DateFormat = "yyyy-MM-dd\\\\THH:mm:ss.fff\\\\Z"; - - private const string ISO8601DateFormatNoMS = "yyyy-MM-dd\\\\THH:mm:ss\\\\Z"; - """ - ); - } - /** * Returns a stream of type converters for synthetic types (types that aren't defined in the model). */ @@ -394,13 +383,15 @@ public TypeConverter generateTimestampConverter( ) { final TokenTree fromDafnyBody = Token.of( """ + System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(""); string timestampString = new string(value.Elements); - return System.DateTime.ParseExact(timestampString, new[] {ISO8601DateFormat, ISO8601DateFormatNoMS}, System.Globalization.CultureInfo.InvariantCulture); + return System.DateTime.ParseExact(timestampString, "s", culture); """ ); final TokenTree toDafnyBody = Token.of( """ - string timestampString = value.ToString(ISO8601DateFormat, System.Globalization.CultureInfo.InvariantCulture); + System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(""); + string timestampString = value.ToString("s", culture); return Dafny.Sequence.FromString(timestampString); """ ); diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/AwsSdkGoPointableIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/AwsSdkGoPointableIndex.java index a6524a8a24..c57767d9c8 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/AwsSdkGoPointableIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/AwsSdkGoPointableIndex.java @@ -20,262 +20,226 @@ import software.amazon.smithy.utils.SetUtils; public class AwsSdkGoPointableIndex implements KnowledgeIndex { + public static final NullableIndex.CheckMode DEFAULT_CHECKMODE = + NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1_NO_INPUT; + + private static final Logger LOGGER = Logger.getLogger(AwsSdkGoPointableIndex.class.getName()); + + // All types that are Go value types + private static final Set INHERENTLY_VALUE = SetUtils.of( + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + ShapeType.UNION, + ShapeType.DOCUMENT + ); - public static final NullableIndex.CheckMode DEFAULT_CHECKMODE = - NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1_NO_INPUT; - - private static final Logger LOGGER = Logger.getLogger( - AwsSdkGoPointableIndex.class.getName() - ); - - // All types that are Go value types - private static final Set INHERENTLY_VALUE = SetUtils.of( - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - ShapeType.UNION, - ShapeType.DOCUMENT - ); - - // All types that are Go pointer types - private static final Set INHERENTLY_POINTABLE = SetUtils.of( - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - - // All types that cannot be dereferenced - private static final Set INHERENTLY_NONDEREFERENCABLE = - SetUtils.of( - // built in slice/map - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - // Interfaces - ShapeType.UNION, - ShapeType.DOCUMENT, - // known pointer types. - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER + // All types that are Go pointer types + private static final Set INHERENTLY_POINTABLE = SetUtils.of( + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER ); - // All types types that are comparable to nil - private static final Set INHERENTLY_NILLABLE = SetUtils.of( - // built in slice/map - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - // Interfaces - ShapeType.UNION, - ShapeType.DOCUMENT, - // known pointer types. - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - - private final Model model; - private final NullableIndex nullableIndex; - private final NullableIndex.CheckMode checkMode; - private final Set pointableShapes = new HashSet<>(); - private final Set nillableShapes = new HashSet<>(); - private final Set dereferencableShapes = new HashSet<>(); - - public AwsSdkGoPointableIndex( - Model model, - NullableIndex.CheckMode checkMode - ) { - this.model = model; - this.nullableIndex = NullableIndex.of(model); - this.checkMode = checkMode; - - for (Shape shape : model.toSet()) { - if (shape.asMemberShape().isPresent()) { - MemberShape member = shape.asMemberShape().get(); - Shape targetShape = model.expectShape(member.getTarget()); - - if (isMemberPointable(member, targetShape)) { - pointableShapes.add(shape.getId()); - } - if (isMemberNillable(member, targetShape)) { - nillableShapes.add(shape.getId()); - } - if (isMemberDereferencable(member, targetShape)) { - dereferencableShapes.add(shape.getId()); - } - } else { - if (isShapePointable(shape)) { - pointableShapes.add(shape.getId()); - nillableShapes.add(shape.getId()); - } - if (isShapeNillable(shape)) { - nillableShapes.add(shape.getId()); - } - if (isShapeDereferencable(shape)) { - dereferencableShapes.add(shape.getId()); + // All types that cannot be dereferenced + private static final Set INHERENTLY_NONDEREFERENCABLE = SetUtils.of( + // built in slice/map + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + + // Interfaces + ShapeType.UNION, + ShapeType.DOCUMENT, + + // known pointer types. + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + // All types types that are comparable to nil + private static final Set INHERENTLY_NILLABLE = SetUtils.of( + // built in slice/map + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + + // Interfaces + ShapeType.UNION, + ShapeType.DOCUMENT, + + // known pointer types. + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + + + private final Model model; + private final NullableIndex nullableIndex; + private final NullableIndex.CheckMode checkMode; + private final Set pointableShapes = new HashSet<>(); + private final Set nillableShapes = new HashSet<>(); + private final Set dereferencableShapes = new HashSet<>(); + + public AwsSdkGoPointableIndex(Model model, NullableIndex.CheckMode checkMode) { + this.model = model; + this.nullableIndex = NullableIndex.of(model); + this.checkMode = checkMode; + + for (Shape shape : model.toSet()) { + if (shape.asMemberShape().isPresent()) { + MemberShape member = shape.asMemberShape().get(); + Shape targetShape = model.expectShape(member.getTarget()); + + if (isMemberPointable(member, targetShape)) { + pointableShapes.add(shape.getId()); + } + if (isMemberNillable(member, targetShape)) { + nillableShapes.add(shape.getId()); + } + if (isMemberDereferencable(member, targetShape)) { + dereferencableShapes.add(shape.getId()); + } + } else { + if (isShapePointable(shape)) { + pointableShapes.add(shape.getId()); + nillableShapes.add(shape.getId()); + } + if (isShapeNillable(shape)) { + nillableShapes.add(shape.getId()); + } + if (isShapeDereferencable(shape)) { + dereferencableShapes.add(shape.getId()); + } + } } - } } - } - public AwsSdkGoPointableIndex(Model model) { - this(model, DEFAULT_CHECKMODE); - } + public AwsSdkGoPointableIndex(Model model) { + this(model, DEFAULT_CHECKMODE); + } - public static AwsSdkGoPointableIndex of(Model model) { - return model.getKnowledge( - AwsSdkGoPointableIndex.class, - AwsSdkGoPointableIndex::new - ); - } - - public static AwsSdkGoPointableIndex of( - Model model, - NullableIndex.CheckMode checkMode - ) { - return model.getKnowledge( - AwsSdkGoPointableIndex.class, - model1 -> new AwsSdkGoPointableIndex(model1, checkMode) - ); - } - - private boolean isMemberDereferencable( - MemberShape member, - Shape targetShape - ) { - return ( - !INHERENTLY_NONDEREFERENCABLE.contains(targetShape.getType()) && - isMemberPointable(member, targetShape) - ); - } + public static AwsSdkGoPointableIndex of(Model model) { + return model.getKnowledge(AwsSdkGoPointableIndex.class, AwsSdkGoPointableIndex::new); + } - private boolean isMemberNillable(MemberShape member, Shape targetShape) { - return ( - INHERENTLY_NILLABLE.contains(targetShape.getType()) || - isMemberPointable(member, targetShape) - ); - } + public static AwsSdkGoPointableIndex of(Model model, NullableIndex.CheckMode checkMode) { + return model.getKnowledge(AwsSdkGoPointableIndex.class, (model1) -> new AwsSdkGoPointableIndex(model1, checkMode)); + } - private boolean isMemberPointable(MemberShape member, Shape targetShape) { - // Streamed blob shapes are never pointers because they are interfaces - if (isBlobStream(targetShape)) { - return false; + private boolean isMemberDereferencable(MemberShape member, Shape targetShape) { + return !INHERENTLY_NONDEREFERENCABLE.contains(targetShape.getType()) && isMemberPointable(member, targetShape); } - if ( - INHERENTLY_VALUE.contains(targetShape.getType()) || - isShapeEnum(targetShape) - ) { - return false; + private boolean isMemberNillable(MemberShape member, Shape targetShape) { + return INHERENTLY_NILLABLE.contains(targetShape.getType()) || isMemberPointable(member, targetShape); } - return nullableIndex.isMemberNullable(member, checkMode); - } + private boolean isMemberPointable(MemberShape member, Shape targetShape) { - private boolean isShapeDereferencable(Shape shape) { - return ( - !INHERENTLY_NONDEREFERENCABLE.contains(shape.getType()) && - isShapePointable(shape) - ); - } + // Streamed blob shapes are never pointers because they are interfaces + if (isBlobStream(targetShape)) { + return false; + } - private boolean isShapeNillable(Shape shape) { - return ( - INHERENTLY_NILLABLE.contains(shape.getType()) || isShapePointable(shape) - ); - } + if (INHERENTLY_VALUE.contains(targetShape.getType()) || isShapeEnum(targetShape)) { + return false; + } - private boolean isShapePointable(Shape shape) { - // All operation input and output shapes are pointable. - if (isOperationStruct(shape)) { - return true; + return nullableIndex.isMemberNullable(member, checkMode); } - // Streamed blob shapes are never pointers because they are interfaces - if (isBlobStream(shape)) { - return false; + private boolean isShapeDereferencable(Shape shape) { + return !INHERENTLY_NONDEREFERENCABLE.contains(shape.getType()) && isShapePointable(shape); } - if (shape.isServiceShape()) { - return true; + private boolean isShapeNillable(Shape shape) { + return INHERENTLY_NILLABLE.contains(shape.getType()) || isShapePointable(shape); } - // This is odd because its not a go type but a function with receiver - if (shape.isOperationShape()) { - return false; + private boolean isShapePointable(Shape shape) { + // All operation input and output shapes are pointable. + if (isOperationStruct(shape)) { + return true; + } + + // Streamed blob shapes are never pointers because they are interfaces + if (isBlobStream(shape)) { + return false; + } + + if (shape.isServiceShape()) { + return true; + } + + // This is odd because its not a go type but a function with receiver + if (shape.isOperationShape()) { + return false; + } + + if (INHERENTLY_POINTABLE.contains(shape.getType())) { + return true; + } + + if (INHERENTLY_VALUE.contains(shape.getType()) || isShapeEnum(shape)) { + return false; + } + + return nullableIndex.isNullable(shape); } - if (INHERENTLY_POINTABLE.contains(shape.getType())) { - return true; + private boolean isShapeEnum(Shape shape) { + return shape.getType() == ShapeType.STRING && shape.hasTrait(EnumTrait.class) + || shape.getType() == ShapeType.ENUM + || shape.getType() == ShapeType.INT_ENUM; } - if (INHERENTLY_VALUE.contains(shape.getType()) || isShapeEnum(shape)) { - return false; + private boolean isBlobStream(Shape shape) { + return shape.getType() == ShapeType.BLOB && shape.hasTrait(StreamingTrait.ID); } - return nullableIndex.isNullable(shape); - } + public boolean isOperationStruct(Shape shape) { + NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); + for (Relationship relationship : provider.getNeighbors(shape)) { + RelationshipType relationshipType = relationship.getRelationshipType(); + if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { + return true; + } + } - private boolean isShapeEnum(Shape shape) { - return ( - (shape.getType() == ShapeType.STRING && - shape.hasTrait(EnumTrait.class)) || - shape.getType() == ShapeType.ENUM || - shape.getType() == ShapeType.INT_ENUM - ); - } + return false; + } - private boolean isBlobStream(Shape shape) { - return ( - shape.getType() == ShapeType.BLOB && shape.hasTrait(StreamingTrait.ID) - ); - } - - public boolean isOperationStruct(Shape shape) { - NeighborProvider provider = NeighborProviderIndex - .of(model) - .getReverseProvider(); - for (Relationship relationship : provider.getNeighbors(shape)) { - RelationshipType relationshipType = relationship.getRelationshipType(); - if ( - relationshipType == RelationshipType.INPUT || - relationshipType == RelationshipType.OUTPUT - ) { - return true; - } + /** + * Returns if the shape should be generated as a Go pointer type or not. + * + * @param shape the shape to check if should be pointable type. + * @return if the shape is should be a Go pointer type. + */ + public final boolean isPointable(ToShapeId shape) { + return pointableShapes.contains(shape.toShapeId()); } - return false; - } - - /** - * Returns if the shape should be generated as a Go pointer type or not. - * - * @param shape the shape to check if should be pointable type. - * @return if the shape is should be a Go pointer type. - */ - public final boolean isPointable(ToShapeId shape) { - return pointableShapes.contains(shape.toShapeId()); - } - - /** - * Returns if the Go type generated for the shape is comparable to nil. - * - * @param shape the shape to check - * @return if the shape's go type is comparable to nil - */ - public final boolean isNillable(ToShapeId shape) { - return nillableShapes.contains(shape.toShapeId()); - } - - /** - * Returns if the Go type generated for the shape can be dereferenced. - * - * @param shape the shape to check - * @return if the shape's go type is dereferencable - */ - public final boolean isDereferencable(ToShapeId shape) { - return dereferencableShapes.contains(shape.toShapeId()); - } -} + /** + * Returns if the Go type generated for the shape is comparable to nil. + * + * @param shape the shape to check + * @return if the shape's go type is comparable to nil + */ + public final boolean isNillable(ToShapeId shape) { + return nillableShapes.contains(shape.toShapeId()); + } + + /** + * Returns if the Go type generated for the shape can be dereferenced. + * + * @param shape the shape to check + * @return if the shape's go type is dereferencable + */ + public final boolean isDereferencable(ToShapeId shape) { + return dereferencableShapes.contains(shape.toShapeId()); + } +} \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientShimGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientShimGenerator.java index a9835297ae..f0116ce4fc 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientShimGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientShimGenerator.java @@ -15,174 +15,91 @@ public class DafnyAwsSdkClientShimGenerator implements Runnable { - private final GenerationContext context; - private final ServiceShape service; - private final GoDelegator writerDelegator; - private final Model dafnyNonNormalizedModel; - private final Model awsNormalizedModel; - private final SymbolProvider symbolProvider; + private final GenerationContext context; + private final ServiceShape service; + private final GoDelegator writerDelegator; + private final Model dafnyNonNormalizedModel; + private final Model awsNormalizedModel; + private final SymbolProvider symbolProvider; - public DafnyAwsSdkClientShimGenerator( - GenerationContext context, - ServiceShape service - ) { - this.context = context; - this.service = service; - dafnyNonNormalizedModel = context.model(); - awsNormalizedModel = - AddOperationShapes.execute(context.model(), service.toShapeId()); - writerDelegator = context.writerDelegator(); - symbolProvider = context.symbolProvider(); - } + public DafnyAwsSdkClientShimGenerator(GenerationContext context, ServiceShape service) { + this.context = context; + this.service = service; + dafnyNonNormalizedModel = context.model(); + awsNormalizedModel = AddOperationShapes.execute(context.model(), service.toShapeId()); + writerDelegator = context.writerDelegator(); + symbolProvider = context.symbolProvider(); + } - @Override - public void run() { - generateShim(); - } + @Override + public void run() { + generateShim(); + } - void generateShim() { - final var namespace = - "%swrapped".formatted(DafnyNameResolver.dafnyNamespace(service)); + void generateShim() { + final var namespace = "%swrapped".formatted(DafnyNameResolver.dafnyNamespace(service)); - writerDelegator.useFileWriter( - "%s/shim.go".formatted(namespace), - namespace, - writer -> { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - context.settings().getService().getNamespace() - ), - DafnyNameResolver.dafnyTypesNamespace(service) - ); - writer.addImport( - SmithyNameResolver.getGoModuleNameForSdkNamespace( - awsNormalizedModel - .expectShape(service.toShapeId(), ServiceShape.class) - .toShapeId() - .getNamespace() - ) - ); - writer.addImportFromModule( - "github.com/dafny-lang/DafnyStandardLibGo", - "Wrappers" - ); - writer.addUseImports(SmithyGoDependency.CONTEXT); - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - context.settings().getService().getNamespace() - ), - SmithyNameResolver.shapeNamespace(service) - ); - writer.write( - """ - type Shim struct { - $L - Client *$L - } - """, - DafnyNameResolver.getDafnyInterfaceClient( - service, - service.expectTrait(ServiceTrait.class) - ), - SmithyNameResolver.getAwsServiceClient( - service.expectTrait(ServiceTrait.class) - ) - ); + writerDelegator.useFileWriter("%s/shim.go".formatted(namespace), namespace, writer -> { - service - .getOperations() - .forEach(operation -> { - final var awsNormalizedOperation = awsNormalizedModel.expectShape( - operation, - OperationShape.class - ); - final var awsNormalizedInputShape = awsNormalizedModel.expectShape( - awsNormalizedOperation.getInputShape() - ); - final var awsNormalizedOutputShape = awsNormalizedModel.expectShape( - awsNormalizedOperation.getOutputShape() + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(service)); + writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedModel.expectShape(service.toShapeId(), ServiceShape.class).toShapeId().getNamespace())); + writer.addImportFromModule("github.com/dafny-lang/DafnyStandardLibGo", "Wrappers"); + writer.addUseImports(SmithyGoDependency.CONTEXT); + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.shapeNamespace(service)); + writer.write(""" + type Shim struct { + $L + Client *$L + } + """, + DafnyNameResolver.getDafnyInterfaceClient(service, service.expectTrait(ServiceTrait.class)), + SmithyNameResolver.getAwsServiceClient(service.expectTrait(ServiceTrait.class)) ); - final var operationShape = dafnyNonNormalizedModel.expectShape( - operation, - OperationShape.class - ); - final var inputShape = dafnyNonNormalizedModel.expectShape( - operationShape.getInputShape() - ); - final var outputShape = dafnyNonNormalizedModel.expectShape( - operationShape.getOutputShape() - ); - final var inputType = awsNormalizedInputShape.hasTrait( - UnitTypeTrait.class - ) - ? "" - : "input %s".formatted( - DafnyNameResolver.getDafnyType( - inputShape, - symbolProvider.toSymbol(inputShape) - ) - ); - final var typeConversion = awsNormalizedInputShape.hasTrait( - UnitTypeTrait.class - ) - ? "" - : "var native_request = %s(input)".formatted( - SmithyNameResolver.getFromDafnyMethodName( - awsNormalizedInputShape, - "" - ) - ); + service.getOperations().forEach(operation -> { + final var awsNormalizedOperation = awsNormalizedModel.expectShape(operation, OperationShape.class); + final var awsNormalizedInputShape = awsNormalizedModel.expectShape(awsNormalizedOperation.getInputShape()); + final var awsNormalizedOutputShape = awsNormalizedModel.expectShape(awsNormalizedOperation.getOutputShape()); - final var clientCall = - "shim.Client.%s(context.Background() %s)".formatted( - operationShape.getId().getName(), - awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) - ? "" - : ", &native_request" - ); + final var operationShape = dafnyNonNormalizedModel.expectShape(operation, OperationShape.class); + final var inputShape = dafnyNonNormalizedModel.expectShape(operationShape.getInputShape()); + final var outputShape = dafnyNonNormalizedModel.expectShape(operationShape.getOutputShape()); + final var inputType = awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) ? "" + : "input %s".formatted(DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(inputShape))); + + final var typeConversion = awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) ? "" + : "var native_request = %s(input)".formatted(SmithyNameResolver.getFromDafnyMethodName(awsNormalizedInputShape, "")); - String clientResponse, returnResponse; - if (awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class)) { - clientResponse = "var _, native_error"; - returnResponse = "dafny.TupleOf()"; - writer.addImportFromModule( - "github.com/dafny-lang/DafnyRuntimeGo", - "dafny" - ); - } else { - clientResponse = "var native_response, native_error"; - returnResponse = - "%s(*native_response)".formatted( - SmithyNameResolver.getToDafnyMethodName( - awsNormalizedOutputShape, - "" - ) - ); - } + final var clientCall = "shim.Client.%s(context.Background() %s)".formatted(operationShape.getId().getName(), + awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) ? "" : ", &native_request"); - writer.write( - """ - func (shim *Shim) $L($L) Wrappers.Result { - $L - $L = $L - if native_error != nil { - return Wrappers.Companion_Result_.Create_Failure_($L.Error_ToDafny(native_error)) - } - return Wrappers.Companion_Result_.Create_Success_($L) + String clientResponse, returnResponse; + if (awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class)) { + clientResponse = "var _, native_error"; + returnResponse = "dafny.TupleOf()"; + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + } else { + clientResponse = "var native_response, native_error"; + returnResponse = "%s(*native_response)".formatted(SmithyNameResolver.getToDafnyMethodName(awsNormalizedOutputShape, "")); } - """, - operationShape.getId().getName(), - inputType, - typeConversion, - clientResponse, - clientCall, - SmithyNameResolver.shapeNamespace(service), - returnResponse - ); - }); - } - ); - } + + writer.write(""" + func (shim *Shim) $L($L) Wrappers.Result { + $L + $L = $L + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_($L.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_($L) + } + """, + operationShape.getId().getName(), + inputType, typeConversion, clientResponse, clientCall, + SmithyNameResolver.shapeNamespace(service), + returnResponse + ); + }); + }); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientTypeConversionProtocol.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientTypeConversionProtocol.java index 3a82903637..0b50402b28 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientTypeConversionProtocol.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientTypeConversionProtocol.java @@ -1,10 +1,5 @@ package software.amazon.polymorph.smithygo.awssdk; -import static software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceTypeConversionProtocol.TO_DAFNY; -import static software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceTypeConversionProtocol.TO_NATIVE; - -import java.util.HashSet; -import java.util.Set; import software.amazon.polymorph.smithygo.awssdk.shapevisitor.AwsSdkToDafnyShapeVisitor; import software.amazon.polymorph.smithygo.awssdk.shapevisitor.DafnyToAwsSdkShapeVisitor; import software.amazon.polymorph.smithygo.codegen.AddOperationShapes; @@ -23,744 +18,359 @@ import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.UnitTypeTrait; -public class DafnyAwsSdkClientTypeConversionProtocol - implements ProtocolGenerator { - - final Model dafnyNonNormalizedModel; - final Model awsNormalizedModel; - final ServiceShape serviceShape; - - public DafnyAwsSdkClientTypeConversionProtocol( - Model model, - ServiceShape serviceShape - ) { - dafnyNonNormalizedModel = model; - awsNormalizedModel = - AddOperationShapes.execute(model, serviceShape.toShapeId()); - - this.serviceShape = serviceShape; - } - - @Override - public ShapeId getProtocol() { - return null; - } - - @Override - public ApplicationProtocol getApplicationProtocol() { - return null; - } - - @Override - public void generateSerializers(GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var symbolProvider = context.symbolProvider(); - final var writerDelegator = context.writerDelegator(); - serviceShape - .getOperations() - .forEach(eachOperation -> { - final var awsNormalizedOperation = awsNormalizedModel.expectShape( - eachOperation, - OperationShape.class - ); - final var awsNormalizedInputShape = awsNormalizedModel.expectShape( - awsNormalizedOperation.getInputShape() - ); - if (!alreadyVisited.contains(awsNormalizedInputShape.toShapeId())) { - alreadyVisited.add(awsNormalizedInputShape.toShapeId()); - if ( - !awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) && - awsNormalizedInputShape - .toShapeId() - .getNamespace() - .equals(serviceShape.toShapeId().getNamespace()) - ) { - final var awsNormalizedInputToDafnyMethodName = - SmithyNameResolver.getToDafnyMethodName( - serviceShape, - awsNormalizedInputShape, - "" - ); - final var awsNormalizedInputSymbol = symbolProvider.toSymbol( - awsNormalizedInputShape - ); - final var dafnyInput = dafnyNonNormalizedModel - .expectShape(eachOperation, OperationShape.class) - .getInputShape(); - final var dafnyInputSymbol = symbolProvider.toSymbol( - dafnyNonNormalizedModel.expectShape(dafnyInput) - ); - writerDelegator.useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_DAFNY - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - writer.addImport( - SmithyNameResolver.getGoModuleNameForSdkNamespace( - awsNormalizedInputShape.toShapeId().getNamespace() - ) - ); - writer.write( - """ - func $L(nativeInput $L)($L) { - ${C|} - }""", - awsNormalizedInputToDafnyMethodName, - SmithyNameResolver.getSmithyTypeAws( - serviceShape.expectTrait(ServiceTrait.class), - awsNormalizedInputSymbol, - false - ), - DafnyNameResolver.getDafnyType( - dafnyNonNormalizedModel.expectShape(dafnyInput), - dafnyInputSymbol - ), - writer.consumer(w -> - generateRequestSerializer( - context, - awsNormalizedOperation, - context.writerDelegator() - ) - ) - ); - } - ); - } - } +import java.util.HashSet; +import java.util.Set; - final var awsNormalizedOutputShape = awsNormalizedModel.expectShape( - awsNormalizedOperation.getOutputShape() - ); - if (!alreadyVisited.contains(awsNormalizedOutputShape.toShapeId())) { - alreadyVisited.add(awsNormalizedOutputShape.toShapeId()); - if ( - !awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class) && - awsNormalizedOutputShape - .toShapeId() - .getNamespace() - .equals(serviceShape.toShapeId().getNamespace()) - ) { - final var awsNormalizedOutputToDafnyMethodName = - SmithyNameResolver.getToDafnyMethodName( - serviceShape, - awsNormalizedOutputShape, - "" - ); - final var awsNormalizedOutputSymbol = symbolProvider.toSymbol( - awsNormalizedOutputShape - ); - final var dafnyOutput = dafnyNonNormalizedModel - .expectShape(eachOperation, OperationShape.class) - .getOutputShape(); - final var dafnyOutputSymbol = symbolProvider.toSymbol( - dafnyNonNormalizedModel.expectShape(dafnyOutput) - ); - writerDelegator.useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_DAFNY - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - writer.addImport( - SmithyNameResolver.getGoModuleNameForSdkNamespace( - awsNormalizedInputShape.toShapeId().getNamespace() - ) - ); - writer.write( - """ - func $L(nativeOutput $L)($L) { - ${C|} - }""", - awsNormalizedOutputToDafnyMethodName, - SmithyNameResolver.getSmithyTypeAws( - serviceShape.expectTrait(ServiceTrait.class), - awsNormalizedOutputSymbol, - false - ), - DafnyNameResolver.getDafnyType( - dafnyNonNormalizedModel.expectShape(dafnyOutput), - dafnyOutputSymbol - ), - writer.consumer(w -> - generateResponseSerializer( - context, - awsNormalizedOperation, - context.writerDelegator() - ) - ) - ); - } - ); - } - } - }); - generateErrorSerializer(context); - } - - @Override - public void generateDeserializers(GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var symbolProvider = context.symbolProvider(); - final var delegator = context.writerDelegator(); - - serviceShape - .getOperations() - .forEach(eachOperation -> { - final var awsNormalizedOperationShape = awsNormalizedModel.expectShape( - eachOperation, - OperationShape.class - ); - final var awsNormalizedInputShape = awsNormalizedModel.expectShape( - awsNormalizedOperationShape.getInputShape() - ); - if (!alreadyVisited.contains(awsNormalizedInputShape.toShapeId())) { - alreadyVisited.add(awsNormalizedInputShape.toShapeId()); - if ( - !awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) && - awsNormalizedInputShape - .toShapeId() - .getNamespace() - .equals(serviceShape.toShapeId().getNamespace()) - ) { - final var awsNormalizedInputFromDafnyMethodName = - SmithyNameResolver.getFromDafnyMethodName( - serviceShape, - awsNormalizedInputShape, - "" - ); - final var awsNormalizedInputSymbol = symbolProvider.toSymbol( - awsNormalizedInputShape - ); - final var dafnyInput = dafnyNonNormalizedModel - .expectShape(eachOperation, OperationShape.class) - .getInputShape(); - final var dafnyInputSymbol = symbolProvider.toSymbol( - dafnyNonNormalizedModel.expectShape(dafnyInput) - ); - delegator.useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - writer.addImport( - SmithyNameResolver.getGoModuleNameForSdkNamespace( - awsNormalizedInputShape.toShapeId().getNamespace() - ) - ); - writer.write( - """ - func $L(dafnyInput $L)($L) { - ${C|} - }""", - awsNormalizedInputFromDafnyMethodName, - DafnyNameResolver.getDafnyType( - dafnyNonNormalizedModel.expectShape(dafnyInput), - dafnyInputSymbol - ), - SmithyNameResolver.getSmithyTypeAws( - serviceShape.expectTrait(ServiceTrait.class), - awsNormalizedInputSymbol, - false - ), - writer.consumer(w -> - generateRequestDeserializer( - context, - awsNormalizedOperationShape, - context.writerDelegator() - ) - ) - ); - } - ); - } - } +import static software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceTypeConversionProtocol.TO_DAFNY; +import static software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceTypeConversionProtocol.TO_NATIVE; - final var awsNormalizedOutputShape = awsNormalizedModel.expectShape( - awsNormalizedOperationShape.getOutputShape() - ); - if (!alreadyVisited.contains(awsNormalizedOutputShape.toShapeId())) { - alreadyVisited.add(awsNormalizedOutputShape.toShapeId()); - if ( - !awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class) && - awsNormalizedOutputShape - .toShapeId() - .getNamespace() - .equals(serviceShape.toShapeId().getNamespace()) - ) { - final var awsNormalizedOutputFromDafnyMethodName = - SmithyNameResolver.getFromDafnyMethodName( - serviceShape, - awsNormalizedOutputShape, - "" - ); - final var awsNormalizedOutputSymbol = context - .symbolProvider() - .toSymbol(awsNormalizedOutputShape); - final var dafnyOutput = dafnyNonNormalizedModel - .expectShape(eachOperation, OperationShape.class) - .getOutputShape(); - final var dafnyOutputSymbol = symbolProvider.toSymbol( - dafnyNonNormalizedModel.expectShape(dafnyOutput) - ); - delegator.useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - writer.addImport( - SmithyNameResolver.getGoModuleNameForSdkNamespace( - awsNormalizedInputShape.toShapeId().getNamespace() - ) - ); - writer.write( - """ - func $L(dafnyOutput $L)($L) { - ${C|} - }""", - awsNormalizedOutputFromDafnyMethodName, - DafnyNameResolver.getDafnyType( - dafnyNonNormalizedModel.expectShape(dafnyOutput), - dafnyOutputSymbol - ), - SmithyNameResolver.getSmithyTypeAws( - serviceShape.expectTrait(ServiceTrait.class), - awsNormalizedOutputSymbol, - false - ), - writer.consumer(w -> - generateResponseDeserializer( - context, - awsNormalizedOperationShape, - context.writerDelegator() - ) - ) - ); - } - ); - } - } - }); - - generateErrorDeserializer(context); - } - - private void generateRequestSerializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - final var nonNormalizedOperation = dafnyNonNormalizedModel.expectShape( - operation.toShapeId(), - OperationShape.class - ); - final var targetShape = dafnyNonNormalizedModel.expectShape( - nonNormalizedOperation.getInputShape() - ); - delegator.useFileWriter( - "%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), - SmithyNameResolver.shapeNamespace(operation), - writer -> { - final var input = targetShape.accept( - new AwsSdkToDafnyShapeVisitor( - context, - "nativeInput", - writer, - false, - false, - false - ) - ); - writer.write( - """ - return $L - """, - input - ); - } - ); - } - - private void generateResponseSerializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - final var nonNormalizedOperation = dafnyNonNormalizedModel.expectShape( - operation.toShapeId(), - OperationShape.class - ); - final var targetShape = dafnyNonNormalizedModel.expectShape( - nonNormalizedOperation.getOutputShape() - ); - delegator.useFileWriter( - "%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), - SmithyNameResolver.shapeNamespace(operation), - writer -> { - final var input = targetShape.accept( - new AwsSdkToDafnyShapeVisitor( - context, - "nativeOutput", - writer, - false, - false, - false - ) - ); - writer.write( - """ - return $L - """, - input - ); - } - ); - } - - private void generateRequestDeserializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - delegator.useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(operation), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace(operation), - writer -> { - final var inputShape = operation.getInputShape(); - - final var targetShape = awsNormalizedModel.expectShape(inputShape); - final var input = targetShape.accept( - new DafnyToAwsSdkShapeVisitor(context, "dafnyInput", writer) - ); +public class DafnyAwsSdkClientTypeConversionProtocol implements ProtocolGenerator { + final Model dafnyNonNormalizedModel; + final Model awsNormalizedModel; + final ServiceShape serviceShape; + public DafnyAwsSdkClientTypeConversionProtocol(Model model, ServiceShape serviceShape) { + dafnyNonNormalizedModel = model; + awsNormalizedModel = AddOperationShapes.execute(model, serviceShape.toShapeId()); - writer.write( - """ - return $L - """, - input - ); - } - ); - } - - private void generateResponseDeserializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - delegator.useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(operation), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace(operation), - writer -> { - final var outputShape = operation.getOutputShape(); - - final var targetShape = awsNormalizedModel.expectShape(outputShape); - final var output = targetShape.accept( - new DafnyToAwsSdkShapeVisitor(context, "dafnyOutput", writer) - ); + this.serviceShape = serviceShape; + } - writer.write( - """ - return $L - """, - output - ); - } - ); - } - - private void generateErrorSerializer(final GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var errorShapes = awsNormalizedModel.getShapesWithTrait( - ErrorTrait.class - ); - - for (final var errorShape : errorShapes) { - if ( - !errorShape - .toShapeId() - .getNamespace() - .equals(serviceShape.toShapeId().getNamespace()) - ) { - continue; - } - if (!alreadyVisited.contains(errorShape.toShapeId())) { - alreadyVisited.add(errorShape.toShapeId()); - final var getInputToDafnyMethodName = - SmithyNameResolver.getToDafnyMethodName(serviceShape, errorShape, ""); - - context - .writerDelegator() - .useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(errorShape), - TO_DAFNY - ), - SmithyNameResolver.shapeNamespace(errorShape), - writer -> { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSdkNamespace( - errorShape.toShapeId().getNamespace() - ), - SmithyNameResolver.smithyTypesNamespaceAws( - serviceShape.expectTrait(ServiceTrait.class), - true - ) - ); - writer.write( - """ - func $L(nativeInput types.$L)($L) { - ${C|} - }""", - getInputToDafnyMethodName, - context.symbolProvider().toSymbol(errorShape).getName(), - DafnyNameResolver.getDafnyBaseErrorType(errorShape), - writer.consumer(w -> { - String output = errorShape.accept( - new AwsSdkToDafnyShapeVisitor( - context, - "nativeInput", - writer, - false, - false, - false - ) - ); - writer.write( - """ - return $L - """, - output - ); - }) - ); + @Override + public ShapeId getProtocol() { + return null; + } + + @Override + public ApplicationProtocol getApplicationProtocol() { + return null; + } + + @Override + public void generateSerializers(GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var symbolProvider = context.symbolProvider(); + final var writerDelegator = context.writerDelegator(); + serviceShape.getOperations().forEach(eachOperation -> { + final var awsNormalizedOperation = awsNormalizedModel.expectShape(eachOperation, OperationShape.class); + final var awsNormalizedInputShape = awsNormalizedModel.expectShape(awsNormalizedOperation.getInputShape()); + if (!alreadyVisited.contains(awsNormalizedInputShape.toShapeId())) { + alreadyVisited.add(awsNormalizedInputShape.toShapeId()); + if (!awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) && awsNormalizedInputShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { + final var awsNormalizedInputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, awsNormalizedInputShape, ""); + final var awsNormalizedInputSymbol = symbolProvider.toSymbol(awsNormalizedInputShape); + final var dafnyInput = dafnyNonNormalizedModel.expectShape(eachOperation, OperationShape.class).getInputShape(); + final var dafnyInputSymbol = symbolProvider.toSymbol(dafnyNonNormalizedModel.expectShape(dafnyInput)); + writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedInputShape.toShapeId().getNamespace())); + writer.write(""" + func $L(nativeInput $L)($L) { + ${C|} + }""", awsNormalizedInputToDafnyMethodName, SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), awsNormalizedInputSymbol, false), + DafnyNameResolver.getDafnyType(dafnyNonNormalizedModel.expectShape(dafnyInput), dafnyInputSymbol), + writer.consumer(w -> generateRequestSerializer(context, awsNormalizedOperation, context.writerDelegator()))); + }); + } + } + + final var awsNormalizedOutputShape = awsNormalizedModel.expectShape(awsNormalizedOperation.getOutputShape()); + if (!alreadyVisited.contains(awsNormalizedOutputShape.toShapeId())) { + alreadyVisited.add(awsNormalizedOutputShape.toShapeId()); + if (!awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class) && awsNormalizedOutputShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { + final var awsNormalizedOutputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, awsNormalizedOutputShape, ""); + final var awsNormalizedOutputSymbol = symbolProvider.toSymbol(awsNormalizedOutputShape); + final var dafnyOutput = dafnyNonNormalizedModel.expectShape(eachOperation, OperationShape.class).getOutputShape(); + final var dafnyOutputSymbol = symbolProvider.toSymbol(dafnyNonNormalizedModel.expectShape(dafnyOutput)); + writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedInputShape.toShapeId().getNamespace())); + writer.write(""" + func $L(nativeOutput $L)($L) { + ${C|} + }""", awsNormalizedOutputToDafnyMethodName, + SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), awsNormalizedOutputSymbol, false), + DafnyNameResolver.getDafnyType(dafnyNonNormalizedModel.expectShape(dafnyOutput), dafnyOutputSymbol), + writer.consumer(w -> generateResponseSerializer(context, awsNormalizedOperation, context.writerDelegator()))); + }); + } } - ); - } + }); + generateErrorSerializer(context); } - context - .writerDelegator() - .useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_DAFNY - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - writer.write( - """ - func OpaqueError_Input_ToDafny(nativeInput error)($L.Error) { - return $L.Companion_Error_.Create_Opaque_(nativeInput) - }""", - DafnyNameResolver.dafnyTypesNamespace(serviceShape), - DafnyNameResolver.dafnyTypesNamespace(serviceShape) - ); - } - ); - - context - .writerDelegator() - .useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_DAFNY - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - writer.write( - """ - func Error_ToDafny(err error)($L.Error) { - switch err.(type) { - // Service Errors - ${C|} - - default: - return OpaqueError_Input_ToDafny(err) + @Override + public void generateDeserializers(GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var symbolProvider = context.symbolProvider(); + final var delegator = context.writerDelegator(); + + serviceShape.getOperations().forEach(eachOperation -> { + final var awsNormalizedOperationShape = awsNormalizedModel.expectShape(eachOperation, OperationShape.class); + final var awsNormalizedInputShape = awsNormalizedModel.expectShape(awsNormalizedOperationShape.getInputShape()); + if (!alreadyVisited.contains(awsNormalizedInputShape.toShapeId())) { + alreadyVisited.add(awsNormalizedInputShape.toShapeId()); + if (!awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) && awsNormalizedInputShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { + final var awsNormalizedInputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, awsNormalizedInputShape, ""); + final var awsNormalizedInputSymbol = symbolProvider.toSymbol(awsNormalizedInputShape); + final var dafnyInput = dafnyNonNormalizedModel.expectShape(eachOperation, OperationShape.class).getInputShape(); + final var dafnyInputSymbol = symbolProvider.toSymbol(dafnyNonNormalizedModel.expectShape(dafnyInput)); + delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedInputShape.toShapeId().getNamespace())); + writer.write(""" + func $L(dafnyInput $L)($L) { + ${C|} + }""", awsNormalizedInputFromDafnyMethodName, DafnyNameResolver.getDafnyType(dafnyNonNormalizedModel.expectShape(dafnyInput), dafnyInputSymbol), + SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), awsNormalizedInputSymbol, false), + writer.consumer(w -> generateRequestDeserializer(context, awsNormalizedOperationShape, context.writerDelegator()))); + }); } } - """, - DafnyNameResolver.dafnyTypesNamespace(serviceShape), - writer.consumer(w -> { - for (var error : errorShapes) { - w.write( - """ - case *$L: - return $L(*err.(*$L)) - """, - SmithyNameResolver.getSmithyTypeAws( - serviceShape.expectTrait(ServiceTrait.class), - context - .symbolProvider() - .toSymbol( - awsNormalizedModel.expectShape(error.toShapeId()) - ), - true - ), - SmithyNameResolver.getToDafnyMethodName( - serviceShape, - awsNormalizedModel.expectShape(error.toShapeId()), - "" - ), - SmithyNameResolver.getSmithyTypeAws( - serviceShape.expectTrait(ServiceTrait.class), - context - .symbolProvider() - .toSymbol( - awsNormalizedModel.expectShape(error.toShapeId()) - ), - true - ) - ); - } - }) - ); - } - ); - } - - private void generateErrorDeserializer(final GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var errorShapes = awsNormalizedModel.getShapesWithTrait( - ErrorTrait.class - ); - for (final var errorShape : errorShapes) { - if ( - !errorShape - .toShapeId() - .getNamespace() - .equals(serviceShape.toShapeId().getNamespace()) - ) { - continue; - } - if (!alreadyVisited.contains(errorShape.toShapeId())) { - alreadyVisited.add(errorShape.toShapeId()); - final var getOutputFromDafnyMethodName = - SmithyNameResolver.getFromDafnyMethodName( - serviceShape, - errorShape, - "" - ); - context - .writerDelegator() - .useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(errorShape), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace(errorShape), - writer -> { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSdkNamespace( - errorShape.toShapeId().getNamespace() - ), - SmithyNameResolver.smithyTypesNamespaceAws( - serviceShape.expectTrait(ServiceTrait.class), - true - ) - ); - writer.write( - """ - func $L(dafnyOutput $L)(types.$L) { - ${C|} - }""", - getOutputFromDafnyMethodName, - DafnyNameResolver.getDafnyBaseErrorType(errorShape), - context.symbolProvider().toSymbol(errorShape).getName(), - writer.consumer(w -> { - String output = errorShape.accept( - new DafnyToAwsSdkShapeVisitor( - context, - "dafnyOutput", - writer - ) - ); - writer.write( - """ - return $L - """, - output - ); - }) - ); + + final var awsNormalizedOutputShape = awsNormalizedModel.expectShape(awsNormalizedOperationShape.getOutputShape()); + if (!alreadyVisited.contains(awsNormalizedOutputShape.toShapeId())) { + alreadyVisited.add(awsNormalizedOutputShape.toShapeId()); + if (!awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class) && awsNormalizedOutputShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { + final var awsNormalizedOutputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, awsNormalizedOutputShape, ""); + final var awsNormalizedOutputSymbol = context.symbolProvider().toSymbol(awsNormalizedOutputShape); + final var dafnyOutput = dafnyNonNormalizedModel.expectShape(eachOperation, OperationShape.class).getOutputShape(); + final var dafnyOutputSymbol = symbolProvider.toSymbol(dafnyNonNormalizedModel.expectShape(dafnyOutput)); + delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedInputShape.toShapeId().getNamespace())); + writer.write(""" + func $L(dafnyOutput $L)($L) { + ${C|} + }""", awsNormalizedOutputFromDafnyMethodName, DafnyNameResolver.getDafnyType(dafnyNonNormalizedModel.expectShape(dafnyOutput), dafnyOutputSymbol), + SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), awsNormalizedOutputSymbol, false), + writer.consumer(w -> generateResponseDeserializer(context, awsNormalizedOperationShape, context.writerDelegator()))); + }); + } } - ); - } + }); + + generateErrorDeserializer(context); + + } + + private void generateRequestSerializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + final var nonNormalizedOperation = dafnyNonNormalizedModel.expectShape(operation.toShapeId(), OperationShape.class); + final var targetShape = dafnyNonNormalizedModel.expectShape(nonNormalizedOperation.getInputShape()); + delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), SmithyNameResolver.shapeNamespace(operation), writer -> { + final var input = targetShape.accept(new AwsSdkToDafnyShapeVisitor( + context, + "nativeInput", + writer, + false, false, false + )); + writer.write(""" + return $L + """, + input); + } + ); + } + + private void generateResponseSerializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + final var nonNormalizedOperation = dafnyNonNormalizedModel.expectShape(operation.toShapeId(), OperationShape.class); + final var targetShape = dafnyNonNormalizedModel.expectShape(nonNormalizedOperation.getOutputShape()); + delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), SmithyNameResolver.shapeNamespace(operation), writer -> { + final var input = targetShape.accept(new AwsSdkToDafnyShapeVisitor( + context, + "nativeOutput", + writer, + false, false, false + )); + writer.write(""" + return $L + """, + input); + } + ); + } + + private void generateRequestDeserializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_NATIVE), SmithyNameResolver.shapeNamespace(operation), writer -> { + + final var inputShape = operation.getInputShape(); + + final var targetShape = awsNormalizedModel.expectShape(inputShape); + final var input = targetShape.accept(new DafnyToAwsSdkShapeVisitor( + context, + "dafnyInput", + writer + )); + + writer.write(""" + return $L + """, input); + }); } - context - .writerDelegator() - .useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - writer.addUseImports(SmithyGoDependency.FMT); - writer.write( - """ - func OpaqueError_Output_FromDafny(dafnyOutput $L.Error)(error) { - return fmt.Errorf(fmt.Sprintf("%v", dafnyOutput.Dtor_obj())) - }""", - DafnyNameResolver.dafnyTypesNamespace(serviceShape) - ); + private void generateResponseDeserializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_NATIVE), SmithyNameResolver.shapeNamespace(operation), writer -> { + + final var outputShape = operation.getOutputShape(); + + final var targetShape = awsNormalizedModel.expectShape(outputShape); + final var output = targetShape.accept(new DafnyToAwsSdkShapeVisitor( + context, + "dafnyOutput", + writer + )); + + writer.write(""" + return $L + """, output); + }); + } + + private void generateErrorSerializer(final GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var errorShapes = awsNormalizedModel.getShapesWithTrait(ErrorTrait.class); + + for (final var errorShape : + errorShapes) { + if (!errorShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { + continue; + } + if (!alreadyVisited.contains(errorShape.toShapeId())) { + alreadyVisited.add(errorShape.toShapeId()); + final var getInputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, errorShape, ""); + + context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(errorShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(errorShape), writer -> { + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSdkNamespace(errorShape.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespaceAws(serviceShape.expectTrait(ServiceTrait.class), true)); + writer.write(""" + func $L(nativeInput types.$L)($L) { + ${C|} + }""", + getInputToDafnyMethodName, context.symbolProvider().toSymbol(errorShape).getName(), DafnyNameResolver.getDafnyBaseErrorType(errorShape), + writer.consumer(w -> { + String output = errorShape.accept(new AwsSdkToDafnyShapeVisitor( + context, + "nativeInput", + writer, + false, false, false + )); + writer.write(""" + return $L + """, output); + })); + }); + } } - ); - - context - .writerDelegator() - .useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - writer.write( - """ - func Error_FromDafny(err $L.Error)(error) { - // Service Errors - ${C|} - - return OpaqueError_Output_FromDafny(err) + + context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + writer.write(""" + func OpaqueError_Input_ToDafny(nativeInput error)($L.Error) { + return $L.Companion_Error_.Create_Opaque_(nativeInput) + }""", DafnyNameResolver.dafnyTypesNamespace(serviceShape), DafnyNameResolver.dafnyTypesNamespace(serviceShape)); + }); + + + context.writerDelegator() + .useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), + SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + writer.write(""" + func Error_ToDafny(err error)($L.Error) { + switch err.(type) { + // Service Errors + ${C|} + + default: + return OpaqueError_Input_ToDafny(err) + } + } + """, DafnyNameResolver.dafnyTypesNamespace(serviceShape), + writer.consumer(w -> { + for (var error : errorShapes) { + w.write(""" + case *$L: + return $L(*err.(*$L)) + """, SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), context.symbolProvider().toSymbol(awsNormalizedModel.expectShape(error.toShapeId())), true), + SmithyNameResolver.getToDafnyMethodName(serviceShape, awsNormalizedModel.expectShape(error.toShapeId()), ""), + SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), context.symbolProvider().toSymbol(awsNormalizedModel.expectShape(error.toShapeId())), true)); + } + }) + ); + }); + } + + private void generateErrorDeserializer(final GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var errorShapes = awsNormalizedModel.getShapesWithTrait(ErrorTrait.class); + for (final var errorShape : + errorShapes) { + if (!errorShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { + continue; + } + if (!alreadyVisited.contains(errorShape.toShapeId())) { + alreadyVisited.add(errorShape.toShapeId()); + final var getOutputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, errorShape, ""); + context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(errorShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(errorShape), writer -> { + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSdkNamespace(errorShape.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespaceAws(serviceShape.expectTrait(ServiceTrait.class), true)); + writer.write(""" + func $L(dafnyOutput $L)(types.$L) { + ${C|} + }""", + getOutputFromDafnyMethodName, DafnyNameResolver.getDafnyBaseErrorType(errorShape), context.symbolProvider().toSymbol(errorShape).getName(), + writer.consumer(w -> { + String output = errorShape.accept(new DafnyToAwsSdkShapeVisitor( + context, + "dafnyOutput", + writer + )); + writer.write(""" + return $L + """, output); + })); + }); } - """, - DafnyNameResolver.dafnyTypesNamespace(serviceShape), - writer.consumer(w -> { - for (var error : awsNormalizedModel.getShapesWithTrait( - ErrorTrait.class - )) { - w.write( - """ - if err.Is_$L() { - e := $L(err) - return &e - } - """, - error.toShapeId().getName(), - SmithyNameResolver.getFromDafnyMethodName( - serviceShape, - awsNormalizedModel.expectShape(error.toShapeId()), - "" - ) - ); - } - }) - ); } - ); - } + + context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + writer.addUseImports(SmithyGoDependency.FMT); + writer.write(""" + func OpaqueError_Output_FromDafny(dafnyOutput $L.Error)(error) { + return fmt.Errorf(fmt.Sprintf("%v", dafnyOutput.Dtor_obj())) + }""", + DafnyNameResolver.dafnyTypesNamespace(serviceShape)); + }); + + context.writerDelegator() + .useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), + SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + writer.write(""" + func Error_FromDafny(err $L.Error)(error) { + // Service Errors + ${C|} + + return OpaqueError_Output_FromDafny(err) + } + """, DafnyNameResolver.dafnyTypesNamespace(serviceShape), + writer.consumer(w -> { + for (var error : awsNormalizedModel.getShapesWithTrait(ErrorTrait.class)) { + w.write(""" + if err.Is_$L() { + e := $L(err) + return &e + } + """, error.toShapeId().getName(), SmithyNameResolver.getFromDafnyMethodName(serviceShape, awsNormalizedModel.expectShape(error.toShapeId()), "")); + } + }) + ); + }); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkClientCodegenPlugin.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkClientCodegenPlugin.java index 1398a55c1c..a8ef0ae239 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkClientCodegenPlugin.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkClientCodegenPlugin.java @@ -1,6 +1,5 @@ package software.amazon.polymorph.smithygo.awssdk; -import java.util.Map; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoSettings; import software.amazon.polymorph.smithygo.codegen.GoWriter; @@ -10,59 +9,52 @@ import software.amazon.smithy.build.SmithyBuildPlugin; import software.amazon.smithy.codegen.core.directed.CodegenDirector; +import java.util.Map; + public class DafnyGoAwsSdkClientCodegenPlugin implements SmithyBuildPlugin { - public DafnyGoAwsSdkClientCodegenPlugin( - final Map smithyNamespaceToPythonModuleNameMap - ) { - super(); - SmithyNameResolver.setSmithyNamespaceToGoModuleNameMap( - smithyNamespaceToPythonModuleNameMap - ); - } + public DafnyGoAwsSdkClientCodegenPlugin(final Map smithyNamespaceToPythonModuleNameMap) { + super(); + SmithyNameResolver.setSmithyNamespaceToGoModuleNameMap(smithyNamespaceToPythonModuleNameMap); + } - @Override - public String getName() { - return "dafny-go-aws-sdk-client-codegen"; - } + @Override + public String getName() { + return "dafny-go-aws-sdk-client-codegen"; } - public void run(PluginContext context) { - CodegenDirector< - GoWriter, - GoIntegration, - GenerationContext, - GoSettings - > runner = new CodegenDirector<>(); + public void run(PluginContext context) { + CodegenDirector runner + = new CodegenDirector<>(); - runner.directedCodegen(new DafnyGoAwsSdkDirectedCodegen()); + runner.directedCodegen(new DafnyGoAwsSdkDirectedCodegen()); - // Set the SmithyIntegration class to look for and apply using SPI. - runner.integrationClass(GoIntegration.class); + // Set the SmithyIntegration class to look for and apply using SPI. + runner.integrationClass(GoIntegration.class); - // Set the FileManifest and Model from the plugin. - runner.fileManifest(context.getFileManifest()); + // Set the FileManifest and Model from the plugin. + runner.fileManifest(context.getFileManifest()); - // Create the GoSettings object from the plugin settings. - GoSettings settings = GoSettings.from(context.getSettings()); - runner.settings(settings); + // Create the GoSettings object from the plugin settings. + GoSettings settings = GoSettings.from(context.getSettings()); + runner.settings(settings); - runner.model(context.getModel()); + runner.model(context.getModel()); - runner.service(settings.getService()); + runner.service(settings.getService()); - // Configure the director to perform some common model transforms. - runner.performDefaultCodegenTransforms(); + // Configure the director to perform some common model transforms. + runner.performDefaultCodegenTransforms(); - // TODO: Not using below because it would break existing AWS SDKs. Maybe it should be configurable - // so generic SDKs call this by default, but AWS SDKs can opt-out of it via a setting. - // runner.createDedicatedInputsAndOutputs(); + // TODO: Not using below because it would break existing AWS SDKs. Maybe it should be configurable + // so generic SDKs call this by default, but AWS SDKs can opt-out of it via a setting. + // runner.createDedicatedInputsAndOutputs(); - // Run it! - runner.run(); - } + // Run it! + runner.run(); + } - @Override - public void execute(PluginContext context) { - this.run(context); - } + @Override + public void execute(PluginContext context) { + this.run(context); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkDirectedCodegen.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkDirectedCodegen.java index ddbccecbe4..16798586aa 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkDirectedCodegen.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkDirectedCodegen.java @@ -16,84 +16,62 @@ import software.amazon.smithy.codegen.core.directed.GenerateStructureDirective; import software.amazon.smithy.codegen.core.directed.GenerateUnionDirective; -public class DafnyGoAwsSdkDirectedCodegen - implements DirectedCodegen { - - @Override - public SymbolProvider createSymbolProvider( - CreateSymbolProviderDirective directive - ) { - return new SymbolVisitor(directive.model(), directive.settings()); - } - - @Override - public GenerationContext createContext( - CreateContextDirective directive - ) { - return GenerationContext - .builder() - .model(directive.model()) - .settings(directive.settings()) - .symbolProvider(directive.symbolProvider()) - .fileManifest(directive.fileManifest()) - .integrations(directive.integrations()) - .writerDelegator( - new GoDelegator(directive.fileManifest(), directive.symbolProvider()) - ) - .protocolGenerator( - new DafnyAwsSdkClientTypeConversionProtocol( - directive.model(), - directive.service() - ) - ) - .build(); - } - - @Override - public void generateService( - GenerateServiceDirective directive - ) { - new DafnyAwsSdkClientShimGenerator(directive.context(), directive.service()) - .run(); - - var protocolGenerator = directive.context().protocolGenerator(); - if (protocolGenerator == null) { - return; +public class DafnyGoAwsSdkDirectedCodegen implements DirectedCodegen { + @Override + public SymbolProvider createSymbolProvider(CreateSymbolProviderDirective directive) { + return new SymbolVisitor(directive.model(), directive.settings()); } - protocolGenerator.generateSerializers(directive.context()); - - protocolGenerator.generateDeserializers(directive.context()); - } - - @Override - public void generateStructure( - GenerateStructureDirective< - GenerationContext, - GoSettings - > generateStructureDirective - ) {} - - @Override - public void generateError( - GenerateErrorDirective generateErrorDirective - ) {} - - @Override - public void generateUnion( - GenerateUnionDirective generateUnionDirective - ) {} - - @Override - public void generateEnumShape( - GenerateEnumDirective generateEnumDirective - ) {} - - @Override - public void generateIntEnumShape( - GenerateIntEnumDirective< - GenerationContext, - GoSettings - > generateIntEnumDirective - ) {} + @Override + public GenerationContext createContext(CreateContextDirective directive) { + return GenerationContext.builder() + .model(directive.model()) + .settings(directive.settings()) + .symbolProvider(directive.symbolProvider()) + .fileManifest(directive.fileManifest()) + .integrations(directive.integrations()) + .writerDelegator(new GoDelegator(directive.fileManifest(), directive.symbolProvider())) + .protocolGenerator(new DafnyAwsSdkClientTypeConversionProtocol(directive.model(), directive.service())) + .build(); + } + + @Override + public void generateService(GenerateServiceDirective directive) { + new DafnyAwsSdkClientShimGenerator(directive.context(), directive.service()).run(); + + var protocolGenerator = directive.context().protocolGenerator(); + if (protocolGenerator == null) { + return; + } + + protocolGenerator.generateSerializers(directive.context()); + + protocolGenerator.generateDeserializers(directive.context()); + + } + + @Override + public void generateStructure(GenerateStructureDirective generateStructureDirective) { + + } + + @Override + public void generateError(GenerateErrorDirective generateErrorDirective) { + + } + + @Override + public void generateUnion(GenerateUnionDirective generateUnionDirective) { + + } + + @Override + public void generateEnumShape(GenerateEnumDirective generateEnumDirective) { + + } + + @Override + public void generateIntEnumShape(GenerateIntEnumDirective generateIntEnumDirective) { + + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/AwsSdkToDafnyShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/AwsSdkToDafnyShapeVisitor.java index d89e542548..62d13f66b3 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/AwsSdkToDafnyShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/AwsSdkToDafnyShapeVisitor.java @@ -1,7 +1,5 @@ package software.amazon.polymorph.smithygo.awssdk.shapevisitor; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - import software.amazon.polymorph.smithygo.awssdk.AwsSdkGoPointableIndex; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoWriter; @@ -28,538 +26,394 @@ import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.utils.StringUtils; +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + public class AwsSdkToDafnyShapeVisitor extends ShapeVisitor.Default { + private final GenerationContext context; + private final String dataSource; + private final GoWriter writer; + private final boolean isConfigShape; - private final GenerationContext context; - private final String dataSource; - private final GoWriter writer; - private final boolean isConfigShape; - - private final boolean isOptional; - protected boolean isPointerType; - - public void setPointerType() { - this.isPointerType = false; - } - - public AwsSdkToDafnyShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isConfigShape, - final boolean isOptional, - final boolean isPointerType - ) { - this.context = context; - this.dataSource = dataSource; - this.writer = writer; - this.isConfigShape = isConfigShape; - this.isOptional = isOptional; - this.isPointerType = isPointerType; - } - - @Override - protected String getDefault(Shape shape) { - throw new CodegenException( - String.format( - "Unsupported conversion of %s to %s using the %s protocol", - shape, - shape.getType(), - context.protocolGenerator().getName() - ) - ); - } - - @Override - public String blobShape(BlobShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - return """ - func () %s { - var v []interface{} - if %s == nil {return %s} - for _, e := range %s { - v = append(v, e) - } - return %s; - }()""".formatted( - returnType, - dataSource, - nilWrapIfRequired, - dataSource, - someWrapIfRequired.formatted("dafny.SeqOf(v...)") - ); - } - - @Override - public String structureShape(final StructureShape shape) { - final var builder = new StringBuilder(); - writer.addImportFromModule( - "github.com/dafny-lang/DafnyStandardLibGo", - "Wrappers" - ); - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - shape.toShapeId().getNamespace() - ), - DafnyNameResolver.dafnyTypesNamespace(shape) - ); - - String someWrapIfRequired = "%s"; - - String companionStruct; - String returnType; - if (shape.hasTrait(ErrorTrait.class)) { - companionStruct = - DafnyNameResolver.getDafnyErrorCompanionCreate( - shape, - context.symbolProvider().toSymbol(shape) - ); - returnType = DafnyNameResolver.getDafnyBaseErrorType(shape); - } else { - companionStruct = - DafnyNameResolver.getDafnyCompanionTypeCreate( - shape, - context.symbolProvider().toSymbol(shape) - ); - returnType = - DafnyNameResolver.getDafnyType( - shape, - context.symbolProvider().toSymbol(shape) - ); - } - String nilWrapIfRequired = returnType.concat("{}"); + private final boolean isOptional; + protected boolean isPointerType; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; + public void setPointerType() { + this.isPointerType = false; } - var nilCheck = ""; - if (isPointerType) { - nilCheck = - "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + public AwsSdkToDafnyShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isConfigShape, + final boolean isOptional, + final boolean isPointerType + ) { + this.context = context; + this.dataSource = dataSource; + this.writer = writer; + this.isConfigShape = isConfigShape; + this.isOptional = isOptional; + this.isPointerType = isPointerType; } - var goCodeBlock = - """ - func () %s { - %s - return %s - }()"""; - - builder.append("%1$s(".formatted(companionStruct)); - String fieldSeparator = ","; - for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { - final var memberName = memberShapeEntry.getKey(); - final var memberShape = memberShapeEntry.getValue(); - final var targetShape = context - .model() - .expectShape(memberShape.getTarget()); - builder.append( - "%1$s%2$s".formatted( - targetShape.accept( - new AwsSdkToDafnyShapeVisitor( - context, - dataSource + "." + StringUtils.capitalize(memberName), - writer, - isConfigShape, - memberShape.isOptional(), - AwsSdkGoPointableIndex - .of(context.model()) - .isPointable(memberShape) - ) - ), - fieldSeparator - ) - ); + + @Override + protected String getDefault(Shape shape) { + throw new CodegenException(String.format( + "Unsupported conversion of %s to %s using the %s protocol", + shape, shape.getType(), context.protocolGenerator().getName())); } - return goCodeBlock.formatted( - returnType, - nilCheck, - someWrapIfRequired.formatted(builder.append(")").toString()) - ); - } - - @Override - public String mapShape(MapShape shape) { - StringBuilder builder = new StringBuilder(); - - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - MemberShape keyMemberShape = shape.getKey(); - final Shape keyTargetShape = context - .model() - .expectShape(keyMemberShape.getTarget()); - MemberShape valueMemberShape = shape.getValue(); - final Shape valueTargetShape = context - .model() - .expectShape(valueMemberShape.getTarget()); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Map"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; + @Override + public String blobShape(BlobShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + return """ + func () %s { + var v []interface{} + if %s == nil {return %s} + for _, e := range %s { + v = append(v, e) + } + return %s; + }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, someWrapIfRequired.formatted("dafny.SeqOf(v...)")); } - var nilCheck = ""; - if (isPointerType) { - nilCheck = - "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + + @Override + public String structureShape(final StructureShape shape) { + final var builder = new StringBuilder(); + writer.addImportFromModule("github.com/dafny-lang/DafnyStandardLibGo", "Wrappers"); + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(shape.toShapeId().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(shape)); + + String someWrapIfRequired = "%s"; + + String companionStruct; + String returnType; + if (shape.hasTrait(ErrorTrait.class)) { + companionStruct = DafnyNameResolver.getDafnyErrorCompanionCreate(shape, context.symbolProvider().toSymbol(shape)); + returnType = DafnyNameResolver.getDafnyBaseErrorType(shape); + } else { + companionStruct = DafnyNameResolver.getDafnyCompanionTypeCreate(shape, context.symbolProvider().toSymbol(shape)); + returnType = DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)); + } + String nilWrapIfRequired = returnType.concat("{}"); + + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + var nilCheck = ""; + if (isPointerType) { + nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + var goCodeBlock = """ + func () %s { + %s + return %s + }()"""; + + + builder.append("%1$s(".formatted(companionStruct)); + String fieldSeparator = ","; + for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { + final var memberName = memberShapeEntry.getKey(); + final var memberShape = memberShapeEntry.getValue(); + final var targetShape = context.model().expectShape(memberShape.getTarget()); + builder.append("%1$s%2$s".formatted( + targetShape.accept( + new AwsSdkToDafnyShapeVisitor(context, dataSource + "." + StringUtils.capitalize(memberName), + writer, isConfigShape, memberShape.isOptional(), AwsSdkGoPointableIndex.of(context.model()).isPointable(memberShape) + )), fieldSeparator + )); + } + + + return goCodeBlock.formatted(returnType, nilCheck, someWrapIfRequired.formatted(builder.append(")").toString())); } - builder.append( - """ - func () %s { - %s - fieldValue := dafny.NewMapBuilder() - for key, val := range %s { - fieldValue.Add(%s, %s) - } - return %s - }()""".formatted( - returnType, - nilCheck, - dataSource, - keyTargetShape.accept( - new AwsSdkToDafnyShapeVisitor( - context, - "key", - writer, - isConfigShape, - false, - false - ) - ), - valueTargetShape.accept( - new AwsSdkToDafnyShapeVisitor( - context, - "val", - writer, - isConfigShape, - false, - false - ) - ), - someWrapIfRequired.formatted("fieldValue.ToMap()") - ) - ); - - // Close structure - return builder.toString(); - } - - @Override - public String listShape(ListShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - StringBuilder builder = new StringBuilder(); - - MemberShape memberShape = shape.getMember(); - final Shape targetShape = context - .model() - .expectShape(memberShape.getTarget()); - - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; + + @Override + public String mapShape(MapShape shape) { + StringBuilder builder = new StringBuilder(); + + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + MemberShape keyMemberShape = shape.getKey(); + final Shape keyTargetShape = context.model().expectShape(keyMemberShape.getTarget()); + MemberShape valueMemberShape = shape.getValue(); + final Shape valueTargetShape = context.model().expectShape(valueMemberShape.getTarget()); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Map"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + var nilCheck = ""; + if (isPointerType) { + nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + builder.append(""" + func () %s { + %s + fieldValue := dafny.NewMapBuilder() + for key, val := range %s { + fieldValue.Add(%s, %s) + } + return %s + }()""".formatted(returnType, nilCheck, dataSource, + keyTargetShape.accept( + new AwsSdkToDafnyShapeVisitor(context, "key", writer, isConfigShape, false, false)), + valueTargetShape.accept( + new AwsSdkToDafnyShapeVisitor(context, "val", writer, isConfigShape, false, false)), + someWrapIfRequired.formatted("fieldValue.ToMap()") + ) + ); + + // Close structure + return builder.toString(); + } - builder.append( - """ - func () %s { - if %s == nil { return %s } - var fieldValue []interface{} = make([]interface{}, 0) - for _, val := range %s { - element := %s - fieldValue = append(fieldValue, element) - } - return %s - }()""".formatted( - returnType, - dataSource, - nilWrapIfRequired, - dataSource, - targetShape.accept( - new AwsSdkToDafnyShapeVisitor( - context, - "val", - writer, - isConfigShape, - false, - false - ) - ), - someWrapIfRequired.formatted("dafny.SeqOf(fieldValue...)") - ) - ); - - // Close structure - return builder.toString(); - } - - @Override - public String booleanShape(BooleanShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "false"; - String someWrapIfRequired = "%s%s"; - String returnType = "bool"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; + @Override + public String listShape(ListShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + StringBuilder builder = new StringBuilder(); + + MemberShape memberShape = shape.getMember(); + final Shape targetShape = context.model().expectShape(memberShape.getTarget()); + + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + builder.append(""" + func () %s { + if %s == nil { return %s } + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range %s { + element := %s + fieldValue = append(fieldValue, element) + } + return %s + }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, + targetShape.accept( + new AwsSdkToDafnyShapeVisitor(context, "val", writer, isConfigShape, false, false) + ), someWrapIfRequired.formatted("dafny.SeqOf(fieldValue...)"))); + + // Close structure + return builder.toString(); } - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = - "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + @Override + public String booleanShape(BooleanShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "false"; + String someWrapIfRequired = "%s%s"; + String returnType = "bool"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; + } + + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + + return """ + func () %s { + %s + return %s + }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); } - return """ - func () %s { - %s - return %s - }()""".formatted( - returnType, - nilCheck, - someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) - ); - } - - @Override - public String stringShape(StringShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (shape.hasTrait(EnumTrait.class)) { - String someWrapIfRequired = "%s"; - String returnType = DafnyNameResolver.getDafnyType( - shape, - context.symbolProvider().toSymbol(shape) - ); - if (this.isOptional) { - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - - return """ - func () %s { - var index int - for _, enumVal := range %s.Values() { - index++ - if enumVal == %s{ - break; - } - } - var enum interface{} - for allEnums, i := dafny.Iterate(%s{}.AllSingletonConstructors()), 0; i < index; i++ { - var ok bool - enum, ok = allEnums() - if !ok { - break; - } - } - return %s - }()""".formatted( - returnType, - dataSource, - dataSource, - DafnyNameResolver.getDafnyCompanionStructType( - shape, - context.symbolProvider().toSymbol(shape) - ), - someWrapIfRequired.formatted( - "enum.(%s)".formatted( - DafnyNameResolver.getDafnyType( - shape, - context.symbolProvider().toSymbol(shape) - ) - ) - ) - ); - } else { - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - - var nilCheck = ""; - var dereferenceIfRequired = isPointerType ? "*" : ""; - if (isPointerType) { - nilCheck = - "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - - if (shape.hasTrait(DafnyUtf8BytesTrait.class)) writer.addUseImports( - SmithyGoDependency.stdlib("unicode/utf8") - ); - - var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) - ? """ - dafny.SeqOf(func () []interface{} { - utf8.ValidString(%s%s) - b := []byte(%s%s) - f := make([]interface{}, len(b)) - for i, v := range b { - f[i] = v + @Override + public String stringShape(StringShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (shape.hasTrait(EnumTrait.class)) { + String someWrapIfRequired = "%s"; + String returnType = DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)); + if (this.isOptional) { + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + return """ + func () %s { + var index int + for _, enumVal := range %s.Values() { + index++ + if enumVal == %s{ + break; + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(%s{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break; + } + } + return %s + }()""".formatted(returnType, dataSource, dataSource, DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), someWrapIfRequired.formatted("enum.(%s)".formatted(DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))))); + } else { + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - return f - }()...)""".formatted( - dereferenceIfRequired, - dataSource, - dereferenceIfRequired, - dataSource - ) - : "dafny.SeqOfChars([]dafny.Char(%s%s)...)".formatted( - dereferenceIfRequired, - dataSource - ); - - return """ - func () %s { - %s - return %s - }()""".formatted( - returnType, - nilCheck, - someWrapIfRequired.formatted(underlyingType) - ); - } - } - - @Override - public String integerShape(IntegerShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "0"; - String someWrapIfRequired = "%s%s"; - String returnType = "int"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; - } - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = - "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + var nilCheck = ""; + var dereferenceIfRequired = isPointerType ? "*" : ""; + if (isPointerType) { + nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + + if (shape.hasTrait(DafnyUtf8BytesTrait.class)) + writer.addUseImports(SmithyGoDependency.stdlib("unicode/utf8")); + + var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) ? """ + dafny.SeqOf(func () []interface{} { + utf8.ValidString(%s%s) + b := []byte(%s%s) + f := make([]interface{}, len(b)) + for i, v := range b { + f[i] = v + } + return f + }()...)""".formatted(dereferenceIfRequired, dataSource, dereferenceIfRequired, dataSource) : "dafny.SeqOfChars([]dafny.Char(%s%s)...)".formatted(dereferenceIfRequired, dataSource); + + return """ + func () %s { + %s + return %s + }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(underlyingType)); + } } - return """ - func () %s { - %s - return %s - }()""".formatted( - returnType, - nilCheck, - someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) - ); - } - - @Override - public String longShape(LongShape shape) { - String nilWrapIfRequired = "0"; - String someWrapIfRequired = "%s%s"; - String returnType = "int64"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; + @Override + public String integerShape(IntegerShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "0"; + String someWrapIfRequired = "%s%s"; + String returnType = "int"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; + } + + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + + return """ + func () %s { + %s + return %s + }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); + } - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = - "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + @Override + public String longShape(LongShape shape) { + String nilWrapIfRequired = "0"; + String someWrapIfRequired = "%s%s"; + String returnType = "int64"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; + } + + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + return """ + func () %s { + %s + return %s + }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); } - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - return """ - func () %s { - %s - return %s - }()""".formatted( - returnType, - nilCheck, - someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) - ); - } - - @Override - public String doubleShape(DoubleShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); - writer.addUseImports(SmithyGoDependency.MATH); - - String nilWrapIfRequired = "dafny.SeqOf()"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; + @Override + public String doubleShape(DoubleShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); + writer.addUseImports(SmithyGoDependency.MATH); + + String nilWrapIfRequired = "dafny.SeqOf()"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + + return """ + func () %s { + %s + var bits = math.Float64bits(%s%s) + var bytes = make([]byte, 8) + binary.LittleEndian.PutUint64(bytes, bits) + var v []interface{} + for _, e := range bytes { + v = append(v, e) + } + return %s; + }()""".formatted(returnType, nilCheck, dereferenceIfRequired, dataSource, someWrapIfRequired.formatted("dafny.SeqOf(v...)")); } - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = - "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + @Override + public String unionShape(UnionShape shape) { + return """ + func () Wrappers.Option { + _ = val + return Wrappers.Companion_Option_.Create_None_() + }()"""; } - return """ - func () %s { - %s - var bits = math.Float64bits(%s%s) - var bytes = make([]byte, 8) - binary.LittleEndian.PutUint64(bytes, bits) - var v []interface{} - for _, e := range bytes { - v = append(v, e) - } - return %s; - }()""".formatted( - returnType, - nilCheck, - dereferenceIfRequired, - dataSource, - someWrapIfRequired.formatted("dafny.SeqOf(v...)") - ); - } - - @Override - public String unionShape(UnionShape shape) { - return """ - func () Wrappers.Option { - _ = val - return Wrappers.Companion_Option_.Create_None_() - }()"""; - } - - @Override - public String timestampShape(TimestampShape shape) { - if (this.isOptional) { - return "Wrappers.Companion_Option_.Create_None_()"; + @Override + public String timestampShape(TimestampShape shape) { + if (this.isOptional) { + return "Wrappers.Companion_Option_.Create_None_()"; + } + return "dafny.SeqOf()"; } - return "dafny.SeqOf()"; - } -} +} \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/DafnyToAwsSdkShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/DafnyToAwsSdkShapeVisitor.java index a427578d93..db3d54c719 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/DafnyToAwsSdkShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/DafnyToAwsSdkShapeVisitor.java @@ -1,11 +1,9 @@ package software.amazon.polymorph.smithygo.awssdk.shapevisitor; -import java.util.Arrays; -import java.util.List; -import software.amazon.polymorph.smithygo.awssdk.AwsSdkGoPointableIndex; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoWriter; import software.amazon.polymorph.smithygo.codegen.SmithyGoDependency; +import software.amazon.polymorph.smithygo.awssdk.AwsSdkGoPointableIndex; import software.amazon.polymorph.smithygo.codegen.SymbolUtils; import software.amazon.polymorph.smithygo.codegen.Synthetic; import software.amazon.polymorph.smithygo.codegen.knowledge.GoPointableIndex; @@ -35,537 +33,363 @@ import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.utils.StringUtils; -public class DafnyToAwsSdkShapeVisitor extends ShapeVisitor.Default { +import java.util.Arrays; +import java.util.List; - private static final List shapeName = Arrays.asList( - "IndexSizeBytes", - "ItemCount", - "ProcessedSizeBytes", - "TableSizeBytes" - ); - private final AwsSdkGoPointableIndex awsSdkGoPointableIndex; - private final GenerationContext context; - private final String dataSource; - private final GoWriter writer; - private final ServiceTrait serviceTrait; - private final boolean isOptional; - private final boolean isPointable; +public class DafnyToAwsSdkShapeVisitor extends ShapeVisitor.Default { + private static final List shapeName = Arrays.asList("IndexSizeBytes", "ItemCount", "ProcessedSizeBytes", "TableSizeBytes"); + private final AwsSdkGoPointableIndex awsSdkGoPointableIndex; + private final GenerationContext context; + private final String dataSource; + private final GoWriter writer; + private final ServiceTrait serviceTrait; + private final boolean isOptional; + private final boolean isPointable; - public DafnyToAwsSdkShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer - ) { - this(context, dataSource, writer, false, false); - } + public DafnyToAwsSdkShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer + ) { + this(context, dataSource, writer, false, false); + } - public DafnyToAwsSdkShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isOptional, - final boolean isPointable - ) { - this.context = context; - this.dataSource = dataSource; - this.writer = writer; - this.isOptional = isOptional; - this.isPointable = isPointable; - this.awsSdkGoPointableIndex = new AwsSdkGoPointableIndex(context.model()); - this.serviceTrait = - context - .model() - .expectShape(context.settings().getService(context.model()).toShapeId()) - .getTrait(ServiceTrait.class) - .get(); - } + public DafnyToAwsSdkShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isOptional, + final boolean isPointable + ) { + this.context = context; + this.dataSource = dataSource; + this.writer = writer; + this.isOptional = isOptional; + this.isPointable = isPointable; + this.awsSdkGoPointableIndex = new AwsSdkGoPointableIndex(context.model()); + this.serviceTrait = context.model().expectShape(context.settings().getService(context.model()).toShapeId()).getTrait(ServiceTrait.class).get(); + } - @Override - protected String getDefault(Shape shape) { - throw new CodegenException( - String.format( - "Unsupported conversion of %s to %s using the %s protocol", - shape, - shape.getType(), - context.protocolGenerator().getName() - ) - ); - } + @Override + protected String getDefault(Shape shape) { + throw new CodegenException(String.format( + "Unsupported conversion of %s to %s using the %s protocol", + shape, shape.getType(), context.protocolGenerator().getName())); + } - @Override - public String blobShape(BlobShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - return """ - func () []byte { - var b []byte - if %s == nil { - return nil + @Override + public String blobShape(BlobShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + return """ + func () []byte { + var b []byte + if %s == nil { + return nil + } + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }()""".formatted(dataSource, dataSource); } - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return b - } else { - b = append(b, val.(byte)) + + @Override + public String structureShape(final StructureShape shape) { + final var builder = new StringBuilder(); + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(shape.toShapeId().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(shape)); + var subtype = !(awsSdkGoPointableIndex.isOperationStruct(shape) || shape.hasTrait(Synthetic.class)) + || shape.toShapeId().getName().contains("Exception"); + var nilcheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilcheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilcheck = ""; + } + } + builder.append(""" + func() %s%s { + %s + return %s%s { + """.formatted(this.isPointable ? "*" : "", SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, subtype).concat(".").concat(shape.getId().getName()), + nilcheck, + this.isPointable ? "&" : "", + SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, subtype).concat(".").concat(shape.getId().getName())) + ); + for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { + final var memberName = memberShapeEntry.getKey(); + final var memberShape = memberShapeEntry.getValue(); + final var targetShape = context.model().expectShape(memberShape.getTarget()); + //TODO: Is it ever possible for structure to be nil? + final var derivedDataSource = "%1$s%2$s%3$s%4$s".formatted(dataSource, this.isOptional ? ".(%s)".formatted(DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))) : "", + ".Dtor_%s()".formatted(memberName), + memberShape.isOptional() ? ".UnwrapOr(nil)" : ""); + builder.append("%1$s: %2$s,".formatted( + StringUtils.capitalize(memberName), + targetShape.accept( + new DafnyToAwsSdkShapeVisitor(context, derivedDataSource, writer, memberShape.isOptional(), shapeName.contains(memberName) || awsSdkGoPointableIndex.isPointable(targetShape)) + ) + )); } - } - }()""".formatted(dataSource, dataSource); - } - @Override - public String structureShape(final StructureShape shape) { - final var builder = new StringBuilder(); - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - shape.toShapeId().getNamespace() - ), - DafnyNameResolver.dafnyTypesNamespace(shape) - ); - var subtype = - !(awsSdkGoPointableIndex.isOperationStruct(shape) || - shape.hasTrait(Synthetic.class)) || - shape.toShapeId().getName().contains("Exception"); - var nilcheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilcheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilcheck = ""; - } + return builder.append("}}()").toString(); } - builder.append( - """ - func() %s%s { - %s - return %s%s { - """.formatted( - this.isPointable ? "*" : "", - SmithyNameResolver - .smithyTypesNamespaceAws(serviceTrait, subtype) - .concat(".") - .concat(shape.getId().getName()), - nilcheck, - this.isPointable ? "&" : "", - SmithyNameResolver - .smithyTypesNamespaceAws(serviceTrait, subtype) - .concat(".") - .concat(shape.getId().getName()) - ) - ); - for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { - final var memberName = memberShapeEntry.getKey(); - final var memberShape = memberShapeEntry.getValue(); - final var targetShape = context - .model() - .expectShape(memberShape.getTarget()); - //TODO: Is it ever possible for structure to be nil? - final var derivedDataSource = - "%1$s%2$s%3$s%4$s".formatted( - dataSource, - this.isOptional - ? ".(%s)".formatted( - DafnyNameResolver.getDafnyType( - shape, - context.symbolProvider().toSymbol(shape) - ) - ) - : "", - ".Dtor_%s()".formatted(memberName), - memberShape.isOptional() ? ".UnwrapOr(nil)" : "" - ); - builder.append( - "%1$s: %2$s,".formatted( - StringUtils.capitalize(memberName), - targetShape.accept( - new DafnyToAwsSdkShapeVisitor( - context, - derivedDataSource, - writer, - memberShape.isOptional(), - shapeName.contains(memberName) || - awsSdkGoPointableIndex.isPointable(targetShape) - ) - ) - ) - ); - } - - return builder.append("}}()").toString(); - } - // TODO: smithy-dafny-conversion library - @Override - public String listShape(ListShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - StringBuilder builder = new StringBuilder(); + // TODO: smithy-dafny-conversion library + @Override + public String listShape(ListShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + StringBuilder builder = new StringBuilder(); - MemberShape memberShape = shape.getMember(); - final Shape targetShape = context - .model() - .expectShape(memberShape.getTarget()); - var typeName = GoCodegenUtils.getType( - context.symbolProvider().toSymbol(targetShape), - serviceTrait - ); - builder.append( - """ - func() []%s{ - var fieldValue []%s - %s - for i := dafny.Iterate(%s.(dafny.Sequence)); ; { - val, ok := i() - if !ok { - break - } - fieldValue = append(fieldValue, %s)} - """.formatted( - typeName, - typeName, - this.isOptional - ? """ - if %s == nil { - return nil - }""".formatted(dataSource) - : "", - dataSource, - targetShape.accept( - new DafnyToAwsSdkShapeVisitor( - context, - "val%s".formatted( - memberShape.isOptional() - ? ".(%s)".formatted( - DafnyNameResolver.getDafnyType( - targetShape, - context.symbolProvider().toSymbol(targetShape) - ) - ) - : "" - ), - writer, - false, - awsSdkGoPointableIndex.isPointable(memberShape) - ) - ) - ) - ); + MemberShape memberShape = shape.getMember(); + final Shape targetShape = context.model().expectShape(memberShape.getTarget()); + var typeName = GoCodegenUtils.getType(context.symbolProvider().toSymbol(targetShape), serviceTrait); + builder.append(""" + func() []%s{ + var fieldValue []%s + %s + for i := dafny.Iterate(%s.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, %s)} + """.formatted(typeName, typeName, this.isOptional ? """ + if %s == nil { + return nil + }""".formatted(dataSource) : "", dataSource, + targetShape.accept( + new DafnyToAwsSdkShapeVisitor(context, "val%s".formatted(memberShape.isOptional() ? ".(%s)".formatted(DafnyNameResolver.getDafnyType(targetShape, context.symbolProvider().toSymbol(targetShape))) : ""), writer, false, awsSdkGoPointableIndex.isPointable(memberShape)) + ))); - // Close structure - return builder.append("return fieldValue }()").toString(); - } + // Close structure + return builder.append("return fieldValue }()").toString(); + } - @Override - public String mapShape(MapShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - StringBuilder builder = new StringBuilder(); + @Override + public String mapShape(MapShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + StringBuilder builder = new StringBuilder(); - MemberShape keyMemberShape = shape.getKey(); - final Shape keyTargetShape = context - .model() - .expectShape(keyMemberShape.getTarget()); - MemberShape valueMemberShape = shape.getValue(); - final Shape valueTargetShape = context - .model() - .expectShape(valueMemberShape.getTarget()); - var typeName = GoCodegenUtils.getType( - context.symbolProvider().toSymbol(valueTargetShape), - serviceTrait - ); + MemberShape keyMemberShape = shape.getKey(); + final Shape keyTargetShape = context.model().expectShape(keyMemberShape.getTarget()); + MemberShape valueMemberShape = shape.getValue(); + final Shape valueTargetShape = context.model().expectShape(valueMemberShape.getTarget()); + var typeName = GoCodegenUtils.getType(context.symbolProvider().toSymbol(valueTargetShape), serviceTrait); - var nilCheck = ""; - if (this.isOptional) { - nilCheck = - """ - if %s == nil { - return nil + var nilCheck = ""; + if (this.isOptional) { + nilCheck = """ + if %s == nil { + return nil + } + """.formatted(dataSource); } - """.formatted(dataSource); + builder.append(""" + func() map[string]%s { + var m map[string]%s = make(map[string]%s) + %s + for i := dafny.Iterate(%s%s.Items());; { + val, ok := i() + if !ok { + break; + } + m[%s] = %s + } + return m + }()""".formatted(typeName, typeName, typeName, nilCheck, dataSource, this.isOptional ? ".(dafny.Map)" : "", + keyTargetShape.accept( + new DafnyToAwsSdkShapeVisitor(context, "(*val.(dafny.Tuple).IndexInt(0))", writer, keyMemberShape.isOptional(), awsSdkGoPointableIndex.isPointable(keyMemberShape))), + valueTargetShape.accept( + new DafnyToAwsSdkShapeVisitor(context, "(*val.(dafny.Tuple).IndexInt(1))%s".formatted(valueMemberShape.isOptional() ? ".(%s)".formatted(DafnyNameResolver.getDafnyType(valueTargetShape, context.symbolProvider().toSymbol(valueTargetShape))) : ""), writer, false, awsSdkGoPointableIndex.isPointable(valueMemberShape)) + ) + )); + return builder.toString(); } - builder.append( - """ - func() map[string]%s { - var m map[string]%s = make(map[string]%s) - %s - for i := dafny.Iterate(%s%s.Items());; { - val, ok := i() - if !ok { - break; - } - m[%s] = %s - } - return m - }()""".formatted( - typeName, - typeName, - typeName, - nilCheck, - dataSource, - this.isOptional ? ".(dafny.Map)" : "", - keyTargetShape.accept( - new DafnyToAwsSdkShapeVisitor( - context, - "(*val.(dafny.Tuple).IndexInt(0))", - writer, - keyMemberShape.isOptional(), - awsSdkGoPointableIndex.isPointable(keyMemberShape) - ) - ), - valueTargetShape.accept( - new DafnyToAwsSdkShapeVisitor( - context, - "(*val.(dafny.Tuple).IndexInt(1))%s".formatted( - valueMemberShape.isOptional() - ? ".(%s)".formatted( - DafnyNameResolver.getDafnyType( - valueTargetShape, - context.symbolProvider().toSymbol(valueTargetShape) - ) - ) - : "" - ), - writer, - false, - awsSdkGoPointableIndex.isPointable(valueMemberShape) - ) - ) - ) - ); - return builder.toString(); - } - @Override - public String booleanShape(BooleanShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - var nilCheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilCheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilCheck = "if %s == nil { return b }".formatted(dataSource); - } + @Override + public String booleanShape(BooleanShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + var nilCheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilCheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilCheck = "if %s == nil { return b }".formatted(dataSource); + } + } + return """ + func() %sbool { + var b bool + %s + b = %s%s + return %sb + }()""".formatted(this.isPointable ? "*" : "", nilCheck, dataSource, this.isOptional ? ".(%s)".formatted(context.symbolProvider().toSymbol(shape).getName()) : "", + this.isPointable ? "&" : ""); } - return """ - func() %sbool { - var b bool - %s - b = %s%s - return %sb - }()""".formatted( - this.isPointable ? "*" : "", - nilCheck, - dataSource, - this.isOptional - ? ".(%s)".formatted( - context.symbolProvider().toSymbol(shape).getName() - ) - : "", - this.isPointable ? "&" : "" - ); - } - @Override - public String stringShape(StringShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (shape.hasTrait(EnumTrait.class)) { - if (this.isOptional) { - return """ - func () %s.%s { - var u %s.%s - //TODO: What to do if nil - if %s == nil { - return u + @Override + public String stringShape(StringShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (shape.hasTrait(EnumTrait.class)) { + if (this.isOptional) { + return """ + func () %s.%s { + var u %s.%s + //TODO: What to do if nil + if %s == nil { + return u + } + inputEnum := %s.(%s) + index := -1; + for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(%s).Equals(inputEnum) { + break; + } + } + } + return u.Values()[index] + }()""".formatted(SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), context.symbolProvider().toSymbol(shape).getName(), + SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), context.symbolProvider().toSymbol(shape).getName(), + dataSource, + dataSource, DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)), + DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), + DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))); + } else { + return """ + func () %s.%s { + var u %s.%s + + inputEnum := %s + index := -1; + for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(%s).Equals(inputEnum) { + break; + } + } + } + return u.Values()[index] + }()""".formatted(SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), context.symbolProvider().toSymbol(shape).getName(), + SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), context.symbolProvider().toSymbol(shape).getName(), + dataSource, + DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), + DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))); } - inputEnum := %s.(%s) - index := -1; - for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { - enum, ok := allEnums() - if ok { - index++ - if enum.(%s).Equals(inputEnum) { - break; - } - } - } - return u.Values()[index] - }()""".formatted( - SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), - context.symbolProvider().toSymbol(shape).getName(), - SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), - context.symbolProvider().toSymbol(shape).getName(), - dataSource, - dataSource, - DafnyNameResolver.getDafnyType( - shape, - context.symbolProvider().toSymbol(shape) - ), - DafnyNameResolver.getDafnyCompanionStructType( - shape, - context.symbolProvider().toSymbol(shape) - ), - DafnyNameResolver.getDafnyType( - shape, - context.symbolProvider().toSymbol(shape) - ) - ); - } else { - return """ - func () %s.%s { - var u %s.%s + } - inputEnum := %s - index := -1; - for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { - enum, ok := allEnums() - if ok { - index++ - if enum.(%s).Equals(inputEnum) { - break; - } - } - } - return u.Values()[index] - }()""".formatted( - SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), - context.symbolProvider().toSymbol(shape).getName(), - SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), - context.symbolProvider().toSymbol(shape).getName(), - dataSource, - DafnyNameResolver.getDafnyCompanionStructType( - shape, - context.symbolProvider().toSymbol(shape) - ), - DafnyNameResolver.getDafnyType( - shape, - context.symbolProvider().toSymbol(shape) - ) - ); - } + var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) ? "uint8" : "dafny.Char"; + var nilCheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilCheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilCheck = "if %s == nil { return s }".formatted(dataSource); + } + } + return """ + func() (%sstring) { + var s string + %s + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return %s[]string{s}[0] + } else { + s = s + string(val.(%s)) + } + } + }()""".formatted(this.isPointable ? "*" : "", nilCheck, dataSource, this.isPointable ? "&" : "", underlyingType); } - var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) - ? "uint8" - : "dafny.Char"; - var nilCheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilCheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilCheck = "if %s == nil { return s }".formatted(dataSource); - } - } - return """ - func() (%sstring) { - var s string - %s - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return %s[]string{s}[0] - } else { - s = s + string(val.(%s)) - } + @Override + public String integerShape(IntegerShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (AwsSdkGoPointableIndex.of(context.model()).isPointable(shape)) { + return """ + func() *int32 { + var i int32 + if %s == nil { + return nil + } + i = %s.(int32) + return &i + }()""".formatted(dataSource, dataSource); + } else { + return "%s.(%s)".formatted(dataSource, context.symbolProvider().toSymbol(shape).getName()); } - }()""".formatted( - this.isPointable ? "*" : "", - nilCheck, - dataSource, - this.isPointable ? "&" : "", - underlyingType - ); - } + } - @Override - public String integerShape(IntegerShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (AwsSdkGoPointableIndex.of(context.model()).isPointable(shape)) { - return """ - func() *int32 { - var i int32 - if %s == nil { - return nil - } - i = %s.(int32) - return &i - }()""".formatted(dataSource, dataSource); - } else { - return "%s.(%s)".formatted( - dataSource, - context.symbolProvider().toSymbol(shape).getName() - ); + @Override + public String longShape(LongShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + var nilCheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilCheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilCheck = "if %s == nil { return i}".formatted(dataSource); + } + } + return """ + func() %sint64 { + var i int64 + %s + i = %s%s + return %si + }()""".formatted(this.isPointable ? "*" : "", nilCheck, dataSource, this.isOptional ? ".(int64)" : "", this.isPointable ? "&" : ""); } - } - @Override - public String longShape(LongShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - var nilCheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilCheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilCheck = "if %s == nil { return i}".formatted(dataSource); - } + @Override + public String doubleShape(DoubleShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + writer.addUseImports(SmithyGoDependency.MATH); + writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); + var nilCheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilCheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilCheck = "if %s == nil { var f float64; return f}".formatted(dataSource); + } + } + return """ + func () %sfloat64 { + var b []byte + %s + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return %s[]float64{math.Float64frombits(binary.LittleEndian.Uint64(b))}[0] + } else { + b = append(b, val.(byte)) + } + } + }()""".formatted(this.isPointable ? "*" : "", nilCheck, dataSource, this.isPointable ? "&" : ""); } - return """ - func() %sint64 { - var i int64 - %s - i = %s%s - return %si - }()""".formatted( - this.isPointable ? "*" : "", - nilCheck, - dataSource, - this.isOptional ? ".(int64)" : "", - this.isPointable ? "&" : "" - ); - } - @Override - public String doubleShape(DoubleShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - writer.addUseImports(SmithyGoDependency.MATH); - writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); - var nilCheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilCheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilCheck = - "if %s == nil { var f float64; return f}".formatted(dataSource); - } + @Override + public String unionShape(UnionShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + return """ + func () types.%s { + _ = val + return nil + }()""".formatted(context.symbolProvider().toSymbol(shape).getName()); } - return """ - func () %sfloat64 { - var b []byte - %s - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return %s[]float64{math.Float64frombits(binary.LittleEndian.Uint64(b))}[0] - } else { - b = append(b, val.(byte)) - } - } - }()""".formatted( - this.isPointable ? "*" : "", - nilCheck, - dataSource, - this.isPointable ? "&" : "" - ); - } - @Override - public String unionShape(UnionShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - return """ - func () types.%s { - _ = val - return nil - }()""".formatted(context.symbolProvider().toSymbol(shape).getName()); - } + @Override + public String timestampShape(TimestampShape shape) { + return "nil"; + } - @Override - public String timestampShape(TimestampShape shape) { - return "nil"; - } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/AddOperationShapes.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/AddOperationShapes.java index bd63a39ed6..36a3d64526 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/AddOperationShapes.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/AddOperationShapes.java @@ -17,6 +17,7 @@ import java.util.TreeSet; import java.util.logging.Logger; + import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.shapes.AbstractShapeBuilder; @@ -30,117 +31,85 @@ * Ensures that each operation has a unique input and output shape. */ public final class AddOperationShapes { + private static final Logger LOGGER = Logger.getLogger(AddOperationShapes.class.getName()); + + private AddOperationShapes() { + } + + /** + * Processes the given model and returns a new model ensuring service operation has an unique input and output + * synthesized shape. + * + * @param model the model + * @param serviceShapeId the service shape + * @return a model with unique operation input and output shapes + */ + public static Model execute(Model model, ShapeId serviceShapeId) { + TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); + ServiceShape service = model.expectShape(serviceShapeId, ServiceShape.class); + TreeSet operations = new TreeSet<>(topDownIndex.getContainedOperations( + model.expectShape(serviceShapeId))); + + Model.Builder modelBuilder = model.toBuilder(); + for (OperationShape operation : operations) { + OperationShape.Builder operationBuilder = operation.toBuilder(); + ShapeId operationId = operation.getId(); + LOGGER.info(() -> "building unique input/output shapes for " + operationId); + if (operation.getInput().isPresent()) { + StructureShape newInputShape = operation.getInput() + .map(shapeId -> cloneOperationShape( + service, operationId, (StructureShape) model.expectShape(shapeId), "Input")).get(); + modelBuilder.addShape(newInputShape); + operationBuilder.input(newInputShape.toShapeId()); + } + + if (operation.getOutput().isPresent()) { + StructureShape newOutputShape = operation.getOutput() + .map(shapeId -> cloneOperationShape( + service, operationId, (StructureShape) model.expectShape(shapeId), "Output")).get(); + modelBuilder.addShape(newOutputShape); + operationBuilder.output(newOutputShape.toShapeId()); + } + + // Update operation model with the input/output shape ids + modelBuilder.addShape(operationBuilder.build()); + } + + return modelBuilder.build(); + } - private static final Logger LOGGER = Logger.getLogger( - AddOperationShapes.class.getName() - ); - - private AddOperationShapes() {} - - /** - * Processes the given model and returns a new model ensuring service operation has an unique input and output - * synthesized shape. - * - * @param model the model - * @param serviceShapeId the service shape - * @return a model with unique operation input and output shapes - */ - public static Model execute(Model model, ShapeId serviceShapeId) { - TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - ServiceShape service = model.expectShape( - serviceShapeId, - ServiceShape.class - ); - TreeSet operations = new TreeSet<>( - topDownIndex.getContainedOperations(model.expectShape(serviceShapeId)) - ); - - Model.Builder modelBuilder = model.toBuilder(); - for (OperationShape operation : operations) { - OperationShape.Builder operationBuilder = operation.toBuilder(); - ShapeId operationId = operation.getId(); - LOGGER.info(() -> "building unique input/output shapes for " + operationId - ); - if (operation.getInput().isPresent()) { - StructureShape newInputShape = operation - .getInput() - .map(shapeId -> - cloneOperationShape( - service, - operationId, - (StructureShape) model.expectShape(shapeId), - "Input" - ) - ) - .get(); - modelBuilder.addShape(newInputShape); - operationBuilder.input(newInputShape.toShapeId()); - } - - if (operation.getOutput().isPresent()) { - StructureShape newOutputShape = operation - .getOutput() - .map(shapeId -> - cloneOperationShape( - service, - operationId, - (StructureShape) model.expectShape(shapeId), - "Output" - ) - ) - .get(); - modelBuilder.addShape(newOutputShape); - operationBuilder.output(newOutputShape.toShapeId()); - } - - // Update operation model with the input/output shape ids - modelBuilder.addShape(operationBuilder.build()); +// private static StructureShape emptyOperationStructure(ServiceShape service, ShapeId opShapeId, String suffix) { +// return StructureShape.builder() +// .id(ShapeId.fromParts(service.toShapeId().getNamespace(), opShapeId.getName(service) + suffix)) +// .addTrait(Synthetic.builder().build()) +// .build(); +// } + + private static StructureShape cloneOperationShape( + ServiceShape service, + ShapeId operationShapeId, + StructureShape structureShape, + String suffix + ) { + return (StructureShape) cloneShape(structureShape, operationShapeId.getName(service) + suffix); } - return modelBuilder.build(); - } - - // private static StructureShape emptyOperationStructure(ServiceShape service, ShapeId opShapeId, String suffix) { - // return StructureShape.builder() - // .id(ShapeId.fromParts(service.toShapeId().getNamespace(), opShapeId.getName(service) + suffix)) - // .addTrait(Synthetic.builder().build()) - // .build(); - // } - - private static StructureShape cloneOperationShape( - ServiceShape service, - ShapeId operationShapeId, - StructureShape structureShape, - String suffix - ) { - return (StructureShape) cloneShape( - structureShape, - operationShapeId.getName(service) + suffix - ); - } - - private static Shape cloneShape(Shape shape, String cloneShapeName) { - ShapeId cloneShapeId = ShapeId.fromParts( - shape.toShapeId().getNamespace(), - cloneShapeName - ); - - AbstractShapeBuilder builder = Shape - .shapeToBuilder(shape) - .id(cloneShapeId) - .addTrait(Synthetic.builder().archetype(shape.getId()).build()); - - shape - .members() - .forEach(memberShape -> { - builder.addMember( - memberShape - .toBuilder() - .id(cloneShapeId.withMember(memberShape.getMemberName())) - .build() - ); - }); - - return (Shape) builder.build(); - } -} + private static Shape cloneShape(Shape shape, String cloneShapeName) { + ShapeId cloneShapeId = ShapeId.fromParts(shape.toShapeId().getNamespace(), cloneShapeName); + + AbstractShapeBuilder builder = Shape.shapeToBuilder(shape) + .id(cloneShapeId) + .addTrait(Synthetic.builder() + .archetype(shape.getId()) + .build()); + + shape.members().forEach(memberShape -> { + builder.addMember(memberShape.toBuilder() + .id(cloneShapeId.withMember(memberShape.getMemberName())) + .build()); + }); + + + return (Shape) builder.build(); + } +} \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ApplicationProtocol.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ApplicationProtocol.java index d66d096247..a436b7d90a 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ApplicationProtocol.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ApplicationProtocol.java @@ -2,14 +2,10 @@ import software.amazon.smithy.codegen.core.SymbolReference; import software.amazon.smithy.utils.SmithyUnstableApi; - /** * Represents the resolves {@link Symbol}s and references for an * application protocol (e.g., "http", "mqtt", etc). */ @SmithyUnstableApi -public record ApplicationProtocol( - String name, - SymbolReference requestType, - SymbolReference responseType -) {} +public record ApplicationProtocol(String name, SymbolReference requestType, SymbolReference responseType) { +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/CodegenUtils.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/CodegenUtils.java index aef04700fa..9e4d363813 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/CodegenUtils.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/CodegenUtils.java @@ -15,17 +15,6 @@ package software.amazon.polymorph.smithygo.codegen; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Optional; -import java.util.function.Predicate; -import java.util.logging.Logger; import software.amazon.polymorph.smithygo.codegen.knowledge.GoPointableIndex; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; @@ -42,422 +31,402 @@ import software.amazon.smithy.model.traits.TitleTrait; import software.amazon.smithy.utils.StringUtils; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.logging.Logger; + /** * Utility methods likely to be needed across packages. */ public final class CodegenUtils { - private static final Logger LOGGER = Logger.getLogger( - CodegenUtils.class.getName() - ); - - private static final String SYNTHETIC_NAMESPACE = "smithy.go.synthetic"; - - private CodegenUtils() {} - - /** - * Executes a given shell command in a given directory. - * - * @param command The string command to execute, e.g. "go fmt". - * @param directory The directory to run the command in. - * @return Returns the console output of the command. - */ - public static String runCommand(String command, Path directory) { - String[] finalizedCommand; - if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { - finalizedCommand = new String[] { "cmd.exe", "/c", command }; - } else { - finalizedCommand = new String[] { "sh", "-c", command }; + private static final Logger LOGGER = Logger.getLogger(CodegenUtils.class.getName()); + + private static final String SYNTHETIC_NAMESPACE = "smithy.go.synthetic"; + + private CodegenUtils() { + } + + /** + * Executes a given shell command in a given directory. + * + * @param command The string command to execute, e.g. "go fmt". + * @param directory The directory to run the command in. + * @return Returns the console output of the command. + */ + public static String runCommand(String command, Path directory) { + String[] finalizedCommand; + if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { + finalizedCommand = new String[]{"cmd.exe", "/c", command}; + } else { + finalizedCommand = new String[]{"sh", "-c", command}; + } + + ProcessBuilder processBuilder = new ProcessBuilder(finalizedCommand) + .redirectErrorStream(true) + .directory(directory.toFile()); + + try { + Process process = processBuilder.start(); + List output = new ArrayList<>(); + + // Capture output for reporting. + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( + process.getInputStream(), Charset.defaultCharset()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + LOGGER.finest(line); + output.add(line); + } + } + + process.waitFor(); + process.destroy(); + + String joinedOutput = String.join(System.lineSeparator(), output); + if (process.exitValue() != 0) { + throw new CodegenException(String.format( + "Command `%s` failed with output:%n%n%s", command, joinedOutput)); + } + return joinedOutput; + } catch (InterruptedException | IOException e) { + throw new CodegenException(e); + } } - ProcessBuilder processBuilder = new ProcessBuilder(finalizedCommand) - .redirectErrorStream(true) - .directory(directory.toFile()); - - try { - Process process = processBuilder.start(); - List output = new ArrayList<>(); - - // Capture output for reporting. - try ( - BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader( - process.getInputStream(), - Charset.defaultCharset() - ) - ) - ) { - String line; - while ((line = bufferedReader.readLine()) != null) { - LOGGER.finest(line); - output.add(line); + /** + * Gets the name under which the given package will be exported by default. + * + * @param packageName The full package name of the exported package. + * @return The name a the package will be imported under by default. + */ + public static String getDefaultPackageImportName(String packageName) { + if (StringUtils.isBlank(packageName) || !packageName.contains("/")) { + return packageName; } - } - - process.waitFor(); - process.destroy(); - - String joinedOutput = String.join(System.lineSeparator(), output); - if (process.exitValue() != 0) { - throw new CodegenException( - String.format( - "Command `%s` failed with output:%n%n%s", - command, - joinedOutput - ) - ); - } - return joinedOutput; - } catch (InterruptedException | IOException e) { - throw new CodegenException(e); + return packageName.substring(packageName.lastIndexOf('/') + 1); } - } - - /** - * Gets the name under which the given package will be exported by default. - * - * @param packageName The full package name of the exported package. - * @return The name a the package will be imported under by default. - */ - public static String getDefaultPackageImportName(String packageName) { - if (StringUtils.isBlank(packageName) || !packageName.contains("/")) { - return packageName; + + /** + * Gets the alias to use when referencing the given symbol outside of its namespace. + * + *

The default value is the last path component of the symbol's namespace. + * + * @param symbol The symbol whose whose namespace alias should be retrieved. + * @return The alias of the symbol's namespace. + */ + public static String getSymbolNamespaceAlias(Symbol symbol) { + return symbol.getProperty(SymbolUtils.NAMESPACE_ALIAS, String.class) + .filter(StringUtils::isNotBlank) + .orElse(CodegenUtils.getDefaultPackageImportName(symbol.getNamespace())); } - return packageName.substring(packageName.lastIndexOf('/') + 1); - } - - /** - * Gets the alias to use when referencing the given symbol outside of its namespace. - * - *

The default value is the last path component of the symbol's namespace. - * - * @param symbol The symbol whose whose namespace alias should be retrieved. - * @return The alias of the symbol's namespace. - */ - public static String getSymbolNamespaceAlias(Symbol symbol) { - return symbol - .getProperty(SymbolUtils.NAMESPACE_ALIAS, String.class) - .filter(StringUtils::isNotBlank) - .orElse(CodegenUtils.getDefaultPackageImportName(symbol.getNamespace())); - } - - /** - * Detects if an annotated mediatype indicates JSON contents. - * - * @param mediaType The media type to inspect. - * @return If the media type indicates JSON contents. - */ - public static boolean isJsonMediaType(String mediaType) { - return mediaType.equals("application/json") || mediaType.endsWith("+json"); - } - - /** - * Get the namespace where synthetic types are generated at runtime. - * - * @return synthetic type namespace - */ - public static String getSyntheticTypeNamespace() { - return CodegenUtils.SYNTHETIC_NAMESPACE; - } - - /** - * Get if the passed in shape is decorated as a synthetic clone, but there is no other shape the clone is - * created from. - * - * @param shape the shape to check if its a stubbed synthetic clone without an archetype. - * @return if the shape is synthetic clone, but not based on a specific shape. - */ - public static boolean isStubSynthetic(Shape shape) { - Optional optional = shape.getTrait(Synthetic.class); - if (!optional.isPresent()) { - return false; + + /** + * Detects if an annotated mediatype indicates JSON contents. + * + * @param mediaType The media type to inspect. + * @return If the media type indicates JSON contents. + */ + public static boolean isJsonMediaType(String mediaType) { + return mediaType.equals("application/json") || mediaType.endsWith("+json"); } - Synthetic synth = optional.get(); - return !synth.getArchetype().isPresent(); - } - - /** - * Returns the operand decorated with an & if the address of the shape type can be taken. - * - * @param model API model reference - * @param pointableIndex pointable index - * @param shape shape to use - * @param operand value to decorate - * @return updated operand - */ - public static String asAddressIfAddressable( - Model model, - GoPointableIndex pointableIndex, - Shape shape, - String operand - ) { - boolean isStruct = shape.getType() == ShapeType.STRUCTURE; - if (shape.isMemberShape()) { - isStruct = - model.expectShape(shape.asMemberShape().get().getTarget()).getType() == - ShapeType.STRUCTURE; + /** + * Get the namespace where synthetic types are generated at runtime. + * + * @return synthetic type namespace + */ + public static String getSyntheticTypeNamespace() { + return CodegenUtils.SYNTHETIC_NAMESPACE; } - boolean shouldAddress = pointableIndex.isPointable(shape) && isStruct; - return shouldAddress ? "&" + operand : operand; - } - - /** - * Returns the operand decorated with an "*" if the shape is dereferencable. - * - * @param pointableIndex knowledge index for if shape is pointable. - * @param shape The shape whose value needs to be read. - * @param operand The value to be read from. - * @return updated operand - */ - public static String getAsValueIfDereferencable( - GoPointableIndex pointableIndex, - Shape shape, - String operand - ) { - if (!pointableIndex.isDereferencable(shape)) { - return operand; + /** + * Get if the passed in shape is decorated as a synthetic clone, but there is no other shape the clone is + * created from. + * + * @param shape the shape to check if its a stubbed synthetic clone without an archetype. + * @return if the shape is synthetic clone, but not based on a specific shape. + */ + public static boolean isStubSynthetic(Shape shape) { + Optional optional = shape.getTrait(Synthetic.class); + if (!optional.isPresent()) { + return false; + } + + Synthetic synth = optional.get(); + return !synth.getArchetype().isPresent(); } - return '*' + operand; - } - - /** - * Returns the operand decorated as a pointer type, without creating double pointer. - * - * @param pointableIndex knowledge index for if shape is pointable. - * @param shape The shape whose value of the type. - * @param operand The value to read. - * @return updated operand - */ - public static String getTypeAsTypePointer( - GoPointableIndex pointableIndex, - Shape shape, - String operand - ) { - if (pointableIndex.isPointable(shape)) { - return operand; + /** + * Returns the operand decorated with an & if the address of the shape type can be taken. + * + * @param model API model reference + * @param pointableIndex pointable index + * @param shape shape to use + * @param operand value to decorate + * @return updated operand + */ + public static String asAddressIfAddressable( + Model model, + GoPointableIndex pointableIndex, + Shape shape, + String operand + ) { + boolean isStruct = shape.getType() == ShapeType.STRUCTURE; + if (shape.isMemberShape()) { + isStruct = model.expectShape(shape.asMemberShape().get().getTarget()).getType() == ShapeType.STRUCTURE; + } + + boolean shouldAddress = pointableIndex.isPointable(shape) && isStruct; + return shouldAddress ? "&" + operand : operand; } - return '*' + operand; - } - - /** - * Get the pointer reference to operand , if symbol is pointable. - * This method can be used by deserializers to get pointer to - * operand. - * - * @param model model for api. - * @param writer The writer dependencies will be added to, if needed. - * @param pointableIndex knowledge index for if shape is pointable. - * @param shape The shape whose value needs to be assigned. - * @param operand The Operand is the value to be assigned to the symbol shape. - * @return The Operand, along with pointer reference if applicable - */ - public static String getAsPointerIfPointable( - Model model, - GoWriter writer, - GoPointableIndex pointableIndex, - Shape shape, - String operand - ) { - if (!pointableIndex.isPointable(shape)) { - return operand; + /** + * Returns the operand decorated with an "*" if the shape is dereferencable. + * + * @param pointableIndex knowledge index for if shape is pointable. + * @param shape The shape whose value needs to be read. + * @param operand The value to be read from. + * @return updated operand + */ + public static String getAsValueIfDereferencable( + GoPointableIndex pointableIndex, + Shape shape, + String operand + ) { + if (!pointableIndex.isDereferencable(shape)) { + return operand; + } + + return '*' + operand; } - if (shape.isMemberShape()) { - shape = model.expectShape(shape.asMemberShape().get().getTarget()); + /** + * Returns the operand decorated as a pointer type, without creating double pointer. + * + * @param pointableIndex knowledge index for if shape is pointable. + * @param shape The shape whose value of the type. + * @param operand The value to read. + * @return updated operand + */ + public static String getTypeAsTypePointer( + GoPointableIndex pointableIndex, + Shape shape, + String operand + ) { + if (pointableIndex.isPointable(shape)) { + return operand; + } + + return '*' + operand; } - String prefix = ""; - String suffix = ")"; - - switch (shape.getType()) { - case STRING: - prefix = "ptr.String("; - break; - case BOOLEAN: - prefix = "ptr.Bool("; - break; - case BYTE: - prefix = "ptr.Int8("; - break; - case SHORT: - prefix = "ptr.Int16("; - break; - case INTEGER: - prefix = "ptr.Int32("; - break; - case LONG: - prefix = "ptr.Int64("; - break; - case FLOAT: - prefix = "ptr.Float32("; - break; - case DOUBLE: - prefix = "ptr.Float64("; - break; - case TIMESTAMP: - prefix = "ptr.Time("; - break; - default: - return '&' + operand; + /** + * Get the pointer reference to operand , if symbol is pointable. + * This method can be used by deserializers to get pointer to + * operand. + * + * @param model model for api. + * @param writer The writer dependencies will be added to, if needed. + * @param pointableIndex knowledge index for if shape is pointable. + * @param shape The shape whose value needs to be assigned. + * @param operand The Operand is the value to be assigned to the symbol shape. + * @return The Operand, along with pointer reference if applicable + */ + public static String getAsPointerIfPointable( + Model model, + GoWriter writer, + GoPointableIndex pointableIndex, + Shape shape, + String operand + ) { + if (!pointableIndex.isPointable(shape)) { + return operand; + } + + if (shape.isMemberShape()) { + shape = model.expectShape(shape.asMemberShape().get().getTarget()); + } + + String prefix = ""; + String suffix = ")"; + + switch (shape.getType()) { + case STRING: + prefix = "ptr.String("; + break; + + case BOOLEAN: + prefix = "ptr.Bool("; + break; + + case BYTE: + prefix = "ptr.Int8("; + break; + case SHORT: + prefix = "ptr.Int16("; + break; + case INTEGER: + prefix = "ptr.Int32("; + break; + case LONG: + prefix = "ptr.Int64("; + break; + + case FLOAT: + prefix = "ptr.Float32("; + break; + case DOUBLE: + prefix = "ptr.Float64("; + break; + + case TIMESTAMP: + prefix = "ptr.Time("; + break; + + default: + return '&' + operand; + } + + writer.addUseImports(SmithyGoDependency.SMITHY_PTR); + return prefix + operand + suffix; } - writer.addUseImports(SmithyGoDependency.SMITHY_PTR); - return prefix + operand + suffix; - } - - /** - * Returns the shape unpacked as a CollectionShape. Throws an exception if the passed in - * shape is not a list or set. - * - * @param shape the list or set shape. - * @return The unpacked CollectionShape. - */ - public static CollectionShape expectCollectionShape(Shape shape) { - if (shape instanceof CollectionShape) { - return (CollectionShape) (shape); + /** + * Returns the shape unpacked as a CollectionShape. Throws an exception if the passed in + * shape is not a list or set. + * + * @param shape the list or set shape. + * @return The unpacked CollectionShape. + */ + public static CollectionShape expectCollectionShape(Shape shape) { + if (shape instanceof CollectionShape) { + return (CollectionShape) (shape); + } + + throw new CodegenException("expect shape " + shape.getId() + " to be Collection, was " + shape.getType()); } - throw new CodegenException( - "expect shape " + - shape.getId() + - " to be Collection, was " + - shape.getType() - ); - } - - /** - * Returns the shape unpacked as a MapShape. Throws an exception if the passed in - * shape is not a map. - * - * @param shape the map shape. - * @return The unpacked MapShape. - */ - public static MapShape expectMapShape(Shape shape) { - if (shape instanceof MapShape) { - return (MapShape) (shape); + /** + * Returns the shape unpacked as a MapShape. Throws an exception if the passed in + * shape is not a map. + * + * @param shape the map shape. + * @return The unpacked MapShape. + */ + public static MapShape expectMapShape(Shape shape) { + if (shape instanceof MapShape) { + return (MapShape) (shape); + } + + throw new CodegenException("expect shape " + shape.getId() + " to be Map, was " + shape.getType()); } - throw new CodegenException( - "expect shape " + shape.getId() + " to be Map, was " + shape.getType() - ); - } + /** + * Comparator to sort ShapeMember lists alphabetically, with required members first followed by optional members. + */ + public static final class SortedMembers implements Comparator { + private final SymbolProvider symbolProvider; + + /** + * Initializes the SortedMembers. + * + * @param symbolProvider symbol provider used for codegen. + */ + public SortedMembers(SymbolProvider symbolProvider) { + this.symbolProvider = symbolProvider; + } - /** - * Comparator to sort ShapeMember lists alphabetically, with required members first followed by optional members. - */ - public static final class SortedMembers implements Comparator { + @Override + public int compare(MemberShape a, MemberShape b) { + // first compare if the members are required or not, which ever member is required should win. If both + // members are required or not required, continue on to alphabetic search. + + // If a is required but b isn't return -1 so a is sorted before b + // If b is required but a isn't, return 1 so a is sorted after b + // If both a and b are required or optional, use alphabetic sorting of a and b's member name. + + int requiredMember = 0; + if (a.hasTrait(RequiredTrait.class)) { + requiredMember -= 1; + } + if (b.hasTrait(RequiredTrait.class)) { + requiredMember += 1; + } + if (requiredMember != 0) { + return requiredMember; + } + + return symbolProvider.toMemberName(a) + .compareTo(symbolProvider.toMemberName(b)); + } + } - private final SymbolProvider symbolProvider; + /** + * Attempts to find the first member by exact name in the containing structure. If the member is not found an + * exception will be thrown. + * + * @param shape structure containing member + * @param name member name + * @return MemberShape if found + */ + public static MemberShape expectMember(StructureShape shape, String name) { + return expectMember(shape, name::equals); + } /** - * Initializes the SortedMembers. + * Attempts to find the first member by name using a member name predicate in the containing structure. If the + * member is not found an exception will be thrown. * - * @param symbolProvider symbol provider used for codegen. + * @param shape structure containing member + * @param memberNamePredicate member name to search for + * @return MemberShape if found */ - public SortedMembers(SymbolProvider symbolProvider) { - this.symbolProvider = symbolProvider; + public static MemberShape expectMember(StructureShape shape, Predicate memberNamePredicate) { + return shape.getAllMembers().values().stream() + .filter((p) -> memberNamePredicate.test(p.getMemberName())) + .findFirst() + .orElseThrow(() -> new CodegenException("did not find member in structure shape, " + shape.getId())); } - @Override - public int compare(MemberShape a, MemberShape b) { - // first compare if the members are required or not, which ever member is required should win. If both - // members are required or not required, continue on to alphabetic search. - - // If a is required but b isn't return -1 so a is sorted before b - // If b is required but a isn't, return 1 so a is sorted after b - // If both a and b are required or optional, use alphabetic sorting of a and b's member name. - - int requiredMember = 0; - if (a.hasTrait(RequiredTrait.class)) { - requiredMember -= 1; - } - if (b.hasTrait(RequiredTrait.class)) { - requiredMember += 1; - } - if (requiredMember != 0) { - return requiredMember; - } - - return symbolProvider - .toMemberName(a) - .compareTo(symbolProvider.toMemberName(b)); + /** + * Attempts to get the title of the API's service from the model. If unalbe to get the title the fallback value + * will be returned instead. + * + * @param shape service shape + * @param fallback string to return if service does not have a title + * @return title of service + */ + public static String getServiceTitle(ServiceShape shape, String fallback) { + return shape.getTrait(TitleTrait.class).map(TitleTrait::getValue).orElse(fallback); } - } - - /** - * Attempts to find the first member by exact name in the containing structure. If the member is not found an - * exception will be thrown. - * - * @param shape structure containing member - * @param name member name - * @return MemberShape if found - */ - public static MemberShape expectMember(StructureShape shape, String name) { - return expectMember(shape, name::equals); - } - - /** - * Attempts to find the first member by name using a member name predicate in the containing structure. If the - * member is not found an exception will be thrown. - * - * @param shape structure containing member - * @param memberNamePredicate member name to search for - * @return MemberShape if found - */ - public static MemberShape expectMember( - StructureShape shape, - Predicate memberNamePredicate - ) { - return shape - .getAllMembers() - .values() - .stream() - .filter(p -> memberNamePredicate.test(p.getMemberName())) - .findFirst() - .orElseThrow(() -> - new CodegenException( - "did not find member in structure shape, " + shape.getId() - ) - ); - } - - /** - * Attempts to get the title of the API's service from the model. If unalbe to get the title the fallback value - * will be returned instead. - * - * @param shape service shape - * @param fallback string to return if service does not have a title - * @return title of service - */ - public static String getServiceTitle(ServiceShape shape, String fallback) { - return shape - .getTrait(TitleTrait.class) - .map(TitleTrait::getValue) - .orElse(fallback); - } - - /** - * isNumber returns if the shape is a number shape. - * - * @param shape shape to check - * @return true if is a number shape. - */ - public static boolean isNumber(Shape shape) { - switch (shape.getType()) { - case BYTE: - case SHORT: - case INTEGER: - case INT_ENUM: - case LONG: - case FLOAT: - case DOUBLE: - return true; - default: - return false; + + /** + * isNumber returns if the shape is a number shape. + * + * @param shape shape to check + * @return true if is a number shape. + */ + public static boolean isNumber(Shape shape) { + switch (shape.getType()) { + case BYTE: + case SHORT: + case INTEGER: + case INT_ENUM: + case LONG: + case FLOAT: + case DOUBLE: + return true; + default: + return false; + } } - } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/EnumGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/EnumGenerator.java index f86ec20ccf..739c4ea685 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/EnumGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/EnumGenerator.java @@ -19,6 +19,7 @@ import java.util.Locale; import java.util.Set; import java.util.logging.Logger; + import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.shapes.EnumShape; @@ -32,101 +33,66 @@ * Renders enums and their constants. */ public final class EnumGenerator implements Runnable { + private static final Logger LOGGER = Logger.getLogger(EnumGenerator.class.getName()); - private static final Logger LOGGER = Logger.getLogger( - EnumGenerator.class.getName() - ); + private final SymbolProvider symbolProvider; + private final GoWriter writer; + private final Shape shape; - private final SymbolProvider symbolProvider; - private final GoWriter writer; - private final Shape shape; + public EnumGenerator(SymbolProvider symbolProvider, GoWriter writer, Shape shape) { + this.symbolProvider = symbolProvider; + this.writer = writer; + this.shape = shape; + } - public EnumGenerator( - SymbolProvider symbolProvider, - GoWriter writer, - Shape shape - ) { - this.symbolProvider = symbolProvider; - this.writer = writer; - this.shape = shape; - } + @Override + public void run() { + Symbol symbol = symbolProvider.toSymbol(shape); + EnumTrait enumTrait = shape.expectTrait(EnumTrait.class); - @Override - public void run() { - Symbol symbol = symbolProvider.toSymbol(shape); - EnumTrait enumTrait = shape.expectTrait(EnumTrait.class); + writer.write("type $L string", symbol.getName()).write(""); - writer.write("type $L string", symbol.getName()).write(""); + // Don't generate constants if there are no explicitly modeled names. We only need to + // look at one, since Smithy validates that if one has a name then they must all have + // a name. + if (enumTrait.getValues().get(0).getName().isPresent()) { + Set constants = new LinkedHashSet<>(); + writer.openBlock("const (", ")", () -> { + for (EnumDefinition definition : enumTrait.getValues()) { + StringBuilder labelBuilder = new StringBuilder(symbol.getName()); + String name = definition.getName().get(); - // Don't generate constants if there are no explicitly modeled names. We only need to - // look at one, since Smithy validates that if one has a name then they must all have - // a name. - if (enumTrait.getValues().get(0).getName().isPresent()) { - Set constants = new LinkedHashSet<>(); - writer - .openBlock( - "const (", - ")", - () -> { - for (EnumDefinition definition : enumTrait.getValues()) { - StringBuilder labelBuilder = new StringBuilder(symbol.getName()); - String name = definition.getName().get(); + for (String part : name.split("(?U)[\\W_]")) { + if (part.matches(".*[a-z].*") && part.matches(".*[A-Z].*")) { + // Mixed case names should not be changed other than first letter capitalized. + labelBuilder.append(StringUtils.capitalize(part)); + } else { + // For all non-mixed case parts title case first letter, followed by all other lower cased. + labelBuilder.append(StringUtils.capitalize(part.toLowerCase(Locale.US))); + } + } + String label = labelBuilder.toString(); - for (String part : name.split("(?U)[\\W_]")) { - if (part.matches(".*[a-z].*") && part.matches(".*[A-Z].*")) { - // Mixed case names should not be changed other than first letter capitalized. - labelBuilder.append(StringUtils.capitalize(part)); - } else { - // For all non-mixed case parts title case first letter, followed by all other lower cased. - labelBuilder.append( - StringUtils.capitalize(part.toLowerCase(Locale.US)) - ); - } - } - String label = labelBuilder.toString(); + // If camel-casing would cause a conflict, don't camel-case this enum value. + if (constants.contains(label)) { + LOGGER.warning(String.format( + "Multiple enums resolved to the same name, `%s`, using unaltered value for: %s", + label, name)); + label = name; + } + constants.add(label); - // If camel-casing would cause a conflict, don't camel-case this enum value. - if (constants.contains(label)) { - LOGGER.warning( - String.format( - "Multiple enums resolved to the same name, `%s`, using unaltered value for: %s", - label, - name - ) - ); - label = name; - } - constants.add(label); + writer.write("$L $L = $S", label, symbol.getName(), definition.getValue()); + } + }).write(""); + } - writer.write( - "$L $L = $S", - label, - symbol.getName(), - definition.getValue() - ); - } - } - ) - .write(""); + writer.openBlock("func ($L) Values() []$L {", "}", symbol.getName(), symbol.getName(), () -> { + writer.openBlock("return []$L{", "}", symbol.getName(), () -> { + for (EnumDefinition definition : enumTrait.getValues()) { + writer.write("$S,", definition.getValue()); + } + }); + }); } - - writer.openBlock( - "func ($L) Values() []$L {", - "}", - symbol.getName(), - symbol.getName(), - () -> { - writer.openBlock( - "return []$L{", - "}", - symbol.getName(), - () -> { - for (EnumDefinition definition : enumTrait.getValues()) { - writer.write("$S,", definition.getValue()); - } - } - ); - } - ); - } -} +} \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GenerationContext.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GenerationContext.java index d14117be43..7fb586c8a6 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GenerationContext.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GenerationContext.java @@ -1,7 +1,5 @@ package software.amazon.polymorph.smithygo.codegen; -import java.util.ArrayList; -import java.util.List; import software.amazon.polymorph.smithygo.codegen.integration.GoIntegration; import software.amazon.polymorph.smithygo.codegen.integration.ProtocolGenerator; import software.amazon.smithy.build.FileManifest; @@ -10,160 +8,152 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.utils.SmithyBuilder; -public class GenerationContext - implements CodegenContext { - - private final Model model; - private final GoSettings settings; - private final SymbolProvider symbolProvider; - private final FileManifest fileManifest; - private final GoDelegator writerDelegator; - private final List integrations; - private final ProtocolGenerator protocolGenerator; - - /** - * @return Returns the protocol generator to use in code generation. - */ - public ProtocolGenerator protocolGenerator() { - return protocolGenerator; - } - - private GenerationContext(Builder builder) { - model = SmithyBuilder.requiredState("model", builder.model); - settings = SmithyBuilder.requiredState("settings", builder.settings); - symbolProvider = - SmithyBuilder.requiredState("symbolProvider", builder.symbolProvider); - fileManifest = - SmithyBuilder.requiredState("fileManifest", builder.fileManifest); - writerDelegator = - SmithyBuilder.requiredState("writerDelegator", builder.writerDelegator); - integrations = - SmithyBuilder.requiredState("integrations", builder.integrations); - protocolGenerator = - SmithyBuilder.requiredState( - "protocolGenerator", - builder.protocolGenerator - ); - } - - @Override - public Model model() { - return model; - } - - @Override - public GoSettings settings() { - return settings; - } - - @Override - public SymbolProvider symbolProvider() { - return symbolProvider; - } - - @Override - public FileManifest fileManifest() { - return fileManifest; - } - - @Override - public GoDelegator writerDelegator() { - return writerDelegator; - } - - @Override - public List integrations() { - return integrations; - } - - /** - * @return Returns a builder. - */ - public static Builder builder() { - return new Builder(); - } - - /** - * Builds {@link GenerationContext}s. - */ - public static final class Builder - implements SmithyBuilder { - - private Model model; - private GoSettings settings; - private SymbolProvider symbolProvider; - private FileManifest fileManifest; - private GoDelegator writerDelegator; - private List integrations = new ArrayList<>(); - private ProtocolGenerator protocolGenerator; +import java.util.ArrayList; +import java.util.List; - @Override - public GenerationContext build() { - return new GenerationContext(this); - } +public class GenerationContext implements CodegenContext { + private final Model model; + private final GoSettings settings; + private final SymbolProvider symbolProvider; + private final FileManifest fileManifest; + private final GoDelegator writerDelegator; + private final List integrations; + private final ProtocolGenerator protocolGenerator; /** - * @param model The model being generated. - * @return Returns the builder. + * @return Returns the protocol generator to use in code generation. */ - public Builder model(Model model) { - this.model = model; - return this; + public ProtocolGenerator protocolGenerator() { + return protocolGenerator; } - /** - * @param settings The resolved settings for the generator. - * @return Returns the builder. - */ - public Builder settings(GoSettings settings) { - this.settings = settings; - return this; + private GenerationContext(Builder builder) { + model = SmithyBuilder.requiredState("model", builder.model); + settings = SmithyBuilder.requiredState("settings", builder.settings); + symbolProvider = SmithyBuilder.requiredState("symbolProvider", builder.symbolProvider); + fileManifest = SmithyBuilder.requiredState("fileManifest", builder.fileManifest); + writerDelegator = SmithyBuilder.requiredState("writerDelegator", builder.writerDelegator); + integrations = SmithyBuilder.requiredState("integrations", builder.integrations); + protocolGenerator = SmithyBuilder.requiredState("protocolGenerator", builder.protocolGenerator); } - /** - * @param symbolProvider The finalized symbol provider for the generator. - * @return Returns the builder. - */ - public Builder symbolProvider(SymbolProvider symbolProvider) { - this.symbolProvider = symbolProvider; - return this; + @Override + public Model model() { + return model; } - /** - * @param fileManifest The file manifest being used in the generator. - * @return Returns the builder. - */ - public Builder fileManifest(FileManifest fileManifest) { - this.fileManifest = fileManifest; - return this; + @Override + public GoSettings settings() { + return settings; } - /** - * @param writerDelegator The writer delegator to use in the generator. - * @return Returns the builder. - */ - public Builder writerDelegator(GoDelegator writerDelegator) { - this.writerDelegator = writerDelegator; - return this; + @Override + public SymbolProvider symbolProvider() { + return symbolProvider; + } + + @Override + public FileManifest fileManifest() { + return fileManifest; + } + + @Override + public GoDelegator writerDelegator() { + return writerDelegator; + } + + @Override + public List integrations() { + return integrations; } /** - * @param integrations The integrations to use in the generator. - * @return Returns the builder. + * @return Returns a builder. */ - public Builder integrations(List integrations) { - this.integrations.clear(); - this.integrations.addAll(integrations); - return this; + public static Builder builder() { + return new Builder(); } /** - * @param protocolGenerator The resolved protocol generator to use. - * @return Returns the builder. + * Builds {@link GenerationContext}s. */ - public Builder protocolGenerator(ProtocolGenerator protocolGenerator) { - this.protocolGenerator = protocolGenerator; - return this; + public static final class Builder implements SmithyBuilder { + private Model model; + private GoSettings settings; + private SymbolProvider symbolProvider; + private FileManifest fileManifest; + private GoDelegator writerDelegator; + private List integrations = new ArrayList<>(); + private ProtocolGenerator protocolGenerator; + + @Override + public GenerationContext build() { + return new GenerationContext(this); + } + + /** + * @param model The model being generated. + * @return Returns the builder. + */ + public Builder model(Model model) { + this.model = model; + return this; + } + + /** + * @param settings The resolved settings for the generator. + * @return Returns the builder. + */ + public Builder settings(GoSettings settings) { + this.settings = settings; + return this; + } + + /** + * @param symbolProvider The finalized symbol provider for the generator. + * @return Returns the builder. + */ + public Builder symbolProvider(SymbolProvider symbolProvider) { + this.symbolProvider = symbolProvider; + return this; + } + + /** + * @param fileManifest The file manifest being used in the generator. + * @return Returns the builder. + */ + public Builder fileManifest(FileManifest fileManifest) { + this.fileManifest = fileManifest; + return this; + } + + /** + * @param writerDelegator The writer delegator to use in the generator. + * @return Returns the builder. + */ + public Builder writerDelegator(GoDelegator writerDelegator) { + this.writerDelegator = writerDelegator; + return this; + } + + /** + * @param integrations The integrations to use in the generator. + * @return Returns the builder. + */ + public Builder integrations(List integrations) { + this.integrations.clear(); + this.integrations.addAll(integrations); + return this; + } + + /** + * @param protocolGenerator The resolved protocol generator to use. + * @return Returns the builder. + */ + public Builder protocolGenerator(ProtocolGenerator protocolGenerator) { + this.protocolGenerator = protocolGenerator; + return this; + } + } - } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDelegator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDelegator.java index 76503ca034..c2d5956024 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDelegator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDelegator.java @@ -24,8 +24,7 @@ * for getting shape specific GoWriters. */ public final class GoDelegator extends WriterDelegator { - - public GoDelegator(FileManifest fileManifest, SymbolProvider symbolProvider) { - super(fileManifest, symbolProvider, new GoWriter.GoWriterFactory()); - } + public GoDelegator(FileManifest fileManifest, SymbolProvider symbolProvider) { + super(fileManifest, symbolProvider, new GoWriter.GoWriterFactory()); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDependency.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDependency.java index 1092553d69..ef207ff401 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDependency.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDependency.java @@ -15,6 +15,11 @@ package software.amazon.polymorph.smithygo.codegen; +import software.amazon.smithy.codegen.core.SymbolDependency; +import software.amazon.smithy.codegen.core.SymbolDependencyContainer; +import software.amazon.smithy.utils.SetUtils; +import software.amazon.smithy.utils.SmithyBuilder; + import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -22,377 +27,330 @@ import java.util.Objects; import java.util.Set; import java.util.TreeSet; -import software.amazon.smithy.codegen.core.SymbolDependency; -import software.amazon.smithy.codegen.core.SymbolDependencyContainer; -import software.amazon.smithy.utils.SetUtils; -import software.amazon.smithy.utils.SmithyBuilder; public final class GoDependency implements SymbolDependencyContainer { - - private final Type type; - private final String sourcePath; - private final String importPath; - private final String alias; - private final String version; - private final Set dependencies; - private final SymbolDependency symbolDependency; - - private GoDependency(Builder builder) { - this.type = SmithyBuilder.requiredState("type", builder.type); - this.sourcePath = - !this.type.equals(Type.STANDARD_LIBRARY) - ? SmithyBuilder.requiredState("sourcePath", builder.sourcePath) - : ""; - this.importPath = - SmithyBuilder.requiredState("importPath", builder.importPath); - this.alias = builder.alias; - this.version = SmithyBuilder.requiredState("version", builder.version); - this.dependencies = builder.dependencies; - - this.symbolDependency = - SymbolDependency - .builder() - .dependencyType(this.type.toString()) - .packageName(this.sourcePath) - .version(this.version) - .build(); - } - - /** - * Get the the set of {@link GoDependency} required by this dependency. - * - * @return the set of dependencies - */ - public Set getGoDependencies() { - return this.dependencies; - } - - /** - * Get the symbol dependency representing the dependency. - * - * @return the symbol dependency - */ - public SymbolDependency getSymbolDependency() { - return symbolDependency; - } - - /** - * Get the type of dependency. - * - * @return the dependency type - */ - public Type getType() { - return type; - } - - /** - * Get the source code path of the dependency. - * - * @return the dependency source code path - */ - public String getSourcePath() { - return sourcePath; - } - - /** - * Get the import path of the dependency. - * - * @return the import path of the dependency - */ - public String getImportPath() { - return importPath; - } - - /** - * Get the alias of the module to use. - * - * @return the alias - */ - public String getAlias() { - return alias; - } - - /** - * Get the version of the dependency. - * - * @return the version - */ - public String getVersion() { - return version; - } - - @Override - public List getDependencies() { - Set symbolDependencySet = new TreeSet<>( - SetUtils.of(getSymbolDependency()) - ); - - symbolDependencySet.addAll( - resolveDependencies(getGoDependencies(), new HashSet<>(SetUtils.of(this))) - ); - - return new ArrayList<>(symbolDependencySet); - } - - private Set resolveDependencies( - Set goDependencies, - Set processed - ) { - Set symbolDependencies = new TreeSet<>(); - if (goDependencies.size() == 0) { - return symbolDependencies; + private final Type type; + private final String sourcePath; + private final String importPath; + private final String alias; + private final String version; + private final Set dependencies; + private final SymbolDependency symbolDependency; + + private GoDependency(Builder builder) { + this.type = SmithyBuilder.requiredState("type", builder.type); + this.sourcePath = !this.type.equals(Type.STANDARD_LIBRARY) + ? SmithyBuilder.requiredState("sourcePath", builder.sourcePath) : ""; + this.importPath = SmithyBuilder.requiredState("importPath", builder.importPath); + this.alias = builder.alias; + this.version = SmithyBuilder.requiredState("version", builder.version); + this.dependencies = builder.dependencies; + + this.symbolDependency = SymbolDependency.builder() + .dependencyType(this.type.toString()) + .packageName(this.sourcePath) + .version(this.version) + .build(); } - Set dependenciesToResolve = new TreeSet<>(); - for (GoDependency dependency : goDependencies) { - if (processed.contains(dependency)) { - continue; - } - processed.add(dependency); - symbolDependencies.add(dependency.getSymbolDependency()); - dependenciesToResolve.addAll(dependency.getGoDependencies()); + /** + * Get the the set of {@link GoDependency} required by this dependency. + * + * @return the set of dependencies + */ + public Set getGoDependencies() { + return this.dependencies; } - symbolDependencies.addAll( - resolveDependencies(dependenciesToResolve, processed) - ); - - return symbolDependencies; - } - - public static Builder builder() { - return new Builder(); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } else if (!(o instanceof GoDependency)) { - return false; + /** + * Get the symbol dependency representing the dependency. + * + * @return the symbol dependency + */ + public SymbolDependency getSymbolDependency() { + return symbolDependency; } - GoDependency other = (GoDependency) o; - - return ( - this.type.equals(other.type) && - this.sourcePath.equals(other.sourcePath) && - this.importPath.equals(other.importPath) && - this.alias.equals(other.alias) && - this.version.equals(other.version) && - this.dependencies.equals(other.dependencies) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - type, - sourcePath, - importPath, - alias, - version, - dependencies - ); - } - - /** - * Represents a dependency type. - */ - public enum Type { - STANDARD_LIBRARY, - DEPENDENCY; - - @Override - public String toString() { - switch (this) { - case STANDARD_LIBRARY: - return "stdlib"; - case DEPENDENCY: - return "dependency"; - default: - return "unknown"; - } - } - } - - /** - * Get {@link GoDependency} representing the provided module description. - * - * @param sourcePath the root source path for the given code - * @param importPath the import path of the package - * @param version the version of source module - * @param alias a default alias to use when importing the package, can be null - * @return the dependency - */ - public static GoDependency moduleDependency( - String sourcePath, - String importPath, - String version, - String alias - ) { - Builder builder = GoDependency - .builder() - .type(Type.DEPENDENCY) - .sourcePath(sourcePath) - .importPath(importPath) - .version(version); - if (alias != null) { - builder.alias(alias); - } - return builder.build(); - } - - /** - * Get {@link GoDependency} representing the standard library import description. - * - * @param importPath the import path of the package - * @param version the version of source module - * @return the dependency - */ - public static GoDependency standardLibraryDependency( - String importPath, - String version - ) { - return GoDependency - .builder() - .type(Type.STANDARD_LIBRARY) - .importPath(importPath) - .version(version) - .build(); - } - - /** - * Get {@link GoDependency} representing the standard library import description. - * - * @param importPath the import path of the package - * @param version the version of source module - * @param alias the alias for stdlib dependency - * @return the dependency - */ - public static GoDependency standardLibraryDependency( - String importPath, - String version, - String alias - ) { - Builder builder = GoDependency - .builder() - .type(Type.STANDARD_LIBRARY) - .importPath(importPath) - .version(version); - - if (alias != null) { - builder.alias(alias); + /** + * Get the type of dependency. + * + * @return the dependency type + */ + public Type getType() { + return type; } - return builder.build(); - } - - /** - * Builder for {@link GoDependency}. - */ - public static final class Builder implements SmithyBuilder { - - private Type type; - private String sourcePath; - private String importPath; - private String alias; - private String version; - private final Set dependencies = new TreeSet<>(); - - private Builder() {} /** - * Set the dependency type. + * Get the source code path of the dependency. * - * @param type dependency type - * @return the builder + * @return the dependency source code path */ - public Builder type(Type type) { - this.type = type; - return this; + public String getSourcePath() { + return sourcePath; } /** - * Set the source path. + * Get the import path of the dependency. * - * @param sourcePath the source path root - * @return the builder + * @return the import path of the dependency */ - public Builder sourcePath(String sourcePath) { - this.sourcePath = sourcePath; - return this; + public String getImportPath() { + return importPath; } /** - * Set the import path. + * Get the alias of the module to use. * - * @param importPath the import path - * @return the builder + * @return the alias */ - public Builder importPath(String importPath) { - this.importPath = importPath; - return this; + public String getAlias() { + return alias; } /** - * Set the dependency alias. + * Get the version of the dependency. * - * @param alias the alias - * @return the builder + * @return the version */ - public Builder alias(String alias) { - this.alias = alias; - return this; + public String getVersion() { + return version; + } + + @Override + public List getDependencies() { + Set symbolDependencySet = new TreeSet<>(SetUtils.of(getSymbolDependency())); + + symbolDependencySet.addAll(resolveDependencies(getGoDependencies(), new HashSet<>(SetUtils.of(this)))); + + return new ArrayList<>(symbolDependencySet); + } + + private Set resolveDependencies(Set goDependencies, Set processed) { + Set symbolDependencies = new TreeSet<>(); + if (goDependencies.size() == 0) { + return symbolDependencies; + } + + Set dependenciesToResolve = new TreeSet<>(); + for (GoDependency dependency : goDependencies) { + if (processed.contains(dependency)) { + continue; + } + processed.add(dependency); + symbolDependencies.add(dependency.getSymbolDependency()); + dependenciesToResolve.addAll(dependency.getGoDependencies()); + } + + symbolDependencies.addAll(resolveDependencies(dependenciesToResolve, processed)); + + return symbolDependencies; + } + + public static Builder builder() { + return new Builder(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } else if (!(o instanceof GoDependency)) { + return false; + } + + GoDependency other = (GoDependency) o; + + return this.type.equals(other.type) && this.sourcePath.equals(other.sourcePath) + && this.importPath.equals(other.importPath) && this.alias.equals(other.alias) + && this.version.equals(other.version) && this.dependencies.equals(other.dependencies); + } + + @Override + public int hashCode() { + return Objects.hash(type, sourcePath, importPath, alias, version, dependencies); } /** - * Set the dependency version. - * - * @param version the version - * @return the builder + * Represents a dependency type. */ - public Builder version(String version) { - this.version = version; - return this; + public enum Type { + STANDARD_LIBRARY, DEPENDENCY; + + @Override + public String toString() { + switch (this) { + case STANDARD_LIBRARY: + return "stdlib"; + case DEPENDENCY: + return "dependency"; + default: + return "unknown"; + } + } } /** - * Set the collection of {@link GoDependency} required by this dependency. + * Get {@link GoDependency} representing the provided module description. * - * @param dependencies a collection of dependencies - * @return the builder + * @param sourcePath the root source path for the given code + * @param importPath the import path of the package + * @param version the version of source module + * @param alias a default alias to use when importing the package, can be null + * @return the dependency */ - public Builder dependencies(Collection dependencies) { - this.dependencies.clear(); - this.dependencies.addAll(dependencies); - return this; + public static GoDependency moduleDependency(String sourcePath, String importPath, String version, String alias) { + Builder builder = GoDependency.builder() + .type(Type.DEPENDENCY) + .sourcePath(sourcePath) + .importPath(importPath) + .version(version); + if (alias != null) { + builder.alias(alias); + } + return builder.build(); } /** - * Add a dependency on another {@link GoDependency}. + * Get {@link GoDependency} representing the standard library import description. * - * @param dependency the dependency - * @return the builder + * @param importPath the import path of the package + * @param version the version of source module + * @return the dependency */ - public Builder addDependency(GoDependency dependency) { - this.dependencies.add(dependency); - return this; + public static GoDependency standardLibraryDependency(String importPath, String version) { + return GoDependency.builder() + .type(Type.STANDARD_LIBRARY) + .importPath(importPath) + .version(version) + .build(); } /** - * Remove a dependency on another {@link GoDependency}. + * Get {@link GoDependency} representing the standard library import description. * - * @param dependency the dependency - * @return the builder + * @param importPath the import path of the package + * @param version the version of source module + * @param alias the alias for stdlib dependency + * @return the dependency */ - public Builder removeDependency(GoDependency dependency) { - this.dependencies.remove(dependency); - return this; + public static GoDependency standardLibraryDependency(String importPath, String version, String alias) { + Builder builder = GoDependency.builder() + .type(Type.STANDARD_LIBRARY) + .importPath(importPath) + .version(version); + + if (alias != null) { + builder.alias(alias); + } + return builder.build(); } - @Override - public GoDependency build() { - return new GoDependency(this); + /** + * Builder for {@link GoDependency}. + */ + public static final class Builder implements SmithyBuilder { + private Type type; + private String sourcePath; + private String importPath; + private String alias; + private String version; + private final Set dependencies = new TreeSet<>(); + + private Builder() { + } + + /** + * Set the dependency type. + * + * @param type dependency type + * @return the builder + */ + public Builder type(Type type) { + this.type = type; + return this; + } + + /** + * Set the source path. + * + * @param sourcePath the source path root + * @return the builder + */ + public Builder sourcePath(String sourcePath) { + this.sourcePath = sourcePath; + return this; + } + + /** + * Set the import path. + * + * @param importPath the import path + * @return the builder + */ + public Builder importPath(String importPath) { + this.importPath = importPath; + return this; + } + + /** + * Set the dependency alias. + * + * @param alias the alias + * @return the builder + */ + public Builder alias(String alias) { + this.alias = alias; + return this; + } + + /** + * Set the dependency version. + * + * @param version the version + * @return the builder + */ + public Builder version(String version) { + this.version = version; + return this; + } + + /** + * Set the collection of {@link GoDependency} required by this dependency. + * + * @param dependencies a collection of dependencies + * @return the builder + */ + public Builder dependencies(Collection dependencies) { + this.dependencies.clear(); + this.dependencies.addAll(dependencies); + return this; + } + + /** + * Add a dependency on another {@link GoDependency}. + * + * @param dependency the dependency + * @return the builder + */ + public Builder addDependency(GoDependency dependency) { + this.dependencies.add(dependency); + return this; + } + + /** + * Remove a dependency on another {@link GoDependency}. + * + * @param dependency the dependency + * @return the builder + */ + public Builder removeDependency(GoDependency dependency) { + this.dependencies.remove(dependency); + return this; + } + + @Override + public GoDependency build() { + return new GoDependency(this); + } } - } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoSettings.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoSettings.java index 5d9871a06f..0c079a9b3c 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoSettings.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoSettings.java @@ -1,195 +1,175 @@ package software.amazon.polymorph.smithygo.codegen; -import java.util.Arrays; -import java.util.Objects; -import java.util.Optional; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.node.ObjectNode; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.ShapeId; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; + public class GoSettings { + private static final String SERVICE = "service"; + private static final String MODULE_NAME = "module"; + private static final String MODULE_DESCRIPTION = "moduleDescription"; + private static final String MODULE_VERSION = "moduleVersion"; + private static final String GENERATE_GO_MOD = "generateGoMod"; + private static final String GO_DIRECTIVE = "goDirective"; + + private ShapeId service; + private String moduleName; + private String moduleDescription = ""; + private String moduleVersion; + private Boolean generateGoMod = false; + private ShapeId protocol; + + /** + * Create a settings object from a configuration object node. + * + * @param config Config object to load. + * @return Returns the extracted settings. + */ + public static GoSettings from(ObjectNode config) { + GoSettings settings = new GoSettings(); + config.warnIfAdditionalProperties( + Arrays.asList(SERVICE, MODULE_NAME, MODULE_DESCRIPTION, MODULE_VERSION, GENERATE_GO_MOD, GO_DIRECTIVE)); + + settings.setService(config.expectStringMember(SERVICE).expectShapeId()); + settings.setModuleName(config.expectStringMember("moduleName").getValue()); + settings.setModuleDescription(config.getStringMemberOrDefault( + MODULE_DESCRIPTION, settings.getModuleName() + " client")); + settings.setModuleVersion(config.getStringMemberOrDefault(MODULE_VERSION, null)); + settings.setGenerateGoMod(config.getBooleanMemberOrDefault(GENERATE_GO_MOD, false)); + return settings; + } + + /** + * Gets the id of the service that is being generated. + * + * @return Returns the service id. + * @throws NullPointerException if the service has not been set. + */ + public ShapeId getService() { + return Objects.requireNonNull(service, SERVICE + " not set"); + } + + /** + * Gets the corresponding {@link ServiceShape} from a model. + * + * @param model Model to search for the service shape by ID. + * @return Returns the found {@code Service}. + * @throws NullPointerException if the service has not been set. + * @throws CodegenException if the service is invalid or not found. + */ + public ServiceShape getService(Model model) { + return model + .getShape(getService()) + .orElseThrow(() -> new CodegenException("Service shape not found: " + getService())) + .asServiceShape() + .orElseThrow(() -> new CodegenException("Shape is not a Service: " + getService())); + } + + /** + * Sets the service to generate. + * + * @param service The service to generate. + */ + public void setService(ShapeId service) { + this.service = Objects.requireNonNull(service); + } + + /** + * Gets the required module name for the module that will be generated. + * + * @return Returns the module name. + * @throws NullPointerException if the module name has not been set. + */ + public String getModuleName() { + return Objects.requireNonNull(moduleName, MODULE_NAME + " not set"); + } + + /** + * Sets the name of the module to generate. + * + * @param moduleName The name of the module to generate. + */ + public void setModuleName(String moduleName) { + this.moduleName = Objects.requireNonNull(moduleName); + } + + /** + * Gets the optional module description for the module that will be generated. + * + * @return Returns the module description. + */ + public String getModuleDescription() { + return moduleDescription; + } + + /** + * Sets the description of the module to generate. + * + * @param moduleDescription The description of the module to generate. + */ + public void setModuleDescription(String moduleDescription) { + this.moduleDescription = Objects.requireNonNull(moduleDescription); + } + + /** + * Gets the optional module version for the module that will be generated. + * + * @return Returns the module version. + */ + public Optional getModuleVersion() { + return Optional.ofNullable(moduleVersion); + } + + /** + * Sets the version of the module to generate. + * + * @param moduleVersion The version of the module to generate. + */ + public void setModuleVersion(String moduleVersion) { + if (moduleVersion != null) { + this.moduleVersion = moduleVersion; + } + } + + /** + * Gets the flag for generating go.mod file. + * + * @return Returns if go.mod will be generated (true) or not (false) + */ + public Boolean getGenerateGoMod() { + return generateGoMod; + } + + /** + * Sets the flag for generating go.mod file. + * + * @param generateGoMod If go.mod will be generated (true) or not (false) + */ + public void setGenerateGoMod(Boolean generateGoMod) { + this.generateGoMod = Objects.requireNonNull(generateGoMod); + } + + /** + * Gets the configured protocol to generate. + * + * @return Returns the configured protocol. + */ + public ShapeId getProtocol() { + return protocol; + } - private static final String SERVICE = "service"; - private static final String MODULE_NAME = "module"; - private static final String MODULE_DESCRIPTION = "moduleDescription"; - private static final String MODULE_VERSION = "moduleVersion"; - private static final String GENERATE_GO_MOD = "generateGoMod"; - private static final String GO_DIRECTIVE = "goDirective"; - - private ShapeId service; - private String moduleName; - private String moduleDescription = ""; - private String moduleVersion; - private Boolean generateGoMod = false; - private ShapeId protocol; - - /** - * Create a settings object from a configuration object node. - * - * @param config Config object to load. - * @return Returns the extracted settings. - */ - public static GoSettings from(ObjectNode config) { - GoSettings settings = new GoSettings(); - config.warnIfAdditionalProperties( - Arrays.asList( - SERVICE, - MODULE_NAME, - MODULE_DESCRIPTION, - MODULE_VERSION, - GENERATE_GO_MOD, - GO_DIRECTIVE - ) - ); - - settings.setService(config.expectStringMember(SERVICE).expectShapeId()); - settings.setModuleName(config.expectStringMember("moduleName").getValue()); - settings.setModuleDescription( - config.getStringMemberOrDefault( - MODULE_DESCRIPTION, - settings.getModuleName() + " client" - ) - ); - settings.setModuleVersion( - config.getStringMemberOrDefault(MODULE_VERSION, null) - ); - settings.setGenerateGoMod( - config.getBooleanMemberOrDefault(GENERATE_GO_MOD, false) - ); - return settings; - } - - /** - * Gets the id of the service that is being generated. - * - * @return Returns the service id. - * @throws NullPointerException if the service has not been set. - */ - public ShapeId getService() { - return Objects.requireNonNull(service, SERVICE + " not set"); - } - - /** - * Gets the corresponding {@link ServiceShape} from a model. - * - * @param model Model to search for the service shape by ID. - * @return Returns the found {@code Service}. - * @throws NullPointerException if the service has not been set. - * @throws CodegenException if the service is invalid or not found. - */ - public ServiceShape getService(Model model) { - return model - .getShape(getService()) - .orElseThrow(() -> - new CodegenException("Service shape not found: " + getService()) - ) - .asServiceShape() - .orElseThrow(() -> - new CodegenException("Shape is not a Service: " + getService()) - ); - } - - /** - * Sets the service to generate. - * - * @param service The service to generate. - */ - public void setService(ShapeId service) { - this.service = Objects.requireNonNull(service); - } - - /** - * Gets the required module name for the module that will be generated. - * - * @return Returns the module name. - * @throws NullPointerException if the module name has not been set. - */ - public String getModuleName() { - return Objects.requireNonNull(moduleName, MODULE_NAME + " not set"); - } - - /** - * Sets the name of the module to generate. - * - * @param moduleName The name of the module to generate. - */ - public void setModuleName(String moduleName) { - this.moduleName = Objects.requireNonNull(moduleName); - } - - /** - * Gets the optional module description for the module that will be generated. - * - * @return Returns the module description. - */ - public String getModuleDescription() { - return moduleDescription; - } - - /** - * Sets the description of the module to generate. - * - * @param moduleDescription The description of the module to generate. - */ - public void setModuleDescription(String moduleDescription) { - this.moduleDescription = Objects.requireNonNull(moduleDescription); - } - - /** - * Gets the optional module version for the module that will be generated. - * - * @return Returns the module version. - */ - public Optional getModuleVersion() { - return Optional.ofNullable(moduleVersion); - } - - /** - * Sets the version of the module to generate. - * - * @param moduleVersion The version of the module to generate. - */ - public void setModuleVersion(String moduleVersion) { - if (moduleVersion != null) { - this.moduleVersion = moduleVersion; + /** + * Sets the protocol to generate. + * + * @param protocol Protocols to generate. + */ + public void setProtocol(ShapeId protocol) { + this.protocol = Objects.requireNonNull(protocol); } - } - - /** - * Gets the flag for generating go.mod file. - * - * @return Returns if go.mod will be generated (true) or not (false) - */ - public Boolean getGenerateGoMod() { - return generateGoMod; - } - - /** - * Sets the flag for generating go.mod file. - * - * @param generateGoMod If go.mod will be generated (true) or not (false) - */ - public void setGenerateGoMod(Boolean generateGoMod) { - this.generateGoMod = Objects.requireNonNull(generateGoMod); - } - - /** - * Gets the configured protocol to generate. - * - * @return Returns the configured protocol. - */ - public ShapeId getProtocol() { - return protocol; - } - - /** - * Sets the protocol to generate. - * - * @param protocol Protocols to generate. - */ - public void setProtocol(ShapeId protocol) { - this.protocol = Objects.requireNonNull(protocol); - } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoWriter.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoWriter.java index bf3ec60ac4..aae981c2be 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoWriter.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoWriter.java @@ -1,13 +1,5 @@ package software.amazon.polymorph.smithygo.codegen; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.regex.Pattern; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolContainer; @@ -20,840 +12,708 @@ import software.amazon.smithy.model.traits.DeprecatedTrait; import software.amazon.smithy.utils.StringUtils; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.regex.Pattern; + public class GoWriter extends SymbolWriter { + private static final Pattern ARGUMENT_NAME_PATTERN = Pattern.compile("\\$([a-z][a-zA-Z_0-9]+)(:\\w)?"); + private final String fullPackageName; + private final ImportDeclarations imports = new ImportDeclarations(); + private final List dependencies = new ArrayList<>(); + private final boolean innerWriter; + + /** + * Initializes the GoWriter for the package and filename to be written to. + * + * @param fullPackageName package and filename to be written to. + */ + public GoWriter(String fullPackageName) { + this(fullPackageName, false); + } - private static final Pattern ARGUMENT_NAME_PATTERN = Pattern.compile( - "\\$([a-z][a-zA-Z_0-9]+)(:\\w)?" - ); - private final String fullPackageName; - private final ImportDeclarations imports = new ImportDeclarations(); - private final List dependencies = new ArrayList<>(); - private final boolean innerWriter; - - /** - * Initializes the GoWriter for the package and filename to be written to. - * - * @param fullPackageName package and filename to be written to. - */ - public GoWriter(String fullPackageName) { - this(fullPackageName, false); - } - - private GoWriter(String fullPackageName, boolean innerWriter) { - super(new ImportDeclarations()); - this.fullPackageName = fullPackageName; - this.innerWriter = innerWriter; - init(); - } - - private void init() { - trimBlankLines(); - trimTrailingSpaces(); - setIndentText("\t"); - putFormatter('T', new GoSymbolFormatter()); - putFormatter('P', new PointableGoSymbolFormatter()); - putFormatter('W', new GoWritableInjector()); - } - - // TODO figure out better way to annotate where the failure occurs, check templates and args - // TODO to try to find programming bugs. - - /** - * Returns a Writable for the string and args to be composed inline to another writer's contents. - * - * @param contents string to write. - * @param args Arguments to use when evaluating the contents string. - * @return Writable to be evaluated. - */ - @SafeVarargs - public static Writable goTemplate( - String contents, - Map... args - ) { - validateTemplateArgsNotNull(args); - return (GoWriter w) -> { - w.writeGoTemplate(contents, args); - }; - } - - public static final class GoWriterFactory - implements SymbolWriter.Factory { + private GoWriter(String fullPackageName, boolean innerWriter) { + super(new ImportDeclarations()); + this.fullPackageName = fullPackageName; + this.innerWriter = innerWriter; + init(); + } - @Override - public GoWriter apply(String filename, String namespace) { - GoWriter writer = new GoWriter(namespace); - return writer; - } - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Consumer fn - ) { - return goBlockTemplate(beforeNewLine, afterNewLine, new Map[0], fn); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Consumer fn - ) { - return goBlockTemplate( - beforeNewLine, - afterNewLine, - new Map[] { args1 }, - fn - ); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param args2 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Map args2, - Consumer fn - ) { - return goBlockTemplate( - beforeNewLine, - afterNewLine, - new Map[] { args1, args2 }, - fn - ); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param args2 template arguments - * @param args3 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Map args2, - Map args3, - Consumer fn - ) { - return goBlockTemplate( - beforeNewLine, - afterNewLine, - new Map[] { args1, args2, args3 }, - fn - ); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param args2 template arguments - * @param args3 template arguments - * @param args4 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Map args2, - Map args3, - Map args4, - Consumer fn - ) { - return goBlockTemplate( - beforeNewLine, - afterNewLine, - new Map[] { args1, args2, args3, args4 }, - fn - ); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param args2 template arguments - * @param args3 template arguments - * @param args4 template arguments - * @param args5 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Map args2, - Map args3, - Map args4, - Map args5, - Consumer fn - ) { - return goBlockTemplate( - beforeNewLine, - afterNewLine, - new Map[] { args1, args2, args3, args4, args5 }, - fn - ); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map[] args, - Consumer fn - ) { - validateTemplateArgsNotNull(args); - return (GoWriter w) -> { - w.writeGoBlockTemplate(beforeNewLine, afterNewLine, args, fn); - }; - } - - /** - * Returns a Writable that does nothing. - * - * @return Writable that does nothing - */ - public static Writable emptyGoTemplate() { - return (GoWriter w) -> {}; - } - - /** - * Writes the contents and arguments as a template to the writer. - * - * @param contents string to write - * @param args Arguments to use when evaluating the contents string. - */ - @SafeVarargs - public final void writeGoTemplate( - String contents, - Map... args - ) { - withTemplate( - contents, - args, - template -> { - try { - write(contents); - } catch (Exception e) { - throw new CodegenException( - "Failed to render template\n" + - contents + - "\nReason: " + - e.getMessage(), - e - ); + private void init() { + trimBlankLines(); + trimTrailingSpaces(); + setIndentText("\t"); + putFormatter('T', new GoSymbolFormatter()); + putFormatter('P', new PointableGoSymbolFormatter()); + putFormatter('W', new GoWritableInjector()); + } + + // TODO figure out better way to annotate where the failure occurs, check templates and args + // TODO to try to find programming bugs. + + /** + * Returns a Writable for the string and args to be composed inline to another writer's contents. + * + * @param contents string to write. + * @param args Arguments to use when evaluating the contents string. + * @return Writable to be evaluated. + */ + @SafeVarargs + public static Writable goTemplate(String contents, Map... args) { + validateTemplateArgsNotNull(args); + return (GoWriter w) -> { + w.writeGoTemplate(contents, args); + }; + } + + public static final class GoWriterFactory implements SymbolWriter.Factory { + + @Override + public GoWriter apply(String filename, String namespace) { + GoWriter writer = new GoWriter(namespace); + return writer; } - } - ); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Consumer fn - ) { - writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[0], fn); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Consumer fn - ) { - writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[] { arg1 }, fn); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param arg2 second map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Map arg2, - Consumer fn - ) { - writeGoBlockTemplate( - beforeNewLine, - afterNewLine, - new Map[] { arg1, arg2 }, - fn - ); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param arg2 second map argument - * @param arg3 third map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Map arg2, - Map arg3, - Consumer fn - ) { - writeGoBlockTemplate( - beforeNewLine, - afterNewLine, - new Map[] { arg1, arg2, arg3 }, - fn - ); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param arg2 second map argument - * @param arg3 third map argument - * @param arg4 forth map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Map arg2, - Map arg3, - Map arg4, - Consumer fn - ) { - writeGoBlockTemplate( - beforeNewLine, - afterNewLine, - new Map[] { arg1, arg2, arg3, arg4 }, - fn - ); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param arg2 second map argument - * @param arg3 third map argument - * @param arg4 forth map argument - * @param arg5 forth map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Map arg2, - Map arg3, - Map arg4, - Map arg5, - Consumer fn - ) { - writeGoBlockTemplate( - beforeNewLine, - afterNewLine, - new Map[] { arg1, arg2, arg3, arg4, arg5 }, - fn - ); - } - - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map[] args, - Consumer fn - ) { - withTemplate( - beforeNewLine, - args, - header -> { - conditionalBlock(header, afterNewLine, true, new Object[0], fn); - } - ); - } - - private void withTemplate( - String template, - Map[] argMaps, - Consumer fn - ) { - pushState(); - for (var args : argMaps) { - putContext(args); - } - validateContext(template); - fn.accept(template); - popState(); - } - - private GoWriter conditionalBlock( - String beforeNewLine, - String afterNewLine, - boolean conditional, - Object[] args, - Consumer fn - ) { - if (conditional) { - openBlock(beforeNewLine.trim(), args); - } - - fn.accept(this); - - if (conditional) { - closeBlock(afterNewLine.trim()); - } - - return this; - } - - private static void validateTemplateArgsNotNull( - Map[] argMaps - ) { - for (var args : argMaps) { - args.forEach((k, v) -> { - if (v == null) { - throw new CodegenException( - "Template argument " + k + " cannot be null" - ); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Consumer fn + ) { + return goBlockTemplate(beforeNewLine, afterNewLine, new Map[0], fn); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Consumer fn + ) { + return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1}, fn); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param args2 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Map args2, + Consumer fn + ) { + return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2}, fn); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param args2 template arguments + * @param args3 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Map args2, + Map args3, + Consumer fn + ) { + return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2, args3}, fn); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param args2 template arguments + * @param args3 template arguments + * @param args4 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Map args2, + Map args3, + Map args4, + Consumer fn + ) { + return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2, args3, args4}, fn); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param args2 template arguments + * @param args3 template arguments + * @param args4 template arguments + * @param args5 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Map args2, + Map args3, + Map args4, + Map args5, + Consumer fn + ) { + return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2, args3, args4, args5}, fn); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map[] args, + Consumer fn + ) { + validateTemplateArgsNotNull(args); + return (GoWriter w) -> { + w.writeGoBlockTemplate(beforeNewLine, afterNewLine, args, fn); + }; + } + + /** + * Returns a Writable that does nothing. + * + * @return Writable that does nothing + */ + public static Writable emptyGoTemplate() { + return (GoWriter w) -> { + }; + } + + /** + * Writes the contents and arguments as a template to the writer. + * + * @param contents string to write + * @param args Arguments to use when evaluating the contents string. + */ + @SafeVarargs + public final void writeGoTemplate(String contents, Map... args) { + withTemplate(contents, args, (template) -> { + try { + write(contents); + } catch (Exception e) { + throw new CodegenException("Failed to render template\n" + contents + "\nReason: " + e.getMessage(), e); + } + }); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Consumer fn + ) { + writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[0], fn); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Consumer fn + ) { + writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1}, fn); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param arg2 second map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Map arg2, + Consumer fn + ) { + writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2}, fn); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param arg2 second map argument + * @param arg3 third map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Map arg2, + Map arg3, + Consumer fn + ) { + writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2, arg3}, fn); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param arg2 second map argument + * @param arg3 third map argument + * @param arg4 forth map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Map arg2, + Map arg3, + Map arg4, + Consumer fn + ) { + writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2, arg3, arg4}, fn); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param arg2 second map argument + * @param arg3 third map argument + * @param arg4 forth map argument + * @param arg5 forth map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Map arg2, + Map arg3, + Map arg4, + Map arg5, + Consumer fn + ) { + writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2, arg3, arg4, arg5}, fn); + } + + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map[] args, + Consumer fn + ) { + withTemplate(beforeNewLine, args, (header) -> { + conditionalBlock(header, afterNewLine, true, new Object[0], fn); + }); + } + + private void withTemplate( + String template, + Map[] argMaps, + Consumer fn + ) { + pushState(); + for (var args : argMaps) { + putContext(args); } - }); - } - } - - private void validateContext(String template) { - var matcher = ARGUMENT_NAME_PATTERN.matcher(template); - - while (matcher.find()) { - var keyName = matcher.group(1); - var value = getContext(keyName); - if (value == null) { - throw new CodegenException( - "Go template expected " + - keyName + - " but was not present in context scope." + - " Template: \n" + - template - ); - } - } - } - - /** - * Imports one or more symbols if necessary, using the name of the - * symbol and only "USE" references. - * - * @param container Container of symbols to add. - * @return Returns the writer. - */ - public GoWriter addUseImports(SymbolContainer container) { - for (Symbol symbol : container.getSymbols()) { - addImport( - symbol, - CodegenUtils.getSymbolNamespaceAlias(symbol), - SymbolReference.ContextOption.USE - ); - } - return this; - } - - /** - * Imports a symbol reference if necessary, using the alias of the - * reference and only associated "USE" references. - * - * @param symbolReference Symbol reference to import. - * @return Returns the writer. - */ - public GoWriter addUseImports(SymbolReference symbolReference) { - return addImport( - symbolReference.getSymbol(), - symbolReference.getAlias(), - SymbolReference.ContextOption.USE - ); - } - - /** - * Adds and imports the given dependency. - * - * @param goDependency The GoDependency to import. - * @return Returns the writer. - */ - public GoWriter addUseImports(GoDependency goDependency) { - dependencies.addAll(goDependency.getDependencies()); - return addImport(goDependency.getImportPath(), goDependency.getAlias()); - } - - private GoWriter addImports(GoWriter other) { - this.imports.addImports(other.imports); - return this; - } - - private boolean isExternalNamespace(String namespace) { - return ( - !StringUtils.isBlank(namespace) && !namespace.equals(fullPackageName) - ); - } - - void addImportReferences( - Symbol symbol, - SymbolReference.ContextOption... options - ) { - for (SymbolReference reference : symbol.getReferences()) { - for (SymbolReference.ContextOption option : options) { - if (reference.hasOption(option)) { - addImport(reference.getSymbol(), reference.getAlias(), options); - break; + validateContext(template); + fn.accept(template); + popState(); + } + + private GoWriter conditionalBlock( + String beforeNewLine, + String afterNewLine, + boolean conditional, + Object[] args, + Consumer fn + ) { + if (conditional) { + openBlock(beforeNewLine.trim(), args); } - } - } - } - - /** - * Imports a package using an alias if necessary. - * - * @param packageName Package to import. - * @param as Alias to refer to the package as. - * @return Returns the writer. - */ - public GoWriter addImport(String packageName, String as) { - imports.addImport(packageName, as); - return this; - } - - public GoWriter addImportFromModule( - String moduleName, - String packageName, - String as - ) { - imports.addImport(moduleName.concat("/").concat(packageName), as); - return this; - } - - public GoWriter addImportFromModule(String moduleName, String packageName) { - imports.addImport(moduleName.concat("/").concat(packageName), ""); - return this; - } - - public GoWriter addImport(String packageName) { - imports.addImport(packageName, ""); - return this; - } - - private GoWriter addDependencies(GoWriter other) { - this.dependencies.addAll(other.getDependencies()); - return this; - } - - private boolean isTargetDeprecated(Model model, MemberShape member) { - return ( - model - .expectShape(member.getTarget()) - .getTrait(DeprecatedTrait.class) - .isPresent() && - // don't consider deprecated prelude shapes (like PrimitiveBoolean) - !Prelude.isPreludeShape(member.getTarget()) - ); - } - - @Override - public String toString() { - String contents = super.toString(); - - if (innerWriter) { - return contents; - } - - String[] packageParts = fullPackageName.split("/"); - String header = String.format( - "// Code generated by smithy-go-codegen DO NOT EDIT.%n%n" - ); - - String packageName = packageParts[packageParts.length - 1]; - if (packageName.startsWith("v") && packageParts.length >= 2) { - String remaining = packageName.substring(1); - try { - int value = Integer.parseInt(remaining); - packageName = packageParts[packageParts.length - 2]; - if (value == 0 || value == 1) { - throw new CodegenException( - "module paths vN version component must only be N >= 2" - ); + + fn.accept(this); + + if (conditional) { + closeBlock(afterNewLine.trim()); } - } catch (NumberFormatException ne) { - // Do nothing - } + + return this; } - String packageStatement = String.format("package %s%n%n", packageName); + private static void validateTemplateArgsNotNull(Map[] argMaps) { + for (var args : argMaps) { + args.forEach((k, v) -> { + if (v == null) { + throw new CodegenException("Template argument " + k + " cannot be null"); + } + }); + } + } - String importString = imports.toString(); - String strippedContents = StringUtils.stripStart(contents, null); - String strippedImportString = StringUtils.strip(importString, null); + private void validateContext(String template) { + var matcher = ARGUMENT_NAME_PATTERN.matcher(template); + + while (matcher.find()) { + var keyName = matcher.group(1); + var value = getContext(keyName); + if (value == null) { + throw new CodegenException( + "Go template expected " + keyName + " but was not present in context scope." + + " Template: \n" + template); + } + } + } - // Don't add an additional new line between explicit imports and managed imports. - if ( - !strippedImportString.isEmpty() && strippedContents.startsWith("import ") - ) { - return header + strippedImportString + "\n" + strippedContents; + /** + * Imports one or more symbols if necessary, using the name of the + * symbol and only "USE" references. + * + * @param container Container of symbols to add. + * @return Returns the writer. + */ + public GoWriter addUseImports(SymbolContainer container) { + for (Symbol symbol : container.getSymbols()) { + addImport(symbol, + CodegenUtils.getSymbolNamespaceAlias(symbol), + SymbolReference.ContextOption.USE); + } + return this; + } + + /** + * Imports a symbol reference if necessary, using the alias of the + * reference and only associated "USE" references. + * + * @param symbolReference Symbol reference to import. + * @return Returns the writer. + */ + public GoWriter addUseImports(SymbolReference symbolReference) { + return addImport(symbolReference.getSymbol(), symbolReference.getAlias(), SymbolReference.ContextOption.USE); + } + + /** + * Adds and imports the given dependency. + * + * @param goDependency The GoDependency to import. + * @return Returns the writer. + */ + public GoWriter addUseImports(GoDependency goDependency) { + dependencies.addAll(goDependency.getDependencies()); + return addImport(goDependency.getImportPath(), goDependency.getAlias()); + } + + private GoWriter addImports(GoWriter other) { + this.imports.addImports(other.imports); + return this; + } + + private boolean isExternalNamespace(String namespace) { + return !StringUtils.isBlank(namespace) && !namespace.equals(fullPackageName); + } + + void addImportReferences(Symbol symbol, SymbolReference.ContextOption... options) { + for (SymbolReference reference : symbol.getReferences()) { + for (SymbolReference.ContextOption option : options) { + if (reference.hasOption(option)) { + addImport(reference.getSymbol(), reference.getAlias(), options); + break; + } + } + } } - return header + packageStatement + importString + contents; - } + /** + * Imports a package using an alias if necessary. + * + * @param packageName Package to import. + * @param as Alias to refer to the package as. + * @return Returns the writer. + */ + public GoWriter addImport(String packageName, String as) { + imports.addImport(packageName, as); + return this; + } - /** - * Implements Go symbol formatting for the {@code $T} formatter. - */ - private class GoSymbolFormatter - implements BiFunction { + public GoWriter addImportFromModule(String moduleName, String packageName, String as) { + imports.addImport(moduleName.concat("/").concat(packageName), as); + return this; + } + + public GoWriter addImportFromModule(String moduleName, String packageName) { + imports.addImport(moduleName.concat("/").concat(packageName), ""); + return this; + } + + public GoWriter addImport(String packageName) { + imports.addImport(packageName, ""); + return this; + } + + private GoWriter addDependencies(GoWriter other) { + this.dependencies.addAll(other.getDependencies()); + return this; + } + + + private boolean isTargetDeprecated(Model model, MemberShape member) { + return model.expectShape(member.getTarget()).getTrait(DeprecatedTrait.class).isPresent() + // don't consider deprecated prelude shapes (like PrimitiveBoolean) + && !Prelude.isPreludeShape(member.getTarget()); + } @Override - public String apply(Object type, String indent) { - if (type instanceof Symbol) { - Symbol resolvedSymbol = (Symbol) type; - String literal = resolvedSymbol.getName(); - - boolean isSlice = resolvedSymbol - .getProperty(SymbolUtils.GO_SLICE, Boolean.class) - .orElse(false); - boolean isMap = resolvedSymbol - .getProperty(SymbolUtils.GO_MAP, Boolean.class) - .orElse(false); - if (isSlice || isMap) { - resolvedSymbol = - resolvedSymbol - .getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class) - .orElseThrow(() -> - new CodegenException( - "Expected go element type property to be defined" - ) - ); - literal = - new PointableGoSymbolFormatter().apply(resolvedSymbol, "nested"); - } else if ( - !SymbolUtils.isUniverseType(resolvedSymbol) && - isExternalNamespace(resolvedSymbol.getNamespace()) - ) { - literal = formatWithNamespace(resolvedSymbol); + public String toString() { + String contents = super.toString(); + + if (innerWriter) { + return contents; } - addUseImports(resolvedSymbol); - - if (isSlice) { - return "[]" + literal; - } else if (isMap) { - return "map[string]" + literal; - } else { - return literal; + + + String[] packageParts = fullPackageName.split("/"); + String header = String.format("// Code generated by smithy-go-codegen DO NOT EDIT.%n%n"); + + String packageName = packageParts[packageParts.length - 1]; + if (packageName.startsWith("v") && packageParts.length >= 2) { + String remaining = packageName.substring(1); + try { + int value = Integer.parseInt(remaining); + packageName = packageParts[packageParts.length - 2]; + if (value == 0 || value == 1) { + throw new CodegenException("module paths vN version component must only be N >= 2"); + } + } catch (NumberFormatException ne) { + // Do nothing + } } - } else if (type instanceof SymbolReference) { - SymbolReference typeSymbol = (SymbolReference) type; - addImport( - typeSymbol.getSymbol(), - typeSymbol.getAlias(), - SymbolReference.ContextOption.USE - ); - return typeSymbol.getAlias(); - } else { - throw new CodegenException( - "Invalid type provided to $T. Expected a Symbol, but found `" + - type + - "`" - ); - } - } - - private String formatWithNamespace(Symbol symbol) { - if (StringUtils.isEmpty(symbol.getNamespace())) { - return symbol.getName(); - } - return String.format( - "%s.%s", - CodegenUtils.getSymbolNamespaceAlias(symbol), - symbol.getName() - ); - } - } - - /** - * Implements Go symbol formatting for the {@code $P} formatter. This is identical to the $T - * formatter, except that it will add a * to symbols that can be pointers. - */ - private class PointableGoSymbolFormatter extends GoSymbolFormatter { - @Override - public String apply(Object type, String indent) { - String formatted = super.apply(type, indent); - if (isPointer(type)) { - formatted = "*" + formatted; - } - return formatted; - } - - private boolean isPointer(Object type) { - if (type instanceof Symbol) { - Symbol typeSymbol = (Symbol) type; - return typeSymbol - .getProperty(SymbolUtils.POINTABLE, Boolean.class) - .orElse(false); - } else if (type instanceof SymbolReference) { - SymbolReference typeSymbol = (SymbolReference) type; - return ( - typeSymbol - .getProperty(SymbolUtils.POINTABLE, Boolean.class) - .orElse(false) || - typeSymbol - .getSymbol() - .getProperty(SymbolUtils.POINTABLE, Boolean.class) - .orElse(false) - ); - } else if (type instanceof String) { - return true; - } else { - throw new CodegenException( - "Invalid type provided to $P. Expected a Symbol, but found `" + - type + - "`" - ); - } - } - } - - class GoWritableInjector extends GoSymbolFormatter { + String packageStatement = String.format("package %s%n%n", packageName); - @Override - public String apply(Object type, String indent) { - if (!(type instanceof Writable)) { - throw new CodegenException( - "expect Writable for GoWriter W injector, but got " + type - ); - } - var innerWriter = new GoWriter(fullPackageName, true); - ((Writable) type).accept(innerWriter); - addImports(innerWriter); - addDependencies(innerWriter); - return innerWriter.toString().trim(); - } - } + String importString = imports.toString(); + String strippedContents = StringUtils.stripStart(contents, null); + String strippedImportString = StringUtils.strip(importString, null); - public interface Writable extends Consumer {} + // Don't add an additional new line between explicit imports and managed imports. + if (!strippedImportString.isEmpty() && strippedContents.startsWith("import ")) { + return header + strippedImportString + "\n" + strippedContents; + } - /** - * Chains together multiple Writables that can be composed into one Writable. - */ - public static final class ChainWritable { + return header + packageStatement + importString + contents; + } - private final List writables; + /** + * Implements Go symbol formatting for the {@code $T} formatter. + */ + private class GoSymbolFormatter implements BiFunction { + @Override + public String apply(Object type, String indent) { + if (type instanceof Symbol) { + Symbol resolvedSymbol = (Symbol) type; + String literal = resolvedSymbol.getName(); + + boolean isSlice = resolvedSymbol.getProperty(SymbolUtils.GO_SLICE, Boolean.class).orElse(false); + boolean isMap = resolvedSymbol.getProperty(SymbolUtils.GO_MAP, Boolean.class).orElse(false); + if (isSlice || isMap) { + resolvedSymbol = resolvedSymbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class) + .orElseThrow(() -> new CodegenException("Expected go element type property to be defined")); + literal = new PointableGoSymbolFormatter().apply(resolvedSymbol, "nested"); + } else if (!SymbolUtils.isUniverseType(resolvedSymbol) + && isExternalNamespace(resolvedSymbol.getNamespace())) { + literal = formatWithNamespace(resolvedSymbol); + } + addUseImports(resolvedSymbol); + + if (isSlice) { + return "[]" + literal; + } else if (isMap) { + return "map[string]" + literal; + } else { + return literal; + } + } else if (type instanceof SymbolReference) { + SymbolReference typeSymbol = (SymbolReference) type; + addImport(typeSymbol.getSymbol(), typeSymbol.getAlias(), SymbolReference.ContextOption.USE); + return typeSymbol.getAlias(); + } else { + throw new CodegenException( + "Invalid type provided to $T. Expected a Symbol, but found `" + type + "`"); + } + } - public ChainWritable() { - writables = new ArrayList<>(); + private String formatWithNamespace(Symbol symbol) { + if (StringUtils.isEmpty(symbol.getNamespace())) { + return symbol.getName(); + } + return String.format("%s.%s", CodegenUtils.getSymbolNamespaceAlias(symbol), symbol.getName()); + } } - public ChainWritable add(GoWriter.Writable writable) { - writables.add(writable); - return this; + /** + * Implements Go symbol formatting for the {@code $P} formatter. This is identical to the $T + * formatter, except that it will add a * to symbols that can be pointers. + */ + private class PointableGoSymbolFormatter extends GoSymbolFormatter { + @Override + public String apply(Object type, String indent) { + String formatted = super.apply(type, indent); + if (isPointer(type)) { + formatted = "*" + formatted; + } + return formatted; + } + + private boolean isPointer(Object type) { + if (type instanceof Symbol) { + Symbol typeSymbol = (Symbol) type; + return typeSymbol.getProperty(SymbolUtils.POINTABLE, Boolean.class).orElse(false); + } else if (type instanceof SymbolReference) { + SymbolReference typeSymbol = (SymbolReference) type; + return typeSymbol.getProperty(SymbolUtils.POINTABLE, Boolean.class).orElse(false) + || typeSymbol.getSymbol().getProperty(SymbolUtils.POINTABLE, Boolean.class).orElse(false); + } else if (type instanceof String) { + return true; + } else { + throw new CodegenException( + "Invalid type provided to $P. Expected a Symbol, but found `" + type + "`"); + } + } } - public ChainWritable add(Optional value, Function fn) { - value.ifPresent(t -> writables.add(fn.apply(t))); - return this; + class GoWritableInjector extends GoSymbolFormatter { + @Override + public String apply(Object type, String indent) { + if (!(type instanceof Writable)) { + throw new CodegenException( + "expect Writable for GoWriter W injector, but got " + type); + } + var innerWriter = new GoWriter(fullPackageName, true); + ((Writable) type).accept(innerWriter); + addImports(innerWriter); + addDependencies(innerWriter); + return innerWriter.toString().trim(); + } } - public ChainWritable add(boolean include, GoWriter.Writable writable) { - if (!include) { - writables.add(writable); - } - return this; + public interface Writable extends Consumer { } - public GoWriter.Writable compose() { - return (GoWriter writer) -> { - var hasPrevious = false; - for (GoWriter.Writable writable : writables) { - if (hasPrevious) { - writer.write(""); - } - hasPrevious = true; - writer.write("$W", writable); + /** + * Chains together multiple Writables that can be composed into one Writable. + */ + public static final class ChainWritable { + private final List writables; + + public ChainWritable() { + writables = new ArrayList<>(); + } + + public ChainWritable add(GoWriter.Writable writable) { + writables.add(writable); + return this; + } + + public ChainWritable add(Optional value, Function fn) { + value.ifPresent(t -> writables.add(fn.apply(t))); + return this; + } + + public ChainWritable add(boolean include, GoWriter.Writable writable) { + if (!include) { + writables.add(writable); + } + return this; + } + + public GoWriter.Writable compose() { + return (GoWriter writer) -> { + var hasPrevious = false; + for (GoWriter.Writable writable : writables) { + if (hasPrevious) { + writer.write(""); + } + hasPrevious = true; + writer.write("$W", writable); + } + }; } - }; } - } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ImportDeclarations.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ImportDeclarations.java index bd528e9d3c..a8c3dcf30f 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ImportDeclarations.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ImportDeclarations.java @@ -1,65 +1,62 @@ package software.amazon.polymorph.smithygo.codegen; -import java.util.Map; -import java.util.TreeMap; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.ImportContainer; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.utils.StringUtils; -public class ImportDeclarations implements ImportContainer { +import java.util.Map; +import java.util.TreeMap; - private final Map imports = new TreeMap<>(); +public class ImportDeclarations implements ImportContainer { - ImportDeclarations addImport(String importPath, String alias) { - String importAlias = CodegenUtils.getDefaultPackageImportName(importPath); - if (!StringUtils.isBlank(alias)) { - if (alias.equals(".")) { - // Global imports are generally a bad practice. - throw new CodegenException( - "Globally importing packages is forbidden: " + importPath - ); - } - importAlias = alias; + private final Map imports = new TreeMap<>(); + + ImportDeclarations addImport(String importPath, String alias) { + String importAlias = CodegenUtils.getDefaultPackageImportName(importPath); + if (!StringUtils.isBlank(alias)) { + if (alias.equals(".")) { + // Global imports are generally a bad practice. + throw new CodegenException("Globally importing packages is forbidden: " + importPath); + } + importAlias = alias; + } + imports.putIfAbsent(importAlias, importPath); + return this; } - imports.putIfAbsent(importAlias, importPath); - return this; - } - - ImportDeclarations addImports(ImportDeclarations other) { - other.imports.forEach((importAlias, importPath) -> { - addImport(importPath, importAlias); - }); - return this; - } - @Override - public String toString() { - if (imports.isEmpty()) { - return ""; + ImportDeclarations addImports(ImportDeclarations other) { + other.imports.forEach((importAlias, importPath) -> { + addImport(importPath, importAlias); + }); + return this; } - StringBuilder builder = new StringBuilder("import (\n"); - for (Map.Entry entry : imports.entrySet()) { - builder.append('\t'); - builder.append(createImportStatement(entry)); - builder.append('\n'); + @Override + public String toString() { + if (imports.isEmpty()) { + return ""; + } + + StringBuilder builder = new StringBuilder("import (\n"); + for (Map.Entry entry : imports.entrySet()) { + builder.append('\t'); + builder.append(createImportStatement(entry)); + builder.append('\n'); + } + builder.append(")\n\n"); + return builder.toString(); } - builder.append(")\n\n"); - return builder.toString(); - } - private String createImportStatement(Map.Entry entry) { - String formattedPackageName = "\"" + entry.getValue() + "\""; - return CodegenUtils - .getDefaultPackageImportName(entry.getValue()) - .equals(entry.getKey()) - ? formattedPackageName - : entry.getKey() + " " + formattedPackageName; - } + private String createImportStatement(Map.Entry entry) { + String formattedPackageName = "\"" + entry.getValue() + "\""; + return CodegenUtils.getDefaultPackageImportName(entry.getValue()).equals(entry.getKey()) + ? formattedPackageName + : entry.getKey() + " " + formattedPackageName; + } - @Override - public void importSymbol(Symbol symbol, String alias) { - addImport(symbol.getName(), alias); - } + @Override + public void importSymbol(Symbol symbol, String alias) { + addImport(symbol.getName(), alias); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/IntEnumGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/IntEnumGenerator.java index 55387111bc..3d23121ce3 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/IntEnumGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/IntEnumGenerator.java @@ -32,87 +32,60 @@ * Renders intEnums and their constants. */ public final class IntEnumGenerator implements Runnable { + private static final Logger LOGGER = Logger.getLogger(IntEnumGenerator.class.getName()); - private static final Logger LOGGER = Logger.getLogger( - IntEnumGenerator.class.getName() - ); + private final SymbolProvider symbolProvider; + private final GoWriter writer; + private final IntEnumShape shape; - private final SymbolProvider symbolProvider; - private final GoWriter writer; - private final IntEnumShape shape; + public IntEnumGenerator(SymbolProvider symbolProvider, GoWriter writer, IntEnumShape shape) { + this.symbolProvider = symbolProvider; + this.writer = writer; + this.shape = shape; + } - public IntEnumGenerator( - SymbolProvider symbolProvider, - GoWriter writer, - IntEnumShape shape - ) { - this.symbolProvider = symbolProvider; - this.writer = writer; - this.shape = shape; - } + @Override + public void run() { + Symbol symbol = symbolProvider.toSymbol(shape); - @Override - public void run() { - Symbol symbol = symbolProvider.toSymbol(shape); +// TODO(smithy): Use type alias instead of type definition until refactoring +// protocol generators is prioritized. + writer.write("type $L = int32", symbol.getName()).write(""); - // TODO(smithy): Use type alias instead of type definition until refactoring - // protocol generators is prioritized. - writer.write("type $L = int32", symbol.getName()).write(""); + Set constants = new LinkedHashSet<>(); + writer.openBlock("const (", ")", () -> { + for (Map.Entry entry : shape.getAllMembers().entrySet()) { + StringBuilder labelBuilder = new StringBuilder(symbol.getName()); + String name = entry.getKey(); - Set constants = new LinkedHashSet<>(); - writer - .openBlock( - "const (", - ")", - () -> { - for (Map.Entry entry : shape - .getAllMembers() - .entrySet()) { - StringBuilder labelBuilder = new StringBuilder(symbol.getName()); - String name = entry.getKey(); + for (String part : name.split("(?U)[\\W_]")) { + if (part.matches(".*[a-z].*") && part.matches(".*[A-Z].*")) { +// Mixed case names should not be changed other than first letter capitalized. + labelBuilder.append(StringUtils.capitalize(part)); + } else { +// For all non-mixed case parts title case first letter, followed by all other lower cased. + labelBuilder.append(StringUtils.capitalize(part.toLowerCase(Locale.US))); + } + } + String label = labelBuilder.toString(); - for (String part : name.split("(?U)[\\W_]")) { - if (part.matches(".*[a-z].*") && part.matches(".*[A-Z].*")) { - // Mixed case names should not be changed other than first letter capitalized. - labelBuilder.append(StringUtils.capitalize(part)); - } else { - // For all non-mixed case parts title case first letter, followed by all other lower cased. - labelBuilder.append( - StringUtils.capitalize(part.toLowerCase(Locale.US)) - ); - } - } - String label = labelBuilder.toString(); +// If camel-casing would cause a conflict, don't camel-case this enum value. + if (constants.contains(label)) { + LOGGER.warning(String.format( + "Multiple enums resolved to the same name, `%s`, using unaltered value for: %s", + label, name)); + label = name; + } + constants.add(label); - // If camel-casing would cause a conflict, don't camel-case this enum value. - if (constants.contains(label)) { - LOGGER.warning( - String.format( - "Multiple enums resolved to the same name, `%s`, using unaltered value for: %s", - label, - name - ) - ); - label = name; + writer.write("$L $L = $L", label, symbol.getName(), + entry.getValue().expectTrait(EnumValueTrait.class).expectIntValue()); } - constants.add(label); + }).write(""); - writer.write( - "$L $L = $L", - label, - symbol.getName(), - entry - .getValue() - .expectTrait(EnumValueTrait.class) - .expectIntValue() - ); - } - } - ) - .write(""); - // TODO(smithy): type aliases don't allow defining methods on base types (e.g. int32). - // Uncomment generating the Value() method when the type alias is migrated to type definition. - /* +// TODO(smithy): type aliases don't allow defining methods on base types (e.g. int32). +// Uncomment generating the Value() method when the type alias is migrated to type definition. +/* writer.writeDocs(String.format("Values returns all known values for %s. Note that this can be expanded in the " + "future, and so it is only as up to date as the client.%n%nThe ordering of this slice is not " + "guaranteed to be stable across updates.", symbol.getName())); @@ -124,5 +97,5 @@ public void run() { }); }); */ - } -} + } +} \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SmithyGoDependency.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SmithyGoDependency.java index c5c95d399c..20955d8ea8 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SmithyGoDependency.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SmithyGoDependency.java @@ -19,171 +19,116 @@ * A class of constants for dependencies used by this package. */ public final class SmithyGoDependency { + // The version in the stdlib dependencies should reflect the minimum Go version. + // The values aren't currently used, but they could potentially used to dynamically + // set the minimum go version. + public static final GoDependency BIG = stdlib("math/big"); + public static final GoDependency TIME = stdlib("time"); + public static final GoDependency FMT = stdlib("fmt"); + public static final GoDependency CONTEXT = stdlib("context"); + public static final GoDependency STRCONV = stdlib("strconv"); + public static final GoDependency BASE64 = stdlib("encoding/base64"); + public static final GoDependency NET = stdlib("net"); + public static final GoDependency NET_URL = stdlib("net/url"); + public static final GoDependency NET_HTTP = stdlib("net/http"); + public static final GoDependency NET_HTTP_TEST = stdlib("net/http/httptest"); + public static final GoDependency BYTES = stdlib("bytes"); + public static final GoDependency STRINGS = stdlib("strings"); + public static final GoDependency JSON = stdlib("encoding/json"); + public static final GoDependency IO = stdlib("io"); + public static final GoDependency IOUTIL = stdlib("io/ioutil"); + public static final GoDependency CRYPTORAND = stdlib("crypto/rand", "cryptorand"); + public static final GoDependency TESTING = stdlib("testing"); + public static final GoDependency ERRORS = stdlib("errors"); + public static final GoDependency XML = stdlib("encoding/xml"); + public static final GoDependency SYNC = stdlib("sync"); + public static final GoDependency PATH = stdlib("path"); + + public static final GoDependency SMITHY = smithy(null, "smithy"); + public static final GoDependency SMITHY_HTTP_TRANSPORT = smithy("transport/http", "smithyhttp"); + public static final GoDependency SMITHY_MIDDLEWARE = smithy("middleware"); + public static final GoDependency SMITHY_TIME = smithy("time", "smithytime"); + public static final GoDependency SMITHY_HTTP_BINDING = smithy("encoding/httpbinding"); + public static final GoDependency SMITHY_JSON = smithy("encoding/json", "smithyjson"); + public static final GoDependency SMITHY_XML = smithy("encoding/xml", "smithyxml"); + public static final GoDependency SMITHY_IO = smithy("io", "smithyio"); + public static final GoDependency SMITHY_LOGGING = smithy("logging"); + public static final GoDependency SMITHY_PTR = smithy("ptr"); + public static final GoDependency SMITHY_RAND = smithy("rand", "smithyrand"); + public static final GoDependency SMITHY_TESTING = smithy("testing", "smithytesting"); + public static final GoDependency SMITHY_WAITERS = smithy("waiter", "smithywaiter"); + public static final GoDependency SMITHY_DOCUMENT = smithy("document", "smithydocument"); + public static final GoDependency SMITHY_DOCUMENT_JSON = smithy("document/json", "smithydocumentjson"); + public static final GoDependency SMITHY_SYNC = smithy("sync", "smithysync"); + public static final GoDependency SMITHY_AUTH_BEARER = smithy("auth/bearer"); + + public static final GoDependency GO_CMP = goCmp("cmp"); + public static final GoDependency GO_CMP_OPTIONS = goCmp("cmp/cmpopts"); + + public static final GoDependency GO_JMESPATH = goJmespath(null); + public static final GoDependency MATH = stdlib("math"); + + private static final String SMITHY_SOURCE_PATH = "github.com/aws/smithy-go"; + private static final String GO_CMP_SOURCE_PATH = "github.com/google/go-cmp"; + private static final String GO_JMESPATH_SOURCE_PATH = "github.com/jmespath/go-jmespath"; + + private SmithyGoDependency() { + } - // The version in the stdlib dependencies should reflect the minimum Go version. - // The values aren't currently used, but they could potentially used to dynamically - // set the minimum go version. - public static final GoDependency BIG = stdlib("math/big"); - public static final GoDependency TIME = stdlib("time"); - public static final GoDependency FMT = stdlib("fmt"); - public static final GoDependency CONTEXT = stdlib("context"); - public static final GoDependency STRCONV = stdlib("strconv"); - public static final GoDependency BASE64 = stdlib("encoding/base64"); - public static final GoDependency NET = stdlib("net"); - public static final GoDependency NET_URL = stdlib("net/url"); - public static final GoDependency NET_HTTP = stdlib("net/http"); - public static final GoDependency NET_HTTP_TEST = stdlib("net/http/httptest"); - public static final GoDependency BYTES = stdlib("bytes"); - public static final GoDependency STRINGS = stdlib("strings"); - public static final GoDependency JSON = stdlib("encoding/json"); - public static final GoDependency IO = stdlib("io"); - public static final GoDependency IOUTIL = stdlib("io/ioutil"); - public static final GoDependency CRYPTORAND = stdlib( - "crypto/rand", - "cryptorand" - ); - public static final GoDependency TESTING = stdlib("testing"); - public static final GoDependency ERRORS = stdlib("errors"); - public static final GoDependency XML = stdlib("encoding/xml"); - public static final GoDependency SYNC = stdlib("sync"); - public static final GoDependency PATH = stdlib("path"); - - public static final GoDependency SMITHY = smithy(null, "smithy"); - public static final GoDependency SMITHY_HTTP_TRANSPORT = smithy( - "transport/http", - "smithyhttp" - ); - public static final GoDependency SMITHY_MIDDLEWARE = smithy("middleware"); - public static final GoDependency SMITHY_TIME = smithy("time", "smithytime"); - public static final GoDependency SMITHY_HTTP_BINDING = smithy( - "encoding/httpbinding" - ); - public static final GoDependency SMITHY_JSON = smithy( - "encoding/json", - "smithyjson" - ); - public static final GoDependency SMITHY_XML = smithy( - "encoding/xml", - "smithyxml" - ); - public static final GoDependency SMITHY_IO = smithy("io", "smithyio"); - public static final GoDependency SMITHY_LOGGING = smithy("logging"); - public static final GoDependency SMITHY_PTR = smithy("ptr"); - public static final GoDependency SMITHY_RAND = smithy("rand", "smithyrand"); - public static final GoDependency SMITHY_TESTING = smithy( - "testing", - "smithytesting" - ); - public static final GoDependency SMITHY_WAITERS = smithy( - "waiter", - "smithywaiter" - ); - public static final GoDependency SMITHY_DOCUMENT = smithy( - "document", - "smithydocument" - ); - public static final GoDependency SMITHY_DOCUMENT_JSON = smithy( - "document/json", - "smithydocumentjson" - ); - public static final GoDependency SMITHY_SYNC = smithy("sync", "smithysync"); - public static final GoDependency SMITHY_AUTH_BEARER = smithy("auth/bearer"); - - public static final GoDependency GO_CMP = goCmp("cmp"); - public static final GoDependency GO_CMP_OPTIONS = goCmp("cmp/cmpopts"); - - public static final GoDependency GO_JMESPATH = goJmespath(null); - public static final GoDependency MATH = stdlib("math"); - - private static final String SMITHY_SOURCE_PATH = "github.com/aws/smithy-go"; - private static final String GO_CMP_SOURCE_PATH = "github.com/google/go-cmp"; - private static final String GO_JMESPATH_SOURCE_PATH = - "github.com/jmespath/go-jmespath"; - - private SmithyGoDependency() {} - - /** - * Get a {@link GoDependency} representing the standard library package import path. - * - * @param importPath standard library import path - * @return the {@link GoDependency} for the package import path - */ - public static GoDependency stdlib(String importPath) { - return GoDependency.standardLibraryDependency( - importPath, - Versions.GO_STDLIB - ); - } - - /** - * Get a {@link GoDependency} representing the standard library package import path with the given alias. - * - * @param importPath standard library package import path - * @param alias the package alias - * @return the {@link GoDependency} for the package import path - */ - public static GoDependency stdlib(String importPath, String alias) { - return GoDependency.standardLibraryDependency( - importPath, - Versions.GO_STDLIB, - alias - ); - } + /** + * Get a {@link GoDependency} representing the standard library package import path. + * + * @param importPath standard library import path + * @return the {@link GoDependency} for the package import path + */ + public static GoDependency stdlib(String importPath) { + return GoDependency.standardLibraryDependency(importPath, Versions.GO_STDLIB); + } - private static GoDependency smithy(String relativePath) { - return smithy(relativePath, null); - } + /** + * Get a {@link GoDependency} representing the standard library package import path with the given alias. + * + * @param importPath standard library package import path + * @param alias the package alias + * @return the {@link GoDependency} for the package import path + */ + public static GoDependency stdlib(String importPath, String alias) { + return GoDependency.standardLibraryDependency(importPath, Versions.GO_STDLIB, alias); + } - private static GoDependency smithy(String relativePath, String alias) { - return relativePackage( - SMITHY_SOURCE_PATH, - relativePath, - Versions.SMITHY_GO, - alias - ); - } + private static GoDependency smithy(String relativePath) { + return smithy(relativePath, null); + } - private static GoDependency goCmp(String relativePath) { - return relativePackage( - GO_CMP_SOURCE_PATH, - relativePath, - Versions.GO_CMP, - null - ); - } + private static GoDependency smithy(String relativePath, String alias) { + return relativePackage(SMITHY_SOURCE_PATH, relativePath, Versions.SMITHY_GO, alias); + } - private static GoDependency goJmespath(String relativePath) { - return relativePackage( - GO_JMESPATH_SOURCE_PATH, - relativePath, - Versions.GO_JMESPATH, - null - ); - } + private static GoDependency goCmp(String relativePath) { + return relativePackage(GO_CMP_SOURCE_PATH, relativePath, Versions.GO_CMP, null); + } - private static GoDependency relativePackage( - String moduleImportPath, - String relativePath, - String version, - String alias - ) { - String importPath = moduleImportPath; - if (relativePath != null) { - importPath = importPath + "/" + relativePath; + private static GoDependency goJmespath(String relativePath) { + return relativePackage(GO_JMESPATH_SOURCE_PATH, relativePath, Versions.GO_JMESPATH, null); } - return GoDependency.moduleDependency( - moduleImportPath, - importPath, - version, - alias - ); - } - private static final class Versions { + private static GoDependency relativePackage( + String moduleImportPath, + String relativePath, + String version, + String alias + ) { + String importPath = moduleImportPath; + if (relativePath != null) { + importPath = importPath + "/" + relativePath; + } + return GoDependency.moduleDependency(moduleImportPath, importPath, version, alias); + } - private static final String GO_STDLIB = "1.15"; - private static final String GO_CMP = "v0.5.4"; - private static final String SMITHY_GO = "v1.4.0"; - private static final String GO_JMESPATH = "v0.4.0"; - } + private static final class Versions { + private static final String GO_STDLIB = "1.15"; + private static final String GO_CMP = "v0.5.4"; + private static final String SMITHY_GO = "v1.4.0"; + private static final String GO_JMESPATH = "v0.4.0"; + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java index ecf9687753..cca398c08c 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java @@ -15,21 +15,14 @@ package software.amazon.polymorph.smithygo.codegen; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - -import java.math.BigDecimal; -import java.util.HashSet; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; import software.amazon.polymorph.smithygo.localservice.nameresolver.SmithyNameResolver; import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; import software.amazon.polymorph.traits.ReferenceTrait; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; +import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.LengthTrait; @@ -38,134 +31,48 @@ import software.amazon.smithy.model.traits.StreamingTrait; import software.amazon.smithy.utils.SetUtils; +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + +import java.math.BigDecimal; +import java.util.HashSet; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; + /** * Renders structures. */ public final class StructureGenerator implements Runnable { - - private static final Set ERROR_MEMBER_NAMES = SetUtils.of( - "ErrorMessage", - "Message", - "ErrorCodeOverride" - ); - - private final Model model; - private final SymbolProvider symbolProvider; - private final GoWriter writer; - private final StructureShape shape; - private final GenerationContext context; - private final ValidationGenerator validationGenerator; - - public StructureGenerator( - final GenerationContext context, - GoWriter writer, - StructureShape shape - ) { - this.context = context; - this.model = context.model(); - this.symbolProvider = context.symbolProvider(); - this.writer = writer; - this.shape = shape; - this.validationGenerator = - new ValidationGenerator(model, symbolProvider, writer); - } - - @Override - public void run() { - if (!shape.hasTrait(ErrorTrait.class)) { - renderStructure(() -> {}); - } else { - renderErrorStructure(); + private static final Set ERROR_MEMBER_NAMES = SetUtils.of("ErrorMessage", "Message", "ErrorCodeOverride"); + + private final Model model; + private final SymbolProvider symbolProvider; + private final GoWriter writer; + private final StructureShape shape; + private final GenerationContext context; + private final ValidationGenerator validationGenerator; + + public StructureGenerator( + final GenerationContext context, + GoWriter writer, + StructureShape shape) { + this.context = context; + this.model = context.model(); + this.symbolProvider = context.symbolProvider(); + this.writer = writer; + this.shape = shape; + this.validationGenerator = new ValidationGenerator(model, symbolProvider, writer); } - } - - /** - * Renders a non-error structure. - * - * @param runnable A runnable that runs before the structure definition is closed. This can be used to write - * additional members. - */ - public void renderStructure(Runnable runnable) { - renderStructure(runnable, false); - } - - /** - * Renders a non-error structure. - * - * @param runnable A runnable that runs before the structure definition is closed. This can be used to write - * additional members. - * @param isInputStructure A boolean indicating if input variants for member symbols should be used. - */ - public void renderStructure(Runnable runnable, boolean isInputStructure) { - writer.addImport("fmt"); - Symbol symbol = symbolProvider.toSymbol(shape); - writer.openBlock("type $L struct {", symbol.getName()); - CodegenUtils.SortedMembers sortedMembers = new CodegenUtils.SortedMembers( - symbolProvider - ); - shape - .getAllMembers() - .values() - .stream() - .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) - .sorted(sortedMembers) - .forEach(member -> { - writer.write(""); - String memberName = symbolProvider.toMemberName(member); - - Symbol memberSymbol = symbolProvider.toSymbol(member); - - var targetShape = model.expectShape(member.getTarget()); - - if (isInputStructure) { - memberSymbol = - memberSymbol - .getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) - .orElse(memberSymbol); - } - var namespace = SmithyNameResolver.smithyTypesNamespace(targetShape); - - if (targetShape.hasTrait(ReferenceTrait.class)) { - memberSymbol = - memberSymbol.getProperty("Referred", Symbol.class).get(); - var refShape = targetShape.expectTrait(ReferenceTrait.class); - if (refShape.isService()) { - namespace = - SmithyNameResolver.shapeNamespace( - model.expectShape(refShape.getReferentId()) - ); - } - if ( - !member - .toShapeId() - .getNamespace() - .equals(refShape.getReferentId().getNamespace()) - ) { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - refShape.getReferentId().getNamespace() - ), - namespace - ); - } + @Override + public void run() { + if (!shape.hasTrait(ErrorTrait.class)) { + renderStructure(() -> { + }); } else { - if ( - !member - .toShapeId() - .getNamespace() - .equals(targetShape.toShapeId().getNamespace()) && - !targetShape.toShapeId().getNamespace().startsWith("smithy") && - targetShape.asStructureShape().isPresent() - ) { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - targetShape.toShapeId().getNamespace() - ), - namespace - ); - } + renderErrorStructure(); } + } /** * Renders a non-error structure. diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolUtils.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolUtils.java index ec7d1aba80..390a6919d8 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolUtils.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolUtils.java @@ -23,217 +23,173 @@ */ public final class SymbolUtils { - public static final String POINTABLE = "pointable"; - public static final String NAMESPACE_ALIAS = "namespaceAlias"; - public static final String GO_UNIVERSE_TYPE = "universeType"; - public static final String GO_SLICE = "goSlice"; - public static final String GO_MAP = "goMap"; - public static final String GO_ELEMENT_TYPE = "goElementType"; - - // Used when a given shape must be represented differently on input. - public static final String INPUT_VARIANT = "inputVariant"; - - private SymbolUtils() {} - - /** - * Create a value symbol builder. - * - * @param typeName the name of the type. - * @return the symbol builder type. - */ - public static Symbol.Builder createValueSymbolBuilder(String typeName) { - return Symbol.builder().putProperty(POINTABLE, false).name(typeName); - } - - /** - * Create a pointable symbol builder. - * - * @param typeName the name of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder(String typeName) { - return Symbol.builder().putProperty(POINTABLE, true).name(typeName); - } - - /** - * Create a value symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder( - Shape shape, - String typeName - ) { - return createValueSymbolBuilder(typeName).putProperty("shape", shape); - } - - /** - * Create a pointable symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder( - Shape shape, - String typeName - ) { - return createPointableSymbolBuilder(typeName).putProperty("shape", shape); - } - - /** - * Create a pointable symbol builder. - * - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder( - String typeName, - String namespace - ) { - return createPointableSymbolBuilder(typeName).namespace(namespace, "."); - } - - /** - * Create a value symbol builder. - * - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder( - String typeName, - String namespace - ) { - return createValueSymbolBuilder(typeName).namespace(namespace, "."); - } - - /** - * Create a pointable symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder( - Shape shape, - String typeName, - String namespace - ) { - return createPointableSymbolBuilder(shape, typeName) - .namespace(namespace, "."); - } - - /** - * Create a value symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder( - Shape shape, - String typeName, - String namespace - ) { - return createValueSymbolBuilder(shape, typeName).namespace(namespace, "."); - } - - /** - * Create a pointable symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder( - Shape shape, - String typeName, - GoDependency namespace - ) { - return setImportedNamespace( - createPointableSymbolBuilder(shape, typeName), - namespace - ); - } - - /** - * Create a value symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder( - Shape shape, - String typeName, - GoDependency namespace - ) { - return setImportedNamespace( - createValueSymbolBuilder(shape, typeName), - namespace - ); - } - - /** - * Create a pointable symbol builder. - * - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder( - String typeName, - GoDependency namespace - ) { - return setImportedNamespace( - createPointableSymbolBuilder(typeName), - namespace - ); - } - - /** - * Create a value symbol builder. - * - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder( - String typeName, - GoDependency namespace - ) { - return setImportedNamespace(createValueSymbolBuilder(typeName), namespace); - } - - private static Symbol.Builder setImportedNamespace( - Symbol.Builder builder, - GoDependency dependency - ) { - return builder - .namespace(dependency.getImportPath(), ".") - .addDependency(dependency) - .putProperty(NAMESPACE_ALIAS, dependency.getAlias()); - } - - /** - * Go declares several built-in language types in what is known as the Universe block. This function determines - * whether the provided symbol represents a Go universe type. - * - * @param symbol the symbol to check - * @return whether the symbol type is in the Go universe block - * @see The Go Programming Language Specification - */ - public static boolean isUniverseType(Symbol symbol) { - return symbol - .getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class) - .orElse(false); - } + public static final String POINTABLE = "pointable"; + public static final String NAMESPACE_ALIAS = "namespaceAlias"; + public static final String GO_UNIVERSE_TYPE = "universeType"; + public static final String GO_SLICE = "goSlice"; + public static final String GO_MAP = "goMap"; + public static final String GO_ELEMENT_TYPE = "goElementType"; + + // Used when a given shape must be represented differently on input. + public static final String INPUT_VARIANT = "inputVariant"; + + private SymbolUtils() { + } + + /** + * Create a value symbol builder. + * + * @param typeName the name of the type. + * @return the symbol builder type. + */ + public static Symbol.Builder createValueSymbolBuilder(String typeName) { + return Symbol.builder() + .putProperty(POINTABLE, false) + .name(typeName); + } + + /** + * Create a pointable symbol builder. + * + * @param typeName the name of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder(String typeName) { + return Symbol.builder() + .putProperty(POINTABLE, true) + .name(typeName); + } + + /** + * Create a value symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder(Shape shape, String typeName) { + return createValueSymbolBuilder(typeName).putProperty("shape", shape); + } + + /** + * Create a pointable symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder(Shape shape, String typeName) { + return createPointableSymbolBuilder(typeName).putProperty("shape", shape); + } + + /** + * Create a pointable symbol builder. + * + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder(String typeName, String namespace) { + return createPointableSymbolBuilder(typeName).namespace(namespace, "."); + } + + /** + * Create a value symbol builder. + * + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder(String typeName, String namespace) { + return createValueSymbolBuilder(typeName).namespace(namespace, "."); + } + + /** + * Create a pointable symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder(Shape shape, String typeName, String namespace) { + return createPointableSymbolBuilder(shape, typeName).namespace(namespace, "."); + } + + /** + * Create a value symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder(Shape shape, String typeName, String namespace) { + return createValueSymbolBuilder(shape, typeName).namespace(namespace, "."); + } + + /** + * Create a pointable symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder(Shape shape, String typeName, GoDependency namespace) { + return setImportedNamespace(createPointableSymbolBuilder(shape, typeName), namespace); + } + + /** + * Create a value symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder(Shape shape, String typeName, GoDependency namespace) { + return setImportedNamespace(createValueSymbolBuilder(shape, typeName), namespace); + } + + /** + * Create a pointable symbol builder. + * + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder(String typeName, GoDependency namespace) { + return setImportedNamespace(createPointableSymbolBuilder(typeName), namespace); + } + + /** + * Create a value symbol builder. + * + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder(String typeName, GoDependency namespace) { + return setImportedNamespace(createValueSymbolBuilder(typeName), namespace); + } + + private static Symbol.Builder setImportedNamespace(Symbol.Builder builder, GoDependency dependency) { + return builder.namespace(dependency.getImportPath(), ".") + .addDependency(dependency) + .putProperty(NAMESPACE_ALIAS, dependency.getAlias()); + } + + /** + * Go declares several built-in language types in what is known as the Universe block. This function determines + * whether the provided symbol represents a Go universe type. + * + * @param symbol the symbol to check + * @return whether the symbol type is in the Go universe block + * @see The Go Programming Language Specification + */ + public static boolean isUniverseType(Symbol symbol) { + return symbol.getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class) + .orElse(false); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolVisitor.java index d23cbda14f..7bd6ee95ff 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolVisitor.java @@ -15,10 +15,6 @@ package software.amazon.polymorph.smithygo.codegen; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.logging.Logger; import software.amazon.polymorph.smithygo.codegen.knowledge.GoPointableIndex; import software.amazon.polymorph.smithygo.localservice.nameresolver.SmithyNameResolver; import software.amazon.polymorph.traits.ReferenceTrait; @@ -65,6 +61,11 @@ import software.amazon.smithy.model.traits.StreamingTrait; import software.amazon.smithy.utils.StringUtils; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.logging.Logger; + /** * Responsible for type mapping and file/identifier formatting. * @@ -72,593 +73,449 @@ * suffixed with "_". See "reserved-words.txt" for the list of words. */ public class SymbolVisitor implements SymbolProvider, ShapeVisitor { + private static final Logger LOGGER = Logger.getLogger(SymbolVisitor.class.getName()); + + private final Model model; + private final String rootModuleName; + private final ReservedWordSymbolProvider.Escaper escaper; + private final ReservedWordSymbolProvider.Escaper errorMemberEscaper; + private final Map structureSpecificMemberEscapers = new HashMap<>(); + private final GoPointableIndex pointableIndex; + private final GoSettings settings; + + public SymbolVisitor(Model model, GoSettings settings) { + this.model = model; + this.settings = settings; + this.rootModuleName = SmithyNameResolver.shapeNamespace(settings.getService(model)); + this.pointableIndex = GoPointableIndex.of(model); + + // Reserve the generated names for union members, including the unknown case. + ReservedWordsBuilder reservedNames = new ReservedWordsBuilder(); + reserveUnionMemberNames(model, reservedNames); + + ReservedWords reservedMembers = new ReservedWordsBuilder() + // Since Go only exports names if the first character is upper case and all + // the go reserved words are lower case, it's functionally impossible to conflict, + // so we only need to protect against common names. As of now there's only one. + .put("String", "String_") + .put("GetStream", "GetStream_") + .build(); + + model.shapes(StructureShape.class) + .filter(this::supportsInheritance) + .forEach(this::reserveInterfaceMemberAccessors); + + escaper = ReservedWordSymbolProvider.builder() + .nameReservedWords(reservedNames.build()) + .memberReservedWords(reservedMembers) + // Only escape words when the symbol has a definition file to + // prevent escaping intentional references to built-in types. + .escapePredicate((shape, symbol) -> !StringUtils.isEmpty(symbol.getDefinitionFile())) + .buildEscaper(); + + // Reserved words that only apply to error members. + ReservedWords reservedErrorMembers = new ReservedWordsBuilder() + .put("ErrorCode", "ErrorCode_") + .put("ErrorMessage", "ErrorMessage_") + .put("ErrorFault", "ErrorFault_") + .put("Unwrap", "Unwrap_") + .put("Error", "Error_") + .put("ErrorCodeOverride", "ErrorCodeOverride_") + .build(); + + errorMemberEscaper = ReservedWordSymbolProvider.builder() + .memberReservedWords(ReservedWords.compose(reservedMembers, reservedErrorMembers)) + .escapePredicate((shape, symbol) -> !StringUtils.isEmpty(symbol.getDefinitionFile())) + .buildEscaper(); + } + + /** + * Reserves generated member names for unions. + * + *

These have the format {UnionName}Member{MemberName}. + * + * @param model The model whose unions should be reserved. + * @param builder A reserved words builder to add on to. + */ + private void reserveUnionMemberNames(Model model, ReservedWordsBuilder builder) { + model.shapes(UnionShape.class).forEach(union -> { + for (MemberShape member : union.getAllMembers().values()) { + String memberName = formatUnionMemberName(union, member); + builder.put(memberName, escapeWithTrailingUnderscore(memberName)); + } + }); + } + + private boolean supportsInheritance(Shape shape) { + return shape.isStructureShape() && shape.hasTrait(ErrorTrait.class); + } + + /** + * Reserves Get* and Has* member names for the given structure for use as accessor methods. + * + *

These reservations will only apply to the given structure, not to other structures. + * + * @param shape The structure shape whose members should be reserved. + */ + private void reserveInterfaceMemberAccessors(StructureShape shape) { + ReservedWordsBuilder builder = new ReservedWordsBuilder(); + for (MemberShape member : shape.getAllMembers().values()) { + String name = getDefaultMemberName(member); + String getterName = "Get" + name; + String haserName = "Has" + name; + builder.put(getterName, escapeWithTrailingUnderscore(getterName)); + builder.put(haserName, escapeWithTrailingUnderscore(haserName)); + } + ReservedWordSymbolProvider.Escaper structureSpecificMemberEscaper = ReservedWordSymbolProvider.builder() + .memberReservedWords(builder.build()) + .buildEscaper(); + structureSpecificMemberEscapers.put(shape.getId(), structureSpecificMemberEscaper); + } + + private String escapeWithTrailingUnderscore(String symbolName) { + return symbolName + "_"; + } + + @Override + public Symbol toSymbol(Shape shape) { + Symbol symbol = shape.accept(this); + LOGGER.fine(() -> String.format("Creating symbol from %s: %s", shape, symbol)); + return linkArchetypeShape(shape, escaper.escapeSymbol(shape, symbol)); + } + + /** + * Links the archetype shape id for the symbol. + * + * @param shape the model shape + * @param symbol the symbol to set the archetype property on + * @return the symbol with archetype set if shape is a synthetic clone otherwise the original symbol + */ + private Symbol linkArchetypeShape(Shape shape, Symbol symbol) { + return shape.getTrait(Synthetic.class) + .map(synthetic -> symbol.toBuilder() + .putProperty("archetype", synthetic.getArchetype()) + .build()) + .orElse(symbol); + } + + @Override + public String toMemberName(MemberShape shape) { + Shape container = model.expectShape(shape.getContainer()); + if (container.isUnionShape()) { + // Union member names are not escaped as they are used to build the escape set. + return formatUnionMemberName(container.asUnionShape().get(), shape); + } + + String memberName = getDefaultMemberName(shape); + memberName = escaper.escapeMemberName(memberName); + + // Escape words reserved for the specific container. + if (structureSpecificMemberEscapers.containsKey(shape.getContainer())) { + memberName = structureSpecificMemberEscapers.get(shape.getContainer()).escapeMemberName(memberName); + } + + // Escape words that are only reserved for error members. + if (isErrorMember(shape)) { + memberName = errorMemberEscaper.escapeMemberName(memberName); + } + return memberName; + } + + private String formatUnionMemberName(UnionShape union, MemberShape member) { + return String.format("%sMember%s", getDefaultShapeName(union), getDefaultMemberName(member)); + } + + private String getDefaultShapeName(Shape shape) { + ServiceShape serviceShape = model.expectShape(settings.getService(), ServiceShape.class); + return StringUtils.capitalize(removeLeadingInvalidIdentCharacters(shape.getId().getName(serviceShape))); + } + + private String getDefaultMemberName(MemberShape shape) { + String memberName = StringUtils.capitalize(removeLeadingInvalidIdentCharacters(shape.getMemberName())); + + return memberName; + } + + private String removeLeadingInvalidIdentCharacters(String value) { + if (Character.isAlphabetic(value.charAt(0))) { + return value; + } + + int i; + for (i = 0; i < value.length(); i++) { + if (Character.isAlphabetic(value.charAt(i))) { + break; + } + } + + String remaining = value.substring(i); + if (remaining.length() == 0) { + throw new CodegenException("tried to clean name " + value + ", but resulted in empty string"); + } + + return remaining; + } + + + private boolean isErrorMember(MemberShape shape) { + return model.getShape(shape.getContainer()) + .map(container -> container.hasTrait(ErrorTrait.ID)) + .orElse(false); + } + + @Override + public Symbol blobShape(BlobShape shape) { + if (shape.hasTrait(StreamingTrait.ID)) { + Symbol inputVariant = symbolBuilderFor(shape, "Reader", SmithyGoDependency.IO).build(); + return symbolBuilderFor(shape, "ReadCloser", SmithyGoDependency.IO) + .putProperty(SymbolUtils.INPUT_VARIANT, inputVariant) + .build(); + } + return symbolBuilderFor(shape, "[]byte") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol booleanShape(BooleanShape shape) { + return symbolBuilderFor(shape, "bool") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol listShape(ListShape shape) { + return createCollectionSymbol(shape); + } + + @Override + public Symbol setShape(SetShape shape) { + // Go doesn't have a set type. Rather than hack together a set using a map, + // we instead just create a list and let the service be responsible for + // asserting that there are no duplicates. + return createCollectionSymbol(shape); + } + + private Symbol createCollectionSymbol(CollectionShape shape) { + Symbol reference = toSymbol(shape.getMember()); + // Shape name will be unused for symbols that represent a slice, but in the event it does we set the collection + // shape's name to make debugging simpler. + return symbolBuilderFor(shape, getDefaultShapeName(shape)) + .putProperty(SymbolUtils.GO_SLICE, true) + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, + reference.getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class).orElse(false)) + .putProperty(SymbolUtils.GO_ELEMENT_TYPE, reference) + .build(); + } + + @Override + public Symbol mapShape(MapShape shape) { + Symbol reference = toSymbol(shape.getValue()); + // Shape name will be unused for symbols that represent a map, but in the event it does we set the map shape's + // name to make debugging simpler. + return symbolBuilderFor(shape, getDefaultShapeName(shape)) + .putProperty(SymbolUtils.GO_MAP, true) + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, + reference.getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class).orElse(false)) + .putProperty(SymbolUtils.GO_ELEMENT_TYPE, reference) + .build(); + } + + private Symbol.Builder symbolBuilderFor(Shape shape, String typeName) { + if (pointableIndex.isPointable(shape)) { + return SymbolUtils.createPointableSymbolBuilder(shape, typeName, SmithyNameResolver.smithyTypesNamespace(shape)); + } + + return SymbolUtils.createValueSymbolBuilder(shape, typeName, SmithyNameResolver.smithyTypesNamespace(shape)); + } + + private Symbol.Builder symbolBuilderFor(Shape shape, String typeName, GoDependency namespace) { + if (pointableIndex.isPointable(shape)) { + return SymbolUtils.createPointableSymbolBuilder(shape, typeName, namespace); + } + + return SymbolUtils.createValueSymbolBuilder(shape, typeName, namespace); + } - private static final Logger LOGGER = Logger.getLogger( - SymbolVisitor.class.getName() - ); - - private final Model model; - private final String rootModuleName; - private final ReservedWordSymbolProvider.Escaper escaper; - private final ReservedWordSymbolProvider.Escaper errorMemberEscaper; - private final Map< - ShapeId, - ReservedWordSymbolProvider.Escaper - > structureSpecificMemberEscapers = new HashMap<>(); - private final GoPointableIndex pointableIndex; - private final GoSettings settings; - - public SymbolVisitor(Model model, GoSettings settings) { - this.model = model; - this.settings = settings; - this.rootModuleName = - SmithyNameResolver.shapeNamespace(settings.getService(model)); - this.pointableIndex = GoPointableIndex.of(model); - - // Reserve the generated names for union members, including the unknown case. - ReservedWordsBuilder reservedNames = new ReservedWordsBuilder(); - reserveUnionMemberNames(model, reservedNames); - - ReservedWords reservedMembers = new ReservedWordsBuilder() - // Since Go only exports names if the first character is upper case and all - // the go reserved words are lower case, it's functionally impossible to conflict, - // so we only need to protect against common names. As of now there's only one. - .put("String", "String_") - .put("GetStream", "GetStream_") - .build(); - - model - .shapes(StructureShape.class) - .filter(this::supportsInheritance) - .forEach(this::reserveInterfaceMemberAccessors); - - escaper = - ReservedWordSymbolProvider - .builder() - .nameReservedWords(reservedNames.build()) - .memberReservedWords(reservedMembers) - // Only escape words when the symbol has a definition file to - // prevent escaping intentional references to built-in types. - .escapePredicate((shape, symbol) -> - !StringUtils.isEmpty(symbol.getDefinitionFile()) - ) - .buildEscaper(); - - // Reserved words that only apply to error members. - ReservedWords reservedErrorMembers = new ReservedWordsBuilder() - .put("ErrorCode", "ErrorCode_") - .put("ErrorMessage", "ErrorMessage_") - .put("ErrorFault", "ErrorFault_") - .put("Unwrap", "Unwrap_") - .put("Error", "Error_") - .put("ErrorCodeOverride", "ErrorCodeOverride_") - .build(); - - errorMemberEscaper = - ReservedWordSymbolProvider - .builder() - .memberReservedWords( - ReservedWords.compose(reservedMembers, reservedErrorMembers) - ) - .escapePredicate((shape, symbol) -> - !StringUtils.isEmpty(symbol.getDefinitionFile()) - ) - .buildEscaper(); - } - - /** - * Reserves generated member names for unions. - * - *

These have the format {UnionName}Member{MemberName}. - * - * @param model The model whose unions should be reserved. - * @param builder A reserved words builder to add on to. - */ - private void reserveUnionMemberNames( - Model model, - ReservedWordsBuilder builder - ) { - model - .shapes(UnionShape.class) - .forEach(union -> { - for (MemberShape member : union.getAllMembers().values()) { - String memberName = formatUnionMemberName(union, member); - builder.put(memberName, escapeWithTrailingUnderscore(memberName)); + private Symbol.Builder symbolBuilderFor(Shape shape, String typeName, String namespace) { + if (pointableIndex.isPointable(shape)) { + return SymbolUtils.createPointableSymbolBuilder(shape, typeName, namespace); } - }); - } - - private boolean supportsInheritance(Shape shape) { - return shape.isStructureShape() && shape.hasTrait(ErrorTrait.class); - } - - /** - * Reserves Get* and Has* member names for the given structure for use as accessor methods. - * - *

These reservations will only apply to the given structure, not to other structures. - * - * @param shape The structure shape whose members should be reserved. - */ - private void reserveInterfaceMemberAccessors(StructureShape shape) { - ReservedWordsBuilder builder = new ReservedWordsBuilder(); - for (MemberShape member : shape.getAllMembers().values()) { - String name = getDefaultMemberName(member); - String getterName = "Get" + name; - String haserName = "Has" + name; - builder.put(getterName, escapeWithTrailingUnderscore(getterName)); - builder.put(haserName, escapeWithTrailingUnderscore(haserName)); - } - ReservedWordSymbolProvider.Escaper structureSpecificMemberEscaper = - ReservedWordSymbolProvider - .builder() - .memberReservedWords(builder.build()) - .buildEscaper(); - structureSpecificMemberEscapers.put( - shape.getId(), - structureSpecificMemberEscaper - ); - } - - private String escapeWithTrailingUnderscore(String symbolName) { - return symbolName + "_"; - } - - @Override - public Symbol toSymbol(Shape shape) { - Symbol symbol = shape.accept(this); - LOGGER.fine(() -> - String.format("Creating symbol from %s: %s", shape, symbol) - ); - return linkArchetypeShape(shape, escaper.escapeSymbol(shape, symbol)); - } - - /** - * Links the archetype shape id for the symbol. - * - * @param shape the model shape - * @param symbol the symbol to set the archetype property on - * @return the symbol with archetype set if shape is a synthetic clone otherwise the original symbol - */ - private Symbol linkArchetypeShape(Shape shape, Symbol symbol) { - return shape - .getTrait(Synthetic.class) - .map(synthetic -> - symbol - .toBuilder() - .putProperty("archetype", synthetic.getArchetype()) - .build() - ) - .orElse(symbol); - } - - @Override - public String toMemberName(MemberShape shape) { - Shape container = model.expectShape(shape.getContainer()); - if (container.isUnionShape()) { - // Union member names are not escaped as they are used to build the escape set. - return formatUnionMemberName(container.asUnionShape().get(), shape); - } - - String memberName = getDefaultMemberName(shape); - memberName = escaper.escapeMemberName(memberName); - - // Escape words reserved for the specific container. - if (structureSpecificMemberEscapers.containsKey(shape.getContainer())) { - memberName = - structureSpecificMemberEscapers - .get(shape.getContainer()) - .escapeMemberName(memberName); - } - - // Escape words that are only reserved for error members. - if (isErrorMember(shape)) { - memberName = errorMemberEscaper.escapeMemberName(memberName); - } - return memberName; - } - - private String formatUnionMemberName(UnionShape union, MemberShape member) { - return String.format( - "%sMember%s", - getDefaultShapeName(union), - getDefaultMemberName(member) - ); - } - - private String getDefaultShapeName(Shape shape) { - ServiceShape serviceShape = model.expectShape( - settings.getService(), - ServiceShape.class - ); - return StringUtils.capitalize( - removeLeadingInvalidIdentCharacters(shape.getId().getName(serviceShape)) - ); - } - - private String getDefaultMemberName(MemberShape shape) { - String memberName = StringUtils.capitalize( - removeLeadingInvalidIdentCharacters(shape.getMemberName()) - ); - - return memberName; - } - - private String removeLeadingInvalidIdentCharacters(String value) { - if (Character.isAlphabetic(value.charAt(0))) { - return value; - } - - int i; - for (i = 0; i < value.length(); i++) { - if (Character.isAlphabetic(value.charAt(i))) { - break; - } - } - - String remaining = value.substring(i); - if (remaining.length() == 0) { - throw new CodegenException( - "tried to clean name " + value + ", but resulted in empty string" - ); - } - - return remaining; - } - - private boolean isErrorMember(MemberShape shape) { - return model - .getShape(shape.getContainer()) - .map(container -> container.hasTrait(ErrorTrait.ID)) - .orElse(false); - } - - @Override - public Symbol blobShape(BlobShape shape) { - if (shape.hasTrait(StreamingTrait.ID)) { - Symbol inputVariant = symbolBuilderFor( - shape, - "Reader", - SmithyGoDependency.IO - ) - .build(); - return symbolBuilderFor(shape, "ReadCloser", SmithyGoDependency.IO) - .putProperty(SymbolUtils.INPUT_VARIANT, inputVariant) - .build(); - } - return symbolBuilderFor(shape, "[]byte") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol booleanShape(BooleanShape shape) { - return symbolBuilderFor(shape, "bool") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol listShape(ListShape shape) { - return createCollectionSymbol(shape); - } - - @Override - public Symbol setShape(SetShape shape) { - // Go doesn't have a set type. Rather than hack together a set using a map, - // we instead just create a list and let the service be responsible for - // asserting that there are no duplicates. - return createCollectionSymbol(shape); - } - - private Symbol createCollectionSymbol(CollectionShape shape) { - Symbol reference = toSymbol(shape.getMember()); - // Shape name will be unused for symbols that represent a slice, but in the event it does we set the collection - // shape's name to make debugging simpler. - return symbolBuilderFor(shape, getDefaultShapeName(shape)) - .putProperty(SymbolUtils.GO_SLICE, true) - .putProperty( - SymbolUtils.GO_UNIVERSE_TYPE, - reference - .getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class) - .orElse(false) - ) - .putProperty(SymbolUtils.GO_ELEMENT_TYPE, reference) - .build(); - } - - @Override - public Symbol mapShape(MapShape shape) { - Symbol reference = toSymbol(shape.getValue()); - // Shape name will be unused for symbols that represent a map, but in the event it does we set the map shape's - // name to make debugging simpler. - return symbolBuilderFor(shape, getDefaultShapeName(shape)) - .putProperty(SymbolUtils.GO_MAP, true) - .putProperty( - SymbolUtils.GO_UNIVERSE_TYPE, - reference - .getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class) - .orElse(false) - ) - .putProperty(SymbolUtils.GO_ELEMENT_TYPE, reference) - .build(); - } - - private Symbol.Builder symbolBuilderFor(Shape shape, String typeName) { - if (pointableIndex.isPointable(shape)) { - return SymbolUtils.createPointableSymbolBuilder( - shape, - typeName, - SmithyNameResolver.smithyTypesNamespace(shape) - ); - } - - return SymbolUtils.createValueSymbolBuilder( - shape, - typeName, - SmithyNameResolver.smithyTypesNamespace(shape) - ); - } - - private Symbol.Builder symbolBuilderFor( - Shape shape, - String typeName, - GoDependency namespace - ) { - if (pointableIndex.isPointable(shape)) { - return SymbolUtils.createPointableSymbolBuilder( - shape, - typeName, - namespace - ); - } - - return SymbolUtils.createValueSymbolBuilder(shape, typeName, namespace); - } - - private Symbol.Builder symbolBuilderFor( - Shape shape, - String typeName, - String namespace - ) { - if (pointableIndex.isPointable(shape)) { - return SymbolUtils.createPointableSymbolBuilder( - shape, - typeName, - namespace - ); - } - - return SymbolUtils.createValueSymbolBuilder(shape, typeName, namespace); - } - - @Override - public Symbol byteShape(ByteShape shape) { - return symbolBuilderFor(shape, "int8") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol shortShape(ShortShape shape) { - return symbolBuilderFor(shape, "int16") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol integerShape(IntegerShape shape) { - return symbolBuilderFor(shape, "int32") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol longShape(LongShape shape) { - return symbolBuilderFor(shape, "int64") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol floatShape(FloatShape shape) { - return symbolBuilderFor(shape, "float32") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol documentShape(DocumentShape shape) { - return null; - } - - @Override - public Symbol doubleShape(DoubleShape shape) { - return symbolBuilderFor(shape, "float64") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol bigIntegerShape(BigIntegerShape shape) { - return createBigSymbol(shape, "Int"); - } - - @Override - public Symbol bigDecimalShape(BigDecimalShape shape) { - return createBigSymbol(shape, "Float"); - } - - private Symbol createBigSymbol(Shape shape, String symbolName) { - return symbolBuilderFor(shape, symbolName, SmithyGoDependency.BIG).build(); - } - - @Override - public Symbol operationShape(OperationShape shape) { - String name = getDefaultShapeName(shape); - return SymbolUtils - .createPointableSymbolBuilder(shape, name, rootModuleName) - .definitionFile(String.format("./api_op_%s.go", name)) - .addDependency("./types", "./types") - .build(); - } - - @Override - public Symbol resourceShape(ResourceShape shape) { - // TODO: implement resources - return SymbolUtils.createPointableSymbolBuilder(shape, "nil").build(); - } - - @Override - public Symbol serviceShape(ServiceShape shape) { - return symbolBuilderFor(shape, "Client", rootModuleName) - .definitionFile( - "./%s/api_client.go".formatted(SmithyNameResolver.shapeNamespace(shape)) - ) - .build(); - } - - @Override - public Symbol stringShape(StringShape shape) { - if (shape.hasTrait(EnumTrait.class)) { - String name = getDefaultShapeName(shape); - return symbolBuilderFor( - shape, - name, - SmithyNameResolver.smithyTypesNamespace(settings.getService(model)) - ) - .definitionFile( - "./%s/enums.go".formatted( - SmithyNameResolver.smithyTypesNamespace(shape) - ) - ) - .build(); - } - - return symbolBuilderFor(shape, "string") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol structureShape(StructureShape shape) { - String name = getDefaultShapeName(shape); - if ( - shape - .getId() - .getNamespace() - .equals(CodegenUtils.getSyntheticTypeNamespace()) - ) { - Optional boundOperationName = getNameOfBoundOperation(shape); - if (boundOperationName.isPresent()) { - return symbolBuilderFor(shape, name, rootModuleName) - .definitionFile("./api_op_" + boundOperationName.get() + ".go") - .build(); - } - } - Symbol.Builder builder = symbolBuilderFor(shape, name); - if (shape.hasTrait(ErrorTrait.ID)) { - builder.definitionFile( - "./%s/errors.go".formatted( - SmithyNameResolver.smithyTypesNamespace(shape) - ) - ); - } else { - builder.definitionFile( - "./%s/types.go".formatted( - SmithyNameResolver.smithyTypesNamespace(shape) - ) - ); - } - - if (shape.hasTrait(ReferenceTrait.class)) { - var referredShape = model.expectShape( - shape.expectTrait(ReferenceTrait.class).getReferentId() - ); - var isService = shape.expectTrait(ReferenceTrait.class).isService(); - if (isService) { - builder.putProperty( - "Referred", - symbolBuilderFor( - referredShape, - "Client", - SmithyNameResolver.shapeNamespace(referredShape) - ) - .putProperty(SymbolUtils.POINTABLE, true) - .build() - ); - } else { - builder.putProperty( - "Referred", - symbolBuilderFor( - referredShape, - "I".concat(getDefaultShapeName(referredShape)) - ) - .putProperty(SymbolUtils.POINTABLE, false) - .build() - ); - } - } - - return builder.build(); - } - - private Optional getNameOfBoundOperation(StructureShape shape) { - NeighborProvider provider = NeighborProviderIndex - .of(model) - .getReverseProvider(); - for (Relationship relationship : provider.getNeighbors(shape)) { - RelationshipType relationshipType = relationship.getRelationshipType(); - if ( - relationshipType == RelationshipType.INPUT || - relationshipType == RelationshipType.OUTPUT - ) { - return Optional.of( - getDefaultShapeName(relationship.getNeighborShape().get()) - ); - } - } - return Optional.empty(); - } - - @Override - public Symbol unionShape(UnionShape shape) { - String name = getDefaultShapeName(shape); - return symbolBuilderFor( - shape, - name, - SmithyNameResolver.smithyTypesNamespace(settings.getService(model)) - ) - .definitionFile("./types/types.go") - .build(); - } - - @Override - public Symbol memberShape(MemberShape member) { - Shape targetShape = model.expectShape(member.getTarget()); - return toSymbol(targetShape) - .toBuilder() - .putProperty(SymbolUtils.POINTABLE, pointableIndex.isPointable(member)) - .build(); - } - - @Override - public Symbol timestampShape(TimestampShape shape) { - return symbolBuilderFor(shape, "Time", SmithyGoDependency.TIME).build(); - } - - @Override - public Symbol intEnumShape(IntEnumShape shape) { - String name = getDefaultShapeName(shape); - return symbolBuilderFor( - shape, - name, - SmithyNameResolver.smithyTypesNamespace(settings.getService(model)) - ) - .definitionFile( - "./%s/enums.go".formatted( - SmithyNameResolver.smithyTypesNamespace(shape) - ) - ) - .build(); - } + + return SymbolUtils.createValueSymbolBuilder(shape, typeName, namespace); + } + + @Override + public Symbol byteShape(ByteShape shape) { + return symbolBuilderFor(shape, "int8") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol shortShape(ShortShape shape) { + return symbolBuilderFor(shape, "int16") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol integerShape(IntegerShape shape) { + return symbolBuilderFor(shape, "int32") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol longShape(LongShape shape) { + return symbolBuilderFor(shape, "int64") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol floatShape(FloatShape shape) { + return symbolBuilderFor(shape, "float32") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol documentShape(DocumentShape shape) { + return null; + } + + @Override + public Symbol doubleShape(DoubleShape shape) { + return symbolBuilderFor(shape, "float64") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol bigIntegerShape(BigIntegerShape shape) { + return createBigSymbol(shape, "Int"); + } + + @Override + public Symbol bigDecimalShape(BigDecimalShape shape) { + + return createBigSymbol(shape, "Float"); + } + + private Symbol createBigSymbol(Shape shape, String symbolName) { + return symbolBuilderFor(shape, symbolName, SmithyGoDependency.BIG) + .build(); + } + + @Override + public Symbol operationShape(OperationShape shape) { + String name = getDefaultShapeName(shape); + return SymbolUtils.createPointableSymbolBuilder(shape, name, rootModuleName) + .definitionFile(String.format("./api_op_%s.go", name)) + .addDependency("./types", "./types") + .build(); + } + + @Override + public Symbol resourceShape(ResourceShape shape) { + // TODO: implement resources + return SymbolUtils.createPointableSymbolBuilder(shape, "nil").build(); + } + + @Override + public Symbol serviceShape(ServiceShape shape) { + return symbolBuilderFor(shape, "Client", rootModuleName) + .definitionFile("./%s/api_client.go".formatted(SmithyNameResolver.shapeNamespace(shape))) + .build(); + } + + @Override + public Symbol stringShape(StringShape shape) { + if (shape.hasTrait(EnumTrait.class)) { + String name = getDefaultShapeName(shape); + return symbolBuilderFor(shape, name, SmithyNameResolver.smithyTypesNamespace(settings.getService(model))) + .definitionFile("./%s/enums.go".formatted(SmithyNameResolver.smithyTypesNamespace(shape))) + .build(); + } + + return symbolBuilderFor(shape, "string") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol structureShape(StructureShape shape) { + String name = getDefaultShapeName(shape); + if (shape.getId().getNamespace().equals(CodegenUtils.getSyntheticTypeNamespace())) { + Optional boundOperationName = getNameOfBoundOperation(shape); + if (boundOperationName.isPresent()) { + return symbolBuilderFor(shape, name, rootModuleName) + .definitionFile("./api_op_" + boundOperationName.get() + ".go") + .build(); + } + } + Symbol.Builder builder = symbolBuilderFor(shape, name); + if (shape.hasTrait(ErrorTrait.ID)) { + builder.definitionFile("./%s/errors.go".formatted(SmithyNameResolver.smithyTypesNamespace(shape))); + } else { + builder.definitionFile("./%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(shape))); + } + + if (shape.hasTrait(ReferenceTrait.class)) { + var referredShape = model.expectShape(shape.expectTrait(ReferenceTrait.class).getReferentId()); + var isService = shape.expectTrait(ReferenceTrait.class).isService(); + if (isService) { + builder.putProperty("Referred", symbolBuilderFor(referredShape, "Client", SmithyNameResolver.shapeNamespace(referredShape)) + .putProperty(SymbolUtils.POINTABLE, true).build()); + } else { + builder.putProperty("Referred", symbolBuilderFor(referredShape, "I".concat(getDefaultShapeName(referredShape))) + .putProperty(SymbolUtils.POINTABLE, false).build()); + } + + } + + return builder.build(); + } + + private Optional getNameOfBoundOperation(StructureShape shape) { + NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); + for (Relationship relationship : provider.getNeighbors(shape)) { + RelationshipType relationshipType = relationship.getRelationshipType(); + if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { + return Optional.of(getDefaultShapeName(relationship.getNeighborShape().get())); + } + } + return Optional.empty(); + } + + @Override + public Symbol unionShape(UnionShape shape) { + String name = getDefaultShapeName(shape); + return symbolBuilderFor(shape, name, SmithyNameResolver.smithyTypesNamespace(settings.getService(model))) + .definitionFile("./types/types.go") + .build(); + } + + @Override + public Symbol memberShape(MemberShape member) { + Shape targetShape = model.expectShape(member.getTarget()); + return toSymbol(targetShape) + .toBuilder() + .putProperty(SymbolUtils.POINTABLE, pointableIndex.isPointable(member)) + .build(); + } + + @Override + public Symbol timestampShape(TimestampShape shape) { + return symbolBuilderFor(shape, "Time", SmithyGoDependency.TIME).build(); + } + + @Override + public Symbol intEnumShape(IntEnumShape shape) { + String name = getDefaultShapeName(shape); + return symbolBuilderFor(shape, name, SmithyNameResolver.smithyTypesNamespace(settings.getService(model))) + .definitionFile("./%s/enums.go".formatted(SmithyNameResolver.smithyTypesNamespace(shape))) + .build(); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/Synthetic.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/Synthetic.java index e71f52778b..5a762dd69b 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/Synthetic.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/Synthetic.java @@ -15,7 +15,6 @@ package software.amazon.polymorph.smithygo.codegen; -import java.util.Optional; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.shapes.ShapeId; @@ -24,106 +23,95 @@ import software.amazon.smithy.utils.SmithyBuilder; import software.amazon.smithy.utils.ToSmithyBuilder; +import java.util.Optional; + /** * Defines a shape as being a clone of another modeled shape. *

* Must only be used as a runtime trait-only applied to shapes based on model processing */ -public final class Synthetic - extends AbstractTrait - implements ToSmithyBuilder { - - public static final ShapeId ID = ShapeId.from("smithy.go.traits#Synthetic"); - - private static final String ARCHETYPE = "archetype"; - - private final Optional archetype; - - private Synthetic(Builder builder) { - super(ID, builder.getSourceLocation()); - this.archetype = builder.archetype; - } - - /** - * Get the archetype shape that this clone is based on. - * - * @return the original archetype shape - */ - public Optional getArchetype() { - return archetype; - } - - @Override - protected Node createNode() { - throw new CodegenException("attempted to serialize runtime only trait"); - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } else if (!(other instanceof Synthetic)) { - return false; - } else { - Synthetic b = (Synthetic) other; - return ( - toShapeId().equals(b.toShapeId()) && archetype.equals(b.getArchetype()) - ); +public final class Synthetic extends AbstractTrait implements ToSmithyBuilder { + public static final ShapeId ID = ShapeId.from("smithy.go.traits#Synthetic"); + + private static final String ARCHETYPE = "archetype"; + + private final Optional archetype; + + private Synthetic(Builder builder) { + super(ID, builder.getSourceLocation()); + this.archetype = builder.archetype; + } + + /** + * Get the archetype shape that this clone is based on. + * + * @return the original archetype shape + */ + public Optional getArchetype() { + return archetype; + } + + @Override + protected Node createNode() { + throw new CodegenException("attempted to serialize runtime only trait"); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } else if (!(other instanceof Synthetic)) { + return false; + } else { + Synthetic b = (Synthetic) other; + return toShapeId().equals(b.toShapeId()) && archetype.equals(b.getArchetype()); + } } - } - - @Override - public int hashCode() { - return ( - toShapeId().hashCode() * 17 + - Node - .objectNode() - .withOptionalMember( - ARCHETYPE, - archetype.map(ShapeId::toString).map(Node::from) - ) - .hashCode() - ); - } - - @Override - public SmithyBuilder toBuilder() { - Builder builder = builder(); - getArchetype().ifPresent(builder::archetype); - - return builder; - } - - /** - * @return Returns a builder used to create {@link Synthetic}. - */ - public static Builder builder() { - return new Builder(); - } - - /** - * Builder for {@link Synthetic}. - */ - public static final class Builder - extends AbstractTraitBuilder { - - private Optional archetype = Optional.empty(); - - private Builder() {} @Override - public Synthetic build() { - return new Synthetic(this); + public int hashCode() { + return toShapeId().hashCode() * 17 + Node.objectNode() + .withOptionalMember(ARCHETYPE, archetype.map(ShapeId::toString).map(Node::from)) + .hashCode(); + } + + @Override + public SmithyBuilder toBuilder() { + Builder builder = builder(); + getArchetype().ifPresent(builder::archetype); + + return builder; } - public Builder archetype(ShapeId archetype) { - this.archetype = Optional.ofNullable(archetype); - return this; + /** + * @return Returns a builder used to create {@link Synthetic}. + */ + public static Builder builder() { + return new Builder(); } - public Builder removeArchetype() { - this.archetype = Optional.empty(); - return this; + /** + * Builder for {@link Synthetic}. + */ + public static final class Builder extends AbstractTraitBuilder { + private Optional archetype = Optional.empty(); + + private Builder() { + } + + @Override + public Synthetic build() { + return new Synthetic(this); + } + + public Builder archetype(ShapeId archetype) { + this.archetype = Optional.ofNullable(archetype); + return this; + } + + public Builder removeArchetype() { + this.archetype = Optional.empty(); + return this; + } } - } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/UnionGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/UnionGenerator.java index 7d800dac15..68cfbbfb26 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/UnionGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/UnionGenerator.java @@ -5,137 +5,100 @@ import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; + import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.MemberShape; -import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.SimpleShape; import software.amazon.smithy.model.shapes.UnionShape; -import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.StreamingTrait; +import software.amazon.smithy.model.shapes.Shape; +import software.amazon.smithy.model.traits.ErrorTrait; public class UnionGenerator { + public static final String UNKNOWN_MEMBER_NAME = "UnknownUnionMember"; - public static final String UNKNOWN_MEMBER_NAME = "UnknownUnionMember"; + private final Model model; + private final SymbolProvider symbolProvider; + private final UnionShape shape; + private final boolean isEventStream; - private final Model model; - private final SymbolProvider symbolProvider; - private final UnionShape shape; - private final boolean isEventStream; + public UnionGenerator(Model model, SymbolProvider symbolProvider, UnionShape shape) { + this.model = model; + this.symbolProvider = symbolProvider; + this.shape = shape; + this.isEventStream = StreamingTrait.isEventStream(shape); + } - public UnionGenerator( - Model model, - SymbolProvider symbolProvider, - UnionShape shape - ) { - this.model = model; - this.symbolProvider = symbolProvider; - this.shape = shape; - this.isEventStream = StreamingTrait.isEventStream(shape); - } + /** + * Generates the Go type definitions for the UnionShape. + * + * @param writer the writer + */ + public void generateUnion(GoWriter writer) { + Symbol symbol = symbolProvider.toSymbol(shape); + Collection memberShapes = shape.getAllMembers().values() + .stream() + .filter(memberShape -> !isEventStreamErrorMember(memberShape)) + .collect(Collectors.toCollection(TreeSet::new)); - /** - * Generates the Go type definitions for the UnionShape. - * - * @param writer the writer - */ - public void generateUnion(GoWriter writer) { - Symbol symbol = symbolProvider.toSymbol(shape); - Collection memberShapes = shape - .getAllMembers() - .values() - .stream() - .filter(memberShape -> !isEventStreamErrorMember(memberShape)) - .collect(Collectors.toCollection(TreeSet::new)); + memberShapes.stream().map(symbolProvider::toMemberName).forEach(name -> { + writer.write("// " + name); + }); + writer.openBlock("type $L interface {", "}", symbol.getName(), () -> { + writer.write("is$L()", symbol.getName()); + }).write(""); - memberShapes - .stream() - .map(symbolProvider::toMemberName) - .forEach(name -> { - writer.write("// " + name); - }); - writer - .openBlock( - "type $L interface {", - "}", - symbol.getName(), - () -> { - writer.write("is$L()", symbol.getName()); - } - ) - .write(""); + // Create structs for each member that satisfy the interface. + for (MemberShape member : memberShapes) { + Symbol memberSymbol = symbolProvider.toSymbol(member); + String exportedMemberName = symbolProvider.toMemberName(member); + Shape target = model.expectShape(member.getTarget()); - // Create structs for each member that satisfy the interface. - for (MemberShape member : memberShapes) { - Symbol memberSymbol = symbolProvider.toSymbol(member); - String exportedMemberName = symbolProvider.toMemberName(member); - Shape target = model.expectShape(member.getTarget()); + writer.openBlock("type $L struct {", "}", exportedMemberName, () -> { + // Union members can't have null values, so for simple shapes we don't + // use pointers. We have to use pointers for complex shapes since, + // for example, we could still have a map that's empty or which has + // null values. + if (target instanceof SimpleShape) { + writer.write("Value $T", memberSymbol); + } else { + writer.write("Value $P", memberSymbol); + } + writer.write(""); + }); - writer.openBlock( - "type $L struct {", - "}", - exportedMemberName, - () -> { - // Union members can't have null values, so for simple shapes we don't - // use pointers. We have to use pointers for complex shapes since, - // for example, we could still have a map that's empty or which has - // null values. - if (target instanceof SimpleShape) { - writer.write("Value $T", memberSymbol); - } else { - writer.write("Value $P", memberSymbol); - } - writer.write(""); + writer.write("func (*$L) is$L() {}", exportedMemberName, symbol.getName()); } - ); - - writer.write( - "func (*$L) is$L() {}", - exportedMemberName, - symbol.getName() - ); } - } - private boolean isEventStreamErrorMember(MemberShape memberShape) { - return ( - isEventStream && - memberShape.getMemberTrait(model, ErrorTrait.class).isPresent() - ); - } + private boolean isEventStreamErrorMember(MemberShape memberShape) { + return isEventStream && memberShape.getMemberTrait(model, ErrorTrait.class).isPresent(); + } - /** - * Generates a struct for unknown union values that applies to every union in the given set. - * - * @param writer The writer to write the union to. - * @param unions A set of unions whose interfaces the union should apply to. - * @param symbolProvider A symbol provider used to get the symbols for the unions. - */ - public static void generateUnknownUnion( - final GoWriter writer, - final Collection unions, - final SymbolProvider symbolProvider - ) { - writer.openBlock( - "type $L struct {", - "}", - UNKNOWN_MEMBER_NAME, - () -> { - // The tag (member) name received over the wire. - writer.write("Tag string"); - // The value received. - writer.write("Value []byte"); - writer.write(""); - } - ); + /** + * Generates a struct for unknown union values that applies to every union in the given set. + * + * @param writer The writer to write the union to. + * @param unions A set of unions whose interfaces the union should apply to. + * @param symbolProvider A symbol provider used to get the symbols for the unions. + */ + public static void generateUnknownUnion( + final GoWriter writer, + final Collection unions, + final SymbolProvider symbolProvider + ) { + writer.openBlock("type $L struct {", "}", UNKNOWN_MEMBER_NAME, () -> { + // The tag (member) name received over the wire. + writer.write("Tag string"); + // The value received. + writer.write("Value []byte"); + writer.write(""); + }); - for (UnionShape union : unions) { - writer.write( - "func (*$L) is$L() {}", - UNKNOWN_MEMBER_NAME, - symbolProvider.toSymbol(union).getName() - ); + for (UnionShape union : unions) { + writer.write("func (*$L) is$L() {}", UNKNOWN_MEMBER_NAME, symbolProvider.toSymbol(union).getName()); + } } - } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ValidationGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ValidationGenerator.java index 13107c50a3..9d8ddc14a4 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ValidationGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ValidationGenerator.java @@ -1,395 +1,306 @@ package software.amazon.polymorph.smithygo.codegen; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - import java.math.BigDecimal; import java.util.Optional; + import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; import software.amazon.polymorph.traits.ReferenceTrait; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.SimpleShape; +import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.traits.LengthTrait; import software.amazon.smithy.model.traits.RangeTrait; import software.amazon.smithy.model.traits.RequiredTrait; import software.amazon.smithy.model.traits.StreamingTrait; +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + // Renders constraint validation public class ValidationGenerator { + private final Model model; + private final SymbolProvider symbolProvider; + private final GoWriter writer; + private final CodegenUtils.SortedMembers sortedMembers; - private final Model model; - private final SymbolProvider symbolProvider; - private final GoWriter writer; - private final CodegenUtils.SortedMembers sortedMembers; - - private static final String LIST_ITEM = "item"; - private static final String MAP_KEY = "key"; - private static final String MAP_VALUE = "value"; - private static final String UNION_DATASOURCE = "unionType.Value"; - - public ValidationGenerator( - final Model model, - final SymbolProvider symbolProvider, - final GoWriter writer - ) { - this.model = model; - this.symbolProvider = symbolProvider; - this.writer = writer; - this.sortedMembers = new CodegenUtils.SortedMembers(symbolProvider); - } - - public void renderValidator( - final Shape shape, - final boolean isInputStructure - ) { - Symbol symbol = symbolProvider.toSymbol(shape); - writer.openBlock("func (input $L) Validate() (error) {", symbol.getName()); - renderValidatorHelper(shape, isInputStructure, "input"); - writer.write("return nil"); - writer.closeBlock("}").write(""); - } + private static final String LIST_ITEM = "item"; + private static final String MAP_KEY = "key"; + private static final String MAP_VALUE = "value"; + private static final String UNION_DATASOURCE = "unionType.Value"; - private void renderValidatorHelper( - final Shape containerShape, - final boolean isInputStructure, - final String dataSource - ) { - containerShape - .getAllMembers() - .values() - .stream() - .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) - .sorted(sortedMembers) - .forEach(member -> { - String memberName; - if ( - containerShape.isListShape() || containerShape.isMapShape() - ) memberName = dataSource; else memberName = - dataSource + "." + symbolProvider.toMemberName(member); - renderValidatorForEachShape( - model.expectShape(member.getTarget()), - member, - isInputStructure, - memberName - ); - }); - } - - private void renderValidatorForEachShape( - final Shape currentShape, - final MemberShape memberShape, - final boolean isInputStructure, - final String dataSource - ) { - Symbol symbol = symbolProvider.toSymbol(currentShape); - if (isInputStructure) { - symbol = - symbol - .getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) - .orElse(symbol); - } - if (currentShape.hasTrait(ReferenceTrait.class)) { - symbol = symbol.getProperty("Referred", Symbol.class).get(); - } - String pointableString = ""; - if ( - !(dataSource.equals(LIST_ITEM) || - dataSource.equals(MAP_KEY) || - dataSource.equals(MAP_VALUE) || - (dataSource.equals(UNION_DATASOURCE) && - currentShape instanceof SimpleShape)) + public ValidationGenerator( + final Model model, + final SymbolProvider symbolProvider, + final GoWriter writer ) { - if ( - (boolean) symbol.getProperty(POINTABLE, Boolean.class).orElse(false) && - memberShape.isOptional() - ) { - pointableString = "*"; - } - } - if (currentShape.hasTrait(RangeTrait.class)) { - addRangeCheck(currentShape, dataSource, pointableString); - } - if (currentShape.hasTrait(LengthTrait.class)) { - addLengthCheck(currentShape, dataSource, pointableString); + this.model = model; + this.symbolProvider = symbolProvider; + this.writer = writer; + this.sortedMembers = new CodegenUtils.SortedMembers(symbolProvider); } - if (currentShape.hasTrait(RequiredTrait.class)) { - addRequiredCheck(symbol, currentShape, dataSource); - } - if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { - addUTFCheck(currentShape, dataSource, pointableString); + + public void renderValidator (final Shape shape, final boolean isInputStructure) { + Symbol symbol = symbolProvider.toSymbol(shape); + writer.openBlock("func (input $L) Validate() (error) {", symbol.getName()); + renderValidatorHelper( shape, isInputStructure, "input"); + writer.write("return nil"); + writer.closeBlock("}").write(""); } - // Broke list and map into two different if else because for _, item := range %s looked good for list - // And for key, value := range %s looked good for map - if (currentShape.isListShape()) { - writer.write( - """ - for _, %s := range %s { - // To avoid declared and not used error for shapes which does not need validation check - _ = item - """.formatted(LIST_ITEM, dataSource) - ); - renderValidatorHelper(currentShape, false, LIST_ITEM); - writer.write( - """ - } - """ - ); - } else if (currentShape.isMapShape()) { - writer.write( - """ - for %s, %s := range %s { - // To avoid declared and not used error for shapes which does not need validation check - _ = key - _ = value - """.formatted(MAP_KEY, MAP_VALUE, dataSource) - ); - renderValidatorHelper(currentShape, false, MAP_KEY); - renderValidatorHelper(currentShape, false, MAP_VALUE); - writer.write( - """ - } - """ - ); - } else if (currentShape.isUnionShape()) { - writer.write( - """ - switch unionType := %s.(type) { - """.formatted(dataSource) - ); - for (var memberInUnion : currentShape.getAllMembers().values()) { - writer.write( - """ - case *%s: - """.formatted(symbolProvider.toMemberName(memberInUnion)) - ); - renderValidatorForEachShape( - model.expectShape(memberInUnion.getTarget()), - memberInUnion, - false, - "unionType.Value" - ); - } - writer.write( - """ - // Default case should not be reached. - default: - // To avoid used and not used error when nothing to validate - _ = unionType - panic("Unhandled union type") - } - """ - ); - } else { - renderValidatorHelper(currentShape, isInputStructure, dataSource); + private void renderValidatorHelper (final Shape containerShape, final boolean isInputStructure, final String dataSource) { + containerShape.getAllMembers().values().stream() + .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) + .sorted(sortedMembers) + .forEach((member) -> { + String memberName; + if (containerShape.isListShape() || containerShape.isMapShape()) + memberName = dataSource; + else + memberName = dataSource + "." + symbolProvider.toMemberName(member); + renderValidatorForEachShape(model.expectShape(member.getTarget()), member, isInputStructure, memberName); + }); } - } - private void addRangeCheck( - final Shape currentShape, - final String dataSource, - final String pointableString - ) { - StringBuilder rangeCheck = new StringBuilder(); - RangeTrait rangeTraitShape = currentShape.expectTrait(RangeTrait.class); - Optional min = rangeTraitShape.getMin(); - Optional max = rangeTraitShape.getMax(); - if (pointableString.equals("*")) { - rangeCheck.append( - """ - if (%s != nil) { - """.formatted(dataSource) - ); + private void renderValidatorForEachShape (final Shape currentShape, final MemberShape memberShape, final boolean isInputStructure, final String dataSource) { + Symbol symbol = symbolProvider.toSymbol(currentShape); + if (isInputStructure) { + symbol = symbol.getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) + .orElse(symbol); + } + if (currentShape.hasTrait(ReferenceTrait.class)) { + symbol = symbol.getProperty("Referred", Symbol.class).get(); + } + String pointableString = ""; + if (!(dataSource.equals(LIST_ITEM) || dataSource.equals(MAP_KEY) || dataSource.equals(MAP_VALUE) || dataSource.equals(UNION_DATASOURCE) && currentShape instanceof SimpleShape)) { + if ((boolean) symbol.getProperty(POINTABLE, Boolean.class).orElse(false) && memberShape.isOptional()){ + pointableString = "*"; + } + } + if (currentShape.hasTrait(RangeTrait.class)) { + addRangeCheck(currentShape, dataSource, pointableString); + } + if (currentShape.hasTrait(LengthTrait.class)) { + addLengthCheck(currentShape, dataSource, pointableString); + } + if (currentShape.hasTrait(RequiredTrait.class)) { + addRequiredCheck(symbol, currentShape, dataSource); + } + if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { + addUTFCheck(currentShape, dataSource, pointableString); + } + // Broke list and map into two different if else because for _, item := range %s looked good for list + // And for key, value := range %s looked good for map + if (currentShape.isListShape()) { + writer.write(""" + for _, %s := range %s { + // To avoid declared and not used error for shapes which does not need validation check + _ = item + """.formatted(LIST_ITEM, dataSource)); + renderValidatorHelper(currentShape, false, LIST_ITEM); + writer.write(""" + } + """); + } + else if (currentShape.isMapShape()) { + writer.write(""" + for %s, %s := range %s { + // To avoid declared and not used error for shapes which does not need validation check + _ = key + _ = value + """.formatted(MAP_KEY, MAP_VALUE, dataSource)); + renderValidatorHelper(currentShape, false, MAP_KEY); + renderValidatorHelper(currentShape, false, MAP_VALUE); + writer.write(""" + } + """); + } + else if (currentShape.isUnionShape()) { + writer.write(""" + switch unionType := %s.(type) { + """.formatted(dataSource)); + for (var memberInUnion : currentShape.getAllMembers().values()) { + writer.write(""" + case *%s: + """.formatted( + symbolProvider.toMemberName(memberInUnion) + )); + + renderValidatorForEachShape(model.expectShape(memberInUnion.getTarget()), memberInUnion, false, "unionType.Value"); + } + writer.write(""" + // Default case should not be reached. + default: + // To avoid used and not used error when nothing to validate + _ = unionType + panic("Unhandled union type") + } + """); + } + else { + renderValidatorHelper(currentShape, isInputStructure, dataSource); + } } - if (min.isPresent()) { - rangeCheck.append( - """ - if (%s%s < %s) { - return fmt.Errorf(\"%s has a minimum of %s but has the value of %%d.\", %s%s) + + private void addRangeCheck(final Shape currentShape, final String dataSource, final String pointableString) { + StringBuilder rangeCheck = new StringBuilder(); + RangeTrait rangeTraitShape = currentShape.expectTrait(RangeTrait.class); + Optional min = rangeTraitShape.getMin(); + Optional max = rangeTraitShape.getMax(); + if (pointableString.equals("*")){ + rangeCheck.append(""" + if (%s != nil) { + """.formatted(dataSource)); } - """.formatted( - pointableString, - dataSource, - min.get().toString(), - currentShape.getId().getName(), - min.get().toString(), - pointableString, - dataSource - ) - ); - } - if (max.isPresent()) { - rangeCheck.append( - """ - if (%s%s > %s) { - return fmt.Errorf(\"%s has a maximum of %s but has the value of %%d.\", %s%s) + if (min.isPresent()) { + rangeCheck.append(""" + if (%s%s < %s) { + return fmt.Errorf(\"%s has a minimum of %s but has the value of %%d.\", %s%s) + } + """.formatted( + pointableString, + dataSource, + min.get().toString(), + currentShape.getId().getName(), + min.get().toString(), + pointableString, + dataSource)); } - """.formatted( - pointableString, - dataSource, - max.get().toString(), - currentShape.getId().getName(), - max.get().toString(), - pointableString, - dataSource - ) - ); - } - if (pointableString.equals("*")) { - rangeCheck.append( - """ + if (max.isPresent()) { + rangeCheck.append(""" + if (%s%s > %s) { + return fmt.Errorf(\"%s has a maximum of %s but has the value of %%d.\", %s%s) + } + """.formatted( + pointableString, + dataSource, + max.get().toString(), + currentShape.getId().getName(), + max.get().toString(), + pointableString, + dataSource)); + } + if (pointableString.equals("*")){ + rangeCheck.append(""" + } + """); } - """ - ); + writer.write(rangeCheck); } - writer.write(rangeCheck); - } - private void addLengthCheck( - final Shape currentShape, - final String dataSource, - final String pointableString - ) { - StringBuilder lengthCheck = new StringBuilder(); - LengthTrait lengthTraitShape = currentShape.expectTrait(LengthTrait.class); - Optional min = lengthTraitShape.getMin(); - Optional max = lengthTraitShape.getMax(); - if (pointableString.equals("*")) { - lengthCheck.append( - """ - if (%s != nil) { - """.formatted(dataSource) - ); - } - if (min.isPresent()) { - if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { - lengthCheck.append( - """ - if (utf8.RuneCountInString(%s%s) < %s) { - return fmt.Errorf(\"%s has a minimum length of %s but has the length of %%d.\", utf8.RuneCountInString(%s%s)) - } - """.formatted( - pointableString, - dataSource, - min.get().toString(), - currentShape.getId().getName(), - min.get().toString(), - pointableString, - dataSource - ) - ); - } else { - lengthCheck.append( - """ - if (len(%s%s) < %s) { - return fmt.Errorf(\"%s has a minimum length of %s but has the length of %%d.\", len(%s%s)) - } - """.formatted( - pointableString, - dataSource, - min.get().toString(), - currentShape.getId().getName(), - min.get().toString(), - pointableString, - dataSource - ) - ); - } - } - if (max.isPresent()) { - if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { - lengthCheck.append( - """ - if (utf8.RuneCountInString(%s%s) > %s) { - return fmt.Errorf(\"%s has a maximum length of %s but has the length of %%d.\", utf8.RuneCountInString(%s%s)) - } - """.formatted( - pointableString, - dataSource, - max.get().toString(), - currentShape.getId().getName(), - max.get().toString(), - pointableString, - dataSource - ) - ); - } else { - lengthCheck.append( - """ - if (len(%s%s) > %s) { - return fmt.Errorf(\"%s has a maximum length of %s but has the length of %%d.\", len(%s%s)) - } - """.formatted( - pointableString, - dataSource, - max.get().toString(), - currentShape.getId().getName(), - max.get().toString(), - pointableString, - dataSource - ) - ); - } - } - if (pointableString.equals("*")) { - lengthCheck.append( - """ + private void addLengthCheck(final Shape currentShape, final String dataSource, final String pointableString) { + StringBuilder lengthCheck = new StringBuilder(); + LengthTrait lengthTraitShape = currentShape.expectTrait(LengthTrait.class); + Optional min = lengthTraitShape.getMin(); + Optional max = lengthTraitShape.getMax(); + if (pointableString.equals("*")){ + lengthCheck.append(""" + if (%s != nil) { + """.formatted(dataSource)); + } + if (min.isPresent()) { + if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { + lengthCheck.append(""" + if (utf8.RuneCountInString(%s%s) < %s) { + return fmt.Errorf(\"%s has a minimum length of %s but has the length of %%d.\", utf8.RuneCountInString(%s%s)) + } + """.formatted( + pointableString, + dataSource, + min.get().toString(), + currentShape.getId().getName(), + min.get().toString(), + pointableString, + dataSource)); + } + else { + lengthCheck.append(""" + if (len(%s%s) < %s) { + return fmt.Errorf(\"%s has a minimum length of %s but has the length of %%d.\", len(%s%s)) + } + """.formatted( + pointableString, + dataSource, + min.get().toString(), + currentShape.getId().getName(), + min.get().toString(), + pointableString, + dataSource)); + } + } + if (max.isPresent()) { + if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { + lengthCheck.append(""" + if (utf8.RuneCountInString(%s%s) > %s) { + return fmt.Errorf(\"%s has a maximum length of %s but has the length of %%d.\", utf8.RuneCountInString(%s%s)) + } + """.formatted( + pointableString, + dataSource, + max.get().toString(), + currentShape.getId().getName(), + max.get().toString(), + pointableString, + dataSource)); + } + else { + lengthCheck.append(""" + if (len(%s%s) > %s) { + return fmt.Errorf(\"%s has a maximum length of %s but has the length of %%d.\", len(%s%s)) + } + """.formatted( + pointableString, + dataSource, + max.get().toString(), + currentShape.getId().getName(), + max.get().toString(), + pointableString, + dataSource)); + } + } + if (pointableString.equals("*")){ + lengthCheck.append(""" + } + """); } - """ - ); + writer.write(lengthCheck); } - writer.write(lengthCheck); - } - - private void addRequiredCheck( - final Symbol memberSymbol, - final Shape currentShape, - final String dataSource - ) { - StringBuilder RequiredCheck = new StringBuilder(); - if ( - memberSymbol.getProperty(POINTABLE).isPresent() && - (boolean) memberSymbol.getProperty(POINTABLE).get() - ) RequiredCheck.append( - """ - if ( %s == nil ) { - return fmt.Errorf(\"%s is required but has a nil value.\") - } - """.formatted(dataSource, dataSource) - ); - writer.write(RequiredCheck); - } - private void addUTFCheck( - final Shape currentShape, - final String dataSource, - final String pointableString - ) { - StringBuilder UTFCheck = new StringBuilder(); - if (pointableString.equals("*")) { - UTFCheck.append( - """ - if ( %s != nil ) { - """.formatted(dataSource) - ); + private void addRequiredCheck(final Symbol memberSymbol, final Shape currentShape, final String dataSource) { + StringBuilder RequiredCheck = new StringBuilder(); + if( memberSymbol.getProperty(POINTABLE).isPresent() && (boolean) memberSymbol.getProperty(POINTABLE).get()) + RequiredCheck.append(""" + if ( %s == nil ) { + return fmt.Errorf(\"%s is required but has a nil value.\") + } + """.formatted( + dataSource, + dataSource)); + writer.write(RequiredCheck); } - UTFCheck.append( - """ - if (!utf8.ValidString(%s%s)) { - return fmt.Errorf(\"Invalid UTF bytes %%s \", %s%s) - } - """.formatted(pointableString, dataSource, pointableString, dataSource) - ); - if (pointableString.equals("*")) { - UTFCheck.append( - """ + + private void addUTFCheck(final Shape currentShape, final String dataSource, final String pointableString) { + StringBuilder UTFCheck = new StringBuilder(); + if (pointableString.equals("*")){ + UTFCheck.append(""" + if ( %s != nil ) { + """.formatted(dataSource)); + } + UTFCheck.append(""" + if (!utf8.ValidString(%s%s)) { + return fmt.Errorf(\"Invalid UTF bytes %%s \", %s%s) + } + """.formatted( + pointableString, + dataSource, + pointableString, + dataSource)); + if (pointableString.equals("*")){ + UTFCheck.append(""" + } + """); } - """ - ); + writer.write(UTFCheck); } - writer.write(UTFCheck); - } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/GoIntegration.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/GoIntegration.java index 5eb8b38504..acf1f770c4 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/GoIntegration.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/GoIntegration.java @@ -8,5 +8,5 @@ import software.amazon.polymorph.smithygo.codegen.GoWriter; import software.amazon.smithy.codegen.core.SmithyIntegration; -public interface GoIntegration - extends SmithyIntegration {} +public interface GoIntegration extends SmithyIntegration { +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/ProtocolGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/ProtocolGenerator.java index c63f0803a0..abda4b6764 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/ProtocolGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/ProtocolGenerator.java @@ -14,57 +14,57 @@ */ package software.amazon.polymorph.smithygo.codegen.integration; -import static java.lang.String.format; - import software.amazon.polymorph.smithygo.codegen.ApplicationProtocol; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.utils.SmithyUnstableApi; +import static java.lang.String.format; + /** * Generates code to implement a protocol for both servers and clients. */ @SmithyUnstableApi public interface ProtocolGenerator { - /** - * Gets the supported protocol {@link ShapeId}. - * - * @return Returns the protocol supported - */ - ShapeId getProtocol(); + /** + * Gets the supported protocol {@link ShapeId}. + * + * @return Returns the protocol supported + */ + ShapeId getProtocol(); - /** - * Gets the name of the protocol. - * - *

The default implementation is the ShapeId name of the protocol trait in - * Smithy models (e.g., "aws.protocols#restJson1" would return "restJson1"). - * - * @return Returns the protocol name. - */ - default String getName() { - return getProtocol().getName(); - } + /** + * Gets the name of the protocol. + * + *

The default implementation is the ShapeId name of the protocol trait in + * Smithy models (e.g., "aws.protocols#restJson1" would return "restJson1"). + * + * @return Returns the protocol name. + */ + default String getName() { + return getProtocol().getName(); + } - /** - * Creates an application protocol for the generator. - * - * @return Returns the created application protocol. - */ - ApplicationProtocol getApplicationProtocol(); + /** + * Creates an application protocol for the generator. + * + * @return Returns the created application protocol. + */ + ApplicationProtocol getApplicationProtocol(); - /** - * Generates the code used to serialize the shapes of a service - * for requests. - * - * @param context Serialization context. - */ - void generateSerializers(GenerationContext context); + /** + * Generates the code used to serialize the shapes of a service + * for requests. + * + * @param context Serialization context. + */ + void generateSerializers(GenerationContext context); - /** - * Generates the code used to deserialize the shapes of a service - * for responses. - * - * @param context Deserialization context. - */ - void generateDeserializers(GenerationContext context); + /** + * Generates the code used to deserialize the shapes of a service + * for responses. + * + * @param context Deserialization context. + */ + void generateDeserializers(GenerationContext context); } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java index 9f490144f0..0a7e5834f4 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java @@ -17,9 +17,6 @@ package software.amazon.polymorph.smithygo.codegen.knowledge; -import java.util.HashSet; -import java.util.Set; -import java.util.logging.Logger; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.KnowledgeIndex; import software.amazon.smithy.model.knowledge.NeighborProviderIndex; @@ -37,276 +34,253 @@ import software.amazon.smithy.model.traits.StreamingTrait; import software.amazon.smithy.utils.SetUtils; +import java.util.HashSet; +import java.util.Set; +import java.util.logging.Logger; + /** * An index that checks if a member or shape type should be a pointer type in Go. *

* Extends the rules of smithy's NullableIndex for Go's translation of the smithy shapes to Go types. */ public class GoPointableIndex implements KnowledgeIndex { + private static final Logger LOGGER = Logger.getLogger(GoPointableIndex.class.getName()); + + // All types that are Go value types + private static final Set INHERENTLY_VALUE = SetUtils.of( + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + ShapeType.UNION, + ShapeType.DOCUMENT + ); - private static final Logger LOGGER = Logger.getLogger( - GoPointableIndex.class.getName() - ); - - // All types that are Go value types - private static final Set INHERENTLY_VALUE = SetUtils.of( - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - ShapeType.UNION, - ShapeType.DOCUMENT - ); - - // All types that are Go pointer types - private static final Set INHERENTLY_POINTABLE = SetUtils.of( - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - - // All types that cannot be dereferenced - private static final Set INHERENTLY_NONDEREFERENCABLE = - SetUtils.of( - // built in slice/map - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - // Interfaces - ShapeType.UNION, - ShapeType.DOCUMENT, - // known pointer types. - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER + // All types that are Go pointer types + private static final Set INHERENTLY_POINTABLE = SetUtils.of( + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER ); - // All types types that are comparable to nil - private static final Set INHERENTLY_NILLABLE = SetUtils.of( - // built in slice/map - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - // Interfaces - ShapeType.UNION, - ShapeType.DOCUMENT, - // known pointer types. - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - - // All the known pointer type if not required - private static final Set KNOWN_POINTER_TYPE = SetUtils.of( - ShapeType.BYTE, - ShapeType.SHORT, - ShapeType.INTEGER, - ShapeType.LONG, - ShapeType.FLOAT, - ShapeType.DOUBLE, - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - - private final Model model; - private final NullableIndex nullableIndex; - private final Set pointableShapes = new HashSet<>(); - private final Set nillableShapes = new HashSet<>(); - private final Set dereferencableShapes = new HashSet<>(); - - public GoPointableIndex(Model model) { - this.model = model; - this.nullableIndex = NullableIndex.of(model); - - for (Shape shape : model.toSet()) { - if (shape.asMemberShape().isPresent()) { - MemberShape member = shape.asMemberShape().get(); - Shape targetShape = model.expectShape(member.getTarget()); - - if (isMemberPointable(member, targetShape)) { - pointableShapes.add(shape.getId()); - } - if (isMemberNillable(member, targetShape)) { - nillableShapes.add(shape.getId()); - } - if (isMemberDereferencable(member, targetShape)) { - dereferencableShapes.add(shape.getId()); - } - } else { - if (isShapePointable(shape)) { - pointableShapes.add(shape.getId()); - nillableShapes.add(shape.getId()); - } - if (isShapeNillable(shape)) { - nillableShapes.add(shape.getId()); - } - if (isShapeDereferencable(shape)) { - dereferencableShapes.add(shape.getId()); - } - } - } - } - - public static GoPointableIndex of(Model model) { - return model.getKnowledge(GoPointableIndex.class, GoPointableIndex::new); - } - - private boolean isMemberDereferencable( - MemberShape member, - Shape targetShape - ) { - return ( - !INHERENTLY_NONDEREFERENCABLE.contains(targetShape.getType()) && - isMemberPointable(member, targetShape) + // All types that cannot be dereferenced + private static final Set INHERENTLY_NONDEREFERENCABLE = SetUtils.of( + // built in slice/map + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + + // Interfaces + ShapeType.UNION, + ShapeType.DOCUMENT, + + // known pointer types. + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER ); - } - private boolean isMemberNillable(MemberShape member, Shape targetShape) { - return ( - INHERENTLY_NILLABLE.contains(targetShape.getType()) || - isMemberPointable(member, targetShape) + // All types types that are comparable to nil + private static final Set INHERENTLY_NILLABLE = SetUtils.of( + // built in slice/map + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + + // Interfaces + ShapeType.UNION, + ShapeType.DOCUMENT, + + // known pointer types. + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER ); - } - private boolean isMemberPointable(MemberShape member, Shape targetShape) { - // Streamed blob shapes are never pointers because they are interfaces - if (isBlobStream(targetShape)) { - return false; - } + // All the known pointer type if not required + private static final Set KNOWN_POINTER_TYPE = SetUtils.of( + ShapeType.BYTE, + ShapeType.SHORT, + ShapeType.INTEGER, + ShapeType.LONG, + ShapeType.FLOAT, + ShapeType.DOUBLE, + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); - if (INHERENTLY_VALUE.contains(targetShape.getType())) { - return false; + private final Model model; + private final NullableIndex nullableIndex; + private final Set pointableShapes = new HashSet<>(); + private final Set nillableShapes = new HashSet<>(); + private final Set dereferencableShapes = new HashSet<>(); + + public GoPointableIndex(Model model) { + this.model = model; + this.nullableIndex = NullableIndex.of(model); + + for (Shape shape : model.toSet()) { + if (shape.asMemberShape().isPresent()) { + MemberShape member = shape.asMemberShape().get(); + Shape targetShape = model.expectShape(member.getTarget()); + + if (isMemberPointable(member, targetShape)) { + pointableShapes.add(shape.getId()); + } + if (isMemberNillable(member, targetShape)) { + nillableShapes.add(shape.getId()); + } + if (isMemberDereferencable(member, targetShape)) { + dereferencableShapes.add(shape.getId()); + } + } else { + if (isShapePointable(shape)) { + pointableShapes.add(shape.getId()); + nillableShapes.add(shape.getId()); + } + if (isShapeNillable(shape)) { + nillableShapes.add(shape.getId()); + } + if (isShapeDereferencable(shape)) { + dereferencableShapes.add(shape.getId()); + } + } + } } - //if membershape is required return it is not pointable - if (member.hasTrait(RequiredTrait.class)) { - return false; + public static GoPointableIndex of(Model model) { + return model.getKnowledge(GoPointableIndex.class, GoPointableIndex::new); } - if (model.expectShape(member.getContainer()).isMapShape()) { - return false; + private boolean isMemberDereferencable(MemberShape member, Shape targetShape) { + return !INHERENTLY_NONDEREFERENCABLE.contains(targetShape.getType()) && isMemberPointable(member, targetShape); } - if (KNOWN_POINTER_TYPE.contains(targetShape.getType())) { - return true; + private boolean isMemberNillable(MemberShape member, Shape targetShape) { + return INHERENTLY_NILLABLE.contains(targetShape.getType()) || isMemberPointable(member, targetShape); } - return nullableIndex.isMemberNullable( - member, - NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1_NO_INPUT - ); - } + private boolean isMemberPointable(MemberShape member, Shape targetShape) { + // Streamed blob shapes are never pointers because they are interfaces + if (isBlobStream(targetShape)) { + return false; + } - private boolean isShapeDereferencable(Shape shape) { - return ( - !INHERENTLY_NONDEREFERENCABLE.contains(shape.getType()) && - isShapePointable(shape) - ); - } + if (INHERENTLY_VALUE.contains(targetShape.getType())) { + return false; + } - private boolean isShapeNillable(Shape shape) { - return ( - INHERENTLY_NILLABLE.contains(shape.getType()) || isShapePointable(shape) - ); - } + //if membershape is required return it is not pointable + if (member.hasTrait(RequiredTrait.class)) { + return false; + } - private boolean isShapePointable(Shape shape) { - // All operation input and output shapes are pointable. - if (isOperationStruct(shape)) { - return true; - } + if (model.expectShape(member.getContainer()).isMapShape()) { + return false; + } - // Streamed blob shapes are never pointers because they are interfaces - if (isBlobStream(shape)) { - return false; - } + if (KNOWN_POINTER_TYPE.contains(targetShape.getType())) { + return true; + } - if (shape.isServiceShape()) { - return true; + return nullableIndex.isMemberNullable(member, NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1_NO_INPUT); } - // This is odd because its not a go type but a function with receiver - if (shape.isOperationShape()) { - return false; + private boolean isShapeDereferencable(Shape shape) { + return !INHERENTLY_NONDEREFERENCABLE.contains(shape.getType()) && isShapePointable(shape); } - if (INHERENTLY_POINTABLE.contains(shape.getType())) { - return true; + private boolean isShapeNillable(Shape shape) { + return INHERENTLY_NILLABLE.contains(shape.getType()) || isShapePointable(shape); } - if (INHERENTLY_VALUE.contains(shape.getType())) { - return false; + private boolean isShapePointable(Shape shape) { + // All operation input and output shapes are pointable. + if (isOperationStruct(shape)) { + return true; + } + + // Streamed blob shapes are never pointers because they are interfaces + if (isBlobStream(shape)) { + return false; + } + + if (shape.isServiceShape()) { + return true; + } + + // This is odd because its not a go type but a function with receiver + if (shape.isOperationShape()) { + return false; + } + + if (INHERENTLY_POINTABLE.contains(shape.getType())) { + return true; + } + + if (INHERENTLY_VALUE.contains(shape.getType())) { + return false; + } + + if (shape.hasTrait(RequiredTrait.class)) { + return false; + } + + if (KNOWN_POINTER_TYPE.contains(shape.getType())) { + return true; + } + + return nullableIndex.isNullable(shape); } - if (shape.hasTrait(RequiredTrait.class)) { - return false; + private boolean isShapeEnum(Shape shape) { + return shape.getType() == ShapeType.STRING && shape.hasTrait(EnumTrait.class) + || shape.getType() == ShapeType.ENUM + || shape.getType() == ShapeType.INT_ENUM; } - if (KNOWN_POINTER_TYPE.contains(shape.getType())) { - return true; + private boolean isBlobStream(Shape shape) { + return shape.getType() == ShapeType.BLOB && shape.hasTrait(StreamingTrait.ID); } - return nullableIndex.isNullable(shape); - } + private boolean isOperationStruct(Shape shape) { + NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); + for (Relationship relationship : provider.getNeighbors(shape)) { + RelationshipType relationshipType = relationship.getRelationshipType(); + if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { + return true; + } + } + + return false; + } - private boolean isShapeEnum(Shape shape) { - return ( - (shape.getType() == ShapeType.STRING && - shape.hasTrait(EnumTrait.class)) || - shape.getType() == ShapeType.ENUM || - shape.getType() == ShapeType.INT_ENUM - ); - } + /** + * Returns if the shape should be generated as a Go pointer type or not. + * + * @param shape the shape to check if should be pointable type. + * @return if the shape is should be a Go pointer type. + */ + public final boolean isPointable(ToShapeId shape) { + return pointableShapes.contains(shape.toShapeId()); + } - private boolean isBlobStream(Shape shape) { - return ( - shape.getType() == ShapeType.BLOB && shape.hasTrait(StreamingTrait.ID) - ); - } - - private boolean isOperationStruct(Shape shape) { - NeighborProvider provider = NeighborProviderIndex - .of(model) - .getReverseProvider(); - for (Relationship relationship : provider.getNeighbors(shape)) { - RelationshipType relationshipType = relationship.getRelationshipType(); - if ( - relationshipType == RelationshipType.INPUT || - relationshipType == RelationshipType.OUTPUT - ) { - return true; - } + /** + * Returns if the Go type generated for the shape is comparable to nil. + * + * @param shape the shape to check + * @return if the shape's go type is comparable to nil + */ + public final boolean isNillable(ToShapeId shape) { + return nillableShapes.contains(shape.toShapeId()); } - return false; - } - - /** - * Returns if the shape should be generated as a Go pointer type or not. - * - * @param shape the shape to check if should be pointable type. - * @return if the shape is should be a Go pointer type. - */ - public final boolean isPointable(ToShapeId shape) { - return pointableShapes.contains(shape.toShapeId()); - } - - /** - * Returns if the Go type generated for the shape is comparable to nil. - * - * @param shape the shape to check - * @return if the shape's go type is comparable to nil - */ - public final boolean isNillable(ToShapeId shape) { - return nillableShapes.contains(shape.toShapeId()); - } - - /** - * Returns if the Go type generated for the shape can be dereferenced. - * - * @param shape the shape to check - * @return if the shape's go type is dereferencable - */ - public final boolean isDereferencable(ToShapeId shape) { - return dereferencableShapes.contains(shape.toShapeId()); - } + /** + * Returns if the Go type generated for the shape can be dereferenced. + * + * @param shape the shape to check + * @return if the shape's go type is dereferencable + */ + public final boolean isDereferencable(ToShapeId shape) { + return dereferencableShapes.contains(shape.toShapeId()); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoUsageIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoUsageIndex.java index 8bd7b5226f..e8e00b0fa0 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoUsageIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoUsageIndex.java @@ -15,9 +15,6 @@ package software.amazon.polymorph.smithygo.codegen.knowledge; -import java.util.HashSet; -import java.util.Set; -import java.util.stream.Collectors; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.KnowledgeIndex; import software.amazon.smithy.model.knowledge.OperationIndex; @@ -30,87 +27,65 @@ import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.ToShapeId; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + /** * Provides {@link KnowledgeIndex} of how shapes are used in the model. */ public class GoUsageIndex implements KnowledgeIndex { + private final Model model; + private final Walker walker; - private final Model model; - private final Walker walker; + private final Set inputShapes = new HashSet<>(); + private final Set outputShapes = new HashSet<>(); - private final Set inputShapes = new HashSet<>(); - private final Set outputShapes = new HashSet<>(); + public GoUsageIndex(Model model) { + this.model = model; + this.walker = new Walker(model); - public GoUsageIndex(Model model) { - this.model = model; - this.walker = new Walker(model); + TopDownIndex topDownIndex = TopDownIndex.of(model); + OperationIndex operationIndex = OperationIndex.of(model); - TopDownIndex topDownIndex = TopDownIndex.of(model); - OperationIndex operationIndex = OperationIndex.of(model); + model.shapes(ServiceShape.class).forEach(serviceShape -> { + topDownIndex.getContainedOperations(serviceShape).forEach(operationShape -> { + StructureShape inputShape = operationIndex.getInput(operationShape).get(); + StructureShape outputShape = operationIndex.getOutput(operationShape).get(); - model - .shapes(ServiceShape.class) - .forEach(serviceShape -> { - topDownIndex - .getContainedOperations(serviceShape) - .forEach(operationShape -> { - StructureShape inputShape = operationIndex - .getInput(operationShape) - .get(); - StructureShape outputShape = operationIndex - .getOutput(operationShape) - .get(); + inputShapes.addAll(walker.walkShapes(inputShape, relationship -> + relationship.getDirection() == RelationshipDirection.DIRECTED).stream() + .map(Shape::toShapeId).collect(Collectors.toList())); - inputShapes.addAll( - walker - .walkShapes( - inputShape, - relationship -> - relationship.getDirection() == - RelationshipDirection.DIRECTED - ) - .stream() - .map(Shape::toShapeId) - .collect(Collectors.toList()) - ); + outputShapes.addAll(walker.walkShapes(outputShape, relationship -> + relationship.getDirection() == RelationshipDirection.DIRECTED).stream() + .map(Shape::toShapeId).collect(Collectors.toList())); - outputShapes.addAll( - walker - .walkShapes( - outputShape, - relationship -> - relationship.getDirection() == - RelationshipDirection.DIRECTED - ) - .stream() - .map(Shape::toShapeId) - .collect(Collectors.toList()) - ); - }); - }); - } + }); + }); + } - /** - * Returns whether shape is used as part of an input to an operation. - * - * @param shape the shape - * @return whether the shape is used as input. - */ - public boolean isUsedForInput(ToShapeId shape) { - return inputShapes.contains(shape.toShapeId()); - } + /** + * Returns whether shape is used as part of an input to an operation. + * + * @param shape the shape + * @return whether the shape is used as input. + */ + public boolean isUsedForInput(ToShapeId shape) { + return inputShapes.contains(shape.toShapeId()); + } - /** - * Returns whether shape is used as output of an operation. - * - * @param shape the shape - * @return whether the shape is used as input. - */ - public boolean isUsedForOutput(ToShapeId shape) { - return outputShapes.contains(shape.toShapeId()); - } + /** + * Returns whether shape is used as output of an operation. + * + * @param shape the shape + * @return whether the shape is used as input. + */ + public boolean isUsedForOutput(ToShapeId shape) { + return outputShapes.contains(shape.toShapeId()); + } - public static GoUsageIndex of(Model model) { - return model.getKnowledge(GoUsageIndex.class, GoUsageIndex::new); - } + public static GoUsageIndex of(Model model) { + return model.getKnowledge(GoUsageIndex.class, GoUsageIndex::new); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoValidationIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoValidationIndex.java index c4410f6eca..60ef46d1b5 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoValidationIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoValidationIndex.java @@ -30,13 +30,6 @@ package software.amazon.polymorph.smithygo.codegen.knowledge; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.TreeSet; -import java.util.function.Consumer; -import java.util.stream.Collectors; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.KnowledgeIndex; import software.amazon.smithy.model.knowledge.TopDownIndex; @@ -51,209 +44,148 @@ import software.amazon.smithy.model.traits.RequiredTrait; import software.amazon.smithy.utils.SetUtils; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.Consumer; +import java.util.stream.Collectors; + /** * Provides a knowledge index of which service operations and shapes require validation helpers. */ public class GoValidationIndex implements KnowledgeIndex { - - private final Map> serviceToOperationMap = - new HashMap<>(); - private final Map> serviceValidationHelpers = - new HashMap<>(); - - public GoValidationIndex(Model model) { - TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - Walker walker = new Walker(model); - - model - .shapes(ServiceShape.class) - .forEach(serviceShape -> { - // Go uses unique input shapes per operation so we can index using the input shape as our key - Map inputShapeToOperation = new HashMap<>(); - Set requireValidationHelpers = new TreeSet<>(); - - // First pass is to collect member containers that contain members requiring validation - Set operations = topDownIndex.getContainedOperations( - serviceShape - ); - operations.forEach(operationShape -> { - Shape inputShape = model.expectShape(operationShape.getInput().get()); - GoValidationIndex.walkValidationTree( - walker, - inputShape, - shape -> { - if (shape.isMemberShape()) { - Shape container = model.expectShape( - ((MemberShape) shape).getContainer() - ); - if ( - isRequiredParameter( - model, - (MemberShape) shape, - inputShape.equals(container) - ) - ) { - inputShapeToOperation.put(inputShape, operationShape); - requireValidationHelpers.add(container.toShapeId()); - } - } - } - ); - }); - - // 2nd step is final all containers that reference the initial containers which require validation until - // we've discovered all intermediate containing types - inputShapeToOperation - .keySet() - .forEach(input -> { - Set helpers = new TreeSet<>(); - do { - GoValidationIndex.walkValidationTree( - walker, - input, - shape -> { - if (shape.isMemberShape()) { - MemberShape memberShape = shape.asMemberShape().get(); - Shape container = model.expectShape( - memberShape.getContainer() - ); - Shape target = model.expectShape(memberShape.getTarget()); - if ( - requireValidationHelpers.contains(target.toShapeId()) && - !requireValidationHelpers.contains(container.toShapeId()) - ) { - helpers.add(container.toShapeId()); + private final Map> serviceToOperationMap = new HashMap<>(); + private final Map> serviceValidationHelpers = new HashMap<>(); + + public GoValidationIndex(Model model) { + TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); + Walker walker = new Walker(model); + + model.shapes(ServiceShape.class).forEach(serviceShape -> { + // Go uses unique input shapes per operation so we can index using the input shape as our key + Map inputShapeToOperation = new HashMap<>(); + Set requireValidationHelpers = new TreeSet<>(); + + // First pass is to collect member containers that contain members requiring validation + Set operations = topDownIndex.getContainedOperations(serviceShape); + operations.forEach(operationShape -> { + Shape inputShape = model.expectShape(operationShape.getInput().get()); + GoValidationIndex.walkValidationTree(walker, inputShape, shape -> { + if (shape.isMemberShape()) { + Shape container = model.expectShape(((MemberShape) shape).getContainer()); + if (isRequiredParameter(model, (MemberShape) shape, inputShape.equals(container))) { + inputShapeToOperation.put(inputShape, operationShape); + requireValidationHelpers.add(container.toShapeId()); + } } - } - } - ); - if (helpers.isEmpty()) { - break; - } - requireValidationHelpers.addAll(helpers); - helpers.clear(); - } while (true); - }); - - serviceToOperationMap.put( - serviceShape.toShapeId(), - new TreeSet<>( - inputShapeToOperation - .values() - .stream() - .map(OperationShape::toShapeId) - .collect(Collectors.toSet()) - ) - ); - serviceValidationHelpers.put( - serviceShape.toShapeId(), - requireValidationHelpers - ); - }); - } - - public static GoValidationIndex of(Model model) { - return model.getKnowledge(GoValidationIndex.class, GoValidationIndex::new); - } - - /** - * Get the set of operations that require validation. - * - * @param service service to find operations for - * @return operations requiring validation - */ - public Set getOperationsRequiringValidation(ToShapeId service) { - return serviceToOperationMap.getOrDefault( - service.toShapeId(), - SetUtils.of() - ); - } - - /** - * Get a set of shapes that require validation helpers. - * - * @param service service to find operations for - * @return operations requiring validation - */ - public Set getShapesRequiringValidationHelpers(ToShapeId service) { - return serviceValidationHelpers.getOrDefault( - service.toShapeId(), - SetUtils.of() - ); - } - - /** - * Returns whether the given shape requires a validation helper. - * - * @param shape the shape to check - * @return whether the shape requires a validation helper - */ - public boolean isValidationHelperRequired(ToShapeId shape) { - return serviceValidationHelpers.containsKey(shape.toShapeId()); - } - - /** - * Checks whether a {@link MemberShape} has any validation constraints. - * - * @param model the model - * @param shape the {@link MemberShape} to check - * @param validateHttpBindings whether http bindings should be checked for additional implicit constraints - * @return whether the {@link MemberShape} has validation costraints - */ - public static boolean hasValidation( - Model model, - MemberShape shape, - boolean validateHttpBindings - ) { - return isRequiredParameter(model, shape, validateHttpBindings); - } - - /** - * Checks whether a {@link MemberShape} is marked as being required explicitly or implicitly. - * - * @param model the model - * @param shape the {@link MemberShape} to check - * @param validateHttpBindings whether http bindings should be checked for additional implicit constraints - * @return whether the {@link MemberShape} is a required parameter - */ - public static boolean isRequiredParameter( - Model model, - MemberShape shape, - boolean validateHttpBindings - ) { - Optional requiredTrait = shape.getMemberTrait( - model, - RequiredTrait.class - ); - return ( - requiredTrait.isPresent() || - (validateHttpBindings && - shape.getMemberTrait(model, HttpLabelTrait.class).isPresent()) - ); - } - - private static void walkValidationTree( - Walker walker, - Shape shape, - Consumer visitor - ) { - walker - .walkShapes( - shape, - relationship -> { - switch (relationship.getRelationshipType()) { - case STRUCTURE_MEMBER: - case UNION_MEMBER: - case MAP_VALUE: - case LIST_MEMBER: - case SET_MEMBER: - case MEMBER_TARGET: - return true; - default: - return false; - } - } - ) - .forEach(visitor::accept); - } + }); + }); + + // 2nd step is final all containers that reference the initial containers which require validation until + // we've discovered all intermediate containing types + inputShapeToOperation.keySet().forEach(input -> { + Set helpers = new TreeSet<>(); + do { + GoValidationIndex.walkValidationTree(walker, input, shape -> { + if (shape.isMemberShape()) { + MemberShape memberShape = shape.asMemberShape().get(); + Shape container = model.expectShape(memberShape.getContainer()); + Shape target = model.expectShape(memberShape.getTarget()); + if (requireValidationHelpers.contains(target.toShapeId()) + && !requireValidationHelpers.contains(container.toShapeId())) { + helpers.add(container.toShapeId()); + } + } + }); + if (helpers.isEmpty()) { + break; + } + requireValidationHelpers.addAll(helpers); + helpers.clear(); + } while (true); + }); + + serviceToOperationMap.put(serviceShape.toShapeId(), new TreeSet<>(inputShapeToOperation.values().stream() + .map(OperationShape::toShapeId).collect(Collectors.toSet()))); + serviceValidationHelpers.put(serviceShape.toShapeId(), requireValidationHelpers); + }); + } + + public static GoValidationIndex of(Model model) { + return model.getKnowledge(GoValidationIndex.class, GoValidationIndex::new); + } + + /** + * Get the set of operations that require validation. + * + * @param service service to find operations for + * @return operations requiring validation + */ + public Set getOperationsRequiringValidation(ToShapeId service) { + return serviceToOperationMap.getOrDefault(service.toShapeId(), SetUtils.of()); + } + + /** + * Get a set of shapes that require validation helpers. + * + * @param service service to find operations for + * @return operations requiring validation + */ + public Set getShapesRequiringValidationHelpers(ToShapeId service) { + return serviceValidationHelpers.getOrDefault(service.toShapeId(), SetUtils.of()); + } + + /** + * Returns whether the given shape requires a validation helper. + * + * @param shape the shape to check + * @return whether the shape requires a validation helper + */ + public boolean isValidationHelperRequired(ToShapeId shape) { + return serviceValidationHelpers.containsKey(shape.toShapeId()); + } + + /** + * Checks whether a {@link MemberShape} has any validation constraints. + * + * @param model the model + * @param shape the {@link MemberShape} to check + * @param validateHttpBindings whether http bindings should be checked for additional implicit constraints + * @return whether the {@link MemberShape} has validation costraints + */ + public static boolean hasValidation(Model model, MemberShape shape, boolean validateHttpBindings) { + return isRequiredParameter(model, shape, validateHttpBindings); + } + + /** + * Checks whether a {@link MemberShape} is marked as being required explicitly or implicitly. + * + * @param model the model + * @param shape the {@link MemberShape} to check + * @param validateHttpBindings whether http bindings should be checked for additional implicit constraints + * @return whether the {@link MemberShape} is a required parameter + */ + public static boolean isRequiredParameter(Model model, MemberShape shape, boolean validateHttpBindings) { + Optional requiredTrait = shape.getMemberTrait(model, RequiredTrait.class); + return requiredTrait.isPresent() || (validateHttpBindings && shape.getMemberTrait(model, + HttpLabelTrait.class).isPresent()); + } + + private static void walkValidationTree(Walker walker, Shape shape, Consumer visitor) { + walker.walkShapes(shape, relationship -> { + switch (relationship.getRelationshipType()) { + case STRUCTURE_MEMBER: + case UNION_MEMBER: + case MAP_VALUE: + case LIST_MEMBER: + case SET_MEMBER: + case MEMBER_TARGET: + return true; + default: + return false; + } + }).forEach(visitor::accept); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyGoPointableIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyGoPointableIndex.java index e9d301b029..7d23954f7d 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyGoPointableIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyGoPointableIndex.java @@ -7,10 +7,7 @@ public class DafnyGoPointableIndex { - public static boolean isNillable(final Model model, final Shape shape) { - return ( - !shape.hasTrait(RequiredTrait.class) && - !GoCodegenUtils.isOperationStruct(model, shape) - ); - } + public static boolean isNillable(final Model model, final Shape shape) { + return !shape.hasTrait(RequiredTrait.class) && !GoCodegenUtils.isOperationStruct(model, shape); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceCodegenPlugin.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceCodegenPlugin.java index 40c1b2e659..eea7ae096f 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceCodegenPlugin.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceCodegenPlugin.java @@ -1,6 +1,5 @@ package software.amazon.polymorph.smithygo.localservice; -import java.util.Map; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoSettings; import software.amazon.polymorph.smithygo.codegen.GoWriter; @@ -10,58 +9,51 @@ import software.amazon.smithy.build.SmithyBuildPlugin; import software.amazon.smithy.codegen.core.directed.CodegenDirector; -public class DafnyLocalServiceCodegenPlugin implements SmithyBuildPlugin { +import java.util.Map; - public DafnyLocalServiceCodegenPlugin( - final Map smithyNamespaceToPythonModuleNameMap - ) { - super(); - SmithyNameResolver.setSmithyNamespaceToGoModuleNameMap( - smithyNamespaceToPythonModuleNameMap - ); - } +public class DafnyLocalServiceCodegenPlugin implements SmithyBuildPlugin { - public void run(PluginContext context) { - CodegenDirector< - GoWriter, - GoIntegration, - GenerationContext, - GoSettings - > runner = new CodegenDirector<>(); + public DafnyLocalServiceCodegenPlugin(final Map smithyNamespaceToPythonModuleNameMap) { + super(); + SmithyNameResolver.setSmithyNamespaceToGoModuleNameMap(smithyNamespaceToPythonModuleNameMap); + } + public void run(PluginContext context) { + CodegenDirector runner + = new CodegenDirector<>(); - runner.directedCodegen(new DafnyLocalServiceDirectedCodegen()); + runner.directedCodegen(new DafnyLocalServiceDirectedCodegen()); - // Set the SmithyIntegration class to look for and apply using SPI. - runner.integrationClass(GoIntegration.class); + // Set the SmithyIntegration class to look for and apply using SPI. + runner.integrationClass(GoIntegration.class); - // Set the FileManifest and Model from the plugin. - runner.fileManifest(context.getFileManifest()); - runner.model(context.getModel()); + // Set the FileManifest and Model from the plugin. + runner.fileManifest(context.getFileManifest()); + runner.model(context.getModel()); - // Create the GoSettings object from the plugin settings. - GoSettings settings = GoSettings.from(context.getSettings()); - runner.settings(settings); + // Create the GoSettings object from the plugin settings. + GoSettings settings = GoSettings.from(context.getSettings()); + runner.settings(settings); - runner.service(settings.getService()); + runner.service(settings.getService()); - // Configure the director to perform some common model transforms. - runner.performDefaultCodegenTransforms(); + // Configure the director to perform some common model transforms. + runner.performDefaultCodegenTransforms(); - // TODO: Not using below because it would break existing AWS SDKs. Maybe it should be configurable - // so generic SDKs call this by default, but AWS SDKs can opt-out of it via a setting. - // runner.createDedicatedInputsAndOutputs(); + // TODO: Not using below because it would break existing AWS SDKs. Maybe it should be configurable + // so generic SDKs call this by default, but AWS SDKs can opt-out of it via a setting. + // runner.createDedicatedInputsAndOutputs(); - // Run it! - runner.run(); - } + // Run it! + runner.run(); + } - @Override - public String getName() { - return "go-client-codegen"; - } + @Override + public String getName() { + return "go-client-codegen"; + } - @Override - public void execute(PluginContext context) { - this.run(context); - } + @Override + public void execute(PluginContext context) { + this.run(context); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceDirectedCodegen.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceDirectedCodegen.java index 7c3b043bee..cd22bd32c5 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceDirectedCodegen.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceDirectedCodegen.java @@ -1,6 +1,5 @@ package software.amazon.polymorph.smithygo.localservice; -import java.util.logging.Logger; import software.amazon.polymorph.smithygo.codegen.EnumGenerator; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoDelegator; @@ -21,191 +20,112 @@ import software.amazon.smithy.codegen.core.directed.GenerateStructureDirective; import software.amazon.smithy.codegen.core.directed.GenerateUnionDirective; -public class DafnyLocalServiceDirectedCodegen - implements DirectedCodegen { - - private static final Logger LOGGER = Logger.getLogger( - DafnyLocalServiceDirectedCodegen.class.getName() - ); - - @Override - public SymbolProvider createSymbolProvider( - CreateSymbolProviderDirective directive - ) { - return new SymbolVisitor(directive.model(), directive.settings()); - } - - @Override - public GenerationContext createContext( - CreateContextDirective directive - ) { - return GenerationContext - .builder() - .model(directive.model()) - .settings(directive.settings()) - .symbolProvider(directive.symbolProvider()) - .fileManifest(directive.fileManifest()) - .integrations(directive.integrations()) - .writerDelegator( - new GoDelegator(directive.fileManifest(), directive.symbolProvider()) - ) - .protocolGenerator(new DafnyLocalServiceTypeConversionProtocol()) - .build(); - } - - @Override - public void generateService( - GenerateServiceDirective directive - ) { - if ( - !directive - .shape() - .getId() - .getNamespace() - .equals(directive.context().settings().getService().getNamespace()) - ) { - return; +import java.util.logging.Logger; + +public class DafnyLocalServiceDirectedCodegen implements DirectedCodegen { + private static final Logger LOGGER = Logger.getLogger(DafnyLocalServiceDirectedCodegen.class.getName()); + @Override + public SymbolProvider createSymbolProvider(CreateSymbolProviderDirective directive) { + return new SymbolVisitor(directive.model(), directive.settings()); } - new DafnyLocalServiceGenerator(directive.context(), directive.service()) - .run(); - var protocolGenerator = directive.context().protocolGenerator(); - if (protocolGenerator == null) { - return; + @Override + public GenerationContext createContext(CreateContextDirective directive) { + return GenerationContext.builder() + .model(directive.model()) + .settings(directive.settings()) + .symbolProvider(directive.symbolProvider()) + .fileManifest(directive.fileManifest()) + .integrations(directive.integrations()) + .writerDelegator(new GoDelegator(directive.fileManifest(), directive.symbolProvider())) + .protocolGenerator(new DafnyLocalServiceTypeConversionProtocol()) + .build(); } - protocolGenerator.generateSerializers(directive.context()); - - protocolGenerator.generateDeserializers(directive.context()); - } - - @Override - public void generateStructure( - GenerateStructureDirective directive - ) { - if ( - !directive - .shape() - .getId() - .getNamespace() - .equals(directive.context().settings().getService().getNamespace()) - ) { - return; + @Override + public void generateService(GenerateServiceDirective directive) { + if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) + { + return; + } + new DafnyLocalServiceGenerator(directive.context(), directive.service()).run(); + + var protocolGenerator = directive.context().protocolGenerator(); + if (protocolGenerator == null) { + return; + } + + protocolGenerator.generateSerializers(directive.context()); + + protocolGenerator.generateDeserializers(directive.context()); + } - directive - .context() - .writerDelegator() - .useShapeWriter( - directive.shape(), - writer -> { - StructureGenerator generator = new StructureGenerator( - directive.context(), - writer, - directive.shape() - ); - generator.run(); + + @Override + public void generateStructure(GenerateStructureDirective directive) { + if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) + { + return; } - ); - } - - @Override - public void generateError( - GenerateErrorDirective directive - ) { - if ( - !directive - .shape() - .getId() - .getNamespace() - .equals(directive.context().settings().getService().getNamespace()) - ) { - return; + directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { + StructureGenerator generator = new StructureGenerator( + directive.context(), + writer, + directive.shape() + ); + generator.run(); + }); } - directive - .context() - .writerDelegator() - .useShapeWriter( - directive.shape(), - writer -> { - StructureGenerator generator = new StructureGenerator( - directive.context(), - writer, - directive.shape() - ); - generator.run(); + + @Override + public void generateError(GenerateErrorDirective directive) { + if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) + { + return; } - ); - } - - @Override - public void generateUnion( - GenerateUnionDirective directive - ) {} - - @Override - public void generateEnumShape( - GenerateEnumDirective directive - ) { - if ( - !directive - .shape() - .getId() - .getNamespace() - .equals(directive.context().settings().getService().getNamespace()) - ) { - return; + directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { + StructureGenerator generator = new StructureGenerator( + directive.context(), + writer, + directive.shape() + ); + generator.run(); + }); } - directive - .context() - .writerDelegator() - .useShapeWriter( - directive.shape(), - writer -> { - EnumGenerator enumGenerator = new EnumGenerator( - directive.symbolProvider(), - writer, - directive.shape() - ); - enumGenerator.run(); + + @Override + public void generateUnion(GenerateUnionDirective directive) { + + } + + @Override + public void generateEnumShape(GenerateEnumDirective directive) { + if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) + { + return; } - ); - } - - @Override - public void generateIntEnumShape( - GenerateIntEnumDirective directive - ) { - if ( - !directive - .shape() - .getId() - .getNamespace() - .equals(directive.context().settings().getService().getNamespace()) - ) { - return; + directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { + EnumGenerator enumGenerator = new EnumGenerator(directive.symbolProvider(), writer, directive.shape()); + enumGenerator.run(); + }); } - directive - .context() - .writerDelegator() - .useShapeWriter( - directive.shape(), - writer -> { - IntEnumGenerator intEnumGenerator = new IntEnumGenerator( - directive.symbolProvider(), - writer, - directive.shape().asIntEnumShape().get() - ); - intEnumGenerator.run(); + + @Override + public void generateIntEnumShape(GenerateIntEnumDirective directive) { + if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) + { + return; } - ); - } - - @Override - public void generateResource( - GenerateResourceDirective directive - ) { - // System.out.println("##############" + directive.shape()); - // directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { - // }); - } + directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { + IntEnumGenerator intEnumGenerator = new IntEnumGenerator(directive.symbolProvider(), writer, directive.shape().asIntEnumShape().get()); + intEnumGenerator.run(); + }); + } + + @Override + public void generateResource(GenerateResourceDirective directive) { +// System.out.println("##############" + directive.shape()); +// directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { +// }); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java index 38c1f0474b..3147ea8eed 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java @@ -4,8 +4,6 @@ package software.amazon.polymorph.smithygo.localservice; import software.amazon.awssdk.core.traits.RequiredTrait; -import java.util.Collection; -import java.util.stream.Collectors; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoDelegator; import software.amazon.polymorph.smithygo.codegen.GoWriter; @@ -30,326 +28,97 @@ import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.UnitTypeTrait; +import java.util.Collection; +import java.util.stream.Collectors; + + public class DafnyLocalServiceGenerator implements Runnable { + private final GenerationContext context; + private final ServiceShape service; + private final TopDownIndex topDownIndex; + private final GoDelegator writerDelegator; + private final Model model; + private final SymbolProvider symbolProvider; + + public DafnyLocalServiceGenerator(GenerationContext context, ServiceShape service) { + this.context = context; + this.service = service; + model = context.model(); + topDownIndex = TopDownIndex.of(model); + writerDelegator = context.writerDelegator(); + symbolProvider = context.symbolProvider(); + } - private final GenerationContext context; - private final ServiceShape service; - private final TopDownIndex topDownIndex; - private final GoDelegator writerDelegator; - private final Model model; - private final SymbolProvider symbolProvider; - - public DafnyLocalServiceGenerator( - GenerationContext context, - ServiceShape service - ) { - this.context = context; - this.service = service; - model = context.model(); - topDownIndex = TopDownIndex.of(model); - writerDelegator = context.writerDelegator(); - symbolProvider = context.symbolProvider(); - } - - @Override - public void run() { - writerDelegator.useShapeWriter(service, this::generateService); - } - - private void generateService(GoWriter writer) { - if (service.hasTrait(LocalServiceTrait.class)) { - generateClient(writer); - generateUnmodelledErrors(context); - generateReferencedResources(context); - generateUnboundedStructures(context); + @Override + public void run() { + writerDelegator.useShapeWriter(service, this::generateService); } - generateShim(); - } - - void generateClient(GoWriter writer) { - // Generate each operation for the service. We do this here instead of via the operation visitor method to - // limit it to the operations bound to the service. - final var serviceSymbol = symbolProvider.toSymbol(service); - final var serviceTrait = service.expectTrait(LocalServiceTrait.class); - final var configSymbol = symbolProvider.toSymbol( - model.expectShape(serviceTrait.getConfigId()) - ); - - writerDelegator.useFileWriter( - "%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), - SmithyNameResolver.smithyTypesNamespace(service), - writer1 -> { - new StructureGenerator( - context, - writer1, - model.expectShape(serviceTrait.getConfigId()).asStructureShape().get() - ) - .run(); - model - .getUnionShapes() - .stream() - .filter(unionShape -> - unionShape - .getId() - .getNamespace() - .equals(service.getId().getNamespace()) - ) - .forEach(unionShape -> { - new UnionGenerator(model, symbolProvider, unionShape) - .generateUnion(writer1); - }); - } - ); - - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - context.settings().getService().getNamespace() - ), - DafnyNameResolver.dafnyTypesNamespace(service) - ); - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - context.settings().getService().getNamespace() - ), - DafnyNameResolver.dafnyNamespace(service) - ); - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - context.settings().getService().getNamespace() - ), - SmithyNameResolver.smithyTypesNamespace(service) - ); - writer.addUseImports(SmithyGoDependency.CONTEXT); - - final var dafnyClient = DafnyNameResolver.getDafnyClient( - service, - serviceTrait.getSdkId() - ); - writer.write( - """ - type $T struct { - DafnyClient *$L - } - - func NewClient(clientConfig $L) (*$T, error) { - var dafnyConfig = $L(clientConfig) - var dafny_response = $L(dafnyConfig) - if (dafny_response.Is_Failure()) { - panic("Client construction failed. This should never happen") - } - var dafnyClient = dafny_response.Extract().(*$L) - client := &$T { dafnyClient } - return client, nil - } - """, - serviceSymbol, - dafnyClient, - SmithyNameResolver.getSmithyType(service, configSymbol), - serviceSymbol, - SmithyNameResolver.getToDafnyMethodName( - service, - context.model().expectShape(serviceTrait.getConfigId()), - "" - ), - DafnyNameResolver.createDafnyClient(service, serviceTrait.getSdkId()), - dafnyClient, - serviceSymbol - ); - - service - .getOperations() - .forEach(operation -> { - final var operationShape = model.expectShape( - operation, - OperationShape.class - ); - final var inputShape = model.expectShape( - operationShape.getInputShape() - ); - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - inputShape.toShapeId().getNamespace() - ), - DafnyNameResolver.dafnyTypesNamespace(inputShape) - ); - if ( - !inputShape - .toShapeId() - .getNamespace() - .equals(service.toShapeId().getNamespace()) - ) { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - inputShape.toShapeId().getNamespace() - ), - SmithyNameResolver.shapeNamespace(inputShape) - ); - } - final var outputShape = model.expectShape( - operationShape.getOutputShape() - ); - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - outputShape.toShapeId().getNamespace() - ), - SmithyNameResolver.smithyTypesNamespace(outputShape) - ); - if ( - !outputShape - .toShapeId() - .getNamespace() - .equals(service.toShapeId().getNamespace()) - ) { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - outputShape.toShapeId().getNamespace() - ), - SmithyNameResolver.shapeNamespace(outputShape) - ); - } - final var inputType = inputShape.hasTrait(UnitTypeTrait.class) - ? "" - : ", params %s.%s".formatted( - SmithyNameResolver.smithyTypesNamespace(inputShape), - inputShape.toShapeId().getName() - ); - final var outputType = outputShape.hasTrait(UnitTypeTrait.class) - ? "" - : "*%s.%s,".formatted( - SmithyNameResolver.smithyTypesNamespace(outputShape), - outputShape.toShapeId().getName() - ); - String validationCheck = ""; - if (!inputType.equals("")) { - validationCheck = - """ - err := params.Validate() - if err != nil { - opaqueErr := %s.OpaqueError{ - ErrObject: err, - } - """.formatted(SmithyNameResolver.smithyTypesNamespace(inputShape)); - if (outputType.equals("")) { - validationCheck += "return opaqueErr }"; - } else { - validationCheck += "return nil, opaqueErr }"; - } - } - String baseClientCall; - if (inputShape.hasTrait(UnitTypeTrait.class)) { - baseClientCall = - "var dafny_response = client.DafnyClient.%s()".formatted( - operationShape.getId().getName() - ); - } else { - baseClientCall = - """ - var dafny_request %s = %s(params) - var dafny_response = client.DafnyClient.%s(dafny_request) - """.formatted( - DafnyNameResolver.getDafnyType( - inputShape, - symbolProvider.toSymbol(inputShape) - ), - SmithyNameResolver.getToDafnyMethodName( - service, - inputShape, - "" - ), - operationShape.getId().getName() - ); - } - String returnResponse, returnError; - if (outputShape.hasTrait(UnitTypeTrait.class)) { - returnResponse = "return nil"; - returnError = "return"; - } else { - returnResponse = - """ - var native_response = %s(dafny_response.Extract().(%s)) - return &native_response, nil - """.formatted( - SmithyNameResolver.getFromDafnyMethodName( - service, - outputShape, - "" - ), - DafnyNameResolver.getDafnyType( - outputShape, - symbolProvider.toSymbol(outputShape) - ) - ); - returnError = "return nil,"; + private void generateService(GoWriter writer) { + if (service.hasTrait(LocalServiceTrait.class)) { + generateClient(writer); + generateUnmodelledErrors(context); + generateReferencedResources(context); + generateUnboundedStructures(context); } + generateShim(); - writer.write( - """ - func (client *$T) $L(ctx context.Context $L) ($L error) { - $L - $L - if (dafny_response.Is_Failure()) { - err := dafny_response.Dtor_error().($L.Error); - $L Error_FromDafny(err) - } - $L - } - """, - serviceSymbol, - operationShape.getId().getName(), - inputType, - outputType, - validationCheck, - baseClientCall, - DafnyNameResolver.dafnyTypesNamespace(service), - returnError, - returnResponse - ); - }); - } - - void generateShim() { - final var namespace = - "%swrapped".formatted(DafnyNameResolver.dafnyNamespace(service)); - - writerDelegator.useFileWriter( - "%s/shim.go".formatted(namespace), - namespace, - writer -> { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - context.settings().getService().getNamespace() - ), - DafnyNameResolver.dafnyTypesNamespace(service) - ); - writer.addImportFromModule( - "github.com/dafny-lang/DafnyStandardLibGo", - "Wrappers" - ); - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - context.settings().getService().getNamespace() - ), - SmithyNameResolver.smithyTypesNamespace(service) - ); + } + void generateClient(GoWriter writer) { + // Generate each operation for the service. We do this here instead of via the operation visitor method to + // limit it to the operations bound to the service. + final var serviceSymbol = symbolProvider.toSymbol(service); + final var serviceTrait = service.expectTrait(LocalServiceTrait.class); + final var configSymbol = symbolProvider.toSymbol(model.expectShape(serviceTrait.getConfigId())); + + writerDelegator.useFileWriter("%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), SmithyNameResolver.smithyTypesNamespace(service), writer1 -> { + new StructureGenerator(context, writer1, + model.expectShape(serviceTrait.getConfigId()).asStructureShape().get()).run(); + model.getUnionShapes().stream() + .filter(unionShape -> unionShape.getId().getNamespace().equals(service.getId().getNamespace())) + .forEach(unionShape -> { + new UnionGenerator(model, symbolProvider, unionShape).generateUnion(writer1); + }); + }); + + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(service)); + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), DafnyNameResolver.dafnyNamespace(service)); + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.smithyTypesNamespace(service)); writer.addUseImports(SmithyGoDependency.CONTEXT); - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - context.settings().getService().getNamespace() - ), - SmithyNameResolver.shapeNamespace(service) - ); - if (service.hasTrait(LocalServiceTrait.class)) { - final var serviceTrait = service.expectTrait(LocalServiceTrait.class); - final var configShape = model.expectShape(serviceTrait.getConfigId()); - final var configSymbol = symbolProvider.toSymbol(configShape); - - writer.write( - """ - type Shim struct { - $L - client *$L.Client + final var dafnyClient = DafnyNameResolver.getDafnyClient(service, serviceTrait.getSdkId()); + writer.write(""" + type $T struct { + DafnyClient *$L + } + + func NewClient(clientConfig $L) (*$T, error) { + var dafnyConfig = $L(clientConfig) + var dafny_response = $L(dafnyConfig) + if (dafny_response.Is_Failure()) { + panic("Client construction failed. This should never happen") + } + var dafnyClient = dafny_response.Extract().(*$L) + client := &$T { dafnyClient } + return client, nil + } + """, + serviceSymbol, dafnyClient, SmithyNameResolver.getSmithyType(service, configSymbol), serviceSymbol, + SmithyNameResolver.getToDafnyMethodName(service, context.model().expectShape(serviceTrait.getConfigId()), ""), + DafnyNameResolver.createDafnyClient(service, serviceTrait.getSdkId()), + dafnyClient, serviceSymbol); + + service.getOperations().forEach(operation -> { + final var operationShape = model.expectShape(operation, OperationShape.class); + final var inputShape = model.expectShape(operationShape.getInputShape()); + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(inputShape.toShapeId().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(inputShape)); + if (!inputShape.toShapeId().getNamespace().equals(service.toShapeId().getNamespace())) { + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(inputShape.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(inputShape)); + } + final var outputShape = model.expectShape(operationShape.getOutputShape()); + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(outputShape.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(outputShape)); + if (!outputShape.toShapeId().getNamespace().equals(service.toShapeId().getNamespace())) { + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(outputShape.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(outputShape)); } final var inputType = inputShape.hasTrait(UnitTypeTrait.class) ? "" : ", params %s.%s".formatted(SmithyNameResolver.smithyTypesNamespace(inputShape), inputShape.toShapeId().getName()); @@ -430,34 +199,51 @@ void generateShim() { validationCheck, baseClientCall, DafnyNameResolver.dafnyTypesNamespace(service), returnError, returnResponse ); - final var inputShape = model.expectShape( - operationShape.getInputShape() - ); - final var outputShape = model.expectShape( - operationShape.getOutputShape() - ); - final var inputType = inputShape.hasTrait(UnitTypeTrait.class) - ? "" - : "input %s".formatted( - DafnyNameResolver.getDafnyType( - inputShape, - symbolProvider.toSymbol(inputShape) - ) - ); + }); + } + + void generateShim() { + final var namespace = "%swrapped".formatted(DafnyNameResolver.dafnyNamespace(service)); - final var typeConversion = inputShape.hasTrait(UnitTypeTrait.class) - ? "" - : "var native_request = %s(input)".formatted( - SmithyNameResolver.getFromDafnyMethodName(inputShape, "") + writerDelegator.useFileWriter("%s/shim.go".formatted(namespace), namespace, writer -> { + + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(service)); + writer.addImportFromModule("github.com/dafny-lang/DafnyStandardLibGo", "Wrappers"); + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.smithyTypesNamespace(service)); + writer.addUseImports(SmithyGoDependency.CONTEXT); + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.shapeNamespace(service)); + + if (service.hasTrait(LocalServiceTrait.class)) { + final var serviceTrait = service.expectTrait(LocalServiceTrait.class); + final var configShape = model.expectShape(serviceTrait.getConfigId()); + final var configSymbol = symbolProvider.toSymbol(configShape); + + writer.write(""" + type Shim struct { + $L + client *$L.Client + } + """, + DafnyNameResolver.getDafnyInterfaceClient(service), + SmithyNameResolver.shapeNamespace(service) ); - final var clientCall = - "shim.client.%s(context.Background() %s)".formatted( - operationShape.getId().getName(), - inputShape.hasTrait(UnitTypeTrait.class) - ? "" - : ", native_request" + writer.write(""" + func Wrapped$L(inputConfig $L) Wrappers.Result { + var nativeConfig = $L.$L(inputConfig) + var nativeClient, nativeError = $L.NewClient(nativeConfig) + if nativeError != nil { + return Wrappers.Companion_Result_.Create_Failure_($L.Companion_Error_.Create_Opaque_(nativeError)) + } + return Wrappers.Companion_Result_.Create_Success_(&Shim{client: nativeClient}) + } + """, + serviceTrait.getSdkId(), DafnyNameResolver.getDafnyType(configShape, configSymbol), + SmithyNameResolver.shapeNamespace(model.expectShape(serviceTrait.getConfigId())), SmithyNameResolver.getFromDafnyMethodName(service, model.expectShape(serviceTrait.getConfigId()), ""), + SmithyNameResolver.shapeNamespace(service), DafnyNameResolver.dafnyTypesNamespace(service) ); + } + service.getOperations().forEach(operation -> { final var operationShape = model.expectShape(operation, OperationShape.class); @@ -512,480 +298,260 @@ void generateShim() { }); }); } - } - - void resourceErrors(GoWriter writer) { - for (final var error : model.getShapesWithTrait(ErrorTrait.class)) { - writer.write( - """ - case $L: - return Wrappers.Companion_Result_.Create_Failure_($L(native_error.($L))) + void shimErrors(GoWriter writer) { + for (final var error : model.getShapesWithTrait(ErrorTrait.class)) { + writer.write(""" + case $L.$L: + return Wrappers.Companion_Result_.Create_Failure_($L(native_error.($L.$L))) + + + """, + SmithyNameResolver.smithyTypesNamespace(error), + symbolProvider.toSymbol(error).getName(), + SmithyNameResolver.getToDafnyMethodName(service, error, ""), SmithyNameResolver.smithyTypesNamespace(error), + symbolProvider.toSymbol(error).getName()); + } + } - """, - SmithyNameResolver.getSmithyType(error, symbolProvider.toSymbol(error)), - SmithyNameResolver.getToDafnyMethodName(service, error, ""), - SmithyNameResolver.getSmithyType(error, symbolProvider.toSymbol(error)) - ); + void resourceErrors(GoWriter writer) { + for (final var error : model.getShapesWithTrait(ErrorTrait.class)) { + writer.write(""" + case $L: + return Wrappers.Companion_Result_.Create_Failure_($L(native_error.($L))) + + + """, + SmithyNameResolver.getSmithyType(error, symbolProvider.toSymbol(error)), SmithyNameResolver.getToDafnyMethodName(service, error, ""), + SmithyNameResolver.getSmithyType(error, symbolProvider.toSymbol(error))); + } } - } - - void generateUnmodelledErrors(GenerationContext context) { - writerDelegator.useFileWriter( - "%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), - SmithyNameResolver.smithyTypesNamespace(service), - writer -> { - writer.write( - """ - type $LBaseException interface { - // This is a dummy method to allow type assertion since Go empty interfaces - // aren't useful for type assertion checks. No concrete class is expected to implement - // this method. This is also not exported. - interfaceBindingMethod() - } - """, - service.toShapeId().getName() - ); - } - ); - writerDelegator.useFileWriter( - "%s/unmodelled_errors.go".formatted( - SmithyNameResolver.smithyTypesNamespace(service) - ), - SmithyNameResolver.smithyTypesNamespace(service), - writer -> { - writer.addUseImports(SmithyGoDependency.FMT); - writer.write( - """ - type CollectionOfErrors struct { - $LBaseException - ListOfErrors []error - Message string - } - - func (e CollectionOfErrors) Error() string { - return fmt.Sprintf("message: %s\\n err %v", e.Message, e.ListOfErrors) - } - - type OpaqueError struct { - $LBaseException - ErrObject interface{} - } - - func (e OpaqueError) Error() string { - return fmt.Sprintf("message: %v", e.ErrObject ) - } - """, - service.toShapeId().getName(), - service.toShapeId().getName() - ); - } - ); - } - - void generateUnboundedStructures(GenerationContext context) { - final var serviceOperationShapes = model - .getServiceShapes() - .stream() - .map(topDownIndex::getContainedOperations) - .flatMap(Collection::stream) - .map(OperationShape::toShapeId) - .collect(Collectors.toSet()); - final var nonServiceOperationShapes = model - .getOperationShapes() - .stream() - .map(Shape::getId) - .filter(operationShapeId -> - operationShapeId.getNamespace().equals(service.getId().getNamespace()) - ) - .collect(Collectors.toSet()); - nonServiceOperationShapes.removeAll(serviceOperationShapes); - for (final var operationShapeId : nonServiceOperationShapes) { - OperationShape operationShape = model.expectShape( - operationShapeId, - OperationShape.class - ); - StructureShape inputShape = model.expectShape( - operationShape.getInputShape(), - StructureShape.class - ); - writerDelegator.useShapeWriter( - inputShape, - w -> new StructureGenerator(context, w, inputShape).run() - ); - StructureShape outputShape = model.expectShape( - operationShape.getOutputShape(), - StructureShape.class - ); - writerDelegator.useShapeWriter( - outputShape, - w -> new StructureGenerator(context, w, outputShape).run() - ); + + void generateUnmodelledErrors(GenerationContext context) { + writerDelegator.useFileWriter("%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), SmithyNameResolver.smithyTypesNamespace(service), writer -> { + writer.write(""" + type $LBaseException interface { + // This is a dummy method to allow type assertion since Go empty interfaces + // aren't useful for type assertion checks. No concrete class is expected to implement + // this method. This is also not exported. + interfaceBindingMethod() + } + """, service.toShapeId().getName()); + }); + writerDelegator.useFileWriter("%s/unmodelled_errors.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), SmithyNameResolver.smithyTypesNamespace(service), writer -> { + writer.addUseImports(SmithyGoDependency.FMT); + writer.write(""" + type CollectionOfErrors struct { + $LBaseException + ListOfErrors []error + Message string + } + + func (e CollectionOfErrors) Error() string { + return fmt.Sprintf("message: %s\\n err %v", e.Message, e.ListOfErrors) + } + + type OpaqueError struct { + $LBaseException + ErrObject interface{} + } + + func (e OpaqueError) Error() string { + return fmt.Sprintf("message: %v", e.ErrObject ) + } + """, service.toShapeId().getName(), service.toShapeId().getName()); + }); } - } - - void generateReferencedResources(GenerationContext context) { - var refResources = model.getShapesWithTrait(ReferenceTrait.class); - for (final var refResource : refResources) { - if (!refResource.expectTrait(ReferenceTrait.class).isService()) { - final var resource = refResource - .expectTrait(ReferenceTrait.class) - .getReferentId(); - final var resourceShape = model.expectShape(resource); - - if ( - !service.toShapeId().getNamespace().equals(resource.getNamespace()) - ) { - continue; - } - writerDelegator.useFileWriter( - "%s/types.go".formatted( - SmithyNameResolver.smithyTypesNamespace(service) - ), - SmithyNameResolver.smithyTypesNamespace(service), - writer -> { - writer.write( - """ - type I$L interface { - ${C|} - } - """, - resource.getName(), - writer.consumer(w -> { - model - .expectShape(resource, ResourceShape.class) - .getOperations() - .forEach(operation -> { - var operationShape = model.expectShape( - operation, - OperationShape.class - ); - w.write( - """ - $L($L) (*$L, error) - """, - operationShape.getId().getName(), - operationShape.getInputShape().getName(), - operationShape.getOutputShape().getName() - ); - }); - }) - ); - } - ); - - if ( - model - .expectShape(resource, ResourceShape.class) - .hasTrait(ExtendableTrait.class) - ) { - generateNativeResourceWrapper( - context, - model.expectShape(resource, ResourceShape.class) - ); + + void generateUnboundedStructures(GenerationContext context) { + final var serviceOperationShapes = model.getServiceShapes().stream() + .map(topDownIndex::getContainedOperations) + .flatMap(Collection::stream) + .map(OperationShape::toShapeId) + .collect(Collectors.toSet()); + final var nonServiceOperationShapes = model.getOperationShapes() + .stream() + .map(Shape::getId) + .filter(operationShapeId -> operationShapeId.getNamespace() + .equals(service.getId().getNamespace())) + .collect(Collectors.toSet()); + nonServiceOperationShapes.removeAll(serviceOperationShapes); + for (final var operationShapeId : nonServiceOperationShapes) { + OperationShape operationShape = model.expectShape(operationShapeId, OperationShape.class); + StructureShape inputShape = model.expectShape(operationShape.getInputShape(), StructureShape.class); + writerDelegator.useShapeWriter(inputShape, w -> new StructureGenerator(context, w, inputShape).run()); + StructureShape outputShape = model.expectShape(operationShape.getOutputShape(), StructureShape.class); + writerDelegator.useShapeWriter(outputShape, w -> new StructureGenerator(context, w, outputShape).run()); } + } - writerDelegator.useFileWriter( - "%s/%s.go".formatted( - SmithyNameResolver.shapeNamespace(service), - resource.getName() - ), - SmithyNameResolver.shapeNamespace(service), - writer -> { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - context.settings().getService().getNamespace() - ), - SmithyNameResolver.smithyTypesNamespace(service) - ); - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - resource.getNamespace() - ), - DafnyNameResolver.dafnyTypesNamespace(resourceShape) - ); - writer.write( - """ - type %s struct { - Impl %s.I%s - } - """.formatted( - resource.getName(), - DafnyNameResolver.dafnyTypesNamespace(resourceShape), - resource.getName() - ) - ); + void generateReferencedResources(GenerationContext context) { + var refResources = model.getShapesWithTrait(ReferenceTrait.class); + for (final var refResource : refResources) { + if (!refResource.expectTrait(ReferenceTrait.class).isService()) { + final var resource = refResource.expectTrait(ReferenceTrait.class).getReferentId(); + final var resourceShape = model.expectShape(resource); - model - .expectShape(resource, ResourceShape.class) - .getOperations() - .forEach(operation -> { - final var operationShape = model.expectShape( - operation, - OperationShape.class - ); - final var inputShape = model.expectShape( - operationShape.getInputShape() - ); + if (!service.toShapeId().getNamespace().equals(resource.getNamespace())) { - final var outputShape = model.expectShape( - operationShape.getOutputShape() - ); - final var inputType = inputShape.hasTrait(UnitTypeTrait.class) - ? "" - : "params %s".formatted( - SmithyNameResolver.getSmithyType( - inputShape, - symbolProvider.toSymbol(inputShape) - ) - ); - final var outputType = outputShape.hasTrait(UnitTypeTrait.class) - ? "" - : "*%s".formatted( - SmithyNameResolver.getSmithyType( - outputShape, - symbolProvider.toSymbol(outputShape) - ) - ); - - String baseClientCall; - if (inputShape.hasTrait(UnitTypeTrait.class)) { - baseClientCall = - "var dafny_response = this.Impl.%s()".formatted( - operationShape.getId().getName() - ); - } else { - baseClientCall = - """ - var dafny_request %s = %s(params) - var dafny_response = this.Impl.%s(dafny_request) - """.formatted( - DafnyNameResolver.getDafnyType( - inputShape, - symbolProvider.toSymbol(inputShape) - ), - SmithyNameResolver.getToDafnyMethodName( - service, - inputShape, - "" - ), - operationShape.getId().getName() - ); + continue; } - - String returnResponse, returnError; - if (outputShape.hasTrait(UnitTypeTrait.class)) { - returnResponse = "return nil"; - returnError = "return"; - } else { - returnResponse = - """ - var native_response = %s(dafny_response.Extract().(%s)) - return &native_response, nil - """.formatted( - SmithyNameResolver.getFromDafnyMethodName( - service, - outputShape, - "" - ), - DafnyNameResolver.getDafnyType( - inputShape, - symbolProvider.toSymbol(outputShape) - ) - ); - returnError = "return nil,"; + writerDelegator.useFileWriter("%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), SmithyNameResolver.smithyTypesNamespace(service), writer -> { + writer.write(""" + type I$L interface { + ${C|} + } + """, resource.getName(), writer.consumer((w) -> { + model.expectShape(resource, ResourceShape.class).getOperations().forEach(operation -> { + var operationShape = model.expectShape(operation, OperationShape.class); + w.write(""" + $L($L) (*$L, error) + """, operationShape.getId().getName(), operationShape.getInputShape().getName(), operationShape.getOutputShape().getName()); + }); + })); + }); + + if (model.expectShape(resource, ResourceShape.class).hasTrait(ExtendableTrait.class)) { + generateNativeResourceWrapper(context, model.expectShape(resource, ResourceShape.class)); } - writer.write( - """ - func (this *$L) $L($L) ($L, error) { - $L - if (dafny_response.Is_Failure()) { - err := dafny_response.Dtor_error().($L.Error); - ${C|} - if err.Is_CollectionOfErrors() { - $L CollectionOfErrors_Output_FromDafny(err) - } - if err.Is_Opaque() { - $L OpaqueError_Output_FromDafny(err) - } + writerDelegator.useFileWriter("%s/%s.go".formatted(SmithyNameResolver.shapeNamespace(service), resource.getName()), SmithyNameResolver.shapeNamespace(service), writer -> { + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.smithyTypesNamespace(service)); + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resource.getNamespace()), DafnyNameResolver.dafnyTypesNamespace(resourceShape)); + writer.write(""" + type %s struct { + Impl %s.I%s + } + """.formatted(resource.getName(), DafnyNameResolver.dafnyTypesNamespace(resourceShape), resource.getName())); + + model.expectShape(resource, ResourceShape.class).getOperations().forEach(operation -> { + final var operationShape = model.expectShape(operation, OperationShape.class); + final var inputShape = model.expectShape(operationShape.getInputShape()); + + + final var outputShape = model.expectShape(operationShape.getOutputShape()); + final var inputType = inputShape.hasTrait(UnitTypeTrait.class) ? "" : "params %s".formatted(SmithyNameResolver.getSmithyType(inputShape, symbolProvider.toSymbol(inputShape))); + final var outputType = outputShape.hasTrait(UnitTypeTrait.class) ? "" : "*%s".formatted(SmithyNameResolver.getSmithyType(outputShape, symbolProvider.toSymbol(outputShape))); + + String baseClientCall; + if (inputShape.hasTrait(UnitTypeTrait.class)) { + baseClientCall = "var dafny_response = this.Impl.%s()".formatted(operationShape.getId().getName()); + } else { + baseClientCall = """ + var dafny_request %s = %s(params) + var dafny_response = this.Impl.%s(dafny_request) + """.formatted(DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(inputShape)), + SmithyNameResolver.getToDafnyMethodName(service, inputShape, ""), operationShape.getId().getName()); } - $L - } - """, - resource.getName(), - operationShape.getId().getName(), - inputType, - outputType, - baseClientCall, - DafnyNameResolver.dafnyTypesNamespace(service), - writer.consumer(w -> { - for (var errorShape : model.getShapesWithTrait( - ErrorTrait.class - )) { - w.write( - """ - if err.Is_$L() { - $L $L(err) - } - """, - errorShape.toShapeId().getName(), - returnError, - SmithyNameResolver.getFromDafnyMethodName( - service, - errorShape, - "" - ) - ); - } - }), - returnError, - returnError, - returnResponse - ); - }); - } - ); - } else { - //Generate Service - } - } - } - - void generateNativeResourceWrapper( - GenerationContext context, - ResourceShape resourceShape - ) { - writerDelegator.useFileWriter( - "%s/NativeWrapper.go".formatted( - SmithyNameResolver.shapeNamespace(service) - ), - SmithyNameResolver.shapeNamespace(service), - writer -> { - writer.addImportFromModule( - context.settings().getModuleName(), - SmithyNameResolver.smithyTypesNamespace(service) - ); - writer.addImportFromModule( - "github.com/dafny-lang/DafnyStandardLibGo", - "Wrappers" - ); - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - resourceShape.toShapeId().getNamespace() - ), - DafnyNameResolver.dafnyTypesNamespace(resourceShape) - ); - - writer.write( - """ - type NativeWrapper struct { - %s.I%s - Impl %s.I%s - } - """.formatted( - DafnyNameResolver.dafnyTypesNamespace(resourceShape), - resourceShape.getId().getName(), - SmithyNameResolver.smithyTypesNamespace(resourceShape), - resourceShape.getId().getName() - ) - ); - - resourceShape - .getOperations() - .forEach(operation -> { - final var operationShape = model.expectShape( - operation, - OperationShape.class - ); - final var inputShape = model.expectShape( - operationShape.getInputShape() - ); - final var outputShape = model.expectShape( - operationShape.getOutputShape() - ); - final var inputType = inputShape.hasTrait(UnitTypeTrait.class) - ? "" - : "input %s".formatted( - DafnyNameResolver.getDafnyType( - resourceShape, - symbolProvider.toSymbol(inputShape) - ) - ); - final var outputType = outputShape.hasTrait(UnitTypeTrait.class) - ? "" - : "*%s,".formatted( - SmithyNameResolver.getSmithyType( - outputShape, - symbolProvider.toSymbol(outputShape) - ) - ); - final var typeConversion = inputShape.hasTrait(UnitTypeTrait.class) - ? "" - : "var native_request = %s(input)".formatted( - SmithyNameResolver.getFromDafnyMethodName( - service, - inputShape, - "" - ) - ); - final var clientCall = - "this.Impl.%s(%s)".formatted( - operationShape.getId().getName(), - inputShape.hasTrait(UnitTypeTrait.class) - ? "" - : "native_request" - ); - String clientResponse, returnResponse; - if (outputShape.hasTrait(UnitTypeTrait.class)) { - clientResponse = "var native_error"; - returnResponse = "dafny.TupleOf()"; - writer.addImportFromModule( - "github.com/dafny-lang/DafnyRuntimeGo", - "dafny" - ); + String returnResponse, returnError; + if (outputShape.hasTrait(UnitTypeTrait.class)) { + returnResponse = "return nil"; + returnError = "return"; + } else { + returnResponse = """ + var native_response = %s(dafny_response.Extract().(%s)) + return &native_response, nil + """.formatted(SmithyNameResolver.getFromDafnyMethodName(service, outputShape, ""), + DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(outputShape))); + returnError = "return nil,"; + } + + + writer.write(""" + func (this *$L) $L($L) ($L, error) { + $L + if (dafny_response.Is_Failure()) { + err := dafny_response.Dtor_error().($L.Error); + ${C|} + if err.Is_CollectionOfErrors() { + $L CollectionOfErrors_Output_FromDafny(err) + } + if err.Is_Opaque() { + $L OpaqueError_Output_FromDafny(err) + } + } + $L + } + """, + resource.getName(), + operationShape.getId().getName(), + inputType, outputType, + baseClientCall, + DafnyNameResolver.dafnyTypesNamespace(service), + writer.consumer(w -> { + for (var errorShape : + model.getShapesWithTrait(ErrorTrait.class)) { + w.write(""" + if err.Is_$L() { + $L $L(err) + } + """, errorShape.toShapeId().getName(), returnError, SmithyNameResolver.getFromDafnyMethodName(service, errorShape, "")); + } + }), returnError, returnError, returnResponse + ); + }); + }); } else { - clientResponse = "var native_response, native_error"; - returnResponse = - "%s(*native_response)".formatted( - SmithyNameResolver.getToDafnyMethodName( - service, - outputShape, - "" - ) - ); + //Generate Service } - writer.write( - """ - func (this *NativeWrapper) $L($L) Wrappers.Result { - $L - $L = $L - if native_error != nil { - switch native_error.(type) { - ${C|} - case $L.CollectionOfErrors: - return Wrappers.Companion_Result_.Create_Failure_(CollectionOfErrors_Input_ToDafny(native_error.($L.CollectionOfErrors))) - default: - return Wrappers.Companion_Result_.Create_Failure_(OpaqueError_Input_ToDafny(native_error.($L.OpaqueError))) - } - } - return Wrappers.Companion_Result_.Create_Success_($L) + } + } + + void generateNativeResourceWrapper(GenerationContext context, ResourceShape resourceShape) { + writerDelegator.useFileWriter("%s/NativeWrapper.go".formatted(SmithyNameResolver.shapeNamespace(service)), SmithyNameResolver.shapeNamespace(service), writer -> { + writer.addImportFromModule(context.settings().getModuleName(), SmithyNameResolver.smithyTypesNamespace(service)); + writer.addImportFromModule("github.com/dafny-lang/DafnyStandardLibGo", "Wrappers"); + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resourceShape.toShapeId().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(resourceShape)); + + writer.write(""" + type NativeWrapper struct { + %s.I%s + Impl %s.I%s + } + """.formatted(DafnyNameResolver.dafnyTypesNamespace(resourceShape), resourceShape.getId().getName(), SmithyNameResolver.smithyTypesNamespace(resourceShape), resourceShape.getId().getName())); + + resourceShape.getOperations().forEach(operation -> { + final var operationShape = model.expectShape(operation, OperationShape.class); + final var inputShape = model.expectShape(operationShape.getInputShape()); + final var outputShape = model.expectShape(operationShape.getOutputShape()); + final var inputType = inputShape.hasTrait(UnitTypeTrait.class) ? "" : "input %s".formatted(DafnyNameResolver.getDafnyType(resourceShape, symbolProvider.toSymbol(inputShape))); + final var outputType = outputShape.hasTrait(UnitTypeTrait.class) ? "" : "*%s,".formatted(SmithyNameResolver.getSmithyType(outputShape, symbolProvider.toSymbol(outputShape))); + + final var typeConversion = inputShape.hasTrait(UnitTypeTrait.class) ? "" : "var native_request = %s(input)".formatted(SmithyNameResolver.getFromDafnyMethodName(service, inputShape, "")); + final var clientCall = "this.Impl.%s(%s)".formatted(operationShape.getId().getName(), inputShape.hasTrait(UnitTypeTrait.class) ? "" : "native_request"); + String clientResponse, returnResponse; + if (outputShape.hasTrait(UnitTypeTrait.class)) { + clientResponse = "var native_error"; + returnResponse = "dafny.TupleOf()"; + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + } else { + clientResponse = "var native_response, native_error"; + returnResponse = "%s(*native_response)".formatted( + SmithyNameResolver.getToDafnyMethodName(service, outputShape, "")); } - """, - operationShape.getId().getName(), - inputType, - typeConversion, - clientResponse, - clientCall, - writer.consumer(w -> resourceErrors(w)), - SmithyNameResolver.smithyTypesNamespace(service), - SmithyNameResolver.smithyTypesNamespace(service), - SmithyNameResolver.smithyTypesNamespace(service), - returnResponse - ); - }); - } - ); - } + writer.write(""" + func (this *NativeWrapper) $L($L) Wrappers.Result { + $L + $L = $L + if native_error != nil { + switch native_error.(type) { + ${C|} + case $L.CollectionOfErrors: + return Wrappers.Companion_Result_.Create_Failure_(CollectionOfErrors_Input_ToDafny(native_error.($L.CollectionOfErrors))) + default: + return Wrappers.Companion_Result_.Create_Failure_(OpaqueError_Input_ToDafny(native_error.($L.OpaqueError))) + } + } + return Wrappers.Companion_Result_.Create_Success_($L) + } + """, + operationShape.getId().getName(), + inputType, typeConversion, clientResponse, clientCall, + writer.consumer(w -> resourceErrors(w)), SmithyNameResolver.smithyTypesNamespace(service), SmithyNameResolver.smithyTypesNamespace(service), SmithyNameResolver.smithyTypesNamespace(service), + returnResponse + ); + }); + }); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java index a2382f988f..fb8ac01d2e 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java @@ -1,8 +1,5 @@ package software.amazon.polymorph.smithygo.localservice; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Set; import software.amazon.polymorph.smithygo.codegen.ApplicationProtocol; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoDelegator; @@ -25,133 +22,23 @@ import software.amazon.smithy.model.traits.UnitTypeTrait; import software.amazon.smithy.codegen.core.Symbol; -public class DafnyLocalServiceTypeConversionProtocol - implements ProtocolGenerator { - - public static String TO_DAFNY = "to_dafny.go"; - public static String TO_NATIVE = "to_native.go"; - - @Override - public ShapeId getProtocol() { - return ShapeId.from("aws.polymorph#localService"); - } +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Set; - @Override - public ApplicationProtocol getApplicationProtocol() { - return null; - } +public class DafnyLocalServiceTypeConversionProtocol implements ProtocolGenerator { + public static String TO_DAFNY = "to_dafny.go"; + public static String TO_NATIVE = "to_native.go"; - @Override - public void generateSerializers(GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var model = context.model(); - final var serviceShape = model.expectShape( - context.settings().getService(), - ServiceShape.class - ); - final var symbolProvider = context.symbolProvider(); - final var writerDelegator = context.writerDelegator(); - serviceShape - .getOperations() - .forEach(eachOperation -> { - final var operation = model.expectShape( - eachOperation, - OperationShape.class - ); - final var input = model.expectShape(operation.getInputShape()); - if (!alreadyVisited.contains(input.toShapeId())) { - alreadyVisited.add(input.toShapeId()); - if ( - !input.hasTrait(UnitTypeTrait.class) && - input - .toShapeId() - .getNamespace() - .equals(serviceShape.toShapeId().getNamespace()) - ) { - final var inputToDafnyMethodName = - SmithyNameResolver.getToDafnyMethodName(serviceShape, input, ""); - final var inputSymbol = symbolProvider.toSymbol(input); - writerDelegator.useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_DAFNY - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - input.toShapeId().getNamespace() - ), - SmithyNameResolver.smithyTypesNamespace(input) - ); - writer.write( - """ - func $L(nativeInput $L)($L) { - ${C|} - }""", - inputToDafnyMethodName, - SmithyNameResolver.getSmithyType(input, inputSymbol), - DafnyNameResolver.getDafnyType(input, inputSymbol), - writer.consumer(w -> - generateRequestSerializer( - context, - operation, - context.writerDelegator() - ) - ) - ); - } - ); - } - } + @Override + public ShapeId getProtocol() { + return ShapeId.from("aws.polymorph#localService"); + } - final var output = model.expectShape(operation.getOutputShape()); - if (!alreadyVisited.contains(output.toShapeId())) { - alreadyVisited.add(output.toShapeId()); - if ( - !output.hasTrait(UnitTypeTrait.class) && - output - .toShapeId() - .getNamespace() - .equals(serviceShape.toShapeId().getNamespace()) - ) { - final var outputToDafnyMethodName = - SmithyNameResolver.getToDafnyMethodName(serviceShape, output, ""); - final var outputSymbol = symbolProvider.toSymbol(output); - writerDelegator.useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_DAFNY - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - output.toShapeId().getNamespace() - ), - SmithyNameResolver.smithyTypesNamespace(output) - ); - writer.write( - """ - func $L(nativeOutput $L)($L) { - ${C|} - }""", - outputToDafnyMethodName, - SmithyNameResolver.getSmithyType(output, outputSymbol), - DafnyNameResolver.getDafnyType(output, outputSymbol), - writer.consumer(w -> - generateResponseSerializer( - context, - operation, - context.writerDelegator() - ) - ) - ); - } - ); - } - } - }); + @Override + public ApplicationProtocol getApplicationProtocol() { + return null; + } @Override public void generateSerializers(GenerationContext context) { @@ -207,205 +94,91 @@ public void generateSerializers(GenerationContext context) { }); } } - if ( - !alreadyVisited.contains(resourceShape.toShapeId()) && - resourceShape - .toShapeId() - .getNamespace() - .equals(serviceShape.toShapeId().getNamespace()) - ) { - alreadyVisited.add(resourceShape.toShapeId()); - writerDelegator.useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_DAFNY - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - var goBody = - """ - return nativeResource.(*%s).Impl - """.formatted(resourceShape.getId().getName()); - if (resourceShape.hasTrait(ExtendableTrait.class)) { - goBody = - """ - val, ok := nativeResource.(*%s) - if ok { - return val.Impl - } - return %s{&NativeWrapper{Impl: nativeResource}}.Impl - """.formatted( - resourceShape.getId().getName(), - resourceShape.getId().getName() - ); - } - writer.write( - """ - func $L_ToDafny(nativeResource $L.I$L) $L.I$L { - $L + }); + + final var refResources = context.model().getShapesWithTrait(ReferenceTrait.class); + for (var refResource : refResources) { + final var resource = refResource.expectTrait(ReferenceTrait.class).getReferentId(); + if (!refResource.expectTrait(ReferenceTrait.class).isService()) { + var resourceShape = model.expectShape(resource, ResourceShape.class); + resourceShape.getOperations().forEach(eachOperation -> { + final var operation = model.expectShape(eachOperation, OperationShape.class); + final var input = model.expectShape(operation.getInputShape()); + if (!alreadyVisited.contains(input.toShapeId())) { + alreadyVisited.add(input.toShapeId()); + if (!input.hasTrait(UnitTypeTrait.class) && input.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { + final var inputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, input, ""); + final var inputSymbol = symbolProvider.toSymbol(input); + writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(input.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(input)); + writer.write(""" + func $L(nativeInput $L)($L) { + ${C|} + }""", inputToDafnyMethodName, SmithyNameResolver.getSmithyType(input, inputSymbol), + DafnyNameResolver.getDafnyType(input, inputSymbol), + writer.consumer(w -> generateRequestSerializer(context, operation, context.writerDelegator()))); + }); + } } - """, - resourceShape.getId().getName(), - SmithyNameResolver.smithyTypesNamespace(resourceShape), - resourceShape.getId().getName(), - DafnyNameResolver.dafnyTypesNamespace(resourceShape), - resourceShape.getId().getName(), - goBody - ); - } - ); - } - }); - } - } - generateErrorSerializer(context); - if (serviceShape.hasTrait(LocalServiceTrait.class)) { - generateConfigSerializer(context); - } - } - - @Override - public void generateDeserializers(GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var serviceShape = context.settings().getService(context.model()); - final var delegator = context.writerDelegator(); - - serviceShape - .getOperations() - .forEach(eachOperation -> { - var operation = context - .model() - .expectShape(eachOperation, OperationShape.class); - - final var input = context - .model() - .expectShape(operation.getInputShape()); - if (!alreadyVisited.contains(input.toShapeId())) { - alreadyVisited.add(input.toShapeId()); - if ( - !input.hasTrait(UnitTypeTrait.class) && - input - .toShapeId() - .getNamespace() - .equals(serviceShape.toShapeId().getNamespace()) - ) { - final var inputFromDafnyMethodName = - SmithyNameResolver.getFromDafnyMethodName( - serviceShape, - input, - "" - ); - final var inputSymbol = context.symbolProvider().toSymbol(input); - delegator.useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - input.toShapeId().getNamespace() - ), - SmithyNameResolver.smithyTypesNamespace(input) - ); - writer.write( - """ - func $L(dafnyInput $L)($L) { - ${C|} - }""", - inputFromDafnyMethodName, - DafnyNameResolver.getDafnyType(input, inputSymbol), - SmithyNameResolver.getSmithyType(input, inputSymbol), - writer.consumer(w -> - generateRequestDeserializer( - context, - operation, - context.writerDelegator() - ) - ) - ); - } - ); - } + final var output = model.expectShape(operation.getOutputShape()); + if (!alreadyVisited.contains(output.toShapeId())) { + alreadyVisited.add(output.toShapeId()); + if (!output.hasTrait(UnitTypeTrait.class) && output.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { + final var outputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, output, ""); + final var outputSymbol = symbolProvider.toSymbol(output); + writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(output.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(output)); + writer.write(""" + func $L(nativeOutput $L)($L) { + ${C|} + }""", outputToDafnyMethodName, SmithyNameResolver.getSmithyType(output, outputSymbol), + DafnyNameResolver.getDafnyType(output, outputSymbol), + writer.consumer(w -> generateResponseSerializer(context, operation, context.writerDelegator()))); + }); + } + } + if (!alreadyVisited.contains(resourceShape.toShapeId()) && resourceShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { + alreadyVisited.add(resourceShape.toShapeId()); + writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + var goBody = """ + return nativeResource.(*%s).Impl + """.formatted(resourceShape.getId().getName()); + if (resourceShape.hasTrait(ExtendableTrait.class)) { + goBody = """ + val, ok := nativeResource.(*%s) + if ok { + return val.Impl + } + return %s{&NativeWrapper{Impl: nativeResource}}.Impl + """.formatted(resourceShape.getId().getName(), resourceShape.getId().getName()); + } + writer.write(""" + func $L_ToDafny(nativeResource $L.I$L) $L.I$L { + $L + } + """, resourceShape.getId().getName(), SmithyNameResolver.smithyTypesNamespace(resourceShape), resourceShape.getId().getName(), DafnyNameResolver.dafnyTypesNamespace(resourceShape), resourceShape.getId().getName(), goBody); + }); + } + }); + } } - - final var output = context - .model() - .expectShape(operation.getOutputShape()); - if (!alreadyVisited.contains(output.toShapeId())) { - alreadyVisited.add(output.toShapeId()); - if ( - !output.hasTrait(UnitTypeTrait.class) && - output - .toShapeId() - .getNamespace() - .equals(serviceShape.toShapeId().getNamespace()) - ) { - final var outputFromDafnyMethodName = - SmithyNameResolver.getFromDafnyMethodName( - serviceShape, - output, - "" - ); - final var outputSymbol = context.symbolProvider().toSymbol(output); - - delegator.useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - output.toShapeId().getNamespace() - ), - SmithyNameResolver.smithyTypesNamespace(output) - ); - - writer.write( - """ - func $L(dafnyOutput $L)($L) { - ${C|} - }""", - outputFromDafnyMethodName, - DafnyNameResolver.getDafnyType(output, outputSymbol), - SmithyNameResolver.getSmithyType(output, outputSymbol), - writer.consumer(w -> - generateResponseDeserializer( - context, - operation, - context.writerDelegator() - ) - ) - ); - } - ); - } + generateErrorSerializer(context); + if (serviceShape.hasTrait(LocalServiceTrait.class)) { + generateConfigSerializer(context); } - }); + } + + @Override + public void generateDeserializers(GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var serviceShape = context.settings().getService(context.model()); + final var delegator = context.writerDelegator(); - var refResources = context.model().getShapesWithTrait(ReferenceTrait.class); - for (var refResource : refResources) { - final var resource = refResource - .expectTrait(ReferenceTrait.class) - .getReferentId(); + serviceShape.getOperations().forEach(eachOperation -> { + var operation = context.model().expectShape(eachOperation, OperationShape.class); - if (!refResource.expectTrait(ReferenceTrait.class).isService()) { - var resourceShape = context - .model() - .expectShape(resource, ResourceShape.class); - resourceShape - .getOperations() - .forEach(eachOperation -> { - final var operation = context - .model() - .expectShape(eachOperation, OperationShape.class); - final var input = context - .model() - .expectShape(operation.getInputShape()); + final var input = context.model().expectShape(operation.getInputShape()); if (!alreadyVisited.contains(input.toShapeId())) { alreadyVisited.add(input.toShapeId()); if (!input.hasTrait(UnitTypeTrait.class) && input.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { @@ -453,674 +226,444 @@ public void generateDeserializers(GenerationContext context) { }); } } - if ( - !alreadyVisited.contains(resourceShape.toShapeId()) && - resourceShape - .toShapeId() - .getNamespace() - .equals(serviceShape.toShapeId().getNamespace()) - ) { - alreadyVisited.add(resourceShape.toShapeId()); - delegator.useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - var extendableResourceWrapperCheck = ""; - if (resourceShape.hasTrait(ExtendableTrait.class)) { - extendableResourceWrapperCheck = - """ - val, ok := dafnyResource.(*NativeWrapper) - if ok { - return val.Impl - } - """; - } - writer.write( - """ - func $L_FromDafny(dafnyResource $L.I$L)($L.I$L) { - $L - return &$L{dafnyResource} + }); + + var refResources = context.model().getShapesWithTrait(ReferenceTrait.class); + for (var refResource : refResources) { + final var resource = refResource.expectTrait(ReferenceTrait.class).getReferentId(); + + if (!refResource.expectTrait(ReferenceTrait.class).isService()) { + var resourceShape = context.model().expectShape(resource, ResourceShape.class); + resourceShape.getOperations().forEach(eachOperation -> { + final var operation = context.model().expectShape(eachOperation, OperationShape.class); + final var input = context.model().expectShape(operation.getInputShape()); + if (!alreadyVisited.contains(input.toShapeId())) { + alreadyVisited.add(input.toShapeId()); + if (!input.hasTrait(UnitTypeTrait.class) && input.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { + final var inputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, input, ""); + final var inputSymbol = context.symbolProvider().toSymbol(input); + + delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(input.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(input)); + + writer.write(""" + func $L(dafnyInput $L)($L) { + ${C|} + }""", inputFromDafnyMethodName, DafnyNameResolver.getDafnyType(input, inputSymbol), + SmithyNameResolver.getSmithyType(input, inputSymbol), + writer.consumer(w -> generateRequestDeserializer(context, operation, context.writerDelegator()))); + }); + } } - """, - resourceShape.getId().getName(), - DafnyNameResolver.dafnyTypesNamespace(resourceShape), - resourceShape.getId().getName(), - SmithyNameResolver.smithyTypesNamespace(resourceShape), - resourceShape.getId().getName(), - extendableResourceWrapperCheck, - resourceShape.getId().getName() - ); - } - ); - } - }); - } - } - generateErrorDeserializer(context); - if (serviceShape.hasTrait(LocalServiceTrait.class)) { - generateConfigDeserializer(context); - } - } - - private void generateRequestSerializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - final var targetShape = context - .model() - .expectShape(operation.getInputShape()); - delegator.useFileWriter( - "%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), - SmithyNameResolver.shapeNamespace(operation), - writer -> { - final var input = targetShape.accept( - new SmithyToDafnyShapeVisitor( - context, - "nativeInput", - writer, - false, - false, - false - ) - ); - writer.write( - """ - return $L - """, - input - ); - } - ); - } - - private void generateResponseSerializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - final var targetShape = context - .model() - .expectShape(operation.getOutputShape()); - delegator.useFileWriter( - "%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), - SmithyNameResolver.shapeNamespace(operation), - writer -> { - final var input = targetShape.accept( - new SmithyToDafnyShapeVisitor( - context, - "nativeOutput", - writer, - false, - false, - false - ) - ); - writer.write( - """ - return $L - """, - input - ); - } - ); - } - private void generateRequestDeserializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - delegator.useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(operation), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace(operation), - writer -> { - final var inputShape = operation.getInputShape(); - - final var targetShape = context.model().expectShape(inputShape); - final var input = targetShape.accept( - new DafnyToSmithyShapeVisitor(context, "dafnyInput", writer, false) - ); + final var output = context.model().expectShape(operation.getOutputShape()); + if (!alreadyVisited.contains(output.toShapeId())) { + alreadyVisited.add(output.toShapeId()); + if (!output.hasTrait(UnitTypeTrait.class) && output.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { + final var outputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, output, ""); + final var outputSymbol = context.symbolProvider().toSymbol(output); + + delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(output.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(output)); + + writer.write(""" + func $L(dafnyOutput $L)($L) { + ${C|} + }""", outputFromDafnyMethodName, DafnyNameResolver.getDafnyType(output, outputSymbol), + SmithyNameResolver.getSmithyType(output, outputSymbol), + writer.consumer(w -> generateResponseDeserializer(context, operation, context.writerDelegator()))); + }); + } + } + if (!alreadyVisited.contains(resourceShape.toShapeId()) && resourceShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { + alreadyVisited.add(resourceShape.toShapeId()); + delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + var extendableResourceWrapperCheck = ""; + if (resourceShape.hasTrait(ExtendableTrait.class)) { + extendableResourceWrapperCheck = """ + val, ok := dafnyResource.(*NativeWrapper) + if ok { + return val.Impl + } + """; + } + writer.write(""" + func $L_FromDafny(dafnyResource $L.I$L)($L.I$L) { + $L + return &$L{dafnyResource} + } + """, resourceShape.getId().getName(), DafnyNameResolver.dafnyTypesNamespace(resourceShape), resourceShape.getId().getName(), SmithyNameResolver.smithyTypesNamespace(resourceShape), resourceShape.getId().getName(), extendableResourceWrapperCheck, resourceShape.getId().getName()); + }); + } - writer.write( - """ - return $L - """, - input - ); - } - ); - } + }); + } + } + generateErrorDeserializer(context); + if (serviceShape.hasTrait(LocalServiceTrait.class)) { + generateConfigDeserializer(context); + } - private void generateResponseDeserializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - delegator.useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(operation), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace(operation), - writer -> { - final var outputShape = operation.getOutputShape(); + } - final var targetShape = context.model().expectShape(outputShape); - final var output = targetShape.accept( - new DafnyToSmithyShapeVisitor(context, "dafnyOutput", writer, false) + private void generateRequestSerializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + final var targetShape = context.model().expectShape(operation.getInputShape()); + delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), SmithyNameResolver.shapeNamespace(operation), writer -> { + final var input = targetShape.accept(new SmithyToDafnyShapeVisitor( + context, + "nativeInput", + writer, + false, false, false + )); + writer.write(""" + return $L + """, + input); + } ); + } - writer.write( - """ - return $L - """, - output + private void generateResponseSerializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + final var targetShape = context.model().expectShape(operation.getOutputShape()); + delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), SmithyNameResolver.shapeNamespace(operation), writer -> { + final var input = targetShape.accept(new SmithyToDafnyShapeVisitor( + context, + "nativeOutput", + writer, + false, false, false + )); + writer.write(""" + return $L + """, + input); + } ); - } - ); - } - - private void generateConfigSerializer(final GenerationContext context) { - final var service = context.settings().getService(context.model()); - final var localServiceTrait = service.expectTrait(LocalServiceTrait.class); - final var configShape = context - .model() - .expectShape(localServiceTrait.getConfigId(), StructureShape.class); - final var getInputToDafnyMethodName = - SmithyNameResolver.getToDafnyMethodName(service, configShape, ""); - - context - .writerDelegator() - .useFileWriter( - "%s/%s".formatted(SmithyNameResolver.shapeNamespace(service), TO_DAFNY), - SmithyNameResolver.shapeNamespace(service), - writer -> { - writer.write( - """ - func $L(nativeInput $L)($L) { - ${C|} - }""", - getInputToDafnyMethodName, - SmithyNameResolver.getSmithyType( - configShape, - context.symbolProvider().toSymbol(configShape) - ), - DafnyNameResolver.getDafnyType( - configShape, - context.symbolProvider().toSymbol(configShape) - ), - writer.consumer(w -> { - String output = configShape.accept( - new SmithyToDafnyShapeVisitor( - context, - "nativeInput", - writer, - true, - false, - false - ) - ); - writer.write( - """ - return $L - """, - output - ); - }) - ); - } - ); - } - - private void generateErrorSerializer(final GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var serviceShape = context.settings().getService(context.model()); - final var errorShapes = context - .model() - .getShapesWithTrait(ErrorTrait.class); - - for (final var errorShape : errorShapes) { - if ( - !errorShape - .toShapeId() - .getNamespace() - .equals(serviceShape.toShapeId().getNamespace()) - ) { - continue; - } - if (!alreadyVisited.contains(errorShape.toShapeId())) { - alreadyVisited.add(errorShape.toShapeId()); - final var getInputToDafnyMethodName = - SmithyNameResolver.getToDafnyMethodName(serviceShape, errorShape, ""); + } - context - .writerDelegator() - .useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(errorShape), - TO_DAFNY - ), - SmithyNameResolver.shapeNamespace(errorShape), - writer -> { - writer.write( - """ - func $L(nativeInput $L)($L) { - ${C|} - }""", - getInputToDafnyMethodName, - SmithyNameResolver.getSmithyType( - errorShape, - context.symbolProvider().toSymbol(errorShape) - ), - DafnyNameResolver.getDafnyBaseErrorType(errorShape), - writer.consumer(w -> { - String output = errorShape.accept( - new SmithyToDafnyShapeVisitor( - context, - "nativeInput", - writer, - false, - false, - false - ) - ); - writer.write( - """ - return $L - """, - output - ); - }) - ); - } - ); - } + private void generateRequestDeserializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_NATIVE), SmithyNameResolver.shapeNamespace(operation), writer -> { + + final var inputShape = operation.getInputShape(); + + final var targetShape = context.model().expectShape(inputShape); + final var input = targetShape.accept(new DafnyToSmithyShapeVisitor( + context, + "dafnyInput", + writer, + false + )); + + writer.write(""" + return $L + """, input); + }); } - context - .writerDelegator() - .useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_DAFNY - ), - SmithyNameResolver.shapeNamespace(serviceShape), - writer -> { - writer.write( - """ - func CollectionOfErrors_Input_ToDafny(nativeInput $L.CollectionOfErrors)($L.Error) { - var e []interface{} - for _, i2 := range nativeInput.ListOfErrors { - e = append(e, Error_ToDafny(i2)) - } - return $L.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) - } - func OpaqueError_Input_ToDafny(nativeInput $L.OpaqueError)($L.Error) { - return $L.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) - }""", - SmithyNameResolver.smithyTypesNamespace(serviceShape), - DafnyNameResolver.dafnyTypesNamespace(serviceShape), - DafnyNameResolver.dafnyTypesNamespace(serviceShape), - SmithyNameResolver.smithyTypesNamespace(serviceShape), - DafnyNameResolver.dafnyTypesNamespace(serviceShape), - DafnyNameResolver.dafnyTypesNamespace(serviceShape) - ); - } - ); + private void generateResponseDeserializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_NATIVE), SmithyNameResolver.shapeNamespace(operation), writer -> { + + final var outputShape = operation.getOutputShape(); + + final var targetShape = context.model().expectShape(outputShape); + final var output = targetShape.accept(new DafnyToSmithyShapeVisitor( + context, + "dafnyOutput", + writer, + false + )); + + writer.write(""" + return $L + """, output); + }); + } - context - .writerDelegator() - .useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace( - context.settings().getService(context.model()) - ), - TO_DAFNY - ), - SmithyNameResolver.shapeNamespace( - context.settings().getService(context.model()) - ), - writer -> { - writer.write( - """ - func Error_ToDafny(err error)($L.Error) { - switch err.(type) { - // Service Errors - ${C|} - //DependentErrors - ${C|} + private void generateConfigSerializer(final GenerationContext context) { + final var service = context.settings().getService(context.model()); + final var localServiceTrait = service.expectTrait(LocalServiceTrait.class); + final var configShape = context.model().expectShape(localServiceTrait.getConfigId(), StructureShape.class); + final var getInputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(service, configShape, ""); + + context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(service), TO_DAFNY), SmithyNameResolver.shapeNamespace(service), writer -> { + writer.write(""" + func $L(nativeInput $L)($L) { + ${C|} + }""", + getInputToDafnyMethodName, SmithyNameResolver.getSmithyType(configShape, context.symbolProvider().toSymbol(configShape)), DafnyNameResolver.getDafnyType(configShape, context.symbolProvider().toSymbol(configShape)), + writer.consumer(w -> { + String output = configShape.accept(new SmithyToDafnyShapeVisitor( + context, + "nativeInput", + writer, + true, false, false + )); + writer.write(""" + return $L + """, output); + })); + }); + } - //Unmodelled Errors - case $L.CollectionOfErrors: - return CollectionOfErrors_Input_ToDafny(err.($L.CollectionOfErrors)) + private void generateErrorSerializer(final GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var serviceShape = context.settings().getService(context.model()); + final var errorShapes = context.model().getShapesWithTrait(ErrorTrait.class); - default: - error, ok := err.($L.OpaqueError) - if !ok { - panic("Error is not an OpaqueError") - } - return OpaqueError_Input_ToDafny(error) - } + for (final var errorShape : + errorShapes) { + if (!errorShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { + continue; + } + if (!alreadyVisited.contains(errorShape.toShapeId())) { + alreadyVisited.add(errorShape.toShapeId()); + final var getInputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, errorShape, ""); + + context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(errorShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(errorShape), writer -> { + writer.write(""" + func $L(nativeInput $L)($L) { + ${C|} + }""", + getInputToDafnyMethodName, SmithyNameResolver.getSmithyType(errorShape, context.symbolProvider().toSymbol(errorShape)), DafnyNameResolver.getDafnyBaseErrorType(errorShape), + writer.consumer(w -> { + String output = errorShape.accept(new SmithyToDafnyShapeVisitor( + context, + "nativeInput", + writer, + false, false, false + )); + writer.write(""" + return $L + """, output); + })); + }); } - """, - DafnyNameResolver.dafnyTypesNamespace(serviceShape), - writer.consumer(w -> { - for (var error : serviceShape.getErrors()) { - w.write( - """ - case $L: - return $L(err.($L)) - """, - SmithyNameResolver.getSmithyType( - context.model().expectShape(error), - context - .symbolProvider() - .toSymbol(context.model().expectShape(error)) - ), - SmithyNameResolver.getToDafnyMethodName( - serviceShape, - context.model().expectShape(error), - "" - ), - SmithyNameResolver.getSmithyType( - context.model().expectShape(error), - context - .symbolProvider() - .toSymbol(context.model().expectShape(error)) - ) - ); - } - }), - writer.consumer(w -> { - var dependencies = serviceShape.hasTrait(LocalServiceTrait.class) - ? serviceShape - .expectTrait(LocalServiceTrait.class) - .getDependencies() - : new LinkedList(); - if (dependencies != null) { - for (var dep : dependencies) { - var depShape = context.model().expectShape(dep); - w.write( - """ - case $L.$LBaseException: - return $L.Create_$L_($L.Error_ToDafny(err)) - """, - SmithyNameResolver.smithyTypesNamespace(depShape), - dep.getName(), - DafnyNameResolver.getDafnyErrorCompanion(serviceShape), - dep.getName(), - SmithyNameResolver.shapeNamespace(depShape) - ); - } - } - }), - SmithyNameResolver.smithyTypesNamespace(serviceShape), - SmithyNameResolver.smithyTypesNamespace(serviceShape), - SmithyNameResolver.smithyTypesNamespace(serviceShape) - ); - } - ); - } - - private void generateConfigDeserializer(final GenerationContext context) { - final var serviceShape = context.settings().getService(context.model()); - final var localServiceTrait = serviceShape.expectTrait( - LocalServiceTrait.class - ); - final var configShape = context - .model() - .expectShape(localServiceTrait.getConfigId(), StructureShape.class); - final var getOutputFromDafnyMethodName = - SmithyNameResolver.getFromDafnyMethodName(serviceShape, configShape, ""); - - context - .writerDelegator() - .useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(serviceShape), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace(configShape), - writer -> { - writer.write( - """ - func $L(dafnyOutput $L)($L) { - ${C|} - }""", - getOutputFromDafnyMethodName, - DafnyNameResolver.getDafnyType( - configShape, - context.symbolProvider().toSymbol(configShape) - ), - SmithyNameResolver.getSmithyType( - configShape, - context.symbolProvider().toSymbol(configShape) - ), - writer.consumer(w -> { - String output = configShape.accept( - new DafnyToSmithyShapeVisitor( - context, - "dafnyOutput", - writer, - true - ) - ); - writer.write( - """ - return $L - """, - output - ); - }) - ); } - ); - } - private void generateErrorDeserializer(final GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var serviceShape = context.settings().getService(context.model()); - final var errorShapes = context - .model() - .getShapesWithTrait(ErrorTrait.class); - for (final var errorShape : errorShapes) { - if ( - !errorShape - .toShapeId() - .getNamespace() - .equals(serviceShape.toShapeId().getNamespace()) - ) { - continue; - } - if (!alreadyVisited.contains(errorShape.toShapeId())) { - alreadyVisited.add(errorShape.toShapeId()); - final var getOutputFromDafnyMethodName = - SmithyNameResolver.getFromDafnyMethodName( - serviceShape, - errorShape, - "" - ); - context - .writerDelegator() - .useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace(errorShape), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace(errorShape), - writer -> { - writer.write( - """ - func $L(dafnyOutput $L)($L) { - ${C|} - }""", - getOutputFromDafnyMethodName, - DafnyNameResolver.getDafnyBaseErrorType(errorShape), - SmithyNameResolver.getSmithyType( - errorShape, - context.symbolProvider().toSymbol(errorShape) - ), - writer.consumer(w -> { - String output = errorShape.accept( - new DafnyToSmithyShapeVisitor( - context, - "dafnyOutput", - writer, - false - ) - ); - writer.write( - """ - return $L - """, - output - ); - }) - ); - } - ); - } + context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { + writer.write(""" + func CollectionOfErrors_Input_ToDafny(nativeInput $L.CollectionOfErrors)($L.Error) { + var e []interface{} + for _, i2 := range nativeInput.ListOfErrors { + e = append(e, Error_ToDafny(i2)) + } + return $L.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) + } + func OpaqueError_Input_ToDafny(nativeInput $L.OpaqueError)($L.Error) { + return $L.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) + }""", SmithyNameResolver.smithyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape), SmithyNameResolver.smithyTypesNamespace(serviceShape), DafnyNameResolver.dafnyTypesNamespace(serviceShape), DafnyNameResolver.dafnyTypesNamespace(serviceShape)); + }); + + + context.writerDelegator() + .useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), TO_DAFNY), + SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), writer -> { + writer.write(""" + func Error_ToDafny(err error)($L.Error) { + switch err.(type) { + // Service Errors + ${C|} + //DependentErrors + ${C|} + + //Unmodelled Errors + case $L.CollectionOfErrors: + return CollectionOfErrors_Input_ToDafny(err.($L.CollectionOfErrors)) + + default: + error, ok := err.($L.OpaqueError) + if !ok { + panic("Error is not an OpaqueError") + } + return OpaqueError_Input_ToDafny(error) + } + } + """, DafnyNameResolver.dafnyTypesNamespace(serviceShape), + writer.consumer(w -> { + for (var error : serviceShape.getErrors()) { + w.write(""" + case $L: + return $L(err.($L)) + """, SmithyNameResolver.getSmithyType(context.model().expectShape(error), context.symbolProvider().toSymbol(context.model().expectShape(error))), + SmithyNameResolver.getToDafnyMethodName(serviceShape, context.model().expectShape(error), ""), + SmithyNameResolver.getSmithyType(context.model().expectShape(error), context.symbolProvider().toSymbol(context.model().expectShape(error)))); + } + }), + writer.consumer(w -> { + var dependencies = serviceShape.hasTrait(LocalServiceTrait.class) ? serviceShape.expectTrait(LocalServiceTrait.class).getDependencies() : new LinkedList(); + if (dependencies != null) { + for (var dep : dependencies) { + var depShape = context.model().expectShape(dep); + w.write(""" + case $L.$LBaseException: + return $L.Create_$L_($L.Error_ToDafny(err)) + """, SmithyNameResolver.smithyTypesNamespace(depShape), dep.getName(), DafnyNameResolver.getDafnyErrorCompanion(serviceShape), dep.getName(), SmithyNameResolver.shapeNamespace(depShape)); + } + } + }), + SmithyNameResolver.smithyTypesNamespace(serviceShape), SmithyNameResolver.smithyTypesNamespace(serviceShape), SmithyNameResolver.smithyTypesNamespace(serviceShape) + ); + }); } - context - .writerDelegator() - .useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace( - context.settings().getService(context.model()) - ), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace( - context.settings().getService(context.model()) - ), - writer -> { - writer.write( - """ - func CollectionOfErrors_Output_FromDafny(dafnyOutput $L.Error)($L.CollectionOfErrors) { - listOfErrors := dafnyOutput.Dtor_list() - message := dafnyOutput.Dtor_message() - t := $L.CollectionOfErrors {} - for i := dafny.Iterate(listOfErrors) ; ; { - val, ok := i() - if !ok { - break; - } - err := val.($L.Error) - t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) + private void generateConfigDeserializer(final GenerationContext context) { + final var serviceShape = context.settings().getService(context.model()); + final var localServiceTrait = serviceShape.expectTrait(LocalServiceTrait.class); + final var configShape = context.model().expectShape(localServiceTrait.getConfigId(), StructureShape.class); + final var getOutputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, configShape, ""); + + context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(configShape), writer -> { + writer.write(""" + func $L(dafnyOutput $L)($L) { + ${C|} + }""", + getOutputFromDafnyMethodName, DafnyNameResolver.getDafnyType(configShape, context.symbolProvider().toSymbol(configShape)), SmithyNameResolver.getSmithyType(configShape, context.symbolProvider().toSymbol(configShape)), + writer.consumer(w -> { + String output = configShape.accept(new DafnyToSmithyShapeVisitor( + context, + "dafnyOutput", + writer, + true + )); + writer.write(""" + return $L + """, output); + })); + }); + } - } - t.Message = func() (string) { - var s string - for i := dafny.Iterate(message) ; ; { - val, ok := i() - if !ok { - return s - } else { - s = s + string(val.(dafny.Char)) - } - } - }() - return t + private void generateErrorDeserializer(final GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var serviceShape = context.settings().getService(context.model()); + final var errorShapes = context.model().getShapesWithTrait(ErrorTrait.class); + for (final var errorShape : + errorShapes) { + if (!errorShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { + continue; } - func OpaqueError_Output_FromDafny(dafnyOutput $L.Error)($L.OpaqueError) { - return $L.OpaqueError { - ErrObject: dafnyOutput.Dtor_obj(), - } - }""", - DafnyNameResolver.dafnyTypesNamespace(serviceShape), - SmithyNameResolver.smithyTypesNamespace(serviceShape), - SmithyNameResolver.smithyTypesNamespace(serviceShape), - DafnyNameResolver.dafnyTypesNamespace(serviceShape), - DafnyNameResolver.dafnyTypesNamespace(serviceShape), - SmithyNameResolver.smithyTypesNamespace(serviceShape), - SmithyNameResolver.smithyTypesNamespace(serviceShape) - ); - } - ); - - context - .writerDelegator() - .useFileWriter( - "%s/%s".formatted( - SmithyNameResolver.shapeNamespace( - context.settings().getService(context.model()) - ), - TO_NATIVE - ), - SmithyNameResolver.shapeNamespace( - context.settings().getService(context.model()) - ), - writer -> { - writer.write( - """ - func Error_FromDafny(err $L.Error)(error) { - // Service Errors - ${C|} - - //DependentErrors - ${C|} - - //Unmodelled Errors - if err.Is_CollectionOfErrors() { - return CollectionOfErrors_Output_FromDafny(err) - } - - return OpaqueError_Output_FromDafny(err) + if (!alreadyVisited.contains(errorShape.toShapeId())) { + alreadyVisited.add(errorShape.toShapeId()); + final var getOutputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, errorShape, ""); + context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(errorShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(errorShape), writer -> { + writer.write(""" + func $L(dafnyOutput $L)($L) { + ${C|} + }""", + getOutputFromDafnyMethodName, DafnyNameResolver.getDafnyBaseErrorType(errorShape), SmithyNameResolver.getSmithyType(errorShape, context.symbolProvider().toSymbol(errorShape)), + writer.consumer(w -> { + String output = errorShape.accept(new DafnyToSmithyShapeVisitor( + context, + "dafnyOutput", + writer, + false + )); + writer.write(""" + return $L + """, output); + })); + }); } - """, - DafnyNameResolver.dafnyTypesNamespace(serviceShape), - writer.consumer(w -> { - for (var error : serviceShape.getErrors()) { - w.write( - """ - if err.Is_$L() { - return $L(err) - } - """, - error.getName(), - SmithyNameResolver.getFromDafnyMethodName( - serviceShape, - context.model().expectShape(error), - "" - ) - ); - } - }), - writer.consumer(w -> { - var dependencies = serviceShape.hasTrait(LocalServiceTrait.class) - ? serviceShape - .expectTrait(LocalServiceTrait.class) - .getDependencies() - : null; - if (dependencies == null) { - return; - } - for (var dep : dependencies) { - var depService = context - .model() - .expectShape(dep, ServiceShape.class); - w.write( - """ - if err.Is_$L() { - return $L.Error_FromDafny(err.Dtor_$L()) - } - """, - depService.expectTrait(LocalServiceTrait.class).getSdkId(), - SmithyNameResolver.shapeNamespace(depService), - depService.expectTrait(LocalServiceTrait.class).getSdkId() - ); - } - }) - ); } - ); - } + + context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), TO_NATIVE), SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), writer -> { + writer.write(""" + func CollectionOfErrors_Output_FromDafny(dafnyOutput $L.Error)($L.CollectionOfErrors) { + listOfErrors := dafnyOutput.Dtor_list() + message := dafnyOutput.Dtor_message() + t := $L.CollectionOfErrors {} + for i := dafny.Iterate(listOfErrors) ; ; { + val, ok := i() + if !ok { + break; + } + err := val.($L.Error) + t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) + + } + t.Message = func() (string) { + var s string + for i := dafny.Iterate(message) ; ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() + return t + } + func OpaqueError_Output_FromDafny(dafnyOutput $L.Error)($L.OpaqueError) { + return $L.OpaqueError { + ErrObject: dafnyOutput.Dtor_obj(), + } + }""", DafnyNameResolver.dafnyTypesNamespace(serviceShape), SmithyNameResolver.smithyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape), DafnyNameResolver.dafnyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape)); + }); + + context.writerDelegator() + .useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), TO_NATIVE), + SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), writer -> { + writer.write(""" + func Error_FromDafny(err $L.Error)(error) { + // Service Errors + ${C|} + + //DependentErrors + ${C|} + + //Unmodelled Errors + if err.Is_CollectionOfErrors() { + return CollectionOfErrors_Output_FromDafny(err) + } + + return OpaqueError_Output_FromDafny(err) + } + """, DafnyNameResolver.dafnyTypesNamespace(serviceShape), + writer.consumer(w -> { + for (var error : serviceShape.getErrors()) { + w.write(""" + if err.Is_$L() { + return $L(err) + } + """, error.getName(), SmithyNameResolver.getFromDafnyMethodName(serviceShape, context.model().expectShape(error), "")); + } + }), + writer.consumer(w -> { + var dependencies = serviceShape.hasTrait(LocalServiceTrait.class) ? serviceShape.expectTrait(LocalServiceTrait.class).getDependencies() : null; + if (dependencies == null) { + return; + } + for (var dep : dependencies) { + var depService = context.model().expectShape(dep, ServiceShape.class); + w.write(""" + if err.Is_$L() { + return $L.Error_FromDafny(err.Dtor_$L()) + } + """, depService.expectTrait(LocalServiceTrait.class).getSdkId(), SmithyNameResolver.shapeNamespace(depService), depService.expectTrait(LocalServiceTrait.class).getSdkId()); + } + }) + ); + }); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/Constants.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/Constants.java index 2d1e961fc6..e443603dff 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/Constants.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/Constants.java @@ -1,9 +1,8 @@ package software.amazon.polymorph.smithygo.localservice.nameresolver; public class Constants { - - public static final String DOT = "."; - public static final String BLANK = ""; - public static final String INTERNAL_DAFNY_TYPES = "internaldafnytypes"; - public static final String INTERNAL_DAFNY = "internaldafny"; + public static final String DOT = "."; + public static final String BLANK = ""; + public static final String INTERNAL_DAFNY_TYPES = "internaldafnytypes"; + public static final String INTERNAL_DAFNY = "internaldafny"; } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java index 29041ac6d2..a5fb3118dd 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java @@ -1,198 +1,153 @@ package software.amazon.polymorph.smithygo.localservice.nameresolver; -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.DOT; -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.INTERNAL_DAFNY; -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.INTERNAL_DAFNY_TYPES; - import software.amazon.smithy.aws.traits.ServiceTrait; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; +import software.amazon.smithy.model.traits.SensitiveTrait; + import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.shapes.UnionShape; import software.amazon.smithy.model.traits.EnumTrait; -import software.amazon.smithy.model.traits.SensitiveTrait; + +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.DOT; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.INTERNAL_DAFNY; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.INTERNAL_DAFNY_TYPES; public class DafnyNameResolver { - public static String dafnyTypesNamespace(final Shape shape) { - return shape - .toShapeId() - .getNamespace() - .replace(DOT, BLANK) - .toLowerCase() - .concat(INTERNAL_DAFNY_TYPES); - } - - public static String dafnyNamespace(final Shape shape) { - return shape - .toShapeId() - .getNamespace() - .replace(DOT, BLANK) - .toLowerCase() - .concat(INTERNAL_DAFNY); - } - - /** - * Returns the Dafny type for a given Shape. - * - * @param shape The Shape for which the Dafny type needs to be determined. - * @param symbol The Symbol representing the Shape. - * @return The Dafny type as a String. - */ - public static String getDafnyType(final Shape shape, final Symbol symbol) { - ShapeType type = shape.getType(); - if (shape.hasTrait(EnumTrait.class)) { - type = ShapeType.ENUM; - } - switch (type) { - case INTEGER, LONG, BOOLEAN: - return symbol.getName(); - case MAP: - return "dafny.Map"; - case DOUBLE, STRING, BLOB, LIST: - return "dafny.Sequence"; - // default catches a case where users may author their own classes that implement and extend resource (ExtendableTrait) - // ENUM, STRUCTURE, UNION can be removed but for posterity it looks great to see all the shapes being covered. - case ENUM, STRUCTURE, UNION: - default: - return DafnyNameResolver - .dafnyTypesNamespace(shape) - .concat(DOT) - .concat(symbol.getName()); - } - } - - public static String getDafnySubErrorType( - final Shape shape, - final Symbol symbol - ) { - return DafnyNameResolver - .getDafnyBaseErrorType(shape) - .concat("_") - .concat(symbol.getName()); - } - - public static String getDafnyBaseErrorType(final Shape shape) { - return DafnyNameResolver - .dafnyTypesNamespace(shape) - .concat(DOT) - .concat("Error"); - } - - public static String getDafnyCompanionType( - final Shape shape, - final Symbol symbol - ) { - return DafnyNameResolver - .dafnyTypesNamespace(shape) - .concat(DOT) - .concat("Companion_%s_".formatted(symbol.getName())); - } - - public static String getDafnyErrorCompanion(final Shape shape) { - return DafnyNameResolver - .dafnyTypesNamespace(shape) - .concat(DOT) - .concat("Companion_Error_"); - } - - public static String getDafnyErrorCompanionCreate( - final Shape shape, - final Symbol symbol - ) { - return DafnyNameResolver - .getDafnyErrorCompanion(shape) - .concat(DOT) - .concat("Create_%s_".formatted(symbol.getName())); - } - - public static String getDafnyCompanionStructType( - final Shape shape, - final Symbol symbol - ) { - return DafnyNameResolver - .dafnyTypesNamespace(shape) - .concat(DOT) - .concat("CompanionStruct_%s_".formatted(symbol.getName())); - } - - public static String getDafnyCompanionTypeCreate( - final Shape shape, - final Symbol symbol - ) { - return DafnyNameResolver - .getDafnyCompanionType(shape, symbol) - .concat(DOT) - .concat("Create_%s_".formatted(symbol.getName())); - } - - /** - * Returns the path to Create_ function for creating member shape within a union shape. - * - * @param unionShape The union shape containing the member shape. - * @param memberName The name of the member shape within the union shape. - */ - public static String getDafnyCreateFuncForUnionMemberShape( - final UnionShape unionShape, - final String memberName - ) { - return "companion".concat(DOT) - .concat( - memberName.replace(unionShape.getId().getName() + "Member", "Create_") - ) - .concat("_"); - } - - public static String getDafnyClient(final Shape shape, final String sdkId) { - return DafnyNameResolver - .dafnyNamespace(shape) - .concat(DOT) - .concat(sdkId) - .concat("Client"); - } - - public static String getDafnyInterfaceClient(final Shape shape) { - return DafnyNameResolver - .dafnyTypesNamespace(shape) - .concat(DOT) - .concat("I") - .concat(shape.toShapeId().getName()) - .concat("Client"); - } - - public static String getDafnyInterfaceClient( - final ServiceShape serviceShape, - final ServiceTrait awsSdkServiceTrait - ) { - return DafnyNameResolver - .dafnyTypesNamespace(serviceShape) - .concat(DOT) - .concat("I") - .concat(awsSdkServiceTrait.getSdkId()) - .concat("Client"); - } - - public static String createDafnyClient( - final Shape shape, - final String sdkId - ) { - return DafnyNameResolver - .dafnyNamespace(shape) - .concat(".Companion_Default___") - .concat(DOT) - .concat(sdkId); - } - - public static String getDafnyDependentErrorType( - final Shape shape, - final String sdkId - ) { - return DafnyNameResolver - .dafnyNamespace(shape) - .concat(".Companion_Default___") - .concat(DOT) - .concat(sdkId); - } -} + + public static String dafnyTypesNamespace(final Shape shape) { + return shape.toShapeId().getNamespace() + .replace(DOT, BLANK).toLowerCase() + .concat(INTERNAL_DAFNY_TYPES); + } + + public static String dafnyNamespace(final Shape shape) { + return shape.toShapeId().getNamespace() + .replace(DOT, BLANK).toLowerCase() + .concat(INTERNAL_DAFNY); + } + + /** + * Returns the Dafny type for a given Shape. + * + * @param shape The Shape for which the Dafny type needs to be determined. + * @param symbol The Symbol representing the Shape. + * @return The Dafny type as a String. + */ + public static String getDafnyType(final Shape shape, final Symbol symbol) { + ShapeType type = shape.getType(); + if (shape.hasTrait(EnumTrait.class)) { + type = ShapeType.ENUM; + } + switch (type) { + case INTEGER, LONG, BOOLEAN: + return symbol.getName(); + case MAP: + return "dafny.Map"; + case DOUBLE, STRING, BLOB, LIST: + return "dafny.Sequence"; + // default catches a case where users may author their own classes that implement and extend resource (ExtendableTrait) + // ENUM, STRUCTURE, UNION can be removed but for posterity it looks great to see all the shapes being covered. + case ENUM, STRUCTURE, UNION: + default: + return DafnyNameResolver.dafnyTypesNamespace(shape) + .concat(DOT) + .concat(symbol.getName()); + } + } + + public static String getDafnySubErrorType(final Shape shape, final Symbol symbol) { + return DafnyNameResolver.getDafnyBaseErrorType(shape) + .concat("_") + .concat(symbol.getName()); + } + + public static String getDafnyBaseErrorType(final Shape shape) { + return DafnyNameResolver.dafnyTypesNamespace(shape) + .concat(DOT) + .concat("Error"); + } + + public static String getDafnyCompanionType(final Shape shape, final Symbol symbol) { + return DafnyNameResolver.dafnyTypesNamespace(shape) + .concat(DOT) + .concat("Companion_%s_".formatted(symbol.getName())); + } + + public static String getDafnyErrorCompanion(final Shape shape) { + return DafnyNameResolver.dafnyTypesNamespace(shape) + .concat(DOT) + .concat("Companion_Error_"); + } + + public static String getDafnyErrorCompanionCreate(final Shape shape, final Symbol symbol) { + return DafnyNameResolver.getDafnyErrorCompanion(shape) + .concat(DOT) + .concat("Create_%s_".formatted(symbol.getName())); + } + + public static String getDafnyCompanionStructType(final Shape shape, final Symbol symbol) { + return DafnyNameResolver.dafnyTypesNamespace(shape) + .concat(DOT) + .concat("CompanionStruct_%s_".formatted(symbol.getName())); + } + + public static String getDafnyCompanionTypeCreate(final Shape shape, final Symbol symbol) { + return DafnyNameResolver.getDafnyCompanionType(shape, symbol) + .concat(DOT) + .concat("Create_%s_".formatted(symbol.getName())); + } + + /** + * Returns the path to Create_ function for creating member shape within a union shape. + * + * @param unionShape The union shape containing the member shape. + * @param memberName The name of the member shape within the union shape. + */ + public static String getDafnyCreateFuncForUnionMemberShape(final UnionShape unionShape, final String memberName) { + return "companion" + .concat(DOT) + .concat(memberName.replace(unionShape.getId().getName() + "Member", "Create_")) + .concat("_"); + } + + public static String getDafnyClient(final Shape shape, final String sdkId) { + return DafnyNameResolver.dafnyNamespace(shape) + .concat(DOT) + .concat(sdkId) + .concat("Client"); + } + public static String getDafnyInterfaceClient(final Shape shape) { + return DafnyNameResolver.dafnyTypesNamespace(shape) + .concat(DOT).concat("I") + .concat(shape.toShapeId().getName()) + .concat("Client"); + } + + public static String getDafnyInterfaceClient(final ServiceShape serviceShape, + final ServiceTrait awsSdkServiceTrait) { + return DafnyNameResolver.dafnyTypesNamespace(serviceShape) + .concat(DOT).concat("I") + .concat(awsSdkServiceTrait.getSdkId()) + .concat("Client"); + } + + + public static String createDafnyClient(final Shape shape, final String sdkId) { + return DafnyNameResolver.dafnyNamespace(shape) + .concat(".Companion_Default___") + .concat(DOT) + .concat(sdkId); + } + + public static String getDafnyDependentErrorType(final Shape shape, final String sdkId) { + return DafnyNameResolver.dafnyNamespace(shape) + .concat(".Companion_Default___") + .concat(DOT) + .concat(sdkId); + } + +} \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java index 179d22b375..7b58ad8ef7 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java @@ -1,9 +1,5 @@ package software.amazon.polymorph.smithygo.localservice.nameresolver; -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.DOT; - -import java.util.Map; import software.amazon.smithy.aws.traits.ServiceTrait; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.model.Model; @@ -11,117 +7,47 @@ import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.SimpleShape; +import java.util.Map; + +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.DOT; + public class SmithyNameResolver { - private static Map smithyNamespaceToGoModuleNameMap; - - public static void setSmithyNamespaceToGoModuleNameMap( - Map smithyNamespaceToGoModuleNameMap - ) { - SmithyNameResolver.smithyNamespaceToGoModuleNameMap = - smithyNamespaceToGoModuleNameMap; - } - - public static String getGoModuleNameForSmithyNamespace( - final String smithyNamespace - ) { - if (smithyNamespace.contains("smithy.")) return ""; - if (!smithyNamespaceToGoModuleNameMap.containsKey(smithyNamespace)) { - throw new IllegalArgumentException( - "Go module name not found for Smithy namespace: " + smithyNamespace - ); + private static Map smithyNamespaceToGoModuleNameMap; + + public static void setSmithyNamespaceToGoModuleNameMap( + Map smithyNamespaceToGoModuleNameMap) { + SmithyNameResolver.smithyNamespaceToGoModuleNameMap = smithyNamespaceToGoModuleNameMap; } - return smithyNamespaceToGoModuleNameMap.get(smithyNamespace); - } - - public static String shapeNamespace(final Shape shape) { - return shape.toShapeId().getNamespace().replace(DOT, BLANK).toLowerCase(); - } - - public static String smithyTypesNamespace(final Shape shape) { - return shape - .toShapeId() - .getNamespace() - .replace(DOT, BLANK) - .toLowerCase() - .concat("types"); - } - - public static String getGoModuleNameForSdkNamespace( - final String smithyNamespace - ) { - return getGoModuleNameForSmithyNamespace("sdk.".concat(smithyNamespace)); - } - - public static String smithyTypesNamespaceAws( - final ServiceTrait serviceTrait, - boolean isAwsSubType - ) { - if (isAwsSubType) { - return "types"; + + public static String getGoModuleNameForSmithyNamespace(final String smithyNamespace) { + if (smithyNamespace.contains("smithy.")) return ""; + if (!smithyNamespaceToGoModuleNameMap.containsKey(smithyNamespace)) { + throw new IllegalArgumentException("Go module name not found for Smithy namespace: " + smithyNamespace); + } + return smithyNamespaceToGoModuleNameMap.get(smithyNamespace); } - return serviceTrait.getSdkId().toLowerCase(); - } - - public static String getSmithyType(final Shape shape, final Symbol symbol) { - if ( - symbol.getNamespace().contains("smithy.") || - symbol.getName().contains("string") - ) { - return symbol.getName(); + + public static String shapeNamespace(final Shape shape) { + return shape.toShapeId().getNamespace().replace(DOT, BLANK).toLowerCase(); } - return SmithyNameResolver - .smithyTypesNamespace(shape) - .concat(DOT) - .concat(symbol.getName()); - } - - public static String getSmithyTypeAws( - final ServiceTrait serviceTrait, - final Symbol symbol, - boolean subtype - ) { - if ( - symbol.getNamespace().contains("smithy.") || - symbol.getName().equals("string") || - symbol.getName().equals("float64") - ) { - return symbol.getName(); + + public static String smithyTypesNamespace(final Shape shape) { + return shape.toShapeId().getNamespace().replace(DOT, BLANK).toLowerCase().concat("types"); } - return SmithyNameResolver - .smithyTypesNamespaceAws(serviceTrait, subtype) - .concat(DOT) - .concat(symbol.getName()); - } - - public static String getSmithyType(final Shape shape) { - return SmithyNameResolver - .smithyTypesNamespace(shape) - .concat(DOT) - .concat(shape.toShapeId().getName()); - } - - public static String getToDafnyMethodName( - final ServiceShape serviceShape, - final Shape shape, - final String disambiguator - ) { - final var methodName = serviceShape - .getContextualName(shape) - .concat("_ToDafny"); - if ( - serviceShape - .toShapeId() - .getNamespace() - .equals(shape.toShapeId().getNamespace()) - ) { - return methodName; - } else { - return SmithyNameResolver - .shapeNamespace(shape) - .concat(DOT) - .concat(methodName); + + public static String getGoModuleNameForSdkNamespace(final String smithyNamespace) { + return getGoModuleNameForSmithyNamespace("sdk.".concat(smithyNamespace)); } + + public static String smithyTypesNamespaceAws(final ServiceTrait serviceTrait, boolean isAwsSubType) { + if (isAwsSubType) { + return "types"; + } + return serviceTrait.getSdkId().toLowerCase(); + } + public static String getSmithyType(final Shape shape, final Symbol symbol) { if(symbol.getNamespace().contains("smithy.") || symbol.getName().contains("string")) { return symbol.getName(); @@ -177,23 +103,4 @@ public static String getAwsServiceClient(final ServiceTrait serviceTrait) { .concat(DOT) .concat("Client"); } - } - - public static String getFromDafnyMethodName( - final Shape shape, - final String disambiguator - ) { - final var methodName = shape.getId().getName().concat("_FromDafny"); - return SmithyNameResolver - .shapeNamespace(shape) - .concat(DOT) - .concat(methodName); - } - - public static String getAwsServiceClient(final ServiceTrait serviceTrait) { - return SmithyNameResolver - .smithyTypesNamespaceAws(serviceTrait, false) - .concat(DOT) - .concat("Client"); - } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java index b83a2e15a5..6d4c88d90c 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java @@ -1,7 +1,5 @@ package software.amazon.polymorph.smithygo.localservice.shapevisitor; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoWriter; import software.amazon.polymorph.smithygo.codegen.SmithyGoDependency; @@ -30,226 +28,105 @@ import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.utils.StringUtils; -public class DafnyToSmithyShapeVisitor extends ShapeVisitor.Default { - - private final GenerationContext context; - private final String dataSource; - private final GoWriter writer; - private final boolean isConfigShape; - private final boolean isOptional; - - public DafnyToSmithyShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isConfigShape - ) { - this(context, dataSource, writer, isConfigShape, false); - } +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - public DafnyToSmithyShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isConfigShape, - final boolean isOptional - ) { - this.context = context; - this.dataSource = dataSource; - this.writer = writer; - this.isConfigShape = isConfigShape; - this.isOptional = isOptional; - } +public class DafnyToSmithyShapeVisitor extends ShapeVisitor.Default { + private final GenerationContext context; + private final String dataSource; + private final GoWriter writer; + private final boolean isConfigShape; + private final boolean isOptional; - protected String referenceStructureShape(StructureShape shape) { - ReferenceTrait referenceTrait = shape.expectTrait(ReferenceTrait.class); - Shape resourceOrService = context - .model() - .expectShape(referenceTrait.getReferentId()); - var namespace = ""; - if (resourceOrService.asResourceShape().isPresent()) { - var resourceShape = resourceOrService.asResourceShape().get(); - if ( - !resourceOrService - .toShapeId() - .getNamespace() - .equals(context.settings().getService().getNamespace()) - ) { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - resourceOrService.toShapeId().getNamespace() - ), - SmithyNameResolver.shapeNamespace(resourceShape) - ); - namespace = - SmithyNameResolver.shapeNamespace(resourceOrService).concat("."); - } - if (!this.isOptional) { - return "%s_FromDafny(%s)".formatted( - namespace.concat(resourceShape.toShapeId().getName()), - dataSource - ); - } - return """ - func () %s.I%s { - if %s == nil { - return nil; - } - return %s - }()""".formatted( - SmithyNameResolver.smithyTypesNamespace(resourceShape), - resourceShape.getId().getName(), - dataSource, - "%s_FromDafny(%s.(%s.I%s))".formatted( - namespace.concat(resourceShape.toShapeId().getName()), - dataSource, - DafnyNameResolver.dafnyTypesNamespace(resourceShape), - resourceShape.getId().getName() - ) - ); - } else { - var serviceShape = resourceOrService.asServiceShape().get(); - if ( - !resourceOrService - .toShapeId() - .getNamespace() - .equals(context.settings().getService().getNamespace()) - ) { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - resourceOrService.toShapeId().getNamespace() - ), - SmithyNameResolver.shapeNamespace(serviceShape) - ); - namespace = - SmithyNameResolver.shapeNamespace(resourceOrService).concat("."); - } - if (!this.isOptional) { - return "%1$s{%2$s}".formatted( - namespace.concat( - context.symbolProvider().toSymbol(serviceShape).getName() - ), - dataSource - ); - } - return """ - func () *%s { - if %s == nil { - return nil; - } - return &%s{%s.(*%s)} - }()""".formatted( - namespace.concat( - context.symbolProvider().toSymbol(serviceShape).getName() - ), - dataSource, - namespace.concat( - context.symbolProvider().toSymbol(serviceShape).getName() - ), - dataSource, - DafnyNameResolver.getDafnyClient( - serviceShape, - serviceShape.toShapeId().getName() - ) - ); + public DafnyToSmithyShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isConfigShape + ) { + this(context, dataSource, writer, isConfigShape, false); } - } - - @Override - protected String getDefault(Shape shape) { - throw new CodegenException( - String.format( - "Unsupported conversion of %s to %s using the %s protocol", - shape, - shape.getType(), - context.protocolGenerator().getName() - ) - ); - } - @Override - public String blobShape(BlobShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - return """ - func () []byte { - var b []byte - if %s == nil { - return nil + public DafnyToSmithyShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isConfigShape, + final boolean isOptional + ) { + this.context = context; + this.dataSource = dataSource; + this.writer = writer; + this.isConfigShape = isConfigShape; + this.isOptional = isOptional; } - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return b + + protected String referenceStructureShape(StructureShape shape) { + ReferenceTrait referenceTrait = shape.expectTrait(ReferenceTrait.class); + Shape resourceOrService = context.model().expectShape(referenceTrait.getReferentId()); + var namespace = ""; + if (resourceOrService.asResourceShape().isPresent()) { + var resourceShape = resourceOrService.asResourceShape().get(); + if (!resourceOrService.toShapeId().getNamespace().equals(context.settings().getService().getNamespace())) { + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resourceOrService.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(resourceShape)); + namespace = SmithyNameResolver.shapeNamespace(resourceOrService).concat("."); + } + if (!this.isOptional) { + return "%s_FromDafny(%s)".formatted(namespace.concat(resourceShape.toShapeId().getName()), dataSource); + } + return """ + func () %s.I%s { + if %s == nil { + return nil; + } + return %s + }()""".formatted(SmithyNameResolver.smithyTypesNamespace(resourceShape), resourceShape.getId().getName(), dataSource, + "%s_FromDafny(%s.(%s.I%s))".formatted(namespace.concat(resourceShape.toShapeId().getName()), dataSource, + DafnyNameResolver.dafnyTypesNamespace(resourceShape), resourceShape.getId().getName())); } else { - b = append(b, val.(byte)) + var serviceShape = resourceOrService.asServiceShape().get(); + if (!resourceOrService.toShapeId().getNamespace().equals(context.settings().getService().getNamespace())) { + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resourceOrService.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(serviceShape)); + namespace = SmithyNameResolver.shapeNamespace(resourceOrService).concat("."); + } + if (!this.isOptional) { + return "%1$s{%2$s}".formatted(namespace.concat(context.symbolProvider().toSymbol(serviceShape).getName()), dataSource); + } + return """ + func () *%s { + if %s == nil { + return nil; + } + return &%s{%s.(*%s)} + }()""".formatted(namespace.concat(context.symbolProvider().toSymbol(serviceShape).getName()), dataSource, namespace.concat(context.symbolProvider().toSymbol(serviceShape).getName()), + dataSource, DafnyNameResolver.getDafnyClient(serviceShape, serviceShape.toShapeId().getName())); } } - }()""".formatted(dataSource, dataSource); - } - @Override - public String structureShape(final StructureShape shape) { - if (shape.hasTrait(ReferenceTrait.class)) { - return referenceStructureShape(shape); + @Override + protected String getDefault(Shape shape) { + throw new CodegenException(String.format( + "Unsupported conversion of %s to %s using the %s protocol", + shape, shape.getType(), context.protocolGenerator().getName())); } - final var builder = new StringBuilder(); - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - shape.toShapeId().getNamespace() - ), - DafnyNameResolver.dafnyTypesNamespace(shape) - ); - builder.append( - "%1$s{".formatted( - SmithyNameResolver - .smithyTypesNamespace(shape) - .concat(".") - .concat(shape.getId().getName()) - ) - ); - String fieldSeparator = ","; - for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { - final var memberName = memberShapeEntry.getKey(); - final var memberShape = memberShapeEntry.getValue(); - final var targetShape = context - .model() - .expectShape(memberShape.getTarget()); - //TODO: Is it ever possible for structure to be nil? - final var derivedDataSource = - "%1$s%2$s%3$s%4$s".formatted( - dataSource, - ".Dtor_%s()".formatted(memberName), - memberShape.isOptional() ? ".UnwrapOr(nil)" : "", - memberShape.isOptional() && - targetShape.isStructureShape() && - !targetShape.hasTrait(ReferenceTrait.class) - ? ".(%s)".formatted( - DafnyNameResolver.getDafnyType( - targetShape, - context.symbolProvider().toSymbol(memberShape) - ) - ) - : "" - ); - builder.append( - "%1$s: %2$s%3$s,".formatted( - StringUtils.capitalize(memberName), - (targetShape.isStructureShape() && memberShape.isOptional()) && - !targetShape.hasTrait(ReferenceTrait.class) - ? "&" - : "", - targetShape.accept( - new DafnyToSmithyShapeVisitor( - context, - derivedDataSource, - writer, - isConfigShape, - memberShape.isOptional() - ) - ) - ) - ); + @Override + public String blobShape(BlobShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + return """ + func () []byte { + var b []byte + if %s == nil { + return nil + } + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }()""".formatted(dataSource, dataSource); } @Override @@ -287,401 +164,297 @@ public String structureShape(final StructureShape shape) { )); } - // TODO: smithy-dafny-conversion library - @Override - public String listShape(ListShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - StringBuilder builder = new StringBuilder(); + return builder.append("}").toString(); + } - MemberShape memberShape = shape.getMember(); - final Shape targetShape = context - .model() - .expectShape(memberShape.getTarget()); - var typeName = targetShape.isStructureShape() - ? context.symbolProvider().toSymbol(memberShape) - : context.symbolProvider().toSymbol(memberShape); - builder.append( - """ - func() []%s{ - var fieldValue []%s - if %s == nil { - return nil - } - for i := dafny.Iterate(%s.(dafny.Sequence)); ; { - val, ok := i() - if !ok { - break - } - fieldValue = append(fieldValue, %s)} - """.formatted( - SmithyNameResolver.getSmithyType(shape, typeName), - SmithyNameResolver.getSmithyType(shape, typeName), - dataSource, - dataSource, - targetShape.accept( - new DafnyToSmithyShapeVisitor( - context, - "val%s".formatted( - targetShape.isStructureShape() - ? ".(%s)".formatted( - DafnyNameResolver.getDafnyType( - targetShape, - context.symbolProvider().toSymbol(targetShape) - ) - ) - : "" - ), - writer, - isConfigShape - ) - ) - ) - ); + // TODO: smithy-dafny-conversion library + @Override + public String listShape(ListShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + StringBuilder builder = new StringBuilder(); - // Close structure - return builder - .append("return fieldValue }()".formatted(dataSource)) - .toString(); - } + MemberShape memberShape = shape.getMember(); + final Shape targetShape = context.model().expectShape(memberShape.getTarget()); + var typeName = targetShape.isStructureShape() ? context.symbolProvider().toSymbol(memberShape) : context.symbolProvider().toSymbol(memberShape); + builder.append(""" + func() []%s{ + var fieldValue []%s + if %s == nil { + return nil + } + for i := dafny.Iterate(%s.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, %s)} + """.formatted(SmithyNameResolver.getSmithyType(shape, typeName), SmithyNameResolver.getSmithyType(shape, typeName), dataSource, dataSource, + targetShape.accept( + new DafnyToSmithyShapeVisitor(context, "val%s".formatted(targetShape.isStructureShape() ? ".(%s)".formatted(DafnyNameResolver.getDafnyType(targetShape, context.symbolProvider().toSymbol(targetShape))) : ""), writer, isConfigShape) + ))); - @Override - public String mapShape(MapShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - StringBuilder builder = new StringBuilder(); + // Close structure + return builder.append("return fieldValue }()".formatted(dataSource)).toString(); + } - MemberShape keyMemberShape = shape.getKey(); - final Shape keyTargetShape = context - .model() - .expectShape(keyMemberShape.getTarget()); - MemberShape valueMemberShape = shape.getValue(); - final Shape valueTargetShape = context - .model() - .expectShape(valueMemberShape.getTarget()); - final var type = context - .symbolProvider() - .toSymbol(valueTargetShape) - .getName(); + @Override + public String mapShape(MapShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + StringBuilder builder = new StringBuilder(); - builder.append( - """ - func() map[string]%s { - var m map[string]%s = make(map[string]%s) - if %s == nil { - return nil - } - for i := dafny.Iterate(%s.(dafny.Map).Items());; { - val, ok := i() - if !ok { - break; - } - m[%s] = %s - } - return m - }()""".formatted( - type, - type, - type, - dataSource, - dataSource, - keyTargetShape.accept( - new DafnyToSmithyShapeVisitor( - context, - "(*val.(dafny.Tuple).IndexInt(0))", - writer, - isConfigShape - ) - ), - valueTargetShape.accept( - new DafnyToSmithyShapeVisitor( - context, - "(*val.(dafny.Tuple).IndexInt(1))", - writer, - isConfigShape - ) - ) - ) - ); - return builder.toString(); - } + MemberShape keyMemberShape = shape.getKey(); + final Shape keyTargetShape = context.model().expectShape(keyMemberShape.getTarget()); + MemberShape valueMemberShape = shape.getValue(); + final Shape valueTargetShape = context.model().expectShape(valueMemberShape.getTarget()); + final var type = context.symbolProvider().toSymbol(valueTargetShape).getName(); - @Override - public String booleanShape(BooleanShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (this.isOptional) { - return """ - func() *bool { - var b bool - if %s == nil { - return nil - } - b = %s.(%s) - return &b - }()""".formatted( - dataSource, - dataSource, - context.symbolProvider().toSymbol(shape).getName() - ); - } else { - return "%s.(%s)".formatted( - dataSource, - context.symbolProvider().toSymbol(shape).getName() - ); + builder.append(""" + func() map[string]%s { + var m map[string]%s = make(map[string]%s) + if %s == nil { + return nil + } + for i := dafny.Iterate(%s.(dafny.Map).Items());; { + val, ok := i() + if !ok { + break; + } + m[%s] = %s + } + return m + }()""".formatted(type, type, type, dataSource, dataSource, keyTargetShape.accept( + new DafnyToSmithyShapeVisitor(context, "(*val.(dafny.Tuple).IndexInt(0))", writer, isConfigShape) + ), + valueTargetShape.accept( + new DafnyToSmithyShapeVisitor(context, "(*val.(dafny.Tuple).IndexInt(1))", writer, isConfigShape) + ) + )); + return builder.toString(); } - } - - @Override - public String stringShape(StringShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (shape.hasTrait(EnumTrait.class)) { - return """ - func () *%s.%s { - var u %s.%s - if %s == nil { - return nil - } - inputEnum := %s.(%s) - index := -1; - for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { - enum, ok := allEnums() - if ok { - index++ - if enum.(%s).Equals(inputEnum) { - break; - } - } - } - return &u.Values()[index] - }()""".formatted( - SmithyNameResolver.smithyTypesNamespace(shape), - context.symbolProvider().toSymbol(shape).getName(), - SmithyNameResolver.smithyTypesNamespace(shape), - context.symbolProvider().toSymbol(shape).getName(), - dataSource, - dataSource, - DafnyNameResolver.getDafnyType( - shape, - context.symbolProvider().toSymbol(shape) - ), - DafnyNameResolver.getDafnyCompanionStructType( - shape, - context.symbolProvider().toSymbol(shape) - ), - DafnyNameResolver.getDafnyType( - shape, - context.symbolProvider().toSymbol(shape) - ) - ); + @Override + public String booleanShape(BooleanShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (this.isOptional) { + return """ + func() *bool { + var b bool + if %s == nil { + return nil + } + b = %s.(%s) + return &b + }()""".formatted(dataSource, dataSource, context.symbolProvider().toSymbol(shape).getName()); + } else { + return "%s.(%s)".formatted(dataSource, context.symbolProvider().toSymbol(shape).getName()); + } } - var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) - ? "uint8" - : "dafny.Char"; - var strConv = "s = s + string(val.(%s))".formatted(underlyingType); - if (underlyingType == "uint8") { - strConv = - """ - // UTF bytes should be always converted from bytes to string in go - // Otherwise go treats the string as a unicode codepoint + @Override + public String stringShape(StringShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (shape.hasTrait(EnumTrait.class)) { + return """ + func () *%s.%s { + var u %s.%s + if %s == nil { + return nil + } + inputEnum := %s.(%s) + index := -1; + for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(%s).Equals(inputEnum) { + break; + } + } + } + + return &u.Values()[index] + }()""".formatted(SmithyNameResolver.smithyTypesNamespace(shape), context.symbolProvider().toSymbol(shape).getName(), SmithyNameResolver.smithyTypesNamespace(shape), context.symbolProvider().toSymbol(shape).getName(), dataSource, dataSource, DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)), DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), + DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))); + } - var valUint, _ = val.(%s) - var byteSlice = []byte{valUint} - s = s + string(byteSlice) - """.formatted(underlyingType); - } - if ((boolean) isOptional) { - return """ - func() (*string) { - var s string - if %s == nil { - return nil - } - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - %s - } - } - }()""".formatted(dataSource, dataSource, strConv); - } else { - return """ - func() (string) { - var s string - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return s - } else { - %s - } - } - }()""".formatted(dataSource, strConv); + var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) ? "uint8" : "dafny.Char"; + var strConv = "s = s + string(val.(%s))".formatted(underlyingType); + if( underlyingType == "uint8" ) { + strConv = """ + // UTF bytes should be always converted from bytes to string in go + // Otherwise go treats the string as a unicode codepoint + + var valUint, _ = val.(%s) + var byteSlice = []byte{valUint} + s = s + string(byteSlice) + """.formatted(underlyingType); + } + if ((boolean)isOptional) { + return """ + func() (*string) { + var s string + if %s == nil { + return nil + } + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + %s + } + } + }()""".formatted(dataSource, dataSource, strConv); + } + else { + return """ + func() (string) { + var s string + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return s + } else { + %s + } + } + }()""".formatted(dataSource, strConv); + } } - } - @Override - public String integerShape(IntegerShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + @Override + public String integerShape(IntegerShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if ((boolean) isOptional) { - return ( - """ - func() *int32 { - var b int32 - if %s == nil { - return nil - } - b = %s.(int32) - return &b - }()""".formatted(dataSource, dataSource) - ); - } else { - return """ - func() int32 { - var b = %s.(int32) - return b - }() - """.formatted(dataSource); + if ((boolean)isOptional) { + return (""" + func() *int32 { + var b int32 + if %s == nil { + return nil + } + b = %s.(int32) + return &b + }()""".formatted(dataSource, dataSource)); + }else { + return """ + func() int32 { + var b = %s.(int32) + return b + }() + """.formatted(dataSource); + } } - } - @Override - public String longShape(LongShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - return ( - """ - func() *int64 { - var b int64 - if %s == nil { - return nil - } - b = %s.(int64) - return &b - }()""" - ).formatted(dataSource, dataSource); - } - - @Override - public String doubleShape(DoubleShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - writer.addUseImports(SmithyGoDependency.MATH); - return """ - func () *float64 { - var b []byte - if %s == nil { - return nil + @Override + public String longShape(LongShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + return (""" + func() *int64 { + var b int64 + if %s == nil { + return nil + } + b = %s.(int64) + return &b + }()""").formatted(dataSource, dataSource); } - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return &[]float64{math.Float64frombits(binary.LittleEndian.Uint64(b))}[0] - } else { - b = append(b, val.(byte)) - } - } - }()""".formatted(dataSource, dataSource); - } - @Override - public String unionShape(UnionShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilCheck; - if (GoPointableIndex.of(context.model()).isPointable(shape) == false) { - nilCheck = ""; - } else { - nilCheck = - """ - if %s == nil { - return nil - }""".formatted(dataSource); + @Override + public String doubleShape(DoubleShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + writer.addUseImports(SmithyGoDependency.MATH); + return """ + func () *float64 { + var b []byte + if %s == nil { + return nil + } + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return &[]float64{math.Float64frombits(binary.LittleEndian.Uint64(b))}[0] + } else { + b = append(b, val.(byte)) + } + } + }()""".formatted(dataSource, dataSource); } - final String functionInit = - """ - func() %s { - var union %s - %s - """.formatted( - context.symbolProvider().toSymbol(shape), - context.symbolProvider().toSymbol(shape), - nilCheck - ); - StringBuilder eachMemberInUnion = new StringBuilder(); - for (var member : shape.getAllMembers().values()) { - final Shape targetShape = context.model().expectShape(member.getTarget()); - final String memberName = context.symbolProvider().toMemberName(member); - final String rawUnionDataSource = - "(" + - dataSource + - ".(" + - DafnyNameResolver.getDafnyType( - shape, - context.symbolProvider().toSymbol(shape) - ) + - "))"; - // unwrap union type, assert it then convert it to its member type with Dtor_ (example: Dtor_BlobValue()). unionDataSource is not a wrapper object until now. - String unionDataSource = - rawUnionDataSource + - ".Dtor_" + - memberName.replace(shape.getId().getName() + "Member", "") + - "()"; - final Boolean isMemberShapePointable = - (GoPointableIndex.of(context.model()).isPointable(targetShape) && - GoPointableIndex.of(context.model()).isDereferencable(targetShape)) && - !targetShape.isStructureShape(); - final String pointerForPointableShape = isMemberShapePointable ? "*" : ""; - final String isMemberCheck = - """ - if ((%s).%s()) {""".formatted( - rawUnionDataSource, - memberName.replace(shape.getId().getName() + "Member", "Is_") - ); - String wrappedDataSource = ""; - if (!(targetShape.isStructureShape())) { - // All other shape except structure needs a Wrapper object but unionDataSource is not a Wrapper object. - wrappedDataSource = - """ - var dataSource = Wrappers.Companion_Option_.Create_Some_(%s)""".formatted( - unionDataSource + + @Override + public String unionShape(UnionShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilCheck; + if (GoPointableIndex.of(context.model()).isPointable(shape) == false) { + nilCheck = ""; + } else { + nilCheck = """ + if %s == nil { + return nil + }""".formatted( + dataSource + ); + } + final String functionInit = """ + func() %s { + var union %s + %s + """.formatted( + context.symbolProvider().toSymbol(shape), + context.symbolProvider().toSymbol(shape), + nilCheck ); - unionDataSource = "dataSource.UnwrapOr(nil)"; - } - eachMemberInUnion.append( - """ - %s - %s - union = &%s.%s{ - Value: %s(%s), + StringBuilder eachMemberInUnion = new StringBuilder(); + for (var member : shape.getAllMembers().values()) { + final Shape targetShape = context.model().expectShape(member.getTarget()); + final String memberName = context.symbolProvider().toMemberName(member); + final String rawUnionDataSource = "(" + dataSource + ".(" + DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)) + "))"; + // unwrap union type, assert it then convert it to its member type with Dtor_ (example: Dtor_BlobValue()). unionDataSource is not a wrapper object until now. + String unionDataSource = rawUnionDataSource + ".Dtor_" + memberName.replace(shape.getId().getName() + "Member", "") + "()"; + final Boolean isMemberShapePointable = (GoPointableIndex.of(context.model()).isPointable(targetShape) && GoPointableIndex.of(context.model()).isDereferencable(targetShape)) && !targetShape.isStructureShape(); + final String pointerForPointableShape = isMemberShapePointable ? "*" : ""; + final String isMemberCheck = """ + if ((%s).%s()) {""".formatted( + rawUnionDataSource, + memberName.replace(shape.getId().getName() + "Member", "Is_") + ); + String wrappedDataSource = ""; + if (!(targetShape.isStructureShape())) { + // All other shape except structure needs a Wrapper object but unionDataSource is not a Wrapper object. + wrappedDataSource = """ + var dataSource = Wrappers.Companion_Option_.Create_Some_(%s)""".formatted(unionDataSource); + unionDataSource = "dataSource.UnwrapOr(nil)"; } + eachMemberInUnion.append(""" + %s + %s + union = &%s.%s{ + Value: %s(%s), + } + } + """.formatted( + isMemberCheck, + wrappedDataSource, + SmithyNameResolver.smithyTypesNamespace(shape), + memberName, + pointerForPointableShape, + targetShape.accept( + new DafnyToSmithyShapeVisitor(context, unionDataSource, writer, isConfigShape, isMemberShapePointable) + ))); } - """.formatted( - isMemberCheck, - wrappedDataSource, - SmithyNameResolver.smithyTypesNamespace(shape), - memberName, - pointerForPointableShape, - targetShape.accept( - new DafnyToSmithyShapeVisitor( - context, - unionDataSource, - writer, - isConfigShape, - isMemberShapePointable - ) - ) - ) - ); + return + """ + %s + %s + return union + }()""".formatted( + functionInit, + eachMemberInUnion + ); } - return """ - %s - %s - return union - }()""".formatted(functionInit, eachMemberInUnion); - } - @Override - public String timestampShape(TimestampShape shape) { - return "nil"; - } -} + @Override + public String timestampShape(TimestampShape shape) { + return "nil"; + } +} \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java index a912031367..425b3436b6 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java @@ -1,7 +1,5 @@ package software.amazon.polymorph.smithygo.localservice.shapevisitor; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoWriter; import software.amazon.polymorph.smithygo.codegen.SmithyGoDependency; @@ -31,192 +29,108 @@ import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.utils.StringUtils; +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + public class SmithyToDafnyShapeVisitor extends ShapeVisitor.Default { + private final GenerationContext context; + private final String dataSource; + private final GoWriter writer; + private final boolean isConfigShape; - private final GenerationContext context; - private final String dataSource; - private final GoWriter writer; - private final boolean isConfigShape; - - private final boolean isOptional; - protected boolean isPointerType; - - public void setPointerType() { - this.isPointerType = false; - } - - public SmithyToDafnyShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isConfigShape, - final boolean isOptional, - final boolean isPointerType - ) { - this.context = context; - this.dataSource = dataSource; - this.writer = writer; - this.isConfigShape = isConfigShape; - this.isOptional = isOptional; - this.isPointerType = isPointerType; - } - - protected String referenceStructureShape(StructureShape shape) { - ReferenceTrait referenceTrait = shape.expectTrait(ReferenceTrait.class); - Shape resourceOrService = context - .model() - .expectShape(referenceTrait.getReferentId()); - - if (resourceOrService.asResourceShape().isPresent()) { - ResourceShape resourceShape = resourceOrService.asResourceShape().get(); - var namespace = ""; - if ( - !resourceShape - .toShapeId() - .getNamespace() - .equals(context.settings().getService().getNamespace()) - ) { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - resourceShape.toShapeId().getNamespace() - ), - SmithyNameResolver.shapeNamespace(resourceShape) - ); - namespace = - SmithyNameResolver.shapeNamespace(resourceShape).concat("."); - } - if (!this.isOptional) { - return "%s_ToDafny(%s)".formatted( - namespace.concat(resourceShape.toShapeId().getName()), - dataSource - ); - } else { - var goCodeBlock = - """ - func () Wrappers.Option { - if %s == nil { - return Wrappers.Companion_Option_.Create_None_() - } - return Wrappers.Companion_Option_.Create_Some_(%s) - }()"""; - return goCodeBlock.formatted( - dataSource, - "%s_ToDafny(%s)".formatted( - namespace.concat(resourceShape.toShapeId().getName()), - dataSource - ) - ); - } - } + private final boolean isOptional; + protected boolean isPointerType; - if (resourceOrService.asServiceShape().isPresent()) { - ServiceShape resourceShape = resourceOrService.asServiceShape().get(); - if (!this.isOptional) { - return dataSource; - } else { - var goCodeBlock = - """ - func () Wrappers.Option { - if %s == nil { - return Wrappers.Companion_Option_.Create_None_() - } - return Wrappers.Companion_Option_.Create_Some_(%s) - }()"""; - return goCodeBlock.formatted(dataSource, dataSource); - } + public void setPointerType() { + this.isPointerType = false; } - throw new UnsupportedOperationException( - "Unknown referenceStructureShape type: " + shape - ); - } - - @Override - protected String getDefault(Shape shape) { - throw new CodegenException( - String.format( - "Unsupported conversion of %s to %s using the %s protocol", - shape, - shape.getType(), - context.protocolGenerator().getName() - ) - ); - } - - @Override - public String blobShape(BlobShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; + public SmithyToDafnyShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isConfigShape, + final boolean isOptional, + final boolean isPointerType + ) { + this.context = context; + this.dataSource = dataSource; + this.writer = writer; + this.isConfigShape = isConfigShape; + this.isOptional = isOptional; + this.isPointerType = isPointerType; } - return """ - func () %s { - var v []interface{} - if %s == nil {return %s} - for _, e := range %s { - v = append(v, e) + + protected String referenceStructureShape(StructureShape shape) { + ReferenceTrait referenceTrait = shape.expectTrait(ReferenceTrait.class); + Shape resourceOrService = context.model().expectShape(referenceTrait.getReferentId()); + + if (resourceOrService.asResourceShape().isPresent()) { + ResourceShape resourceShape = resourceOrService.asResourceShape().get(); + var namespace = ""; + if (!resourceShape.toShapeId().getNamespace().equals(context.settings().getService().getNamespace())) { + writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resourceShape.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(resourceShape)); + namespace = SmithyNameResolver.shapeNamespace(resourceShape).concat("."); + } + if(!this.isOptional) { + return "%s_ToDafny(%s)".formatted(namespace.concat(resourceShape.toShapeId().getName()), dataSource); + } else { + var goCodeBlock = """ + func () Wrappers.Option { + if %s == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(%s) + }()"""; + return goCodeBlock.formatted(dataSource, "%s_ToDafny(%s)".formatted(namespace.concat(resourceShape.toShapeId().getName()), dataSource)); + } + } + + if (resourceOrService.asServiceShape().isPresent()) { + ServiceShape resourceShape = resourceOrService.asServiceShape().get(); + if(!this.isOptional) { + return dataSource; + } else { + var goCodeBlock = """ + func () Wrappers.Option { + if %s == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(%s) + }()"""; + return goCodeBlock.formatted(dataSource, dataSource); + } } - return %s; - }()""".formatted( - returnType, - dataSource, - nilWrapIfRequired, - dataSource, - someWrapIfRequired.formatted("dafny.SeqOf(v...)") - ); - } - - @Override - public String structureShape(final StructureShape shape) { - if (shape.hasTrait(ReferenceTrait.class)) { - return referenceStructureShape(shape); + + throw new UnsupportedOperationException("Unknown referenceStructureShape type: " + shape); } - final var builder = new StringBuilder(); - writer.addImportFromModule( - "github.com/dafny-lang/DafnyStandardLibGo", - "Wrappers" - ); - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - shape.toShapeId().getNamespace() - ), - DafnyNameResolver.dafnyTypesNamespace(shape) - ); - - String someWrapIfRequired = "%s"; - - String companionStruct; - String returnType; - if (shape.hasTrait(ErrorTrait.class)) { - companionStruct = - DafnyNameResolver.getDafnyErrorCompanionCreate( - shape, - context.symbolProvider().toSymbol(shape) - ); - returnType = DafnyNameResolver.getDafnyBaseErrorType(shape); - } else { - companionStruct = - DafnyNameResolver.getDafnyCompanionTypeCreate( - shape, - context.symbolProvider().toSymbol(shape) - ); - returnType = - DafnyNameResolver.getDafnyType( - shape, - context.symbolProvider().toSymbol(shape) - ); + + @Override + protected String getDefault(Shape shape) { + throw new CodegenException(String.format( + "Unsupported conversion of %s to %s using the %s protocol", + shape, shape.getType(), context.protocolGenerator().getName())); } - String nilWrapIfRequired = returnType.concat("{}"); - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; + @Override + public String blobShape(BlobShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + return """ + func () %s { + var v []interface{} + if %s == nil {return %s} + for _, e := range %s { + v = append(v, e) + } + return %s; + }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, someWrapIfRequired.formatted("dafny.SeqOf(v...)")); } @Override @@ -285,488 +199,321 @@ public String structureShape(final StructureShape shape) { } return goCodeBlock.formatted(returnType, nilCheck, someWrapIfRequired.formatted(builder.append(")").toString())); } - var goCodeBlock = - """ - func () %s { - %s - return %s - }()"""; - - builder.append("%1$s(".formatted(companionStruct)); - String fieldSeparator = ","; - for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { - final var memberName = memberShapeEntry.getKey(); - final var memberShape = memberShapeEntry.getValue(); - final var targetShape = context - .model() - .expectShape(memberShape.getTarget()); - builder.append( - "%1$s%2$s".formatted( - targetShape.accept( - new SmithyToDafnyShapeVisitor( - context, - dataSource + "." + StringUtils.capitalize(memberName), - writer, - isConfigShape, - memberShape.isOptional(), - context - .symbolProvider() - .toSymbol(memberShape) - .getProperty(POINTABLE, Boolean.class) - .orElse(false) - ) - ), - fieldSeparator - ) - ); - } - return goCodeBlock.formatted( - returnType, - nilCheck, - someWrapIfRequired.formatted(builder.append(")").toString()) - ); - } - - @Override - public String mapShape(MapShape shape) { - StringBuilder builder = new StringBuilder(); - - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - MemberShape keyMemberShape = shape.getKey(); - final Shape keyTargetShape = context - .model() - .expectShape(keyMemberShape.getTarget()); - MemberShape valueMemberShape = shape.getValue(); - final Shape valueTargetShape = context - .model() - .expectShape(valueMemberShape.getTarget()); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Map"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - builder.append( - """ - func () %s { - if %s == nil { return %s } - fieldValue := dafny.NewMapBuilder() - for key, val := range %s { - fieldValue.Add(%s, %s) - } - return %s - }()""".formatted( - returnType, - dataSource, - nilWrapIfRequired, - dataSource, - keyTargetShape.accept( - new SmithyToDafnyShapeVisitor( - context, - "key", - writer, - isConfigShape, - false, - false - ) - ), - valueTargetShape.accept( - new SmithyToDafnyShapeVisitor( - context, - "val", - writer, - isConfigShape, - false, - false - ) - ), - someWrapIfRequired.formatted("fieldValue.ToMap()") - ) - ); - - // Close structure - return builder.toString(); - } - - @Override - public String listShape(ListShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - StringBuilder builder = new StringBuilder(); - - MemberShape memberShape = shape.getMember(); - final Shape targetShape = context - .model() - .expectShape(memberShape.getTarget()); - - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; + @Override + public String mapShape(MapShape shape) { + StringBuilder builder = new StringBuilder(); + + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + MemberShape keyMemberShape = shape.getKey(); + final Shape keyTargetShape = context.model().expectShape(keyMemberShape.getTarget()); + MemberShape valueMemberShape = shape.getValue(); + final Shape valueTargetShape = context.model().expectShape(valueMemberShape.getTarget()); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Map"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + builder.append(""" + func () %s { + if %s == nil { return %s } + fieldValue := dafny.NewMapBuilder() + for key, val := range %s { + fieldValue.Add(%s, %s) + } + return %s + }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, + keyTargetShape.accept( + new SmithyToDafnyShapeVisitor(context, "key", writer, isConfigShape, false, false)), + valueTargetShape.accept( + new SmithyToDafnyShapeVisitor(context, "val", writer, isConfigShape, false, false)), + someWrapIfRequired.formatted("fieldValue.ToMap()") + ) + ); + + // Close structure + return builder.toString(); + } - builder.append( - """ - func () %s { - if %s == nil { return %s } - var fieldValue []interface{} = make([]interface{}, 0) - for _, val := range %s { - element := %s - fieldValue = append(fieldValue, element) - } - return %s - }()""".formatted( - returnType, - dataSource, - nilWrapIfRequired, - dataSource, - targetShape.accept( - new SmithyToDafnyShapeVisitor( - context, - "val", - writer, - isConfigShape, - false, - false - ) - ), - someWrapIfRequired.formatted("dafny.SeqOf(fieldValue...)") - ) - ); - - // Close structure - return builder.toString(); - } - - @Override - public String booleanShape(BooleanShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s%s"; - String returnType = "interface {}"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; + @Override + public String listShape(ListShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + StringBuilder builder = new StringBuilder(); + + MemberShape memberShape = shape.getMember(); + final Shape targetShape = context.model().expectShape(memberShape.getTarget()); + + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + builder.append(""" + func () %s { + if %s == nil { return %s } + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range %s { + element := %s + fieldValue = append(fieldValue, element) + } + return %s + }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, + targetShape.accept( + new SmithyToDafnyShapeVisitor(context, "val", writer, isConfigShape, false, false) + ), someWrapIfRequired.formatted("dafny.SeqOf(fieldValue...)"))); + + // Close structure + return builder.toString(); } - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = - "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + @Override + public String booleanShape(BooleanShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s%s"; + String returnType = "interface {}"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; + } + + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + + return """ + func () %s { + %s + return %s + }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); } - return """ - func () %s { - %s - return %s - }()""".formatted( - returnType, - nilCheck, - someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) - ); - } - - @Override - public String stringShape(StringShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (shape.hasTrait(EnumTrait.class)) { - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = DafnyNameResolver.getDafnyType( - shape, - context.symbolProvider().toSymbol(shape) - ); - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - - var nilCheck = ""; - var dereferenceIfRequired = isPointerType ? "*" : ""; - if (isPointerType) { - nilCheck = - "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - return """ - func () %s { - %s - var index int - for _, enumVal := range %s.Values() { - index++ - if enumVal == %s%s{ - break; - } - } - var enum interface{} - for allEnums, i := dafny.Iterate(%s{}.AllSingletonConstructors()), 0; i < index; i++ { - var ok bool - enum, ok = allEnums() - if !ok { - break; - } - } - return %s - }()""".formatted( - returnType, - nilCheck, - dataSource, - dereferenceIfRequired, - dataSource, - DafnyNameResolver.getDafnyCompanionStructType( - shape, - context.symbolProvider().toSymbol(shape) - ), - someWrapIfRequired.formatted( - "enum.(%s)".formatted( - DafnyNameResolver.getDafnyType( - shape, - context.symbolProvider().toSymbol(shape) - ) - ) - ) - ); - } else { - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - - var nilCheck = ""; - var dereferenceIfRequired = isPointerType ? "*" : ""; - if (isPointerType) { - nilCheck = - "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - - if (shape.hasTrait(DafnyUtf8BytesTrait.class)) writer.addUseImports( - SmithyGoDependency.stdlib("unicode/utf8") - ); - - var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) - ? """ - dafny.SeqOf(func () []interface{} { - utf8.ValidString(%s%s) - b := []byte(%s%s) - f := make([]interface{}, len(b)) - for i, v := range b { - f[i] = v + @Override + public String stringShape(StringShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (shape.hasTrait(EnumTrait.class)) { + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)); + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - return f - }()...)""".formatted( - dereferenceIfRequired, - dataSource, - dereferenceIfRequired, - dataSource - ) - : "dafny.SeqOfChars([]dafny.Char(%s%s)...)".formatted( - dereferenceIfRequired, - dataSource - ); - - return """ - func () %s { - %s - return %s - }()""".formatted( - returnType, - nilCheck, - someWrapIfRequired.formatted(underlyingType) - ); - } - } - - @Override - public String integerShape(IntegerShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s%s"; - String returnType = "interface {}"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; - } - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = - "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + var nilCheck = ""; + var dereferenceIfRequired = isPointerType ? "*" : ""; + if (isPointerType) { + nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + return """ + func () %s { + %s + var index int + for _, enumVal := range %s.Values() { + index++ + if enumVal == %s%s{ + break; + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(%s{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break; + } + } + return %s + }()""".formatted(returnType, nilCheck, dataSource, dereferenceIfRequired, dataSource, DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), someWrapIfRequired.formatted("enum.(%s)".formatted(DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))))); + } else { + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + var nilCheck = ""; + var dereferenceIfRequired = isPointerType ? "*" : ""; + if (isPointerType) { + nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + + if (shape.hasTrait(DafnyUtf8BytesTrait.class)) + writer.addUseImports(SmithyGoDependency.stdlib("unicode/utf8")); + + var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) ? """ + dafny.SeqOf(func () []interface{} { + utf8.ValidString(%s%s) + b := []byte(%s%s) + f := make([]interface{}, len(b)) + for i, v := range b { + f[i] = v + } + return f + }()...)""".formatted(dereferenceIfRequired, dataSource, dereferenceIfRequired, dataSource) : "dafny.SeqOfChars([]dafny.Char(%s%s)...)".formatted(dereferenceIfRequired, dataSource); + + return """ + func () %s { + %s + return %s + }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(underlyingType)); + } } - return """ - func () %s { - %s - return %s - }()""".formatted( - returnType, - nilCheck, - someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) - ); - } - - @Override - public String longShape(LongShape shape) { - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s%s"; - String returnType = "interface {}"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; + @Override + public String integerShape(IntegerShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s%s"; + String returnType = "interface {}"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; + } + + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + + return """ + func () %s { + %s + return %s + }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); + } - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = - "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + @Override + public String longShape(LongShape shape) { + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s%s"; + String returnType = "interface {}"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; + } + + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + return """ + func () %s { + %s + return %s + }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); } - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - return """ - func () %s { - %s - return %s - }()""".formatted( - returnType, - nilCheck, - someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) - ); - } - - @Override - public String doubleShape(DoubleShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); - writer.addUseImports(SmithyGoDependency.MATH); - - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "interface {}"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; + @Override + public String doubleShape(DoubleShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); + writer.addUseImports(SmithyGoDependency.MATH); + + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "interface {}"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + + return """ + func () %s { + %s + var bits = math.Float64bits(%s%s) + var bytes = make([]byte, 8) + binary.LittleEndian.PutUint64(bytes, bits) + var v []interface{} + for _, e := range bytes { + v = append(v, e) + } + return %s; + }()""".formatted(returnType, nilCheck, dereferenceIfRequired, dataSource, someWrapIfRequired.formatted("dafny.SeqOf(v...)")); } - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = - "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + @Override + public String unionShape(UnionShape shape) { + final String internalDafnyType = DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)); + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + final String functionInit = """ + func() Wrappers.Option { + switch %s.(type) {""".formatted(dataSource); + StringBuilder eachMemberInUnion = new StringBuilder(); + for (var member : shape.getAllMembers().values()) { + final String memberName = context.symbolProvider().toMemberName(member); + final Shape targetShape = context.model().expectShape(member.getTarget()); + final String someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s(%s))"; + final String baseType = DafnyNameResolver.getDafnyType(targetShape, context.symbolProvider().toSymbol(targetShape)); + eachMemberInUnion.append(""" + case *%s.%s: + var companion = %s + var inputToConversion = %s + return %s + """.formatted( + SmithyNameResolver.smithyTypesNamespace(shape), + context.symbolProvider().toMemberName(member), + internalDafnyType.replace(shape.getId().getName(), "CompanionStruct_" + shape.getId().getName() + "_{}"), + targetShape.accept( + new SmithyToDafnyShapeVisitor( + context, dataSource + ".(*" + SmithyNameResolver.smithyTypesNamespace(shape) + "." + context.symbolProvider().toMemberName(member) + ").Value", writer, isConfigShape, true, false + ) + ), + someWrapIfRequired.formatted( + DafnyNameResolver.getDafnyCreateFuncForUnionMemberShape(shape, memberName), + "inputToConversion.UnwrapOr(nil)%s".formatted(baseType != "" ? ".(" + baseType + ")" : "") + ) + )); + } + final String defaultCase = """ + default: + panic("Unhandled union type") + } + }()"""; + return """ + %s + %s + %s""".formatted( + functionInit, + eachMemberInUnion, + defaultCase + ); } - return """ - func () %s { - %s - var bits = math.Float64bits(%s%s) - var bytes = make([]byte, 8) - binary.LittleEndian.PutUint64(bytes, bits) - var v []interface{} - for _, e := range bytes { - v = append(v, e) - } - return %s; - }()""".formatted( - returnType, - nilCheck, - dereferenceIfRequired, - dataSource, - someWrapIfRequired.formatted("dafny.SeqOf(v...)") - ); - } - - @Override - public String unionShape(UnionShape shape) { - final String internalDafnyType = DafnyNameResolver.getDafnyType( - shape, - context.symbolProvider().toSymbol(shape) - ); - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - final String functionInit = - """ - func() Wrappers.Option { - switch %s.(type) {""".formatted(dataSource); - StringBuilder eachMemberInUnion = new StringBuilder(); - for (var member : shape.getAllMembers().values()) { - final String memberName = context.symbolProvider().toMemberName(member); - final Shape targetShape = context.model().expectShape(member.getTarget()); - final String someWrapIfRequired = - "Wrappers.Companion_Option_.Create_Some_(%s(%s))"; - final String baseType = DafnyNameResolver.getDafnyType( - targetShape, - context.symbolProvider().toSymbol(targetShape) - ); - eachMemberInUnion.append( - """ - case *%s.%s: - var companion = %s - var inputToConversion = %s - return %s - """.formatted( - SmithyNameResolver.smithyTypesNamespace(shape), - context.symbolProvider().toMemberName(member), - internalDafnyType.replace( - shape.getId().getName(), - "CompanionStruct_" + shape.getId().getName() + "_{}" - ), - targetShape.accept( - new SmithyToDafnyShapeVisitor( - context, - dataSource + - ".(*" + - SmithyNameResolver.smithyTypesNamespace(shape) + - "." + - context.symbolProvider().toMemberName(member) + - ").Value", - writer, - isConfigShape, - true, - false - ) - ), - someWrapIfRequired.formatted( - DafnyNameResolver.getDafnyCreateFuncForUnionMemberShape( - shape, - memberName - ), - "inputToConversion.UnwrapOr(nil)%s".formatted( - baseType != "" ? ".(" + baseType + ")" : "" - ) - ) - ) - ); + @Override + public String timestampShape(TimestampShape shape) { + return "Wrappers.Companion_Option_.Create_None_()"; } - final String defaultCase = - """ - default: - panic("Unhandled union type") - } - }()"""; - return """ - %s - %s - %s""".formatted(functionInit, eachMemberInUnion, defaultCase); - } - - @Override - public String timestampShape(TimestampShape shape) { - return "Wrappers.Companion_Option_.Create_None_()"; - } -} +} \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/utils/GoCodegenUtils.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/utils/GoCodegenUtils.java index 00f7ade743..086859e8ee 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/utils/GoCodegenUtils.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/utils/GoCodegenUtils.java @@ -13,50 +13,36 @@ public class GoCodegenUtils { - public static String getType(Symbol symbol, ServiceTrait serviceTrait) { - if ( - symbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class).isEmpty() - ) { - return SmithyNameResolver.getSmithyTypeAws(serviceTrait, symbol, true); + public static String getType(Symbol symbol, ServiceTrait serviceTrait) { + if (symbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class).isEmpty()) { + return SmithyNameResolver.getSmithyTypeAws(serviceTrait, symbol, true); + } + var type = getType(symbol.expectProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class), serviceTrait); + if(symbol.getProperty(SymbolUtils.GO_MAP).isPresent()) { + return "map[string]" + type; + } + if (symbol.getProperty(SymbolUtils.GO_SLICE).isPresent()) { + return "[]" + type; + } + throw new RuntimeException("Failed to determine shape type"); } - var type = getType( - symbol.expectProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class), - serviceTrait - ); - if (symbol.getProperty(SymbolUtils.GO_MAP).isPresent()) { - return "map[string]" + type; - } - if (symbol.getProperty(SymbolUtils.GO_SLICE).isPresent()) { - return "[]" + type; - } - throw new RuntimeException("Failed to determine shape type"); - } - public static Symbol getRootSymbol(Symbol symbol) { - if ( - symbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class).isEmpty() - ) { - return symbol; + public static Symbol getRootSymbol(Symbol symbol) { + if (symbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class).isEmpty()) { + return symbol; + } + return getRootSymbol(symbol.expectProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class)); } - return getRootSymbol( - symbol.expectProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class) - ); - } - public static boolean isOperationStruct(Model model, Shape shape) { - NeighborProvider provider = NeighborProviderIndex - .of(model) - .getReverseProvider(); - for (Relationship relationship : provider.getNeighbors(shape)) { - RelationshipType relationshipType = relationship.getRelationshipType(); - if ( - relationshipType == RelationshipType.INPUT || - relationshipType == RelationshipType.OUTPUT - ) { - return true; - } - } + public static boolean isOperationStruct(Model model, Shape shape) { + NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); + for (Relationship relationship : provider.getNeighbors(shape)) { + RelationshipType relationshipType = relationship.getRelationshipType(); + if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { + return true; + } + } - return false; - } + return false; + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/AbstractRustShimGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/AbstractRustShimGenerator.java index 5319e4a0db..7a67e71036 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/AbstractRustShimGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/AbstractRustShimGenerator.java @@ -8,19 +8,15 @@ import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; -import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; -import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; import software.amazon.polymorph.utils.IOUtils; -import software.amazon.polymorph.utils.MapUtils; -import software.amazon.polymorph.utils.ModelUtils; import software.amazon.polymorph.utils.TokenTree; +import software.amazon.smithy.aws.traits.ServiceTrait; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.OperationIndex; -import software.amazon.smithy.model.shapes.EnumShape; import software.amazon.smithy.model.shapes.ListShape; import software.amazon.smithy.model.shapes.MapShape; import software.amazon.smithy.model.shapes.MemberShape; @@ -30,6 +26,7 @@ import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.UnionShape; +import software.amazon.smithy.model.traits.EnumDefinition; import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.RequiredTrait; @@ -106,7 +103,7 @@ protected RustFile conversionsErrorModule() { evalTemplate( getClass(), "runtimes/rust/conversions/error.rs", - serviceVariables() + dafnyModuleVariables() ) ); return new RustFile( @@ -125,6 +122,17 @@ protected TokenTree declarePubModules(Stream moduleNames) { .lineSeparated(); } + protected Map dafnyModuleVariables() { + final Map stringStringMap = new HashMap<>(); + stringStringMap.put("dafnyModuleName", getDafnyModuleName()); + stringStringMap.put( + "dafnyInternalModuleName", + getDafnyInternalModuleName() + ); + stringStringMap.put("dafnyTypesModuleName", getDafnyTypesModuleName()); + return stringStringMap; + } + protected RustFile conversionsModule() { Stream operationModules = model .getOperationShapes() @@ -145,8 +153,9 @@ protected RustFile conversionsModule() { .filter(this::shouldGenerateEnumForUnion) .map(structureShape -> toSnakeCase(structureShape.getId().getName())); - Stream enumModules = ModelUtils - .streamEnumShapes(model, service.getId().getNamespace()) + Stream enumModules = model + .getStringShapesWithTrait(EnumTrait.class) + .stream() .map(structureShape -> toSnakeCase(structureShape.getId().getName())); TokenTree content = declarePubModules( @@ -292,8 +301,8 @@ private TokenTree fromDafny( boolean isDafnyOption ) { return switch (shape.getType()) { - case STRING, ENUM -> { - if (shape.hasTrait(EnumTrait.class) || shape.isEnumShape()) { + case STRING -> { + if (shape.hasTrait(EnumTrait.class)) { var enumShapeName = toSnakeCase(shape.toShapeId().getName()); if (isDafnyOption) { yield TokenTree.of( @@ -319,30 +328,6 @@ private TokenTree fromDafny( } yield result; } - } else if (shape.hasTrait(DafnyUtf8BytesTrait.class)) { - final String dafnyToRust = - "::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&%s, |b| *b)).unwrap()"; - String valueToRust; - if (isDafnyOption) { - valueToRust = - """ - match %s.as_ref() { - crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(%s), - _ => ::std::option::Option::None, - }""".formatted( - dafnyValue, - dafnyToRust.formatted(dafnyValue + ".Extract()") - ); - if (!isRustOption) { - valueToRust = "(%s).unwrap()".formatted(valueToRust); - } - } else { - valueToRust = dafnyToRust.formatted(dafnyValue + ".as_ref()"); - if (isRustOption) { - valueToRust = "Some(%s)".formatted(valueToRust); - } - } - yield TokenTree.of(valueToRust); } else { if (isDafnyOption) { yield TokenTree.of( @@ -586,30 +571,21 @@ private TokenTree toDafnyVariantMemberForOperationRequest( ) { Shape targetShape = model.expectShape(member.getTarget()); String snakeCaseMemberName = toSnakeCase(member.getMemberName()); + boolean isRequired = member.hasTrait(RequiredTrait.class); + // These rules were mostly reverse-engineered from inspection of Rust SDKs, + // and may not be complete! + boolean isRustRequired = + (isRequired && + !operationIndex.isOutputStructure(parent) && + !operationIndex.isInputStructure(parent) && + !targetShape.isStructureShape()) || + (operationIndex.isOutputStructure(parent) && + targetShape.isIntegerShape()); return toDafny( targetShape, "value." + snakeCaseMemberName, - !isRustFieldRequired(parent, member), - !hasRequiredTrait(member) - ); - } - - protected final boolean hasRequiredTrait(final MemberShape member) { - return member.hasTrait(RequiredTrait.class); - } - - protected boolean isRustFieldRequired( - final Shape parent, - final MemberShape member - ) { - // These rules were mostly reverse-engineered from inspection of Rust SDKs, - // and may not be complete! - final Shape targetShape = model.expectShape(member.getTarget()); - return ( - hasRequiredTrait(member) && - !operationIndex.isOutputStructure(parent) && - !operationIndex.isInputStructure(parent) && - !targetShape.isStructureShape() + !isRustRequired, + !isRequired ); } @@ -628,8 +604,8 @@ private TokenTree toDafny( boolean isDafnyOption ) { return switch (shape.getType()) { - case STRING, ENUM -> { - if (shape.hasTrait(EnumTrait.class) || shape.isEnumShape()) { + case STRING -> { + if (shape.hasTrait(EnumTrait.class)) { var enumShapeName = toSnakeCase(shape.toShapeId().getName()); if (isDafnyOption) { yield TokenTree.of( @@ -655,24 +631,6 @@ private TokenTree toDafny( ) ); } - } else if (shape.hasTrait(DafnyUtf8BytesTrait.class)) { - final String rustToDafny = - "dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&%s.as_bytes().to_vec(), |b| *b)"; - String valueToDafny; - if (isRustOption) { - valueToDafny = - """ - match %s { - Some(s) => crate::_Wrappers_Compile::Option::Some { value: %s }, - None => crate::_Wrappers_Compile::Option::None {}, - }""".formatted(rustValue, rustToDafny.formatted("s")); - if (!isDafnyOption) { - valueToDafny = "(%s).Extract()".formatted(valueToDafny); - } - } else { - valueToDafny = rustToDafny.formatted(rustValue); - } - yield TokenTree.of("::std::rc::Rc::new(%s)".formatted(valueToDafny)); } else { if (isRustOption) { var result = TokenTree.of( @@ -909,82 +867,154 @@ private TokenTree toDafny( }; } - protected TokenTree enumToDafnyFunction(final EnumShape enumShape) { - final Map variables = MapUtils.merge( - serviceVariables(), - enumVariables(enumShape) + protected TokenTree enumToDafnyFunction(final Shape enumShape) { + String enumName = enumShape.getId().getName(); + String rustEnumName = toPascalCase(enumName); + String sdkId = service + .expectTrait(ServiceTrait.class) + .getSdkId() + .toLowerCase(); + String dafnyTypesModuleName = getDafnyTypesModuleName(); + Map variables = Map.of( + "sdkCrate", + "aws_sdk_" + sdkId, + "enumName", + enumName, + "rustEnumName", + rustEnumName, + "dafnyTypesModuleName", + dafnyTypesModuleName ); - var branches = enumShape - .getEnumValues() - .keySet() - .stream() - .map(memberName -> - evalTemplate( - "$rustTypesModuleName:L::$rustEnumName:L::$rustEnumMemberName:L => crate::r#$dafnyTypesModuleName:L::$enumName:L::$dafnyEnumMemberName:L {},", - MapUtils.merge(variables, enumMemberVariables(memberName)) - ) - ) - .collect(Collectors.joining("\n")); - variables.put("branches", branches); - // TODO: This should not be a panic, but the Dafny image of the enum shape doesn't have an Unknown variant of any kind, - // so there's no way to succeed. - // See https://github.com/smithy-lang/smithy-dafny/issues/476. - // This could be handled more cleanly if conversion functions returned Results, - // but that would be a large and disruptive change to the overall code flow. - return TokenTree.of( + String sdkTypeName = evalTemplate( + "$sdkCrate:L::types::$rustEnumName:L", + variables + ); + + var prelude = TokenTree.of( evalTemplate( """ #[allow(dead_code)] pub fn to_dafny( - value: $rustTypesModuleName:L::$rustEnumName:L, + value: $sdkCrate:L::types::$rustEnumName:L, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - $branches:L - _ => panic!("Unknown enum variant: {}", value), - }) - } + """, variables ) ); + + var branches = TokenTree + .of( + enumShape + .expectTrait(EnumTrait.class) + .getValues() + .stream() + .map(e -> + TokenTree.of( + sdkTypeName + + "::" + + rustEnumName(e) + + " => crate::r#" + + dafnyTypesModuleName + + "::" + + enumName + + "::" + + dafnyEnumName(e) + + " {}," + ) + ) + ) + .lineSeparated(); + // TODO: This should not be a panic, but the Dafny image of the enum shape doesn't have an Unknown variant of any kind, + // so there's no way to succeed. + // See https://github.com/smithy-lang/smithy-dafny/issues/476. + // This could be handled more cleanly if conversion functions returned Results, + // but that would be a large and disruptive change to the overall code flow. + final var postlude = TokenTree.of( + """ + + _ => panic!("Unknown enum variant: {}", value), + }) + } + """ + ); + + return TokenTree.of(prelude, branches, postlude); } - protected TokenTree enumFromDafnyFunction(final EnumShape enumShape) { - final Map variables = MapUtils.merge( - serviceVariables(), - enumVariables(enumShape) + protected TokenTree enumFromDafnyFunction(final Shape enumShape) { + String enumName = enumShape.getId().getName(); + String rustEnumName = toPascalCase(enumName); + String sdkId = service + .expectTrait(ServiceTrait.class) + .getSdkId() + .toLowerCase(); + String dafnyTypesModuleName = getDafnyTypesModuleName(); + Map variables = Map.of( + "sdkCrate", + "aws_sdk_" + sdkId, + "enumName", + enumName, + "rustEnumName", + rustEnumName, + "dafnyTypesModuleName", + dafnyTypesModuleName ); - var branches = enumShape - .getEnumValues() - .keySet() - .stream() - .map(memberName -> - evalTemplate( - "crate::r#$dafnyTypesModuleName:L::$enumName:L::$dafnyEnumMemberName:L {} => $rustTypesModuleName:L::$rustEnumName:L::$rustEnumMemberName:L,", - MapUtils.merge(variables, enumMemberVariables(memberName)) - ) - ) - .collect(Collectors.joining("\n")); - variables.put("branches", branches); + String sdkTypeName = evalTemplate( + "$sdkCrate:L::types::$rustEnumName:L", + variables + ); - return TokenTree.of( + var prelude = TokenTree.of( evalTemplate( """ #[allow(dead_code)] pub fn from_dafny( dafny_value: &crate::r#$dafnyTypesModuleName:L::$enumName:L, - ) -> $rustTypesModuleName:L::$rustEnumName:L { + ) -> $sdkCrate:L::types::$rustEnumName:L { match dafny_value { - $branches:L - } - } + """, variables ) ); + + var branches = TokenTree + .of( + enumShape + .expectTrait(EnumTrait.class) + .getValues() + .stream() + .map(e -> + TokenTree.of( + "crate::r#" + + dafnyTypesModuleName + + "::" + + enumName + + "::" + + dafnyEnumName(e) + + " {} => " + + sdkTypeName + + "::" + + rustEnumName(e) + + "," + ) + ) + ) + .lineSeparated(); + final var postlude = TokenTree.of( + """ + + } + } + """ + ); + + return TokenTree.of(prelude, branches, postlude); } protected Set allOperationConversionModules() { @@ -998,40 +1028,16 @@ protected abstract Set operationConversionModules( final OperationShape operationShape ); - protected RustFile enumConversionModule(final EnumShape enumShape) { - Path path = Path.of( - "src", - "conversions", - toSnakeCase(enumName(enumShape)) + ".rs" - ); - - return new RustFile( - path, - TokenTree - .of(enumToDafnyFunction(enumShape), enumFromDafnyFunction(enumShape)) - .lineSeparated() - ); + private String rustEnumName(EnumDefinition ed) { + return toPascalCase(ed.getValue()); } - /** - * Generates values for variables commonly used in service-specific templates. - */ - protected HashMap serviceVariables() { - final HashMap variables = new HashMap<>(); - variables.put("serviceName", service.getId().getName(service)); - variables.put("dafnyModuleName", getDafnyModuleName()); - variables.put("dafnyInternalModuleName", getDafnyInternalModuleName()); - variables.put("dafnyTypesModuleName", getDafnyTypesModuleName()); - variables.put("rustTypesModuleName", getRustTypesModuleName()); - return variables; + private String dafnyEnumName(EnumDefinition ed) { + return ed.getValue(); } protected String getDafnyModuleName() { - return service - .getId() - .getNamespace() - .replace(".", "::") - .toLowerCase(Locale.ROOT); + return service.getId().getNamespace().replace(".", "::"); } protected String getDafnyInternalModuleName() { @@ -1042,7 +1048,14 @@ protected String getDafnyTypesModuleName() { return "%s::types".formatted(getDafnyInternalModuleName()); } - protected abstract String getRustTypesModuleName(); + /** + * Generates values for variables commonly used in service-specific templates. + */ + protected HashMap serviceVariables() { + final HashMap variables = new HashMap<>(); + variables.put("serviceName", service.getId().getName(service)); + return variables; + } /** * Generates values for variables commonly used in operation-specific templates. @@ -1053,8 +1066,6 @@ protected HashMap operationVariables( final String opName = operationName(operationShape); final String opInputName = operationInputName(operationShape); final String opOutputName = operationOutputName(operationShape); - final String synOpInputName = syntheticOperationInputName(operationShape); - final String synOpOutputName = syntheticOperationOutputName(operationShape); final String snakeCaseOpName = toSnakeCase(opName); final HashMap variables = new HashMap<>(); @@ -1062,18 +1073,16 @@ protected HashMap operationVariables( variables.put("operationInputName", opInputName); variables.put("operationOutputName", opOutputName); variables.put("operationErrorName", operationErrorTypeName(operationShape)); - variables.put("syntheticOperationInputName", synOpInputName); - variables.put("syntheticOperationOutputName", synOpOutputName); variables.put("snakeCaseOperationName", snakeCaseOpName); variables.put("snakeCaseOperationInputName", toSnakeCase(opInputName)); variables.put("snakeCaseOperationOutputName", toSnakeCase(opOutputName)); variables.put( - "snakeCaseSyntheticOperationInputName", - toSnakeCase(synOpInputName) + "syntheticOperationInputName", + syntheticOperationInputName(operationShape) ); variables.put( - "snakeCaseSyntheticOperationOutputName", - toSnakeCase(synOpOutputName) + "syntheticOperationOutputName", + syntheticOperationOutputName(operationShape) ); return variables; } @@ -1102,46 +1111,43 @@ protected String operationErrorTypeName(final OperationShape operationShape) { return "%sError".formatted(operationName(operationShape)); } - protected String enumName(final EnumShape enumShape) { - return enumShape.getId().getName(service); - } - - protected String rustEnumName(final EnumShape enumShape) { - return toPascalCase(enumName(enumShape)); - } - - protected String qualifiedRustEnumType(final EnumShape enumShape) { - return "%s::%s".formatted( - getRustTypesModuleName(), - rustEnumName(enumShape) - ); - } - - protected HashMap enumVariables(final EnumShape enumShape) { + /** + * Generates values for variables commonly used in structure-member-specific templates. + */ + protected HashMap memberVariables( + final MemberShape memberShape + ) { final HashMap variables = new HashMap<>(); - final String enumName = enumName(enumShape); - variables.put("enumName", enumName); - variables.put("snakeCaseEnumName", toSnakeCase(enumName)); - variables.put("rustEnumName", rustEnumName(enumShape)); - variables.put("qualifiedRustEnumType", qualifiedRustEnumType(enumShape)); + variables.put("fieldName", toSnakeCase(memberShape.getMemberName())); + variables.put( + "fieldType", + rustTypeForShape(model.expectShape(memberShape.getTarget())) + ); return variables; } - protected String rustEnumMemberName(final String memberName) { - return toPascalCase(memberName); - } - - protected String dafnyEnumMemberName(final String memberName) { - return memberName; - } - - protected HashMap enumMemberVariables( - final String memberName - ) { - final HashMap variables = new HashMap<>(); - variables.put("enumMemberName", memberName); - variables.put("dafnyEnumMemberName", dafnyEnumMemberName(memberName)); - variables.put("rustEnumMemberName", rustEnumMemberName(memberName)); - return variables; + // Currently only handles simple types, and doesn't account for any traits + protected String rustTypeForShape(final Shape shape) { + return switch (shape.getType()) { + case BOOLEAN -> "::std::primitive::bool"; + // integral + case BYTE -> "::std::primitive::i8"; + case SHORT -> "::std::primitive::i16"; + case INTEGER -> "::std::primitive::i32"; + case LONG -> "::std::primitive::i64"; + // floats + case FLOAT -> "::std::primitive::f32"; + case DOUBLE -> "::std::primitive::f64"; + // special numerics + case BIG_INTEGER -> "::num::bigint::BigInt"; + case BIG_DECIMAL -> "::num::rational::BigRational"; + // special collections + case BLOB -> "::std::vec::Vec<::std::primitive::u8>"; + case STRING -> "::std::string::String"; + // TODO: enum, list, map, structure, union + default -> throw new UnsupportedOperationException( + "Unsupported shape type: " + shape.getType() + ); + }; } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustAwsSdkShimGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustAwsSdkShimGenerator.java index ca2ecf80e9..3c08de804c 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustAwsSdkShimGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustAwsSdkShimGenerator.java @@ -13,16 +13,15 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.polymorph.utils.MapUtils; -import software.amazon.polymorph.utils.ModelUtils; import software.amazon.polymorph.utils.TokenTree; import software.amazon.smithy.aws.traits.ServiceTrait; import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.StructureShape; +import software.amazon.smithy.model.traits.EnumTrait; /** * Generates all Rust modules needed to wrap @@ -48,10 +47,11 @@ protected Set rustFiles() { ); result.addAll( - ModelUtils - .streamEnumShapes(model, service.getId().getNamespace()) + model + .getStringShapesWithTrait(EnumTrait.class) + .stream() .map(this::enumConversionModule) - .toList() + .collect(Collectors.toSet()) ); result.add(conversionsModule()); @@ -64,7 +64,12 @@ protected Set rustFiles() { } private RustFile clientModule() { - final Map variables = serviceVariables(); + final Map variables = MapUtils.merge( + serviceVariables(), + dafnyModuleVariables() + ); + variables.put("clientName", "%sClient".formatted(getSdkId())); + var preamble = TokenTree.of( evalTemplate( """ @@ -147,8 +152,10 @@ private TokenTree operationClientFunction( ) { final Map variables = MapUtils.merge( serviceVariables(), + dafnyModuleVariables(), operationVariables(operationShape) ); + variables.put("clientName", "%sClient".formatted(getSdkId())); final ShapeId outputShapeId = operationShape.getOutputShape(); final String outputType = outputShapeId.equals( @@ -214,7 +221,7 @@ private TokenTree structureToDafnyFunction( """ #[allow(dead_code)] pub fn to_dafny( - value: &$rustTypesModuleName:L::$rustStructureName:L, + value: &$sdkCrate:L::types::$rustStructureName:L, ) -> ::std::rc::Rc{ ::std::rc::Rc::new( crate::r#$dafnyTypesModuleName:L::$structureName:L::$structureName:L { @@ -223,7 +230,10 @@ pub fn to_dafny( ) } """; - final Map variables = serviceVariables(); + final Map variables = MapUtils.merge( + serviceVariables(), + dafnyModuleVariables() + ); variables.put("structureName", structureName); variables.put("rustStructureName", toPascalCase(structureName)); variables.put( @@ -249,7 +259,10 @@ private TokenTree structureFromDafnyFunction( ) ? ".unwrap()" : ""; - final Map variables = serviceVariables(); + final Map variables = MapUtils.merge( + serviceVariables(), + dafnyModuleVariables() + ); variables.put("structureName", structureName); variables.put("rustStructureName", toPascalCase(structureName)); variables.put("snakeCaseStructureName", toSnakeCase(structureName)); @@ -267,8 +280,8 @@ pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#$dafnyTypesModuleName:L::$structureName:L, >, - ) -> $rustTypesModuleName:L::$rustStructureName:L { - $rustTypesModuleName:L::$rustStructureName:L::builder() + ) -> $sdkCrate:L::types::$rustStructureName:L { + $sdkCrate:L::types::$rustStructureName:L::builder() $fluentMemberSetters:L .build() $unwrapIfNeeded:L @@ -285,6 +298,7 @@ protected TokenTree operationRequestToDafnyFunction( ) { final Map variables = MapUtils.merge( serviceVariables(), + dafnyModuleVariables(), operationVariables(operationShape) ); StructureShape inputShape = model.expectShape( @@ -315,23 +329,13 @@ pub fn to_dafny( ); } - @Override - protected boolean isRustFieldRequired(Shape parent, MemberShape member) { - // These rules were mostly reverse-engineered from inspection of Rust SDKs, - // and may not be complete! - final Shape targetShape = model.expectShape(member.getTarget()); - return ( - super.isRustFieldRequired(parent, member) || - (operationIndex.isOutputStructure(parent) && targetShape.isIntegerShape()) - ); - } - @Override protected TokenTree operationRequestFromDafnyFunction( final OperationShape operationShape ) { final Map variables = MapUtils.merge( serviceVariables(), + dafnyModuleVariables(), operationVariables(operationShape) ); StructureShape inputShape = model.expectShape( @@ -368,6 +372,7 @@ protected TokenTree operationResponseToDafnyFunction( ) { final Map variables = MapUtils.merge( serviceVariables(), + dafnyModuleVariables(), operationVariables(operationShape) ); StructureShape outputShape = model.expectShape( @@ -468,6 +473,7 @@ protected TokenTree operationErrorToDafnyFunction( final Map variables = MapUtils.merge( serviceVariables(), + dafnyModuleVariables(), operationVariables(operationShape) ); variables.put("errorCases", errorCases.toString()); @@ -505,6 +511,7 @@ protected TokenTree errorVariantToDafny( ) { final Map variables = MapUtils.merge( serviceVariables(), + dafnyModuleVariables(), operationVariables(operationShape) ); String errorName = toPascalCase(errorShape.getId().getName()); @@ -531,7 +538,7 @@ private RustFile errorConversionModule(final Shape errorStructure) { """ #[allow(dead_code)] pub fn to_dafny( - value: $rustTypesModuleName:L::error::$pascalCaseName:L, + value: $sdkCrate:L::types::error::$pascalCaseName:L, ) -> ::std::rc::Rc{ ::std::rc::Rc::new( crate::r#$dafnyTypesModuleName:L::Error::$structureName:L { @@ -540,14 +547,34 @@ pub fn to_dafny( ) } """; - final Map variables = serviceVariables(); + final Map variables = MapUtils.merge( + serviceVariables(), + dafnyModuleVariables() + ); variables.put("structureName", structureName); variables.put("pascalCaseName", pascalCaseName); variables.put( "variants", toDafnyVariantsForStructure(errorStructure).toString() ); - return new RustFile(path, TokenTree.of(evalTemplate(template, variables))); + String evaluated = evalTemplate(template, variables); + return new RustFile(path, TokenTree.of(evaluated)); + } + + private RustFile enumConversionModule(final Shape enumShape) { + Path path = Path.of( + "src", + "conversions", + toSnakeCase(enumShape.getId().getName()) + ".rs" + ); + + return new RustFile( + path, + TokenTree.of( + enumToDafnyFunction(enumShape), + enumFromDafnyFunction(enumShape) + ) + ); } @Override @@ -557,11 +584,6 @@ protected String getDafnyModuleName() { ); } - @Override - protected String getRustTypesModuleName() { - return "%s::types".formatted(getSdkCrate()); - } - private String getSdkId() { return service.expectTrait(ServiceTrait.class).getSdkId(); } @@ -573,10 +595,8 @@ private String getSdkCrate() { @Override protected HashMap serviceVariables() { final HashMap variables = super.serviceVariables(); - final String sdkId = getSdkId(); - variables.put("sdkId", sdkId); + variables.put("sdkId", getSdkId()); variables.put("sdkCrate", getSdkCrate()); - variables.put("clientName", "%sClient".formatted(sdkId)); return variables; } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustLibraryShimGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustLibraryShimGenerator.java index 180fd1b8dd..dbf694082e 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustLibraryShimGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustLibraryShimGenerator.java @@ -1,7 +1,6 @@ package software.amazon.polymorph.smithyrust.generator; import static software.amazon.polymorph.utils.IOUtils.evalTemplate; -import static software.amazon.smithy.rust.codegen.core.util.StringsKt.toPascalCase; import static software.amazon.smithy.rust.codegen.core.util.StringsKt.toSnakeCase; import java.nio.file.Path; @@ -18,14 +17,12 @@ import software.amazon.polymorph.utils.ModelUtils; import software.amazon.polymorph.utils.TokenTree; import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.shapes.EnumShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.StructureShape; -import software.amazon.smithy.model.traits.EnumTrait; /** * Generates all Rust modules needed to wrap a Dafny library as a Rust library. @@ -65,12 +62,6 @@ protected Set rustFiles() { // types result.add(typesModule()); result.add(typesConfigModule()); - result.addAll( - ModelUtils - .streamEnumShapes(model, service.getId().getNamespace()) - .map(this::enumTypeModule) - .toList() - ); // errors result.add(errorModule()); @@ -90,13 +81,8 @@ protected Set rustFiles() { result.add(conversionsErrorModule()); result.addAll(configConversionModules()); result.addAll(allOperationConversionModules()); - result.addAll( - ModelUtils - .streamEnumShapes(model, service.getId().getNamespace()) - .map(this::enumConversionModule) - .toList() - ); // TODO structure conversion modules + // TODO enum conversion modules // TODO union conversion modules // wrapped client @@ -107,7 +93,10 @@ protected Set rustFiles() { } private RustFile clientModule() { - final Map variables = serviceVariables(); + final Map variables = MapUtils.merge( + dafnyModuleVariables(), + serviceVariables() + ); variables.put( "operationModules", serviceOperationShapes() @@ -202,26 +191,10 @@ private String operationClientOutputDoc(final OperationShape operationShape) { } private RustFile typesModule() { - final Map variables = serviceVariables(); - - final String enumModules = ModelUtils - .streamEnumShapes(model, service.getId().getNamespace()) - .map(enumShape -> - IOUtils.evalTemplate( - """ - mod _$snakeCaseEnumName:L; - pub use crate::types::_$snakeCaseEnumName:L::$rustEnumName:L; - """, - enumVariables(enumShape) - ) - ) - .collect(Collectors.joining("\n")); - variables.put("enumModules", enumModules); - final String content = IOUtils.evalTemplate( getClass(), "runtimes/rust/types.rs", - variables + serviceVariables() ); return new RustFile(Path.of("src", "types.rs"), TokenTree.of(content)); } @@ -241,46 +214,6 @@ private RustFile typesConfigModule() { return new RustFile(path, TokenTree.of(content)); } - private RustFile enumTypeModule(final EnumShape enumShape) { - final Map variables = MapUtils.merge( - serviceVariables(), - enumVariables(enumShape) - ); - - final Set memberNames = enumShape.getEnumValues().keySet(); - - final String variants = memberNames - .stream() - .map(this::rustEnumMemberName) - .map("%s,"::formatted) - .collect(Collectors.joining("\n")); - variables.put("variants", variants); - - final String displayVariants = memberNames - .stream() - .map(memberName -> - IOUtils.evalTemplate( - "$rustEnumName:L::$rustEnumMemberName:L => write!(f, \"$enumMemberName:L\"),", - MapUtils.merge(variables, enumMemberVariables(memberName)) - ) - ) - .collect(Collectors.joining("\n")); - variables.put("displayVariants", displayVariants); - - final String content = IOUtils.evalTemplate( - getClass(), - "runtimes/rust/types/enum.rs", - variables - ); - - final Path path = Path.of( - "src", - "types", - "_%s.rs".formatted(toSnakeCase(enumName(enumShape))) - ); - return new RustFile(path, TokenTree.of(content)); - } - private RustFile operationModule() { final String opTemplate = """ @@ -386,22 +319,14 @@ private String operationStructureField(final MemberShape memberShape) { } private String operationStructureGetter(final MemberShape memberShape) { - final Map variables = memberVariables(memberShape); - - // for some simple shapes, the Rust runtime types are not Copy - final Shape targetShape = model.expectShape(memberShape.getTarget()); - final boolean needsClone = - targetShape.isBlobShape() || targetShape.isStringShape(); - variables.put("fieldClone", needsClone ? ".clone()" : ""); - final String template = """ #[allow(missing_docs)] // documentation missing in model pub fn $fieldName:L(&self) -> ::std::option::Option<$fieldType:L> { - self.$fieldName:L$fieldClone:L + self.$fieldName:L } """; - return IOUtils.evalTemplate(template, variables); + return IOUtils.evalTemplate(template, memberVariables(memberShape)); } private String operationStructureBuilderField(final MemberShape memberShape) { @@ -515,7 +440,10 @@ private RustFile errorConversionModule( } private Set configConversionModules() { - final Map variables = serviceVariables(); + final Map variables = MapUtils.merge( + serviceVariables(), + dafnyModuleVariables() + ); final String snakeCaseConfigName = variables.get("snakeCaseConfigName"); final String outerContent = IOUtils.evalTemplate( @@ -558,6 +486,7 @@ protected Set operationConversionModules( ) { final Map variables = MapUtils.merge( serviceVariables(), + dafnyModuleVariables(), operationVariables(operationShape) ); @@ -614,6 +543,7 @@ private TokenTree operationStructureToDafnyFunction( ); final Map variables = MapUtils.merge( serviceVariables(), + dafnyModuleVariables(), operationVariables(operationShape) ); variables.put("structureName", structureId.getName(service)); @@ -671,6 +601,7 @@ private TokenTree operationStructureFromDafnyFunction( ); final Map variables = MapUtils.merge( serviceVariables(), + dafnyModuleVariables(), operationVariables(operationShape) ); variables.put("structureName", structureId.getName(service)); @@ -704,13 +635,16 @@ private RustFile wrappedModule() { final String content = IOUtils.evalTemplate( getClass(), "runtimes/rust/wrapped.rs", - serviceVariables() + MapUtils.merge(serviceVariables(), dafnyModuleVariables()) ); return new RustFile(Path.of("src", "wrapped.rs"), TokenTree.of(content)); } private RustFile wrappedClientModule() { - final Map variables = serviceVariables(); + final Map variables = MapUtils.merge( + serviceVariables(), + dafnyModuleVariables() + ); variables.put( "operationImpls", serviceOperationShapes() @@ -733,6 +667,7 @@ private String wrappedClientOperationImpl( ) { final Map variables = MapUtils.merge( serviceVariables(), + dafnyModuleVariables(), operationVariables(operationShape) ); return IOUtils.evalTemplate( @@ -769,11 +704,6 @@ protected HashMap serviceVariables() { return variables; } - @Override - protected String getRustTypesModuleName() { - return "crate::types"; - } - @Override protected String syntheticOperationInputName(OperationShape operationShape) { return operationName(operationShape) + "Input"; @@ -783,55 +713,4 @@ protected String syntheticOperationInputName(OperationShape operationShape) { protected String syntheticOperationOutputName(OperationShape operationShape) { return operationName(operationShape) + "Output"; } - - /** - * Generates values for variables commonly used in structure-member-specific templates. - */ - private HashMap memberVariables( - final MemberShape memberShape - ) { - final HashMap variables = new HashMap<>(); - variables.put("fieldName", toSnakeCase(memberShape.getMemberName())); - variables.put( - "fieldType", - rustTypeForShape(model.expectShape(memberShape.getTarget())) - ); - return variables; - } - - // Currently only handles simple types and enums, and doesn't account for any traits - private String rustTypeForShape(final Shape shape) { - return switch (shape.getType()) { - case BOOLEAN -> "::std::primitive::bool"; - // integral - case BYTE -> "::std::primitive::i8"; - case SHORT -> "::std::primitive::i16"; - case INTEGER -> "::std::primitive::i32"; - case LONG -> "::std::primitive::i64"; - // floats - case FLOAT -> "::std::primitive::f32"; - case DOUBLE -> "::std::primitive::f64"; - // special numerics - case BIG_INTEGER -> "::num::bigint::BigInt"; - case BIG_DECIMAL -> "::num::rational::BigRational"; - // special collections - case BLOB -> "::aws_smithy_types::Blob"; - case STRING -> { - //noinspection deprecation - if (shape.hasTrait(EnumTrait.class)) { - yield qualifiedRustEnumType( - ModelUtils.stringToEnumShape(shape.asStringShape().orElseThrow()) - ); - } - yield "::std::string::String"; - } - case ENUM -> qualifiedRustEnumType(shape.asEnumShape().orElseThrow()); - // everything else - case TIMESTAMP -> "::aws_smithy_types::DateTime"; - // TODO: list, map, structure, union - default -> throw new UnsupportedOperationException( - "Unsupported shape type: " + shape.getType() - ); - }; - } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/utils/ModelUtils.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/utils/ModelUtils.java index 0795b6a8c8..47e50c7340 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/utils/ModelUtils.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/utils/ModelUtils.java @@ -110,36 +110,6 @@ public static Stream streamNamespaceErrors( ); } - /** - * Returns a stream of enum shapes in the given namespace. - * These include both Smithy v2 enums, - * and Smithy v1 @enum strings converted to {@link EnumShape}s. - */ - public static Stream streamEnumShapes( - final Model model, - final String namespace - ) { - @SuppressWarnings("deprecation") - final Stream v1Enums = model - .getStringShapesWithTrait(EnumTrait.class) - .stream() - .map(ModelUtils::stringToEnumShape); - final Stream v2Enums = model.getEnumShapes().stream(); - return Stream - .concat(v1Enums, v2Enums) - .filter(shape -> shape.getId().getNamespace().equals(namespace)); - } - - public static EnumShape stringToEnumShape(final StringShape stringShape) { - return EnumShape - .fromStringShape(stringShape) - .orElseThrow(() -> - new UnsupportedOperationException( - "Could not convert %s to an enum".formatted(stringShape.getId()) - ) - ); - } - /** * @return true if the given shape ID is in the given service's namespace */ diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/conversions/operation.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/conversions/operation.rs index 9919295c45..874db88a83 100644 --- a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/conversions/operation.rs +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/conversions/operation.rs @@ -25,6 +25,6 @@ pub fn from_dafny_error( } } -pub mod _$snakeCaseSyntheticOperationInputName:L; +pub mod _$snakeCaseOperationInputName:L; -pub mod _$snakeCaseSyntheticOperationOutputName:L; \ No newline at end of file +pub mod _$snakeCaseOperationOutputName:L; \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/operation/outer.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/operation/outer.rs index 0aea337ee7..5d5817d737 100644 --- a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/operation/outer.rs +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/operation/outer.rs @@ -14,7 +14,7 @@ impl $operationName:L { crate::operation::$snakeCaseOperationName:L::$operationOutputName:L, crate::operation::$snakeCaseOperationName:L::$operationErrorName:L, > { - let inner_input = crate::conversions::$snakeCaseOperationName:L::_$snakeCaseSyntheticOperationInputName:L::to_dafny(input); + let inner_input = crate::conversions::$snakeCaseOperationName:L::_$snakeCaseOperationInputName:L::to_dafny(input); let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).$operationName:L(&inner_input); if matches!( @@ -22,7 +22,7 @@ impl $operationName:L { crate::r#_Wrappers_Compile::Result::Success { .. } ) { Ok( - crate::conversions::$snakeCaseOperationName:L::_$snakeCaseSyntheticOperationOutputName:L::from_dafny( + crate::conversions::$snakeCaseOperationName:L::_$snakeCaseOperationOutputName:L::from_dafny( inner_result.value().clone(), ), ) diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/src/standard_library_externs.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/src/standard_library_externs.rs deleted file mode 100644 index eca6a29803..0000000000 --- a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/src/standard_library_externs.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Annotation to ignore the case of this module -use crate::r#_Wrappers_Compile; -use crate::UTF8; - -impl crate::UTF8::_default { - pub fn Encode( - s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let v = s.to_array(); - let mut _accumulator: Vec = vec![]; - // Use of .encode_utf8 method. - let mut surrogate: Option = None; - for c in v.iter() { - let s = if let Some(s) = surrogate { - String::from_utf16(&[s, c.0]) - } else { - String::from_utf16(&[c.0]) - }; - surrogate = None; - match s { - Ok(value) => { - _accumulator.extend(value.as_bytes()); - continue; - } - Err(e) => { - if 0xD800 <= c.0 && c.0 <= 0xDFFF { - surrogate = Some(c.0); - continue; - } - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }); - } - } - } - if let Some(s) = surrogate { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &format!("Surrogate pair missing: 0x{:04x}", s)) - }); - } - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< - UTF8::ValidUTF8Bytes, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >::Success { - value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), - }) - } - pub fn Decode( - b: &::dafny_runtime::Sequence, - ) -> ::std::rc::Rc< - r#_Wrappers_Compile::Result< - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - >, - > { - let b = String::from_utf8(b.to_array().as_ref().clone()); - match b { - Ok(s) => { - ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }) - }, - Err(e) => { - return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, - ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( - &e.to_string()) - }) - } - } - } -} diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types.rs index 94630df9d1..2627a01b4a 100644 --- a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types.rs +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types.rs @@ -1,4 +1,2 @@ /// Types for the `$configName:L` -pub mod $snakeCaseConfigName:L; - -$enumModules:L \ No newline at end of file +pub mod $snakeCaseConfigName:L; \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types/enum.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types/enum.rs deleted file mode 100644 index 0c74b9c52d..0000000000 --- a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types/enum.rs +++ /dev/null @@ -1,12 +0,0 @@ -#[derive(Debug, PartialEq, Copy, Clone)] -pub enum $rustEnumName:L { - $variants:L -} - -impl ::std::fmt::Display for $rustEnumName:L { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - match self { - $displayVariants:L - } - } -} \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/wrapped/client_operation_impl.part.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/wrapped/client_operation_impl.part.rs index ad3ac5afc9..ce6976a530 100644 --- a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/wrapped/client_operation_impl.part.rs +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/wrapped/client_operation_impl.part.rs @@ -12,7 +12,7 @@ >, >{ let inner_input = - crate::conversions::$snakeCaseOperationName:L::_$snakeCaseSyntheticOperationInputName:L::from_dafny(input.clone()); + crate::conversions::$snakeCaseOperationName:L::_$snakeCaseOperationInputName:L::from_dafny(input.clone()); let result = self.rt.block_on(crate::operation::$snakeCaseOperationName:L::$operationName:L::send(&self.wrapped, inner_input)); match result { Err(error) => ::std::rc::Rc::new( @@ -22,7 +22,7 @@ ), Ok(client) => ::std::rc::Rc::new( crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::$snakeCaseOperationName:L::_$snakeCaseSyntheticOperationOutputName:L::to_dafny(client), + value: crate::conversions::$snakeCaseOperationName:L::_$snakeCaseOperationOutputName:L::to_dafny(client), }, ), } diff --git a/codegen/smithy-dafny-codegen/src/test/java/software/amazon/polymorph/smithyjava/ForEachDafnyTest.java b/codegen/smithy-dafny-codegen/src/test/java/software/amazon/polymorph/smithyjava/ForEachDafnyTest.java index 61f032a862..20ace96be3 100644 --- a/codegen/smithy-dafny-codegen/src/test/java/software/amazon/polymorph/smithyjava/ForEachDafnyTest.java +++ b/codegen/smithy-dafny-codegen/src/test/java/software/amazon/polymorph/smithyjava/ForEachDafnyTest.java @@ -17,7 +17,6 @@ public static Collection dafnies() { new Object[][] { { new DafnyVersion(4, 1, 0) }, { new DafnyVersion(4, 3, 0) }, - { new DafnyVersion(4, 8, 0) }, } ); } From 2072d44283f02ed5ec3150d9109279dae0486317 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 9 Sep 2024 11:20:51 -0700 Subject: [PATCH 42/44] Revert "Revert "Merge branch 'Golang/dev' into rishav-positional"" This reverts commit ca4d375e21c76aa4dc2a45bd734670b5e8e0961c. --- .github/workflows/manual.yml | 4 + .github/workflows/nightly_dafny.yml | 1 + .github/workflows/pull.yml | 29 +- .github/workflows/push.yml | 13 +- .github/workflows/test_models_go_tests.yml | 162 +- .github/workflows/test_models_rust_tests.yml | 2 +- SmithyDafnyMakefile.mk | 12 +- .../rust/src/standard_library_externs.rs | 80 + TestModels/Constraints/removeDotFromExtern.sh | 27 - .../rust/src/standard_library_externs.rs | 80 + TestModels/Errors/runtimes/rust/Cargo.toml | 8 +- .../rust/src/implementation_from_dafny.rs-e | 1745 --------------- .../rust/src/standard_library_externs.rs | 80 + .../rust/src/standard_library_externs.rs | 80 + .../rust/src/standard_library_externs.rs | 80 + .../rust/src/standard_library_externs.rs | 80 + TestModels/SimpleTypes/SimpleBlob/Makefile | 3 +- .../SimpleBlob/runtimes/rust/Cargo.toml | 8 +- .../SimpleBlob/runtimes/rust/src/client.rs | 16 +- .../runtimes/rust/src/client/get_blob.rs | 8 +- .../rust/src/client/get_blob_known_value.rs | 17 - .../src/client/get_blob_known_value_test.rs | 15 + .../runtimes/rust/src/conversions.rs | 12 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../runtimes/rust/src/conversions/get_blob.rs | 16 +- .../conversions/get_blob/_get_blob_input.rs | 44 +- .../conversions/get_blob/_get_blob_output.rs | 45 +- .../src/conversions/get_blob_known_value.rs | 39 - .../_get_blob_known_value_input.rs | 41 - .../_get_blob_known_value_output.rs | 43 - .../conversions/get_blob_known_value_test.rs | 33 + .../_get_blob_known_value_test_input.rs | 24 + .../_get_blob_known_value_test_output.rs | 24 + .../src/conversions/simple_blob_config.rs | 5 +- .../simple_blob_config/_simple_blob_config.rs | 9 +- .../SimpleBlob/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleBlob/runtimes/rust/src/lib.rs | 19 - .../SimpleBlob/runtimes/rust/src/operation.rs | 9 +- .../runtimes/rust/src/operation/get_blob.rs | 19 +- .../src/operation/get_blob/_get_blob_input.rs | 50 +- .../operation/get_blob/_get_blob_output.rs | 56 +- .../rust/src/operation/get_blob/builders.rs | 38 +- .../_get_blob_known_value_input.rs | 63 - .../_get_blob_known_value_output.rs | 63 - .../get_blob_known_value/builders.rs | 80 - ..._value.rs => get_blob_known_value_test.rs} | 58 +- .../_get_blob_input.rs | 58 + .../_get_blob_output.rs | 58 + .../get_blob_known_value_test/builders.rs | 74 + .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../SimpleBlob/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_blob_config.rs | 5 +- .../SimpleBlob/runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 119 ++ .../runtimes/rust/tests/simple_blob_test.rs | 10 +- .../rust/src/standard_library_externs.rs | 80 + TestModels/SimpleTypes/SimpleDouble/Makefile | 3 +- .../SimpleDouble/runtimes/rust/Cargo.toml | 8 +- .../SimpleDouble/runtimes/rust/src/client.rs | 7 +- .../runtimes/rust/src/client/get_double.rs | 8 +- .../runtimes/rust/src/conversions.rs | 10 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../rust/src/conversions/get_double.rs | 8 +- .../get_double/_get_double_input.rs | 45 +- .../get_double/_get_double_output.rs | 45 +- .../src/conversions/simple_double_config.rs | 5 +- .../_simple_double_config.rs | 6 +- .../SimpleDouble/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleDouble/runtimes/rust/src/lib.rs | 19 - .../runtimes/rust/src/operation.rs | 5 +- .../runtimes/rust/src/operation/get_double.rs | 8 +- .../operation/get_double/_get_double_input.rs | 40 +- .../get_double/_get_double_output.rs | 46 +- .../rust/src/operation/get_double/builders.rs | 32 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../SimpleDouble/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_double_config.rs | 5 +- .../SimpleDouble/runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 89 + TestModels/SimpleTypes/SimpleEnum/Makefile | 3 +- .../SimpleEnum/runtimes/rust/Cargo.toml | 8 +- .../SimpleEnum/runtimes/rust/src/client.rs | 9 +- .../runtimes/rust/src/client/get_enum.rs | 8 +- .../client/get_enum_first_known_value_test.rs | 23 +- .../get_enum_second_known_value_test.rs | 23 +- .../client/get_enum_third_known_value_test.rs | 23 +- .../runtimes/rust/src/conversions.rs | 21 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../runtimes/rust/src/conversions/get_enum.rs | 5 +- .../conversions/get_enum/_get_enum_input.rs | 53 +- .../conversions/get_enum/_get_enum_output.rs | 53 +- .../get_enum_first_known_value_test.rs | 5 +- .../_get_enum_first_known_value_test_input.rs | 57 +- ..._get_enum_first_known_value_test_output.rs | 57 +- .../get_enum_second_known_value_test.rs | 5 +- ..._get_enum_second_known_value_test_input.rs | 57 +- ...get_enum_second_known_value_test_output.rs | 57 +- .../get_enum_third_known_value_test.rs | 5 +- .../_get_enum_third_known_value_test_input.rs | 57 +- ..._get_enum_third_known_value_test_output.rs | 57 +- .../src/conversions/simple_enum_config.rs | 5 +- .../simple_enum_config/_simple_enum_config.rs | 6 +- .../rust/src/conversions/simple_enum_shape.rs | 26 +- .../simple_enum_shape/_simple_enum_shape.rs | 23 - .../SimpleEnum/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleEnum/runtimes/rust/src/lib.rs | 19 - .../SimpleEnum/runtimes/rust/src/operation.rs | 11 +- .../runtimes/rust/src/operation/get_enum.rs | 19 +- .../src/operation/get_enum/_get_enum_input.rs | 55 +- .../operation/get_enum/_get_enum_output.rs | 59 +- .../rust/src/operation/get_enum/builders.rs | 40 +- .../get_enum_first_known_value_test.rs | 36 +- .../_get_enum_first_known_value_test_input.rs | 69 - ..._get_enum_first_known_value_test_output.rs | 69 - .../_get_enum_input.rs | 58 + .../_get_enum_output.rs | 58 + .../builders.rs | 62 +- .../get_enum_second_known_value_test.rs | 40 +- .../_get_enum_input.rs | 58 + .../_get_enum_output.rs | 58 + ..._get_enum_second_known_value_test_input.rs | 69 - ...get_enum_second_known_value_test_output.rs | 69 - .../builders.rs | 61 +- .../get_enum_third_known_value_test.rs | 36 +- .../_get_enum_input.rs | 58 + .../_get_enum_output.rs | 58 + .../_get_enum_third_known_value_test_input.rs | 68 - ..._get_enum_third_known_value_test_output.rs | 69 - .../builders.rs | 62 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../SimpleEnum/runtimes/rust/src/types.rs | 11 +- .../rust/src/types/_simple_enum_shape.rs | 19 + .../rust/src/types/simple_enum_config.rs | 5 +- .../rust/src/types/simple_enum_shape.rs | 6 - .../SimpleEnum/runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 179 ++ .../runtimes/rust/tests/simple_enum_test.rs | 18 +- TestModels/SimpleTypes/SimpleEnumV2/Makefile | 3 +- .../SimpleEnumV2/runtimes/rust/Cargo.toml | 8 +- .../SimpleEnumV2/runtimes/rust/src/client.rs | 9 +- .../runtimes/rust/src/client/get_enum_v2.rs | 8 +- .../get_enum_v2_first_known_value_test.rs | 23 +- .../get_enum_v2_second_known_value_test.rs | 23 +- .../get_enum_v2_third_known_value_test.rs | 23 +- .../runtimes/rust/src/conversions.rs | 21 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../rust/src/conversions/get_enum_v2.rs | 16 +- .../get_enum_v2/_get_enum_v2_input.rs | 53 +- .../get_enum_v2/_get_enum_v2_output.rs | 53 +- .../get_enum_v2_first_known_value_test.rs | 5 +- ...et_enum_v2_first_known_value_test_input.rs | 59 +- ...t_enum_v2_first_known_value_test_output.rs | 59 +- .../get_enum_v2_second_known_value_test.rs | 5 +- ...t_enum_v2_second_known_value_test_input.rs | 59 +- ..._enum_v2_second_known_value_test_output.rs | 59 +- .../get_enum_v2_third_known_value_test.rs | 5 +- ...et_enum_v2_third_known_value_test_input.rs | 59 +- ...t_enum_v2_third_known_value_test_output.rs | 59 +- .../src/conversions/simple_enum_v2_config.rs | 5 +- .../_simple_enum_v2_config.rs | 6 +- .../src/conversions/simple_enum_v2_shape.rs | 26 +- .../_simple_enum_v2_shape.rs | 23 - .../SimpleEnumV2/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleEnumV2/runtimes/rust/src/lib.rs | 19 - .../runtimes/rust/src/operation.rs | 11 +- .../rust/src/operation/get_enum_v2.rs | 8 +- .../get_enum_v2/_get_enum_v2_input.rs | 51 +- .../get_enum_v2/_get_enum_v2_output.rs | 57 +- .../src/operation/get_enum_v2/builders.rs | 40 +- .../get_enum_v2_first_known_value_test.rs | 39 +- ...et_enum_v2_first_known_value_test_input.rs | 71 - ...t_enum_v2_first_known_value_test_output.rs | 71 - .../_get_enum_v2_input.rs | 58 + .../_get_enum_v2_output.rs | 58 + .../builders.rs | 62 +- .../get_enum_v2_second_known_value_test.rs | 39 +- .../_get_enum_v2_input.rs | 58 + .../_get_enum_v2_output.rs | 58 + ...t_enum_v2_second_known_value_test_input.rs | 71 - ..._enum_v2_second_known_value_test_output.rs | 71 - .../builders.rs | 61 +- .../get_enum_v2_third_known_value_test.rs | 39 +- .../_get_enum_v2_input.rs | 58 + .../_get_enum_v2_output.rs | 58 + ...et_enum_v2_third_known_value_test_input.rs | 70 - ...t_enum_v2_third_known_value_test_output.rs | 71 - .../builders.rs | 62 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../SimpleEnumV2/runtimes/rust/src/types.rs | 11 +- .../rust/src/types/_simple_enum_v2_shape.rs | 19 + .../rust/src/types/simple_enum_v2_config.rs | 5 +- .../rust/src/types/simple_enum_v2_shape.rs | 6 - .../SimpleEnumV2/runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 179 ++ .../rust/tests/simple_enum_v2_test.rs | 18 +- TestModels/SimpleTypes/SimpleInteger/Makefile | 3 +- .../SimpleInteger/runtimes/rust/Cargo.toml | 8 +- .../SimpleInteger/runtimes/rust/src/client.rs | 9 +- .../runtimes/rust/src/client/get_integer.rs | 8 +- .../src/client/get_integer_known_value.rs | 18 - .../client/get_integer_known_value_test.rs | 15 + .../runtimes/rust/src/conversions.rs | 12 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../rust/src/conversions/get_integer.rs | 5 +- .../get_integer/_get_integer_input.rs | 35 +- .../get_integer/_get_integer_output.rs | 35 +- .../conversions/get_integer_known_value.rs | 32 - .../_get_integer_known_value_input.rs | 37 - .../_get_integer_known_value_output.rs | 37 - .../get_integer_known_value_test.rs | 33 + .../_get_integer_known_value_test_input.rs | 24 + .../_get_integer_known_value_test_output.rs | 24 + .../src/conversions/simple_integer_config.rs | 5 +- .../_simple_integer_config.rs | 6 +- .../SimpleInteger/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleInteger/runtimes/rust/src/lib.rs | 19 - .../runtimes/rust/src/operation.rs | 9 +- .../rust/src/operation/get_integer.rs | 8 +- .../get_integer/_get_integer_input.rs | 40 +- .../get_integer/_get_integer_output.rs | 46 +- .../src/operation/get_integer/builders.rs | 34 +- .../_get_integer_known_value_input.rs | 59 - .../_get_integer_known_value_output.rs | 60 - .../get_integer_known_value/builders.rs | 78 - ...lue.rs => get_integer_known_value_test.rs} | 65 +- .../_get_integer_input.rs | 58 + .../_get_integer_output.rs | 58 + .../get_integer_known_value_test/builders.rs | 74 + .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../SimpleInteger/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_integer_config.rs | 33 +- .../runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 119 ++ .../rust/tests/simple_integer_test.rs | 2 +- TestModels/SimpleTypes/SimpleLong/Makefile | 3 +- .../SimpleLong/runtimes/rust/Cargo.toml | 8 +- .../SimpleLong/runtimes/rust/src/client.rs | 9 +- .../runtimes/rust/src/client/get_long.rs | 8 +- .../rust/src/client/get_long_known_value.rs | 17 - .../src/client/get_long_known_value_test.rs | 15 + .../runtimes/rust/src/conversions.rs | 12 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../runtimes/rust/src/conversions/get_long.rs | 5 +- .../conversions/get_long/_get_long_input.rs | 35 +- .../conversions/get_long/_get_long_output.rs | 35 +- .../src/conversions/get_long_known_value.rs | 32 - .../_get_long_known_value_input.rs | 37 - .../_get_long_known_value_output.rs | 37 - .../conversions/get_long_known_value_test.rs | 33 + .../_get_long_known_value_test_input.rs | 24 + .../_get_long_known_value_test_output.rs | 24 + .../src/conversions/simple_long_config.rs | 5 +- .../simple_long_config/_simple_long_config.rs | 6 +- .../SimpleLong/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleLong/runtimes/rust/src/lib.rs | 19 - .../SimpleLong/runtimes/rust/src/operation.rs | 9 +- .../runtimes/rust/src/operation/get_long.rs | 19 +- .../src/operation/get_long/_get_long_input.rs | 44 +- .../operation/get_long/_get_long_output.rs | 50 +- .../rust/src/operation/get_long/builders.rs | 32 +- .../_get_long_known_value_input.rs | 57 - .../_get_long_known_value_output.rs | 57 - .../get_long_known_value/builders.rs | 74 - ..._value.rs => get_long_known_value_test.rs} | 58 +- .../_get_long_input.rs | 58 + .../_get_long_output.rs | 58 + .../get_long_known_value_test/builders.rs | 74 + .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../SimpleLong/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_long_config.rs | 5 +- .../SimpleLong/runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 119 ++ .../runtimes/rust/tests/simple_long_test.rs | 2 +- TestModels/SimpleTypes/SimpleString/Makefile | 3 +- .../SimpleString/runtimes/rust/Cargo.toml | 10 +- .../SimpleString/runtimes/rust/src/client.rs | 11 +- .../runtimes/rust/src/client/get_string.rs | 8 +- .../rust/src/client/get_string_known_value.rs | 18 +- .../rust/src/client/get_string_utf8.rs | 12 +- .../src/client/get_string_utf8_known_value.rs | 14 +- .../runtimes/rust/src/conversions.rs | 16 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../rust/src/conversions/get_string.rs | 8 +- .../get_string/_get_string_input.rs | 41 +- .../get_string/_get_string_output.rs | 45 +- .../src/conversions/get_string_known_value.rs | 8 +- .../_get_string_known_value_input.rs | 45 +- .../_get_string_known_value_output.rs | 49 +- .../rust/src/conversions/get_string_utf8.rs | 8 +- .../get_string_utf8/_get_string_utf8_input.rs | 47 +- .../_get_string_utf8_output.rs | 53 +- .../get_string_utf8_known_value.rs | 8 +- .../_get_string_utf8_known_value_input.rs | 51 +- .../_get_string_utf8_known_value_output.rs | 57 +- .../src/conversions/simple_string_config.rs | 5 +- .../_simple_string_config.rs | 6 +- .../SimpleString/runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../rust/src/implementation_from_dafny.rs-e | 1880 ----------------- .../SimpleString/runtimes/rust/src/lib.rs | 17 - .../runtimes/rust/src/operation.rs | 6 +- .../runtimes/rust/src/operation/get_string.rs | 8 +- .../operation/get_string/_get_string_input.rs | 38 +- .../get_string/_get_string_output.rs | 38 +- .../rust/src/operation/get_string/builders.rs | 36 +- .../src/operation/get_string_known_value.rs | 35 +- .../_get_string_input.rs | 58 + .../_get_string_known_value_input.rs | 60 - .../_get_string_known_value_output.rs | 59 - .../_get_string_output.rs | 58 + .../get_string_known_value/builders.rs | 59 +- .../rust/src/operation/get_string_utf8.rs | 11 +- .../get_string_utf8/_get_string_utf8_input.rs | 38 +- .../_get_string_utf8_output.rs | 38 +- .../src/operation/get_string_utf8/builders.rs | 42 +- .../operation/get_string_utf8_known_value.rs | 19 +- .../_get_string_utf8_input.rs | 58 + .../_get_string_utf8_known_value_input.rs | 56 - .../_get_string_utf8_known_value_output.rs | 56 - .../_get_string_utf8_output.rs | 58 + .../get_string_utf8_known_value/builders.rs | 52 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../SimpleString/runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_string_config.rs | 5 +- .../SimpleString/runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 179 ++ .../SimpleTypes/SimpleTimestamp/Makefile | 5 +- .../SimpleTimestamp/runtimes/rust/Cargo.toml | 11 +- .../runtimes/rust/src/client.rs | 7 +- .../runtimes/rust/src/client/get_timestamp.rs | 12 +- .../runtimes/rust/src/conversions.rs | 10 +- .../runtimes/rust/src/conversions/error.rs | 32 + .../rust/src/conversions/get_timestamp.rs | 8 +- .../get_timestamp/_get_timestamp_input.rs | 39 +- .../get_timestamp/_get_timestamp_output.rs | 39 +- .../conversions/simple_timestamp_config.rs | 5 +- .../_simple_timestamp_config.rs | 8 +- .../runtimes/rust/src/error.rs | 4 +- .../rust/src/error/sealed_unhandled.rs | 10 +- .../SimpleTimestamp/runtimes/rust/src/lib.rs | 19 - .../runtimes/rust/src/operation.rs | 5 +- .../rust/src/operation/get_timestamp.rs | 15 +- .../get_timestamp/_get_timestamp_input.rs | 44 +- .../get_timestamp/_get_timestamp_output.rs | 55 +- .../src/operation/get_timestamp/builders.rs | 32 +- .../rust/src/standard_library_conversions.rs | 358 ++-- .../rust/src/standard_library_externs.rs | 80 + .../runtimes/rust/src/types.rs | 5 +- .../rust/src/types/simple_timestamp_config.rs | 5 +- .../runtimes/rust/src/wrapped.rs | 15 + .../runtimes/rust/src/wrapped/client.rs | 89 + .../rust/tests/simple_timestamp_test.rs | 2 +- .../src/WrappedSimpleTypesTimestampImpl.dfy | 10 + .../test/SimpleTimestampImplTest.dfy | 22 +- .../test/WrappedSimpleTimestampTest.dfy | 1 + .../rust/src/standard_library_externs.rs | 80 + .../rust/src/conversions/attribute_action.rs | 12 +- .../batch_statement_error_code_enum.rs | 44 +- .../rust/src/conversions/billing_mode.rs | 8 +- .../src/conversions/comparison_operator.rs | 52 +- .../src/conversions/conditional_operator.rs | 8 +- .../rust/src/conversions/index_status.rs | 16 +- .../runtimes/rust/src/conversions/key_type.rs | 8 +- .../rust/src/conversions/projection_type.rs | 12 +- .../rust/src/conversions/replica_status.rs | 28 +- .../conversions/return_consumed_capacity.rs | 12 +- .../return_item_collection_metrics.rs | 8 +- .../rust/src/conversions/return_value.rs | 20 +- ...eturn_values_on_condition_check_failure.rs | 8 +- .../src/conversions/scalar_attribute_type.rs | 12 +- .../runtimes/rust/src/conversions/select.rs | 16 +- .../rust/src/conversions/sse_status.rs | 20 +- .../runtimes/rust/src/conversions/sse_type.rs | 8 +- .../rust/src/conversions/stream_view_type.rs | 16 +- .../rust/src/conversions/table_class.rs | 8 +- .../rust/src/conversions/table_status.rs | 28 +- .../rust/src/standard_library_externs.rs | 80 + .../conversions/customer_master_key_spec.rs | 52 +- .../rust/src/conversions/data_key_spec.rs | 8 +- .../conversions/encryption_algorithm_spec.rs | 12 +- .../key_agreement_algorithm_spec.rs | 4 +- .../conversions/key_encryption_mechanism.rs | 4 +- .../runtimes/rust/src/conversions/key_spec.rs | 52 +- .../rust/src/conversions/key_usage_type.rs | 16 +- .../rust/src/conversions/origin_type.rs | 16 +- .../src/conversions/signing_algorithm_spec.rs | 40 +- .../rust/src/standard_library_externs.rs | 80 + .../software/amazon/polymorph/CodegenCli.java | 25 +- .../polymorph/smithygo/GoTestModels.java | 47 + .../amazon/polymorph/CodegenEngine.java | 148 +- .../smithydotnet/TypeConversionCodegen.java | 17 +- .../awssdk/AwsSdkGoPointableIndex.java | 418 ++-- .../DafnyAwsSdkClientShimGenerator.java | 233 +- ...fnyAwsSdkClientTypeConversionProtocol.java | 1070 +++++++--- .../DafnyGoAwsSdkClientCodegenPlugin.java | 76 +- .../awssdk/DafnyGoAwsSdkDirectedCodegen.java | 134 +- .../AwsSdkToDafnyShapeVisitor.java | 870 ++++---- .../DafnyToAwsSdkShapeVisitor.java | 830 +++++--- .../smithygo/codegen/AddOperationShapes.java | 191 +- .../smithygo/codegen/ApplicationProtocol.java | 8 +- .../smithygo/codegen/CodegenUtils.java | 751 +++---- .../smithygo/codegen/EnumGenerator.java | 142 +- .../smithygo/codegen/GenerationContext.java | 264 +-- .../smithygo/codegen/GoDelegator.java | 7 +- .../smithygo/codegen/GoDependency.java | 604 +++--- .../smithygo/codegen/GoSettings.java | 346 +-- .../polymorph/smithygo/codegen/GoWriter.java | 1480 +++++++------ .../smithygo/codegen/ImportDeclarations.java | 93 +- .../smithygo/codegen/IntEnumGenerator.java | 119 +- .../smithygo/codegen/SmithyGoDependency.java | 261 ++- .../smithygo/codegen/StructureGenerator.java | 163 +- .../smithygo/codegen/SymbolUtils.java | 382 ++-- .../smithygo/codegen/SymbolVisitor.java | 1039 +++++---- .../polymorph/smithygo/codegen/Synthetic.java | 168 +- .../smithygo/codegen/UnionGenerator.java | 185 +- .../smithygo/codegen/ValidationGenerator.java | 623 +++--- .../codegen/integration/GoIntegration.java | 4 +- .../integration/ProtocolGenerator.java | 78 +- .../codegen/knowledge/GoPointableIndex.java | 438 ++-- .../codegen/knowledge/GoUsageIndex.java | 119 +- .../codegen/knowledge/GoValidationIndex.java | 346 +-- .../localservice/DafnyGoPointableIndex.java | 9 +- .../DafnyLocalServiceCodegenPlugin.java | 78 +- .../DafnyLocalServiceDirectedCodegen.java | 272 ++- .../DafnyLocalServiceGenerator.java | 1162 ++++++---- ...fnyLocalServiceTypeConversionProtocol.java | 1477 ++++++++----- .../localservice/nameresolver/Constants.java | 9 +- .../nameresolver/DafnyNameResolver.java | 327 +-- .../nameresolver/SmithyNameResolver.java | 161 +- .../DafnyToSmithyShapeVisitor.java | 943 +++++---- .../SmithyToDafnyShapeVisitor.java | 1033 +++++---- .../smithygo/utils/GoCodegenUtils.java | 68 +- .../generator/AbstractRustShimGenerator.java | 402 ++-- .../generator/RustAwsSdkShimGenerator.java | 86 +- .../generator/RustLibraryShimGenerator.java | 163 +- .../amazon/polymorph/utils/ModelUtils.java | 30 + .../runtimes/rust/conversions/operation.rs | 4 +- .../runtimes/rust/operation/outer.rs | 4 +- .../rust/src/standard_library_externs.rs | 80 + .../templates/runtimes/rust/types.rs | 4 +- .../templates/runtimes/rust/types/enum.rs | 12 + .../wrapped/client_operation_impl.part.rs | 4 +- .../smithyjava/ForEachDafnyTest.java | 1 + 456 files changed, 19904 insertions(+), 17478 deletions(-) create mode 100644 TestModels/Aggregate/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/Constraints/removeDotFromExtern.sh create mode 100644 TestModels/Constructor/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/Errors/runtimes/rust/src/implementation_from_dafny.rs-e create mode 100644 TestModels/Errors/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/LanguageSpecificLogic/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/Refinement/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/Resource/runtimes/rust/src/standard_library_externs.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value_test.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_output.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_input.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/lib.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/builders.rs rename TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/{get_blob_known_value.rs => get_blob_known_value_test.rs} (67%) create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_input.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_output.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/builders.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped/client.rs create mode 100644 TestModels/SimpleTypes/SimpleBoolean/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/lib.rs create mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped/client.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape/_simple_enum_shape.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/lib.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/_simple_enum_shape.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_shape.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped/client.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape/_simple_enum_v2_shape.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/lib.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_input.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/_simple_enum_v2_shape.rs delete mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_shape.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped/client.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value_test.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_output.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_input.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/lib.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/builders.rs rename TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/{get_integer_known_value.rs => get_integer_known_value_test.rs} (67%) create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_input.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_output.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/builders.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped/client.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value_test.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_output.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_input.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/lib.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_output.rs delete mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/builders.rs rename TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/{get_long_known_value.rs => get_long_known_value_test.rs} (67%) create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_input.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_output.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/builders.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped/client.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/implementation_from_dafny.rs-e delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/lib.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_output.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_output.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs delete mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_output.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped/client.rs create mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/error.rs delete mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/lib.rs create mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped.rs create mode 100644 TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped/client.rs create mode 100644 TestModels/SimpleTypes/SimpleTimestamp/src/WrappedSimpleTypesTimestampImpl.dfy create mode 100644 TestModels/Union/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/aws-sdks/ddb-lite/runtimes/rust/src/standard_library_externs.rs create mode 100644 TestModels/aws-sdks/kms-lite/runtimes/rust/src/standard_library_externs.rs create mode 100644 codegen/smithy-dafny-codegen-test/src/test/java/software/amazon/polymorph/smithygo/GoTestModels.java create mode 100644 codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/src/standard_library_externs.rs create mode 100644 codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types/enum.rs diff --git a/.github/workflows/manual.yml b/.github/workflows/manual.yml index de51a9e953..fc44ba70e6 100644 --- a/.github/workflows/manual.yml +++ b/.github/workflows/manual.yml @@ -32,3 +32,7 @@ jobs: uses: ./.github/workflows/test_models_python_tests.yml with: dafny: ${{ inputs.dafny }} + manual-ci-go: + uses: ./.github/workflows/test_models_go_tests.yml + with: + dafny: ${{ inputs.dafny }} diff --git a/.github/workflows/nightly_dafny.yml b/.github/workflows/nightly_dafny.yml index 4edb7ab15f..20b5baa2b4 100644 --- a/.github/workflows/nightly_dafny.yml +++ b/.github/workflows/nightly_dafny.yml @@ -50,6 +50,7 @@ jobs: dafny-nightly-java, dafny-nightly-net, dafny-nightly-rust, + dafny-nightly-python, ] if: ${{ always() && contains(needs.*.result, 'failure') }} env: diff --git a/.github/workflows/pull.yml b/.github/workflows/pull.yml index 7ee82eede0..c1954ad279 100644 --- a/.github/workflows/pull.yml +++ b/.github/workflows/pull.yml @@ -10,10 +10,10 @@ jobs: steps: - name: Populate Dafny versions list id: populate-dafny-versions-list - run: echo "dafny-versions-list=['4.2.0', '4.4.0']" >> $GITHUB_OUTPUT + run: echo "dafny-versions-list=['4.2.0', '4.4.0', '4.8.0']" >> $GITHUB_OUTPUT - name: Populate Dafny versions list for "only new versions" languages (Python) id: populate-only-new-dafny-versions-list - run: echo "only-new-dafny-versions-list=['4.7.0']" >> $GITHUB_OUTPUT + run: echo "only-new-dafny-versions-list=['4.8.0']" >> $GITHUB_OUTPUT outputs: dafny-version-list: ${{ steps.populate-dafny-versions-list.outputs.dafny-versions-list }} only-new-dafny-version-list: ${{ steps.populate-only-new-dafny-versions-list.outputs.only-new-dafny-versions-list }} @@ -66,3 +66,28 @@ jobs: uses: ./.github/workflows/test_models_python_tests.yml with: dafny: ${{ matrix.dafny-version }} + pr-ci-go: + needs: pr-populate-dafny-versions + strategy: + fail-fast: false + matrix: + dafny-version: ${{ fromJson(needs.pr-populate-dafny-versions.outputs.only-new-dafny-version-list) }} + uses: ./.github/workflows/test_models_go_tests.yml + with: + dafny: ${{ matrix.dafny-version }} + + pr-ci-all-required: + if: always() + needs: + - pr-ci-verification + - pr-ci-java + - pr-ci-net + - pr-ci-rust + - pr-ci-python + - pr-ci-go + runs-on: ubuntu-latest + steps: + - name: Verify all required jobs passed + uses: re-actors/alls-green@release/v1 + with: + jobs: ${{ toJSON(needs) }} diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml index 43c1298b78..2f164cb8c2 100644 --- a/.github/workflows/push.yml +++ b/.github/workflows/push.yml @@ -12,10 +12,10 @@ jobs: steps: - name: Populate Dafny versions list id: populate-dafny-versions-list - run: echo "dafny-versions-list=['4.2.0', '4.4.0']" >> $GITHUB_OUTPUT + run: echo "dafny-versions-list=['4.2.0', '4.4.0', '4.8.0']" >> $GITHUB_OUTPUT - name: Populate Dafny versions list for "only new versions" languages (Python) id: populate-only-new-dafny-versions-list - run: echo "only-new-dafny-versions-list=['4.7.0']" >> $GITHUB_OUTPUT + run: echo "only-new-dafny-versions-list=['4.8.0']" >> $GITHUB_OUTPUT outputs: dafny-version-list: ${{ steps.populate-dafny-versions-list.outputs.dafny-versions-list }} only-new-dafny-version-list: ${{ steps.populate-only-new-dafny-versions-list.outputs.only-new-dafny-versions-list }} @@ -68,3 +68,12 @@ jobs: uses: ./.github/workflows/test_models_python_tests.yml with: dafny: ${{ matrix.dafny-version }} + push-ci-go: + needs: pr-populate-dafny-versions + strategy: + fail-fast: false + matrix: + dafny-version: ${{ fromJson(needs.pr-populate-dafny-versions.outputs.only-new-dafny-version-list) }} + uses: ./.github/workflows/test_models_go_tests.yml + with: + dafny: ${{ matrix.dafny-version }} diff --git a/.github/workflows/test_models_go_tests.yml b/.github/workflows/test_models_go_tests.yml index 69d0d4abee..946630e1a9 100644 --- a/.github/workflows/test_models_go_tests.yml +++ b/.github/workflows/test_models_go_tests.yml @@ -1,81 +1,64 @@ name: Library Go tests -on: ["pull_request", "push"] +on: + workflow_call: + inputs: + dafny: + description: "The Dafny version to run" + required: true + type: string + num_shards: + required: false + type: number + default: 5 jobs: - test_go: + populate-matrix-dimensions: + runs-on: ubuntu-latest + steps: + - name: Populate shard list + id: populate-shard-list + run: echo "shard-list=[`seq -s , 1 ${{ inputs.num_shards }}`]" >> $GITHUB_OUTPUT + outputs: + shard-list: ${{ steps.populate-shard-list.outputs.shard-list }} + testGo: + needs: populate-matrix-dimensions strategy: - fail-fast: false + fail-fast: false # at least for development; see all errors matrix: - library: [ - # TODO: Uncomment below before making PR - # TestModels/dafny-dependencies/StandardLibrary, # This stores current Polymorph dependencies that all TestModels depend on - TestModels/Aggregate, - # TestModels/AggregateReferences, - TestModels/CodegenPatches, - TestModels/Constraints, - TestModels/Constructor, - TestModels/Dependencies, - TestModels/Errors, - TestModels/Extendable, - TestModels/Extern, - # TestModels/LanguageSpecificLogic, - # TestModels/LocalService, - # TestModels/MultipleModels, - TestModels/Positional, - TestModels/Refinement, - TestModels/Resource, - # TestModels/SimpleTypes/BigDecimal, - # TestModels/SimpleTypes/BigInteger, - TestModels/SimpleTypes/SimpleBlob, - TestModels/SimpleTypes/SimpleBoolean, - # TestModels/SimpleTypes/SimpleByte, - TestModels/SimpleTypes/SimpleDouble, - TestModels/SimpleTypes/SimpleEnum, - # TestModels/SimpleTypes/SimpleEnumV2, - # TestModels/SimpleTypes/SimpleFloat, - TestModels/SimpleTypes/SimpleInteger, - TestModels/SimpleTypes/SimpleLong, - # TestModels/SimpleTypes/SimpleShort, - TestModels/SimpleTypes/SimpleString, - # TestModels/SimpleTypes/SimpleTimestamp, - TestModels/Union, - # TestModels/aws-sdks/ddb, - TestModels/aws-sdks/kms - ] - runs-on: "macos-12" + shard: ${{ fromJson(needs.populate-matrix-dimensions.outputs.shard-list) }} + runs-on: "ubuntu-latest" + permissions: + id-token: write + contents: read + env: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 steps: - - uses: actions/checkout@v2 + - name: Support longpaths on Git checkout + run: | + git config --global core.longpaths true - # - name: Setup Dafny 4.5.0 - # uses: dafny-lang/setup-dafny-action@v1.7.0 - # with: - # dafny-version: 4.5.0 - # TODO: Setup Dafny once its released - - name: Setup dotnet - uses: actions/setup-dotnet@v4 + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@v1 with: - dotnet-version: 6.0.x + aws-region: us-west-2 + role-to-assume: arn:aws:iam::370957321024:role/GitHub-CI-PolymorphTestModels-Role-us-west-2 + role-session-name: PythonTests - - name: Build Dafny from source - run: | - git clone https://github.com/dafny-lang/dafny.git --recurse-submodules - cd dafny - make exe - - - name: Install Z3 version 4.12.1 - run: | - cd $GITHUB_WORKSPACE/dafny - make z3-mac + - uses: actions/checkout@v3 + with: + submodules: recursive - - name: Add Dafny to PATH - run: | - echo "$GITHUB_WORKSPACE/dafny/Scripts" >> $GITHUB_PATH + - name: Setup Dafny + uses: dafny-lang/setup-dafny-action@v1.7.0 + with: + dafny-version: ${{ inputs.dafny }} - name: Install Go uses: actions/setup-go@v2 with: - go-version: '1.21' + go-version: "1.21" - name: Install Go imports run: | @@ -84,33 +67,36 @@ jobs: - name: Add go mod to Dafny Runtime Go shell: bash working-directory: ./DafnyRuntimeGo - run: | + run: | go mod init github.com/dafny-lang/DafnyRuntimeGo go mod tidy - - name: polymorph dafny dependencies - shell: bash - working-directory: ./TestModels/dafny-dependencies/StandardLibrary - run: | - export DAFNY_VERSION=4.6 - make polymorph_dafny - make transpile_go - make polymorph_go - cd ./runtimes/go/ImplementationFromDafny-go/ - go mod init github.com/dafny-lang/DafnyStandardLibGo - # TODO: This should handwritten (in the makefile or something) - echo "replace github.com/dafny-lang/DafnyRuntimeGo => ../../../../../DafnyRuntimeGo/" >> go.mod; + - name: Setup Java 17 for codegen + uses: actions/setup-java@v3 + with: + distribution: "corretto" + java-version: 17 - - name: Generate Polymorph Dafny and Go code - shell: bash - working-directory: ./${{ matrix.library }} - run: | - export DAFNY_VERSION=4.6 - make polymorph_dafny - sh ./removeDotFromExtern.sh - make transpile_go - make polymorph_go + - name: Setup smithy-dafny-conversion + uses: gradle/gradle-build-action@v2 + with: + arguments: publishToMavenLocal + build-root-directory: smithy-dafny-conversion - goimports -w runtimes/go/ - cd runtimes/go/TestsFromDafny-go/ - go run TestsFromDafny.go \ No newline at end of file + - name: Install Smithy-Dafny codegen dependencies + uses: ./.github/actions/install_smithy_dafny_codegen_dependencies + + - name: Install smithy-dafny-codegen locally + uses: gradle/gradle-build-action@v2 + with: + arguments: :smithy-dafny-codegen:pTML + build-root-directory: codegen + + - name: Execute smithy-dafny-codegen-test tests + uses: gradle/gradle-build-action@v2 + env: + JUNIT_SHARD: ${{ matrix.shard }} + JUNIT_SHARD_COUNT: ${{ inputs.num_shards }} + with: + arguments: :smithy-dafny-codegen-test:test --tests '*smithygo*' --info + build-root-directory: codegen diff --git a/.github/workflows/test_models_rust_tests.yml b/.github/workflows/test_models_rust_tests.yml index 5d0175142e..7833df745f 100644 --- a/.github/workflows/test_models_rust_tests.yml +++ b/.github/workflows/test_models_rust_tests.yml @@ -59,7 +59,7 @@ jobs: - name: Set up Rust uses: actions-rust-lang/setup-rust-toolchain@v1 with: - toolchain: "1.76.0" + toolchain: "1.80.0" rustflags: "" components: rustfmt diff --git a/SmithyDafnyMakefile.mk b/SmithyDafnyMakefile.mk index 766df9d585..6f598e4f7b 100644 --- a/SmithyDafnyMakefile.mk +++ b/SmithyDafnyMakefile.mk @@ -434,7 +434,7 @@ _polymorph_dafny: OUTPUT_DAFNY=\ --output-dafny $(if $(DIR_STRUCTURE_V2), $(LIBRARY_ROOT)/dafny/$(SERVICE)/Model, $(LIBRARY_ROOT)/Model) _polymorph_dafny: INPUT_DAFNY=\ --include-dafny $(PROJECT_ROOT)/$(STD_LIBRARY)/src/Index.dfy -_polymorph_dafny: _polymorph removeDots +_polymorph_dafny: _polymorph # Generates dotnet code for all namespaces in this project .PHONY: polymorph_dotnet @@ -767,6 +767,10 @@ clean_go: rm -rf $(LIBRARY_ROOT)/runtimes/go/ImplementationFromDafny-go rm -rf $(LIBRARY_ROOT)/runtimes/go/TestsFromDafny-go +test_go: + cd runtimes/go/TestFromDafny-go + go run TestsFromDafny.go + ########################## Python targets # Python MUST transpile dependencies first to generate .dtr files @@ -862,9 +866,3 @@ local_transpile_test_single: TRANSPILE_DEPENDENCIES= \ $(patsubst %, -library:$(PROJECT_ROOT)/%, $(PROJECT_INDEX)) \ -library:$(PROJECT_ROOT)/$(STD_LIBRARY)/src/Index.dfy local_transpile_test_single: transpile_test - -removeDots: - chmod +x ./removeDotFromExtern.sh - ./removeDotFromExtern.sh - -transpile_implementation_go: removeDots \ No newline at end of file diff --git a/TestModels/Aggregate/runtimes/rust/src/standard_library_externs.rs b/TestModels/Aggregate/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/Aggregate/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/Constraints/removeDotFromExtern.sh b/TestModels/Constraints/removeDotFromExtern.sh deleted file mode 100644 index 410b6a0fe9..0000000000 --- a/TestModels/Constraints/removeDotFromExtern.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash -# TODO: remove this file if codegen is not generating extern with "." in go - -removeDotFromExtern() { - local directory="$1" - # Recursively search for all files in the current directory and subdirectories - for file in $(find "$directory" -type f); do - # Check if the file contains the pattern "{:extern "XYZ" }" - if grep -q '{:extern ".*"' "$file"; then - # Extract the "XYZ" part from the pattern - xyz=$(grep -o '{:extern "\([^"]*\)"' "$file" | sed 's/{:extern "\([^"]*\)"/\1/') - # Check if the "XYZ" part contains a dot - if [[ "$xyz" == *"."* ]]; then - # Remove the dot from "XYZ" - new_xyz=$(echo "$xyz" | sed 's/\.//g') - # Update the file with the new pattern - sed "s/{:extern \"$xyz\"/{:extern \"$new_xyz\"/g" $file > $file.tmp - cat $file.tmp > $file - rm $file.tmp - fi - fi - done -} - -removeDotFromExtern "Model" -removeDotFromExtern "src" - diff --git a/TestModels/Constructor/runtimes/rust/src/standard_library_externs.rs b/TestModels/Constructor/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/Constructor/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/Errors/runtimes/rust/Cargo.toml b/TestModels/Errors/runtimes/rust/Cargo.toml index 9434c16e44..b14b9e9ec0 100644 --- a/TestModels/Errors/runtimes/rust/Cargo.toml +++ b/TestModels/Errors/runtimes/rust/Cargo.toml @@ -6,12 +6,10 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +aws-smithy-runtime = {version = "1.7.1", features=["client"]} +aws-smithy-runtime-api = {version = "1.7.2", features=["client"]} +aws-smithy-types = "1.2.4" dafny_runtime = { path = "../../../dafny-dependencies/dafny_runtime_rust"} -[dependencies.aws-smithy-runtime] -features = ["client"] -[dependencies.aws-smithy-runtime-api] -features = ["client"] -[dependencies.aws-smithy-types] [dev-dependencies.tokio] version = "1.26.0" diff --git a/TestModels/Errors/runtimes/rust/src/implementation_from_dafny.rs-e b/TestModels/Errors/runtimes/rust/src/implementation_from_dafny.rs-e deleted file mode 100644 index 742c6a6ba8..0000000000 --- a/TestModels/Errors/runtimes/rust/src/implementation_from_dafny.rs-e +++ /dev/null @@ -1,1745 +0,0 @@ -#![allow(warnings, unconditional_panic)] -#![allow(nonstandard_style)] - -pub mod _module { - -} -pub mod simple { - pub mod errors { - pub mod internaldafny { - pub use ::dafny_runtime::UpcastObject; - pub use ::std::any::Any; - pub use crate::simple::errors::internaldafny::types::ISimpleErrorsClient; - - pub struct _default {} - - impl _default { - pub fn DefaultSimpleErrorsConfig() -> ::std::rc::Rc { - ::std::rc::Rc::new(crate::simple::errors::internaldafny::types::SimpleErrorsConfig::SimpleErrorsConfig {}) - } - pub fn SimpleErrors(config: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut res = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut client = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object>::new(); - let mut _nw0: ::dafny_runtime::Object = crate::simple::errors::internaldafny::SimpleErrorsClient::_allocate_object(); - crate::simple::errors::internaldafny::SimpleErrorsClient::_ctor(&_nw0, &::std::rc::Rc::new(crate::r#_SimpleErrorsImpl_Compile::Config::Config {})); - client = ::dafny_runtime::MaybePlacebo::from(_nw0.clone()); - res = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Success { - value: client.read() - })); - return res.read(); - } - pub fn CreateSuccessOfClient(client: &::dafny_runtime::Object) -> ::std::rc::Rc, ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Success { - value: client.clone() - }) - } - pub fn CreateFailureOfError(error: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Failure { - error: error.clone() - }) - } - } - - pub struct SimpleErrorsClient { - pub r#__i_config: ::std::rc::Rc - } - - impl SimpleErrorsClient { - pub fn _allocate_object() -> ::dafny_runtime::Object { - ::dafny_runtime::allocate_object::() - } - pub fn _ctor(this: &::dafny_runtime::Object, config: &::std::rc::Rc) -> () { - let mut _set__i_config: bool = false; - ::dafny_runtime::update_field_uninit_object!(this.clone(), r#__i_config, _set__i_config, config.clone()); - return (); - } - pub fn config(&self) -> ::std::rc::Rc { - self.r#__i_config.clone() - } - } - - impl UpcastObject - for crate::simple::errors::internaldafny::SimpleErrorsClient { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); - } - - impl ISimpleErrorsClient - for crate::simple::errors::internaldafny::SimpleErrorsClient { - fn AlwaysError(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut _out0 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - _out0 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleErrorsImpl_Compile::_default::AlwaysError(&self.config().clone(), input)); - output = ::dafny_runtime::MaybePlacebo::from(_out0.read()); - return output.read(); - } - fn AlwaysMultipleErrors(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut _out1 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - _out1 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleErrorsImpl_Compile::_default::AlwaysMultipleErrors(&self.config().clone(), input)); - output = ::dafny_runtime::MaybePlacebo::from(_out1.read()); - return output.read(); - } - fn AlwaysNativeError(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut _out2 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - _out2 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleErrorsImpl_Compile::_default::AlwaysNativeError(&self.config().clone(), input)); - output = ::dafny_runtime::MaybePlacebo::from(_out2.read()); - return output.read(); - } - } - - impl UpcastObject - for crate::simple::errors::internaldafny::SimpleErrorsClient { - ::dafny_runtime::UpcastObjectFn!(dyn crate::simple::errors::internaldafny::types::ISimpleErrorsClient); - } - - pub mod types { - pub use ::std::fmt::Debug; - pub use ::dafny_runtime::DafnyPrint; - pub use ::std::cmp::Eq; - pub use ::std::hash::Hash; - pub use ::std::default::Default; - pub use ::std::convert::AsRef; - pub use ::dafny_runtime::UpcastObject; - pub use ::std::any::Any; - - #[derive(PartialEq, Clone)] - pub enum DafnyCallEvent { - DafnyCallEvent { - input: I, - output: O - } - } - - impl DafnyCallEvent { - pub fn input(&self) -> &I { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => input, - } - } - pub fn output(&self) -> &O { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => output, - } - } - } - - impl Debug - for DafnyCallEvent { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for DafnyCallEvent { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => { - write!(_formatter, "simple.errors.internaldafny.types.DafnyCallEvent.DafnyCallEvent(")?; - ::dafny_runtime::DafnyPrint::fmt_print(input, _formatter, false)?; - write!(_formatter, ", ")?; - ::dafny_runtime::DafnyPrint::fmt_print(output, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for DafnyCallEvent {} - - impl Hash - for DafnyCallEvent { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => { - ::std::hash::Hash::hash(input, _state); - ::std::hash::Hash::hash(output, _state) - }, - } - } - } - - impl Default - for DafnyCallEvent { - fn default() -> DafnyCallEvent { - DafnyCallEvent::DafnyCallEvent { - input: ::std::default::Default::default(), - output: ::std::default::Default::default() - } - } - } - - impl AsRef> - for &DafnyCallEvent { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum GetErrorsInput { - GetErrorsInput { - value: ::std::rc::Rc>> - } - } - - impl GetErrorsInput { - pub fn value(&self) -> &::std::rc::Rc>> { - match self { - GetErrorsInput::GetErrorsInput{value, } => value, - } - } - } - - impl Debug - for GetErrorsInput { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for GetErrorsInput { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - GetErrorsInput::GetErrorsInput{value, } => { - write!(_formatter, "simple.errors.internaldafny.types.GetErrorsInput.GetErrorsInput(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for GetErrorsInput {} - - impl Hash - for GetErrorsInput { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - GetErrorsInput::GetErrorsInput{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for GetErrorsInput { - fn default() -> GetErrorsInput { - GetErrorsInput::GetErrorsInput { - value: ::std::default::Default::default() - } - } - } - - impl AsRef - for &GetErrorsInput { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum GetErrorsOutput { - GetErrorsOutput { - value: ::std::rc::Rc>> - } - } - - impl GetErrorsOutput { - pub fn value(&self) -> &::std::rc::Rc>> { - match self { - GetErrorsOutput::GetErrorsOutput{value, } => value, - } - } - } - - impl Debug - for GetErrorsOutput { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for GetErrorsOutput { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - GetErrorsOutput::GetErrorsOutput{value, } => { - write!(_formatter, "simple.errors.internaldafny.types.GetErrorsOutput.GetErrorsOutput(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for GetErrorsOutput {} - - impl Hash - for GetErrorsOutput { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - GetErrorsOutput::GetErrorsOutput{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for GetErrorsOutput { - fn default() -> GetErrorsOutput { - GetErrorsOutput::GetErrorsOutput { - value: ::std::default::Default::default() - } - } - } - - impl AsRef - for &GetErrorsOutput { - fn as_ref(&self) -> Self { - self - } - } - - pub struct ISimpleErrorsClientCallHistory {} - - impl ISimpleErrorsClientCallHistory { - pub fn _allocate_object() -> ::dafny_runtime::Object { - ::dafny_runtime::allocate_object::() - } - } - - impl UpcastObject - for crate::simple::errors::internaldafny::types::ISimpleErrorsClientCallHistory { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); - } - - pub trait ISimpleErrorsClient: ::std::any::Any + ::dafny_runtime::UpcastObject { - fn AlwaysError(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; - fn AlwaysMultipleErrors(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; - fn AlwaysNativeError(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; - } - - #[derive(PartialEq, Clone)] - pub enum SimpleErrorsConfig { - SimpleErrorsConfig {} - } - - impl SimpleErrorsConfig {} - - impl Debug - for SimpleErrorsConfig { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for SimpleErrorsConfig { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - SimpleErrorsConfig::SimpleErrorsConfig{} => { - write!(_formatter, "simple.errors.internaldafny.types.SimpleErrorsConfig.SimpleErrorsConfig")?; - Ok(()) - }, - } - } - } - - impl SimpleErrorsConfig { - pub fn _AllSingletonConstructors() -> ::dafny_runtime::SequenceIter<::std::rc::Rc> { - ::dafny_runtime::seq![::std::rc::Rc::new(SimpleErrorsConfig::SimpleErrorsConfig {})].iter() - } - } - - impl Eq - for SimpleErrorsConfig {} - - impl Hash - for SimpleErrorsConfig { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - SimpleErrorsConfig::SimpleErrorsConfig{} => { - - }, - } - } - } - - impl Default - for SimpleErrorsConfig { - fn default() -> SimpleErrorsConfig { - SimpleErrorsConfig::SimpleErrorsConfig {} - } - } - - impl AsRef - for &SimpleErrorsConfig { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum Error { - SimpleErrorsException { - message: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> - }, - CollectionOfErrors { - list: ::dafny_runtime::Sequence<::std::rc::Rc>, - message: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> - }, - Opaque { - obj: ::dafny_runtime::Object - } - } - - impl Error { - pub fn message(&self) -> &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - match self { - Error::SimpleErrorsException{message, } => message, - Error::CollectionOfErrors{list, message, } => message, - Error::Opaque{obj, } => panic!("field does not exist on this variant"), - } - } - pub fn list(&self) -> &::dafny_runtime::Sequence<::std::rc::Rc> { - match self { - Error::SimpleErrorsException{message, } => panic!("field does not exist on this variant"), - Error::CollectionOfErrors{list, message, } => list, - Error::Opaque{obj, } => panic!("field does not exist on this variant"), - } - } - pub fn obj(&self) -> &::dafny_runtime::Object { - match self { - Error::SimpleErrorsException{message, } => panic!("field does not exist on this variant"), - Error::CollectionOfErrors{list, message, } => panic!("field does not exist on this variant"), - Error::Opaque{obj, } => obj, - } - } - } - - impl Debug - for Error { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Error { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Error::SimpleErrorsException{message, } => { - write!(_formatter, "simple.errors.internaldafny.types.Error.SimpleErrorsException(")?; - ::dafny_runtime::DafnyPrint::fmt_print(message, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - Error::CollectionOfErrors{list, message, } => { - write!(_formatter, "simple.errors.internaldafny.types.Error.CollectionOfErrors(")?; - ::dafny_runtime::DafnyPrint::fmt_print(list, _formatter, false)?; - write!(_formatter, ", ")?; - ::dafny_runtime::DafnyPrint::fmt_print(message, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - Error::Opaque{obj, } => { - write!(_formatter, "simple.errors.internaldafny.types.Error.Opaque(")?; - ::dafny_runtime::DafnyPrint::fmt_print(obj, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for Error {} - - impl Hash - for Error { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Error::SimpleErrorsException{message, } => { - ::std::hash::Hash::hash(message, _state) - }, - Error::CollectionOfErrors{list, message, } => { - ::std::hash::Hash::hash(list, _state); - ::std::hash::Hash::hash(message, _state) - }, - Error::Opaque{obj, } => { - ::std::hash::Hash::hash(obj, _state) - }, - } - } - } - - impl Default - for Error { - fn default() -> Error { - Error::SimpleErrorsException { - message: ::std::default::Default::default() - } - } - } - - impl AsRef - for &Error { - fn as_ref(&self) -> Self { - self - } - } - - pub type OpaqueError = ::std::rc::Rc; - } - } - } -} -pub mod r#_SimpleErrorsImpl_Compile { - pub use ::std::fmt::Debug; - pub use ::dafny_runtime::DafnyPrint; - pub use ::std::cmp::Eq; - pub use ::std::hash::Hash; - pub use ::std::default::Default; - pub use ::std::convert::AsRef; - pub use ::dafny_runtime::UpcastObject; - pub use ::std::any::Any; - - pub struct _default {} - - impl _default { - pub fn AlwaysError(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { - panic!("Halt") - }; - let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::errors::internaldafny::types::Error::SimpleErrorsException { - message: input.value().value().clone() - }); - output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Failure { - error: res.clone() - })); - return output.read(); - } - pub fn AlwaysMultipleErrors(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { - panic!("Halt") - }; - let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::errors::internaldafny::types::Error::CollectionOfErrors { - list: ::dafny_runtime::seq![::std::rc::Rc::new(crate::simple::errors::internaldafny::types::Error::SimpleErrorsException { - message: input.value().value().clone() - })], - message: ::dafny_runtime::string_utf16_of("Something") - }); - output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Failure { - error: res.clone() - })); - return output.read(); - } - pub fn AlwaysNativeError(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut opaqueObject = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object>::new(); - let mut _nw1: ::dafny_runtime::Object = crate::r#_SimpleErrorsImpl_Compile::SomeOpaqueGeneratedTypeForTesting::_allocate_object(); - crate::r#_SimpleErrorsImpl_Compile::SomeOpaqueGeneratedTypeForTesting::_ctor(&_nw1); - opaqueObject = ::dafny_runtime::MaybePlacebo::from(_nw1.clone()); - let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::errors::internaldafny::types::Error::Opaque { - obj: ::dafny_runtime::upcast_object::()(opaqueObject.read()) - }); - output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Failure { - error: res.clone() - })); - return output.read(); - } - } - - #[derive(PartialEq, Clone)] - pub enum Config { - Config {} - } - - impl Config {} - - impl Debug - for Config { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Config { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Config::Config{} => { - write!(_formatter, "SimpleErrorsImpl_Compile.Config.Config")?; - Ok(()) - }, - } - } - } - - impl Config { - pub fn _AllSingletonConstructors() -> ::dafny_runtime::SequenceIter<::std::rc::Rc> { - ::dafny_runtime::seq![::std::rc::Rc::new(Config::Config {})].iter() - } - } - - impl Eq - for Config {} - - impl Hash - for Config { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Config::Config{} => { - - }, - } - } - } - - impl Default - for Config { - fn default() -> Config { - Config::Config {} - } - } - - impl AsRef - for &Config { - fn as_ref(&self) -> Self { - self - } - } - - pub struct SomeOpaqueGeneratedTypeForTesting {} - - impl SomeOpaqueGeneratedTypeForTesting { - pub fn _allocate_object() -> ::dafny_runtime::Object { - ::dafny_runtime::allocate_object::() - } - pub fn _ctor(this: &::dafny_runtime::Object) -> () { - return (); - } - } - - impl UpcastObject - for SomeOpaqueGeneratedTypeForTesting { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); - } -} -pub mod r#_StandardLibrary_Compile { - pub struct _default {} - - impl _default { - pub fn Join<_T: ::dafny_runtime::DafnyType>(ss: &::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>, joiner: &::dafny_runtime::Sequence<_T>) -> ::dafny_runtime::Sequence<_T> { - let mut _accumulator: ::dafny_runtime::Sequence<_T> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>; - let mut _r0 = ss.clone(); - let mut _r1 = joiner.clone(); - 'TAIL_CALL_START: loop { - let ss = _r0; - let joiner = _r1; - if ss.cardinality() == ::dafny_runtime::int!(1) { - return _accumulator.concat(&ss.get(&::dafny_runtime::int!(0))); - } else { - _accumulator = _accumulator.concat(&ss.get(&::dafny_runtime::int!(0)).concat(&joiner)); - let mut _in0: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ss.drop(&::dafny_runtime::int!(1)); - let mut _in1: ::dafny_runtime::Sequence<_T> = joiner.clone(); - _r0 = _in0.clone(); - _r1 = _in1.clone(); - continue 'TAIL_CALL_START; - } - } - } - pub fn Split<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> { - let mut _accumulator: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>; - let mut _r0 = s.clone(); - let mut _r1 = delim.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let delim = _r1; - let mut i: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(&s, &delim, &::dafny_runtime::int!(0)); - if matches!((&i).as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { - _accumulator = _accumulator.concat(&::dafny_runtime::seq![s.take(i.value())]); - let mut _in2: ::dafny_runtime::Sequence<_T> = s.drop(&(i.value().clone() + ::dafny_runtime::int!(1))); - let mut _in3: _T = delim.clone(); - _r0 = _in2.clone(); - _r1 = _in3.clone(); - continue 'TAIL_CALL_START; - } else { - return _accumulator.concat(&::dafny_runtime::seq![s.clone()]); - } - } - } - pub fn SplitOnce<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> (::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>) { - let mut i: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(s, delim, &::dafny_runtime::int!(0)); - ( - s.take(i.value()), - s.drop(&(i.value().clone() + ::dafny_runtime::int!(1))) - ) - } - pub fn r#_SplitOnce_q<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> ::std::rc::Rc, ::dafny_runtime::Sequence<_T>)>> { - let mut valueOrError0: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(s, delim, &::dafny_runtime::int!(0)); - if valueOrError0.IsFailure() { - valueOrError0.PropagateFailure::<(::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>)>() - } else { - let mut i: ::dafny_runtime::_System::nat = valueOrError0.Extract(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<(::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>)>::Some { - value: ( - s.take(&i), - s.drop(&(i.clone() + ::dafny_runtime::int!(1))) - ) - }) - } - } - pub fn FindIndexMatching<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, c: &_T, i: &::dafny_runtime::_System::nat) -> ::std::rc::Rc> { - crate::r#_StandardLibrary_Compile::_default::FindIndex::<_T>(s, { - let c: _T = c.clone(); - &({ - let mut c = c.clone(); - ::std::rc::Rc::new(move |x: &_T| -> bool{ - x.clone() == c.clone() - }) - }) - }, i) - } - pub fn FindIndex<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>, f: &::std::rc::Rc bool>, i: &::dafny_runtime::_System::nat) -> ::std::rc::Rc> { - let mut _r0 = s.clone(); - let mut _r1 = f.clone(); - let mut _r2 = i.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let f = _r1; - let i = _r2; - if i.clone() == s.cardinality() { - return ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::_System::nat>::None {}); - } else { - if (&f)(&s.get(&i)) { - return ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::_System::nat>::Some { - value: i.clone() - }); - } else { - let mut _in4: ::dafny_runtime::Sequence<_T> = s.clone(); - let mut _in5: ::std::rc::Rc bool> = f.clone(); - let mut _in6: ::dafny_runtime::DafnyInt = i.clone() + ::dafny_runtime::int!(1); - _r0 = _in4.clone(); - _r1 = _in5.clone(); - _r2 = _in6.clone(); - continue 'TAIL_CALL_START; - } - } - } - } - pub fn Filter<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>, f: &::std::rc::Rc bool>) -> ::dafny_runtime::Sequence<_T> { - let mut _accumulator: ::dafny_runtime::Sequence<_T> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>; - let mut _r0 = s.clone(); - let mut _r1 = f.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let f = _r1; - if s.cardinality() == ::dafny_runtime::int!(0) { - return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>)); - } else { - if (&f)(&s.get(&::dafny_runtime::int!(0))) { - _accumulator = _accumulator.concat(&::dafny_runtime::seq![s.get(&::dafny_runtime::int!(0))]); - let mut _in7: ::dafny_runtime::Sequence<_T> = s.drop(&::dafny_runtime::int!(1)); - let mut _in8: ::std::rc::Rc bool> = f.clone(); - _r0 = _in7.clone(); - _r1 = _in8.clone(); - continue 'TAIL_CALL_START; - } else { - let mut _in9: ::dafny_runtime::Sequence<_T> = s.drop(&::dafny_runtime::int!(1)); - let mut _in10: ::std::rc::Rc bool> = f.clone(); - _r0 = _in9.clone(); - _r1 = _in10.clone(); - continue 'TAIL_CALL_START; - } - } - } - } - pub fn Min(a: &::dafny_runtime::DafnyInt, b: &::dafny_runtime::DafnyInt) -> ::dafny_runtime::DafnyInt { - if a.clone() < b.clone() { - a.clone() - } else { - b.clone() - } - } - pub fn Fill<_T: ::dafny_runtime::DafnyType>(value: &_T, n: &::dafny_runtime::_System::nat) -> ::dafny_runtime::Sequence<_T> { - { - let _initializer = { - let value: _T = value.clone(); - { - let mut value = value.clone(); - ::std::rc::Rc::new(move |_v0: &::dafny_runtime::DafnyInt| -> _T{ - value.clone() - }) - } - }; - ::dafny_runtime::integer_range(::dafny_runtime::Zero::zero(), n.clone()).map(|i| _initializer(&i)).collect::<::dafny_runtime::Sequence<_>>() - } - } - pub fn SeqToArray<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> ::dafny_runtime::Object<[_T]> { - let mut a = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object<[_T]>>::new(); - let mut _init0: ::std::rc::Rc _T> = { - let s: ::dafny_runtime::Sequence<_T> = s.clone(); - { - let mut s = s.clone(); - ::std::rc::Rc::new(move |i: &::dafny_runtime::DafnyInt| -> _T{ - s.get(i) - }) - } - }; - let mut _nw2: ::dafny_runtime::Object<[::std::mem::MaybeUninit<_T>]> = ::dafny_runtime::array::placebos_usize_object::<_T>(::dafny_runtime::DafnyUsize::into_usize(s.cardinality())); - for r#__i0_0 in ::dafny_runtime::integer_range(0, ::dafny_runtime::rd!(_nw2.clone()).len()) { - { - let __idx0 = ::dafny_runtime::DafnyUsize::into_usize(r#__i0_0.clone()); - ::dafny_runtime::md!(_nw2)[__idx0] = ::std::mem::MaybeUninit::new((&_init0)(&::dafny_runtime::int!(r#__i0_0.clone()))); - } - } - a = ::dafny_runtime::MaybePlacebo::from(::dafny_runtime::array::construct_object(_nw2.clone())); - return a.read(); - } - pub fn LexicographicLessOrEqual<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, b: &::dafny_runtime::Sequence<_T>, less: &::std::rc::Rc bool>) -> bool { - ::dafny_runtime::integer_range(::dafny_runtime::int!(0), a.cardinality() + ::dafny_runtime::int!(1)).any(({ - let mut a = a.clone(); - let mut b = b.clone(); - let mut less = less.clone(); - ::std::rc::Rc::new(move |r#__exists_var_0: ::dafny_runtime::DafnyInt| -> bool{ - let mut k: ::dafny_runtime::DafnyInt = r#__exists_var_0.clone(); - ::dafny_runtime::int!(0) <= k.clone() && k.clone() <= a.cardinality() && crate::r#_StandardLibrary_Compile::_default::LexicographicLessOrEqualAux::<_T>(&a, &b, &less, &k) - }) - }).as_ref()) - } - pub fn LexicographicLessOrEqualAux<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, b: &::dafny_runtime::Sequence<_T>, less: &::std::rc::Rc bool>, lengthOfCommonPrefix: &::dafny_runtime::_System::nat) -> bool { - lengthOfCommonPrefix.clone() <= b.cardinality() && ::dafny_runtime::integer_range(::dafny_runtime::int!(0), lengthOfCommonPrefix.clone()).all(({ - let mut lengthOfCommonPrefix = lengthOfCommonPrefix.clone(); - let mut a = a.clone(); - let mut b = b.clone(); - ::std::rc::Rc::new(move |r#__forall_var_0: ::dafny_runtime::DafnyInt| -> bool{ - let mut i: ::dafny_runtime::DafnyInt = r#__forall_var_0.clone(); - !(::dafny_runtime::int!(0) <= i.clone() && i.clone() < lengthOfCommonPrefix.clone()) || a.get(&i) == b.get(&i) - }) - }).as_ref()) && (lengthOfCommonPrefix.clone() == a.cardinality() || lengthOfCommonPrefix.clone() < b.cardinality() && less(&a.get(lengthOfCommonPrefix), &b.get(lengthOfCommonPrefix))) - } - pub fn SetToOrderedSequence<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Set<::dafny_runtime::Sequence<_T>>, less: &::std::rc::Rc bool>) -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> { - let mut _accumulator: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>; - let mut _r0 = s.clone(); - let mut _r1 = less.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let less = _r1; - if s.clone() == ::dafny_runtime::set!{} { - return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>)); - } else { - return (&({ - let mut s = s.clone(); - let mut less = less.clone(); - ::std::rc::Rc::new(move |r#__let_dummy_0: &::dafny_runtime::DafnyInt| -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>{ - let mut a = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Sequence<_T>>::new(); - 'label_goto__ASSIGN_SUCH_THAT_0: loop { - for r#__assign_such_that_0 in (&s).iter().cloned() { - a = ::dafny_runtime::MaybePlacebo::from(r#__assign_such_that_0.clone()); - if s.contains(&a.read()) && crate::r#_StandardLibrary_Compile::_default::IsMinimum::<_T>(&a.read(), &s, &less) { - break 'label_goto__ASSIGN_SUCH_THAT_0; - } - } - panic!("Halt"); - break; - }; - ::dafny_runtime::seq![a.read()].concat(&crate::r#_StandardLibrary_Compile::_default::SetToOrderedSequence::<_T>(&s.subtract(&::dafny_runtime::set!{a.read()}), &less)) - }) - }))(&::dafny_runtime::int!(0)); - } - } - } - pub fn IsMinimum<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, s: &::dafny_runtime::Set<::dafny_runtime::Sequence<_T>>, less: &::std::rc::Rc bool>) -> bool { - s.contains(a) && s.iter().all(({ - let mut a = a.clone(); - let mut s = s.clone(); - let mut less = less.clone(); - ::std::rc::Rc::new(move |r#__forall_var_1: &::dafny_runtime::Sequence<_T>| -> bool{ - let mut z: ::dafny_runtime::Sequence<_T> = r#__forall_var_1.clone(); - !s.contains(&z) || crate::r#_StandardLibrary_Compile::_default::LexicographicLessOrEqual::<_T>(&a, &z, &less) - }) - }).as_ref()) - } - } - - pub mod r#_UInt_Compile { - pub use ::std::default::Default; - pub use ::dafny_runtime::DafnyPrint; - - pub struct _default {} - - impl _default { - pub fn UInt8Less(a: u8, b: u8) -> bool { - a < b - } - pub fn HasUint16Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { - s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT16_LIMIT() - } - pub fn HasUint32Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { - s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT32_LIMIT() - } - pub fn HasUint64Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { - s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT64_LIMIT() - } - pub fn UInt16ToSeq(x: u16) -> ::dafny_runtime::Sequence { - let mut b0: u8 = (x / 256) as u8; - let mut b1: u8 = (x % 256) as u8; - ::dafny_runtime::seq![b0, b1] - } - pub fn SeqToUInt16(s: &::dafny_runtime::Sequence) -> u16 { - let mut x0: u16 = s.get(&::dafny_runtime::int!(0)) as u16 * 256; - x0 + s.get(&::dafny_runtime::int!(1)) as u16 - } - pub fn UInt32ToSeq(x: u32) -> ::dafny_runtime::Sequence { - let mut b0: u8 = (x / 16777216) as u8; - let mut x0: u32 = x - b0 as u32 * 16777216; - let mut b1: u8 = (x0 / 65536) as u8; - let mut x1: u32 = x0 - b1 as u32 * 65536; - let mut b2: u8 = (x1 / 256) as u8; - let mut b3: u8 = (x1 % 256) as u8; - ::dafny_runtime::seq![b0, b1, b2, b3] - } - pub fn SeqToUInt32(s: &::dafny_runtime::Sequence) -> u32 { - let mut x0: u32 = s.get(&::dafny_runtime::int!(0)) as u32 * 16777216; - let mut x1: u32 = x0 + s.get(&::dafny_runtime::int!(1)) as u32 * 65536; - let mut x2: u32 = x1 + s.get(&::dafny_runtime::int!(2)) as u32 * 256; - x2 + s.get(&::dafny_runtime::int!(3)) as u32 - } - pub fn UInt64ToSeq(x: u64) -> ::dafny_runtime::Sequence { - let mut b0: u8 = (x / 72057594037927936) as u8; - let mut x0: u64 = x - b0 as u64 * 72057594037927936; - let mut b1: u8 = (x0 / 281474976710656) as u8; - let mut x1: u64 = x0 - b1 as u64 * 281474976710656; - let mut b2: u8 = (x1 / 1099511627776) as u8; - let mut x2: u64 = x1 - b2 as u64 * 1099511627776; - let mut b3: u8 = (x2 / 4294967296) as u8; - let mut x3: u64 = x2 - b3 as u64 * 4294967296; - let mut b4: u8 = (x3 / 16777216) as u8; - let mut x4: u64 = x3 - b4 as u64 * 16777216; - let mut b5: u8 = (x4 / 65536) as u8; - let mut x5: u64 = x4 - b5 as u64 * 65536; - let mut b6: u8 = (x5 / 256) as u8; - let mut b7: u8 = (x5 % 256) as u8; - ::dafny_runtime::seq![b0, b1, b2, b3, b4, b5, b6, b7] - } - pub fn SeqToUInt64(s: &::dafny_runtime::Sequence) -> u64 { - let mut x0: u64 = s.get(&::dafny_runtime::int!(0)) as u64 * 72057594037927936; - let mut x1: u64 = x0 + s.get(&::dafny_runtime::int!(1)) as u64 * 281474976710656; - let mut x2: u64 = x1 + s.get(&::dafny_runtime::int!(2)) as u64 * 1099511627776; - let mut x3: u64 = x2 + s.get(&::dafny_runtime::int!(3)) as u64 * 4294967296; - let mut x4: u64 = x3 + s.get(&::dafny_runtime::int!(4)) as u64 * 16777216; - let mut x5: u64 = x4 + s.get(&::dafny_runtime::int!(5)) as u64 * 65536; - let mut x6: u64 = x5 + s.get(&::dafny_runtime::int!(6)) as u64 * 256; - let mut x: u64 = x6 + s.get(&::dafny_runtime::int!(7)) as u64; - x - } - pub fn UINT16_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"65536") - } - pub fn UINT32_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"4294967296") - } - pub fn UINT64_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"18446744073709551616") - } - pub fn INT32_MAX_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"2147483648") - } - pub fn INT64_MAX_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"9223372036854775808") - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint8(pub u8); - - impl uint8 { - pub fn is(_source: u8) -> bool { - return true; - } - } - - impl Default - for uint8 { - fn default() -> Self { - uint8(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint8 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint8 { - type Target = u8; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint16(pub u16); - - impl uint16 { - pub fn is(_source: u16) -> bool { - return true; - } - } - - impl Default - for uint16 { - fn default() -> Self { - uint16(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint16 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint16 { - type Target = u16; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint32(pub u32); - - impl uint32 { - pub fn is(_source: u32) -> bool { - return true; - } - } - - impl Default - for uint32 { - fn default() -> Self { - uint32(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint32 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint32 { - type Target = u32; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint64(pub u64); - - impl uint64 { - pub fn is(_source: u64) -> bool { - return true; - } - } - - impl Default - for uint64 { - fn default() -> Self { - uint64(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint64 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint64 { - type Target = u64; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct int32(pub i32); - - impl int32 { - pub fn is(_source: i32) -> bool { - return true; - } - } - - impl Default - for int32 { - fn default() -> Self { - int32(::std::default::Default::default()) - } - } - - impl DafnyPrint - for int32 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for int32 { - type Target = i32; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct int64(pub i64); - - impl int64 { - pub fn is(_source: i64) -> bool { - return true; - } - } - - impl Default - for int64 { - fn default() -> Self { - int64(::std::default::Default::default()) - } - } - - impl DafnyPrint - for int64 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for int64 { - type Target = i64; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct posInt64(pub u64); - - impl posInt64 { - pub fn is(_source: u64) -> bool { - let mut x: ::dafny_runtime::DafnyInt = ::std::convert::Into::<::dafny_runtime::DafnyInt>::into(_source.clone()); - return ::dafny_runtime::int!(0) < x.clone() && x.clone() < ::dafny_runtime::int!(b"9223372036854775808"); - } - } - - impl Default - for posInt64 { - fn default() -> Self { - posInt64(1) - } - } - - impl DafnyPrint - for posInt64 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for posInt64 { - type Target = u64; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - pub type seq16 = ::dafny_runtime::Sequence; - - pub type seq32 = ::dafny_runtime::Sequence; - - pub type seq64 = ::dafny_runtime::Sequence; - } -} -pub mod r#_StandardLibraryInterop_Compile { - pub use ::dafny_runtime::UpcastObject; - pub use ::std::any::Any; - - pub struct WrappersInterop {} - - impl WrappersInterop { - pub fn _allocate_object() -> ::dafny_runtime::Object { - ::dafny_runtime::allocate_object::() - } - pub fn CreateStringSome(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Some { - value: s.clone() - }) - } - pub fn CreateStringNone() -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::None {}) - } - pub fn CreateBooleanSome(b: bool) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::Some { - value: b - }) - } - pub fn CreateBooleanNone() -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::None {}) - } - } - - impl UpcastObject - for WrappersInterop { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); - } -} -pub mod UTF8 { - pub struct _default {} - - impl _default { - pub fn CreateEncodeSuccess(bytes: &crate::UTF8::ValidUTF8Bytes) -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Success { - value: bytes.clone() - }) - } - pub fn CreateEncodeFailure(error: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Failure { - error: error.clone() - }) - } - pub fn CreateDecodeSuccess(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: s.clone() - }) - } - pub fn CreateDecodeFailure(error: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: error.clone() - }) - } - pub fn IsASCIIString(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> bool { - let mut _hresult: bool = ::default(); - let mut _hi0: ::dafny_runtime::DafnyInt = s.cardinality(); - for i in ::dafny_runtime::integer_range(::dafny_runtime::int!(0), _hi0.clone()) { - if !(::dafny_runtime::int!(s.get(&i).0) < ::dafny_runtime::int!(128)) { - _hresult = false; - return _hresult; - } - } - _hresult = true; - return _hresult; - } - pub fn EncodeAscii(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> crate::UTF8::ValidUTF8Bytes { - let mut _accumulator: crate::UTF8::ValidUTF8Bytes = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence; - let mut _r0 = s.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - if s.cardinality() == ::dafny_runtime::int!(0) { - return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence)); - } else { - let mut x: ::dafny_runtime::Sequence = ::dafny_runtime::seq![s.get(&::dafny_runtime::int!(0)).0 as u8]; - _accumulator = _accumulator.concat(&x); - let mut _in11: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> = s.drop(&::dafny_runtime::int!(1)); - _r0 = _in11.clone(); - continue 'TAIL_CALL_START; - } - } - } - pub fn Uses1Byte(s: &::dafny_runtime::Sequence) -> bool { - 0 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 127 - } - pub fn Uses2Bytes(s: &::dafny_runtime::Sequence) -> bool { - 194 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 223 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) - } - pub fn Uses3Bytes(s: &::dafny_runtime::Sequence) -> bool { - s.get(&::dafny_runtime::int!(0)) == 224 && (160 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || 225 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 236 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || s.get(&::dafny_runtime::int!(0)) == 237 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 159) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || 238 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 239 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) - } - pub fn Uses4Bytes(s: &::dafny_runtime::Sequence) -> bool { - s.get(&::dafny_runtime::int!(0)) == 240 && (144 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) || 241 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 243 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) || s.get(&::dafny_runtime::int!(0)) == 244 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 143) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) - } - pub fn ValidUTF8Range(a: &::dafny_runtime::Sequence, lo: &::dafny_runtime::_System::nat, hi: &::dafny_runtime::_System::nat) -> bool { - let mut _r0 = a.clone(); - let mut _r1 = lo.clone(); - let mut _r2 = hi.clone(); - 'TAIL_CALL_START: loop { - let a = _r0; - let lo = _r1; - let hi = _r2; - if lo.clone() == hi.clone() { - return true; - } else { - let mut r: ::dafny_runtime::Sequence = a.slice(&lo, &hi); - if crate::UTF8::_default::Uses1Byte(&r) { - let mut _in12: ::dafny_runtime::Sequence = a.clone(); - let mut _in13: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(1); - let mut _in14: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in12.clone(); - _r1 = _in13.clone(); - _r2 = _in14.clone(); - continue 'TAIL_CALL_START; - } else { - if ::dafny_runtime::int!(2) <= r.cardinality() && crate::UTF8::_default::Uses2Bytes(&r) { - let mut _in15: ::dafny_runtime::Sequence = a.clone(); - let mut _in16: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(2); - let mut _in17: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in15.clone(); - _r1 = _in16.clone(); - _r2 = _in17.clone(); - continue 'TAIL_CALL_START; - } else { - if ::dafny_runtime::int!(3) <= r.cardinality() && crate::UTF8::_default::Uses3Bytes(&r) { - let mut _in18: ::dafny_runtime::Sequence = a.clone(); - let mut _in19: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(3); - let mut _in20: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in18.clone(); - _r1 = _in19.clone(); - _r2 = _in20.clone(); - continue 'TAIL_CALL_START; - } else { - if ::dafny_runtime::int!(4) <= r.cardinality() && crate::UTF8::_default::Uses4Bytes(&r) { - let mut _in21: ::dafny_runtime::Sequence = a.clone(); - let mut _in22: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(4); - let mut _in23: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in21.clone(); - _r1 = _in22.clone(); - _r2 = _in23.clone(); - continue 'TAIL_CALL_START; - } else { - return false; - } - } - } - } - } - } - } - pub fn ValidUTF8Seq(s: &::dafny_runtime::Sequence) -> bool { - crate::UTF8::_default::ValidUTF8Range(s, &::dafny_runtime::int!(0), &s.cardinality()) - } - } - - pub type ValidUTF8Bytes = ::dafny_runtime::Sequence; - - pub fn r#__init_ValidUTF8Bytes() -> ::dafny_runtime::Sequence { - ::dafny_runtime::seq![] as ::dafny_runtime::Sequence - } -} -pub mod r#_Wrappers_Compile { - pub use ::std::fmt::Debug; - pub use ::dafny_runtime::DafnyPrint; - pub use ::std::cmp::Eq; - pub use ::std::hash::Hash; - pub use ::std::default::Default; - pub use ::std::convert::AsRef; - - pub struct _default {} - - impl _default { - pub fn Need<_E: ::dafny_runtime::DafnyType>(condition: bool, error: &_E) -> ::std::rc::Rc> { - if condition { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Outcome::<_E>::Pass {}) - } else { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Outcome::<_E>::Fail { - error: error.clone() - }) - } - } - } - - #[derive(PartialEq, Clone)] - pub enum Option { - None {}, - Some { - value: T - } - } - - impl Option { - pub fn ToResult(self: &::std::rc::Rc) -> ::std::rc::Rc>> { - let mut _source0: ::std::rc::Rc> = self.clone(); - if matches!((&_source0).as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::string_utf16_of("Option is None") - }) - } else { - let mut r#___mcc_h0: T = _source0.value().clone(); - let mut v: T = r#___mcc_h0.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Success { - value: v.clone() - }) - } - } - pub fn UnwrapOr(self: &::std::rc::Rc, default: &T) -> T { - let mut _source1: ::std::rc::Rc> = self.clone(); - if matches!((&_source1).as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) { - default.clone() - } else { - let mut r#___mcc_h0: T = _source1.value().clone(); - let mut v: T = r#___mcc_h0.clone(); - v.clone() - } - } - pub fn IsFailure(self: &::std::rc::Rc) -> bool { - matches!(self.as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) - } - pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<_U>::None {}) - } - pub fn Extract(self: &::std::rc::Rc) -> T { - self.value().clone() - } - pub fn value(&self) -> &T { - match self { - Option::None{} => panic!("field does not exist on this variant"), - Option::Some{value, } => value, - } - } - } - - impl Debug - for Option { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Option { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Option::None{} => { - write!(_formatter, "Wrappers_Compile.Option.None")?; - Ok(()) - }, - Option::Some{value, } => { - write!(_formatter, "Wrappers_Compile.Option.Some(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Option { - pub fn coerce(f_0: ::std::rc::Rc r#__T0 + 'static>) -> ::std::rc::Rc) -> Option> { - ::std::rc::Rc::new(move |this: Self| -> Option{ - match this { - Option::None{} => { - Option::None {} - }, - Option::Some{value, } => { - Option::Some { - value: f_0.clone()(value) - } - }, - } - }) - } - } - - impl Eq - for Option {} - - impl Hash - for Option { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Option::None{} => { - - }, - Option::Some{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for Option { - fn default() -> Option { - Option::None {} - } - } - - impl AsRef> - for &Option { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum Result { - Success { - value: T - }, - Failure { - error: R - } - } - - impl Result { - pub fn ToOption(self: &::std::rc::Rc) -> ::std::rc::Rc> { - let mut _source2: ::std::rc::Rc> = self.clone(); - if matches!((&_source2).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { - let mut r#___mcc_h0: T = _source2.value().clone(); - let mut s: T = r#___mcc_h0.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::Some { - value: s.clone() - }) - } else { - let mut r#___mcc_h1: R = _source2.error().clone(); - let mut e: R = r#___mcc_h1.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::None {}) - } - } - pub fn UnwrapOr(self: &::std::rc::Rc, default: &T) -> T { - let mut _source3: ::std::rc::Rc> = self.clone(); - if matches!((&_source3).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { - let mut r#___mcc_h0: T = _source3.value().clone(); - let mut s: T = r#___mcc_h0.clone(); - s.clone() - } else { - let mut r#___mcc_h1: R = _source3.error().clone(); - let mut e: R = r#___mcc_h1.clone(); - default.clone() - } - } - pub fn IsFailure(self: &::std::rc::Rc) -> bool { - matches!(self.as_ref(), crate::r#_Wrappers_Compile::Result::Failure{ .. }) - } - pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<_U, R>::Failure { - error: self.error().clone() - }) - } - pub fn MapFailure<_NewR: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc, reWrap: &::std::rc::Rc _NewR>) -> ::std::rc::Rc> { - let mut _source4: ::std::rc::Rc> = self.clone(); - if matches!((&_source4).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { - let mut r#___mcc_h0: T = _source4.value().clone(); - let mut s: T = r#___mcc_h0.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::::Success { - value: s.clone() - }) - } else { - let mut r#___mcc_h1: R = _source4.error().clone(); - let mut e: R = r#___mcc_h1.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::::Failure { - error: reWrap(&e) - }) - } - } - pub fn Extract(self: &::std::rc::Rc) -> T { - self.value().clone() - } - pub fn value(&self) -> &T { - match self { - Result::Success{value, } => value, - Result::Failure{error, } => panic!("field does not exist on this variant"), - } - } - pub fn error(&self) -> &R { - match self { - Result::Success{value, } => panic!("field does not exist on this variant"), - Result::Failure{error, } => error, - } - } - } - - impl Debug - for Result { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Result { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Result::Success{value, } => { - write!(_formatter, "Wrappers_Compile.Result.Success(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - Result::Failure{error, } => { - write!(_formatter, "Wrappers_Compile.Result.Failure(")?; - ::dafny_runtime::DafnyPrint::fmt_print(error, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Result { - pub fn coerce(f_0: ::std::rc::Rc r#__T0 + 'static>, f_1: ::std::rc::Rc r#__T1 + 'static>) -> ::std::rc::Rc) -> Result> { - ::std::rc::Rc::new(move |this: Self| -> Result{ - match this { - Result::Success{value, } => { - Result::Success { - value: f_0.clone()(value) - } - }, - Result::Failure{error, } => { - Result::Failure { - error: f_1.clone()(error) - } - }, - } - }) - } - } - - impl Eq - for Result {} - - impl Hash - for Result { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Result::Success{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - Result::Failure{error, } => { - ::std::hash::Hash::hash(error, _state) - }, - } - } - } - - impl Default - for Result { - fn default() -> Result { - Result::Success { - value: ::std::default::Default::default() - } - } - } - - impl AsRef> - for &Result { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum Outcome { - Pass {}, - Fail { - error: E - } - } - - impl Outcome { - pub fn IsFailure(self: &::std::rc::Rc) -> bool { - matches!(self.as_ref(), crate::r#_Wrappers_Compile::Outcome::Fail{ .. }) - } - pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<_U, E>::Failure { - error: self.error().clone() - }) - } - pub fn error(&self) -> &E { - match self { - Outcome::Pass{} => panic!("field does not exist on this variant"), - Outcome::Fail{error, } => error, - } - } - } - - impl Debug - for Outcome { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Outcome { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Outcome::Pass{} => { - write!(_formatter, "Wrappers_Compile.Outcome.Pass")?; - Ok(()) - }, - Outcome::Fail{error, } => { - write!(_formatter, "Wrappers_Compile.Outcome.Fail(")?; - ::dafny_runtime::DafnyPrint::fmt_print(error, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for Outcome {} - - impl Hash - for Outcome { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Outcome::Pass{} => { - - }, - Outcome::Fail{error, } => { - ::std::hash::Hash::hash(error, _state) - }, - } - } - } - - impl Default - for Outcome { - fn default() -> Outcome { - Outcome::Pass {} - } - } - - impl AsRef> - for &Outcome { - fn as_ref(&self) -> Self { - self - } - } -} \ No newline at end of file diff --git a/TestModels/Errors/runtimes/rust/src/standard_library_externs.rs b/TestModels/Errors/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/Errors/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/LanguageSpecificLogic/runtimes/rust/src/standard_library_externs.rs b/TestModels/LanguageSpecificLogic/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/LanguageSpecificLogic/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/Refinement/runtimes/rust/src/standard_library_externs.rs b/TestModels/Refinement/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/Refinement/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/Resource/runtimes/rust/src/standard_library_externs.rs b/TestModels/Resource/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/Resource/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/Makefile b/TestModels/SimpleTypes/SimpleBlob/Makefile index cb013bd311..f27fa454f0 100644 --- a/TestModels/SimpleTypes/SimpleBlob/Makefile +++ b/TestModels/SimpleTypes/SimpleBlob/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/Cargo.toml index 7db289b458..743b97c036 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/Cargo.toml @@ -5,13 +5,19 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies.tokio] +[dev-dependencies] +simple_blob = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client.rs index 0e7fbefea4..71235fc03b 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -13,9 +14,10 @@ impl Client { pub fn from_conf( conf: crate::types::simple_blob_config::SimpleBlobConfig, ) -> Result { - let inner = crate::simple::types::blob::internaldafny::_default::SimpleBlob( - &crate::conversions::simple_blob_config::_simple_blob_config::to_dafny(conf), - ); + let inner = + crate::simple::types::blob::internaldafny::_default::SimpleBlob( + &crate::conversions::simple_blob_config::_simple_blob_config::to_dafny(conf), + ); if matches!( inner.as_ref(), crate::_Wrappers_Compile::Result::Failure { .. } @@ -28,11 +30,11 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } mod get_blob; -mod get_blob_known_value; +mod get_blob_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob.rs index c09128d419..4247bbc32d 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetBlob`](crate::operation::get_blob::builders::GetBlobFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into<::dafny_runtime::Sequence>)`](crate::operation::get_blob::builders::GetBlobFluentBuilder::value) / [`set_value(Option<::dafny_runtime::Sequence>)`](crate::operation::get_blob::builders::GetBlobFluentBuilder::set_value):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_blob::builders::GetBlobFluentBuilder::value) / [`set_value(Option<::aws_smithy_types::Blob>)`](crate::operation::get_blob::builders::GetBlobFluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetBlobOutput`](crate::operation::get_blob::GetBlobOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_blob::GetBlobOutput::value): (undocumented) + /// - [`value(Option<::aws_smithy_types::Blob>)`](crate::operation::get_blob::GetBlobOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_blob::GetBlobError) pub fn get_blob(&self) -> crate::operation::get_blob::builders::GetBlobFluentBuilder { crate::operation::get_blob::builders::GetBlobFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value.rs deleted file mode 100644 index a8831d2421..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value.rs +++ /dev/null @@ -1,17 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -impl super::Client { - /// Constructs a fluent builder for the [`GetBlob`](crate::operation::get_blob_known_value::builders::GetBlobFluentBuilder) operation. - /// - /// - The fluent builder is configurable: - /// - [`value(impl Into<::dafny_runtime::Sequence>)`](crate::operation::get_blob_known_value::builders::GetBlobFluentBuilder::value) / [`set_value(Option<::dafny_runtime::Sequence>)`](crate::operation::get_blob_known_value::builders::GetBlobFluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetBlobOutput`](crate::operation::get_blob_known_value::GetBlobOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_blob_known_value::GetBlobOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_blob_known_value::GetBlobError) - pub fn get_blob_known_value( - &self, - ) -> crate::operation::get_blob_known_value::builders::GetBlobKnownValueFluentBuilder { - crate::operation::get_blob_known_value::builders::GetBlobKnownValueFluentBuilder::new( - self.clone(), - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value_test.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value_test.rs new file mode 100644 index 0000000000..eec5e197f0 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/client/get_blob_known_value_test.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +impl super::Client { + /// Constructs a fluent builder for the [`GetBlobKnownValueTest`](crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder) operation. + /// + /// - The fluent builder is configurable: + /// - [`value(impl Into>)`](crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder::value) / [`set_value(Option<::aws_smithy_types::Blob>)`](crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetBlobOutput`](crate::operation::get_blob_known_value_test::GetBlobOutput) with field(s): + /// - [`value(Option<::aws_smithy_types::Blob>)`](crate::operation::get_blob_known_value_test::GetBlobOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError) + pub fn get_blob_known_value_test(&self) -> crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder { + crate::operation::get_blob_known_value_test::builders::GetBlobKnownValueTestFluentBuilder::new(self.clone()) + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions.rs index 1cd4ad224e..cf1c199d5b 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions.rs @@ -1,6 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_blob; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod get_blob_known_value; + pub mod get_blob; -pub mod simple_blob_config; + pub mod get_blob_known_value_test; + + pub mod simple_blob_config; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..6d52bba84a --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::blob::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob.rs index 43479fd3c9..d38674b069 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] @@ -7,14 +8,9 @@ pub fn to_dafny_error( value: crate::operation::get_blob::GetBlobError, ) -> ::std::rc::Rc { match value { - crate::operation::get_blob::GetBlobError::Unhandled(unhandled) => ::std::rc::Rc::new( - crate::r#simple::types::blob::internaldafny::types::Error::Opaque { - obj: ::dafny_runtime::upcast_object()( - ::dafny_runtime::object::new(unhandled), - ), - }, - ), - } + crate::operation::get_blob::GetBlobError::Unhandled(unhandled) => + ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) + } } #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_input.rs index 4e91b06d53..d37000fe2b 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_input.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_input.rs @@ -1,42 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_blob::GetBlobInput, -) -> ::std::rc::Rc -{ - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&v, |x| *x), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +) -> ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobInput, +>{ ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobInput::GetBlobInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::oblob_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::blob::internaldafny::types::GetBlobInput, >, ) -> crate::operation::get_blob::GetBlobInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - ::std::rc::Rc::try_unwrap(dafny_value.value().Extract().to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - - crate::operation::get_blob::GetBlobInput { value } + crate::operation::get_blob::GetBlobInput::builder() + .set_value(crate::standard_library_conversions::oblob_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_output.rs index e9770da2c5..a36a0e65c7 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_output.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob/_get_blob_output.rs @@ -1,43 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_blob::GetBlobOutput, -) -> ::std::rc::Rc -{ - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&b, |e| *e), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +) -> ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, +>{ ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobOutput::GetBlobOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::oblob_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, >, ) -> crate::operation::get_blob::GetBlobOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), - |e| *e, - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_blob::GetBlobOutput { value } + crate::operation::get_blob::GetBlobOutput::builder() + .set_value(crate::standard_library_conversions::oblob_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value.rs deleted file mode 100644 index 50a67357d0..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value.rs +++ /dev/null @@ -1,39 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -use std::any::Any; - -#[allow(dead_code)] -pub fn to_dafny_error( - value: crate::operation::get_blob_known_value::GetBlobKnownValueError, -) -> ::std::rc::Rc { - match value { - crate::operation::get_blob_known_value::GetBlobKnownValueError::Unhandled(unhandled) => { - ::std::rc::Rc::new( - crate::r#simple::types::blob::internaldafny::types::Error::Opaque { - obj: ::dafny_runtime::upcast_object()( - ::dafny_runtime::object::new(unhandled), - ), - }, - ) - } - } -} - -#[allow(dead_code)] -pub fn from_dafny_error( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::Error, - >, -) -> crate::operation::get_blob_known_value::GetBlobKnownValueError { - // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error - if matches!(&dafny_value.as_ref(), crate::r#simple::types::blob::internaldafny::types::Error::CollectionOfErrors { .. }) { - let error_message = "TODO: can't get message yet"; - crate::operation::get_blob_known_value::GetBlobKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) - } else { - crate::operation::get_blob_known_value::GetBlobKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) - } -} - -pub mod _get_blob_known_value_input; - -pub mod _get_blob_known_value_output; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_input.rs deleted file mode 100644 index 1e939e99a8..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_input.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_blob_known_value::GetBlobKnownValueInput, -) -> ::std::rc::Rc -{ - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&v, |x| *x), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobInput::GetBlobInput { - value: ::std::rc::Rc::new(dafny_value) - }) -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::GetBlobInput, - >, -) -> crate::operation::get_blob_known_value::GetBlobKnownValueInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - ::std::rc::Rc::try_unwrap(dafny_value.value().Extract().to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_blob_known_value::GetBlobKnownValueInput { value } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_output.rs deleted file mode 100644 index 19cf635501..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value/_get_blob_known_value_output.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_blob_known_value::GetBlobKnownValueOutput, -) -> ::std::rc::Rc -{ - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&v, |e| *e), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobOutput::GetBlobOutput { - value: ::std::rc::Rc::new(dafny_value) - }) -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, - >, -) -> crate::operation::get_blob_known_value::GetBlobKnownValueOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), - |e| *e, - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_blob_known_value::GetBlobKnownValueOutput { value } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test.rs new file mode 100644 index 0000000000..7ff941094b --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test.rs @@ -0,0 +1,33 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +#[allow(dead_code)] +pub fn to_dafny_error( + value: crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError, +) -> ::std::rc::Rc { + match value { + crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError::Unhandled(unhandled) => + ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) + } +} + +#[allow(dead_code)] +pub fn from_dafny_error( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::Error, + >, +) -> crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError { + // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error + if matches!(&dafny_value.as_ref(), crate::r#simple::types::blob::internaldafny::types::Error::CollectionOfErrors { .. }) { + let error_message = "TODO: can't get message yet"; + crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) + } else { + crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) + } +} + +pub mod _get_blob_known_value_test_input; + +pub mod _get_blob_known_value_test_output; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_input.rs new file mode 100644 index 0000000000..49d2466ee7 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_input.rs @@ -0,0 +1,24 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_blob_known_value_test::GetBlobInput, +) -> ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobInput, +>{ + ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobInput::GetBlobInput { + value: crate::standard_library_conversions::oblob_to_dafny(&value.value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobInput, + >, +) -> crate::operation::get_blob_known_value_test::GetBlobInput { + crate::operation::get_blob_known_value_test::GetBlobInput::builder() + .set_value(crate::standard_library_conversions::oblob_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_output.rs new file mode 100644 index 0000000000..499929ee0a --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/get_blob_known_value_test/_get_blob_known_value_test_output.rs @@ -0,0 +1,24 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_blob_known_value_test::GetBlobOutput, +) -> ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, +>{ + ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::GetBlobOutput::GetBlobOutput { + value: crate::standard_library_conversions::oblob_to_dafny(&value.value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, + >, +) -> crate::operation::get_blob_known_value_test::GetBlobOutput { + crate::operation::get_blob_known_value_test::GetBlobOutput::builder() + .set_value(crate::standard_library_conversions::oblob_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config.rs index 89599c3f8c..7852c4ae19 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_blob_config; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config/_simple_blob_config.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config/_simple_blob_config.rs index d0a4cd5c44..a9e1abdffe 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config/_simple_blob_config.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/conversions/simple_blob_config/_simple_blob_config.rs @@ -1,10 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_blob_config::SimpleBlobConfig, -) -> ::std::rc::Rc -{ +) -> ::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::SimpleBlobConfig, +> { ::std::rc::Rc::new(crate::r#simple::types::blob::internaldafny::types::SimpleBlobConfig::SimpleBlobConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/lib.rs deleted file mode 100644 index 3938142e1c..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub mod implementation_from_dafny; - -pub use client::Client; -pub use types::simple_blob_config::SimpleBlobConfig; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation.rs index a72267eda2..64ee269b55 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation.rs @@ -1,7 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetBlob` operation. pub mod get_blob; -/// Types for the `GetBlobKnownValue` operation. -pub mod get_blob_known_value; +/// Types for the `GetBlobKnownValueTest` operation. +pub mod get_blob_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob.rs index 2c923f1aa7..037e8b83af 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetBlob`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -16,14 +18,17 @@ impl GetBlob { crate::operation::get_blob::GetBlobError, > { let inner_input = crate::conversions::get_blob::_get_blob_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetBlob(&inner_input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetBlob(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - Ok(crate::conversions::get_blob::_get_blob_output::from_dafny( - inner_result.value().clone(), - )) + Ok( + crate::conversions::get_blob::_get_blob_output::from_dafny( + inner_result.value().clone(), + ), + ) } else { Err(crate::conversions::get_blob::from_dafny_error( inner_result.error().clone(), @@ -134,9 +139,9 @@ pub use crate::operation::get_blob::_get_blob_output::GetBlobOutput; pub use crate::operation::get_blob::_get_blob_input::GetBlobInput; -mod _get_blob_input; +pub(crate) mod _get_blob_output; -mod _get_blob_output; +pub(crate) mod _get_blob_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_input.rs index 6a0d554b13..335f1e1a36 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_input.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_input.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetBlobInput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, +pub value: ::std::option::Option<::aws_smithy_types::Blob>, } impl GetBlobInput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::Blob> { + self.value.clone() +} } impl GetBlobInput { /// Creates a new builder-style object to manufacture [`GetBlobInput`](crate::operation::operation::GetBlobInput). @@ -25,29 +27,23 @@ impl GetBlobInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetBlobInputBuilder { - pub(crate) value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, + pub(crate) value: ::std::option::Option<::aws_smithy_types::Blob>, } impl GetBlobInputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { - self.value.as_ref() - } +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { + &self.value +} /// Consumes the builder and constructs a [`GetBlobInput`](crate::operation::operation::GetBlobInput). pub fn build( self, @@ -55,6 +51,8 @@ impl GetBlobInputBuilder { crate::operation::get_blob::GetBlobInput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_blob::GetBlobInput { value: self.value }) + ::std::result::Result::Ok(crate::operation::get_blob::GetBlobInput { + value: self.value, + }) } } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_output.rs index b071eb836e..7de15870c4 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_output.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/_get_blob_output.rs @@ -1,19 +1,19 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetBlobOutput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, +pub value: ::std::option::Option<::aws_smithy_types::Blob>, } - impl GetBlobOutput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::Blob> { + self.value.clone() +} } - impl GetBlobOutput { /// Creates a new builder-style object to manufacture [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). pub fn builder() -> crate::operation::get_blob::builders::GetBlobOutputBuilder { @@ -27,33 +27,23 @@ impl GetBlobOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetBlobOutputBuilder { - pub(crate) value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, + pub(crate) value: ::std::option::Option<::aws_smithy_types::Blob>, } - impl GetBlobOutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = input; - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { - self.value.as_ref() - } - +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { + &self.value +} /// Consumes the builder and constructs a [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). pub fn build( self, @@ -61,6 +51,8 @@ impl GetBlobOutputBuilder { crate::operation::get_blob::GetBlobOutput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_blob::GetBlobOutput { value: self.value }) + ::std::result::Result::Ok(crate::operation::get_blob::GetBlobOutput { + value: self.value, + }) } } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/builders.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/builders.rs index bedb57b108..7fd6ca61e8 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/builders.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob/builders.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_blob::_get_blob_output::GetBlobOutputBuilder; pub use crate::operation::get_blob::_get_blob_input::GetBlobInputBuilder; @@ -22,7 +24,7 @@ impl GetBlobInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetBlobFluentBuilder { client: crate::client::Client, - inner: crate::operation::get_blob::builders::GetBlobInputBuilder, + pub(crate) inner: crate::operation::get_blob::builders::GetBlobInputBuilder, } impl GetBlobFluentBuilder { /// Creates a new `GetBlob`. @@ -56,23 +58,17 @@ impl GetBlobFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.inner = self.inner.value(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_input.rs deleted file mode 100644 index be28c19c10..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_input.rs +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetBlobKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, -} -impl GetBlobKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { - self.value.as_ref() - } -} -impl GetBlobKnownValueInput { - /// Creates a new builder-style object to manufacture [`GetBlobKnownValueInput`](crate::operation::operation::GetBlobKnownValueInput). - pub fn builder( - ) -> crate::operation::get_blob_known_value::builders::GetBlobKnownValueInputBuilder { - crate::operation::get_blob_known_value::builders::GetBlobKnownValueInputBuilder::default() - } -} - -/// A builder for [`GetBlobKnownValueInput`](crate::operation::operation::GetBlobKnownValueInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetBlobKnownValueInputBuilder { - pub(crate) value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, -} -impl GetBlobKnownValueInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::vec::Vec<::std::primitive::u8>> { - &self.value - } - /// Consumes the builder and constructs a [`GetBlobKnownValueInput`](crate::operation::operation::GetBlobKnownValueInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_blob_known_value::GetBlobKnownValueInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_blob_known_value::GetBlobKnownValueInput { value: self.value }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_output.rs deleted file mode 100644 index 794b83ce46..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/_get_blob_known_value_output.rs +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetBlobKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, -} -impl GetBlobKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&::std::vec::Vec<::std::primitive::u8>> { - self.value.as_ref() - } -} -impl GetBlobKnownValueOutput { - /// Creates a new builder-style object to manufacture [`GetBlobKnownValueOutput`](crate::operation::operation::GetBlobKnownValueOutput). - pub fn builder( - ) -> crate::operation::get_blob_known_value::builders::GetBlobKnownValueOutputBuilder { - crate::operation::get_blob_known_value::builders::GetBlobKnownValueOutputBuilder::default() - } -} - -/// A builder for [`GetBlobKnownValueOutput`](crate::operation::operation::GetBlobKnownValueOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetBlobKnownValueOutputBuilder { - pub(crate) value: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, -} -impl GetBlobKnownValueOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::vec::Vec<::std::primitive::u8>> { - &self.value - } - /// Consumes the builder and constructs a [`GetBlobKnownValueOutput`](crate::operation::operation::GetBlobKnownValueOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_blob_known_value::GetBlobKnownValueOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_blob_known_value::GetBlobKnownValueOutput { value: self.value }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/builders.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/builders.rs deleted file mode 100644 index 274bb3f376..0000000000 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value/builders.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_blob_known_value::_get_blob_known_value_output::GetBlobKnownValueOutputBuilder; - -pub use crate::operation::get_blob_known_value::_get_blob_known_value_input::GetBlobKnownValueInputBuilder; - -impl GetBlobKnownValueInputBuilder { - /// Sends a request with this input using the given client. - pub async fn send_with( - self, - client: &crate::Client, - ) -> ::std::result::Result< - crate::operation::get_blob_known_value::GetBlobKnownValueOutput, - crate::operation::get_blob_known_value::GetBlobKnownValueError, - > { - let mut fluent_builder = client.get_blob_known_value(); - fluent_builder.inner = self; - fluent_builder.send().await - } -} -/// Fluent builder constructing a request to `GetBlobKnownValue`. -/// -#[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct GetBlobKnownValueFluentBuilder { - client: crate::client::Client, - inner: crate::operation::get_blob_known_value::builders::GetBlobKnownValueInputBuilder, -} -impl GetBlobKnownValueFluentBuilder { - /// Creates a new `GetBlobKnownValue`. - pub(crate) fn new(client: crate::client::Client) -> Self { - Self { - client, - inner: ::std::default::Default::default(), - } - } - /// Access the GetBlobKnownValue as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_blob_known_value::builders::GetBlobKnownValueInputBuilder { - &self.inner - } - /// Sends the request and returns the response. - pub async fn send( - self, - ) -> ::std::result::Result< - crate::operation::get_blob_known_value::GetBlobKnownValueOutput, - crate::operation::get_blob_known_value::GetBlobKnownValueError, - > { - let input = self - .inner - .build() - // Using unhandled since GetBlob doesn't declare any validation, - // and smithy-rs seems to not generate a ValidationError case unless there is - // (but isn't that a backwards compatibility problem for output structures?) - // Vanilla smithy-rs uses SdkError::construction_failure, - // but we aren't using SdkError. - .map_err(crate::operation::get_blob_known_value::GetBlobKnownValueError::unhandled)?; - crate::operation::get_blob_known_value::GetBlobKnownValue::send(&self.client, input).await - } - - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.inner = self.inner.value(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option<::std::vec::Vec<::std::primitive::u8>>, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::vec::Vec<::std::primitive::u8>> { - self.inner.get_value() - } -} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test.rs similarity index 67% rename from TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value.rs rename to TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test.rs index ee1819d4fd..32709dd754 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test.rs @@ -1,44 +1,46 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -/// Orchestration and serialization glue logic for `GetBlobKnownValue`. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +/// Orchestration and serialization glue logic for `GetBlobKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] -pub struct GetBlobKnownValue; -impl GetBlobKnownValue { - /// Creates a new `GetBlobKnownValue` +pub struct GetBlobKnownValueTest; +impl GetBlobKnownValueTest { + /// Creates a new `GetBlobKnownValueTest` pub fn new() -> Self { Self } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_blob_known_value::GetBlobKnownValueInput, + input: crate::operation::get_blob_known_value_test::GetBlobInput, ) -> ::std::result::Result< - crate::operation::get_blob_known_value::GetBlobKnownValueOutput, - crate::operation::get_blob_known_value::GetBlobKnownValueError, + crate::operation::get_blob_known_value_test::GetBlobOutput, + crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError, > { - let inner_input = - crate::conversions::get_blob_known_value::_get_blob_known_value_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetBlob(&inner_input); + let inner_input = crate::conversions::get_blob_known_value_test::_get_blob_known_value_test_input::to_dafny(input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetBlobKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { Ok( - crate::conversions::get_blob_known_value::_get_blob_known_value_output::from_dafny( + crate::conversions::get_blob_known_value_test::_get_blob_known_value_test_output::from_dafny( inner_result.value().clone(), ), ) } else { - Err(crate::conversions::get_blob_known_value::from_dafny_error( + Err(crate::conversions::get_blob_known_value_test::from_dafny_error( inner_result.error().clone(), )) } } } -/// Error type for the `GetBlobKnownValue` operation. +/// Error type for the `GetBlobKnownValueTest` operation. #[non_exhaustive] #[derive(::std::fmt::Debug)] -pub enum GetBlobKnownValueError { +pub enum GetBlobKnownValueTestError { /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ @@ -46,12 +48,12 @@ pub enum GetBlobKnownValueError { \    `err if err.code() == Some(\"SpecificExceptionCode\") => { /* handle the error */ }` \ - See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetBlobKnownValueError) for what information is available for the error." + See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetBlobKnownValueTestError) for what information is available for the error." )] Unhandled(crate::error::sealed_unhandled::Unhandled), } -impl GetBlobKnownValueError { - /// Creates the `GetBlobKnownValueError::Unhandled` variant from any error type. +impl GetBlobKnownValueTestError { + /// Creates the `GetBlobKnownValueTestError::Unhandled` variant from any error type. pub fn unhandled( err: impl ::std::convert::Into< ::std::boxed::Box< @@ -65,7 +67,7 @@ impl GetBlobKnownValueError { }) } - /// Creates the `GetBlobKnownValueError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). + /// Creates the `GetBlobKnownValueTestError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). pub fn generic(err: ::aws_smithy_types::error::ErrorMetadata) -> Self { Self::Unhandled(crate::error::sealed_unhandled::Unhandled { source: err.clone().into(), @@ -82,14 +84,14 @@ impl GetBlobKnownValueError { } } } -impl ::std::error::Error for GetBlobKnownValueError { +impl ::std::error::Error for GetBlobKnownValueTestError { fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> { match self { Self::Unhandled(_inner) => ::std::option::Option::Some(&*_inner.source), } } } -impl ::std::fmt::Display for GetBlobKnownValueError { +impl ::std::fmt::Display for GetBlobKnownValueTestError { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self { Self::Unhandled(_inner) => { @@ -104,7 +106,7 @@ impl ::std::fmt::Display for GetBlobKnownValueError { } } } -impl ::aws_smithy_types::retry::ProvideErrorKind for GetBlobKnownValueError { +impl ::aws_smithy_types::retry::ProvideErrorKind for GetBlobKnownValueTestError { fn code(&self) -> ::std::option::Option<&str> { ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self) } @@ -112,14 +114,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetBlobKnownValueError { ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetBlobKnownValueError { +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetBlobKnownValueTestError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetBlobKnownValueError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetBlobKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -133,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetBlobK } } -pub use crate::operation::get_blob_known_value::_get_blob_known_value_output::GetBlobKnownValueOutput; +pub use crate::operation::get_blob_known_value_test::_get_blob_output::GetBlobOutput; -pub use crate::operation::get_blob_known_value::_get_blob_known_value_input::GetBlobKnownValueInput; +pub use crate::operation::get_blob_known_value_test::_get_blob_input::GetBlobInput; -mod _get_blob_known_value_input; +pub(crate) mod _get_blob_output; -mod _get_blob_known_value_output; +pub(crate) mod _get_blob_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_input.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_input.rs new file mode 100644 index 0000000000..9eb9a55b98 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetBlobInput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::aws_smithy_types::Blob>, +} +impl GetBlobInput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::Blob> { + self.value.clone() +} +} +impl GetBlobInput { + /// Creates a new builder-style object to manufacture [`GetBlobInput`](crate::operation::operation::GetBlobInput). + pub fn builder() -> crate::operation::get_blob_known_value_test::builders::GetBlobInputBuilder { + crate::operation::get_blob_known_value_test::builders::GetBlobInputBuilder::default() + } +} + +/// A builder for [`GetBlobInput`](crate::operation::operation::GetBlobInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetBlobInputBuilder { + pub(crate) value: ::std::option::Option<::aws_smithy_types::Blob>, +} +impl GetBlobInputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { + &self.value +} + /// Consumes the builder and constructs a [`GetBlobInput`](crate::operation::operation::GetBlobInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_blob_known_value_test::GetBlobInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_blob_known_value_test::GetBlobInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_output.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_output.rs new file mode 100644 index 0000000000..81cb83d89b --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/_get_blob_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetBlobOutput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::aws_smithy_types::Blob>, +} +impl GetBlobOutput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::Blob> { + self.value.clone() +} +} +impl GetBlobOutput { + /// Creates a new builder-style object to manufacture [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). + pub fn builder() -> crate::operation::get_blob_known_value_test::builders::GetBlobOutputBuilder { + crate::operation::get_blob_known_value_test::builders::GetBlobOutputBuilder::default() + } +} + +/// A builder for [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetBlobOutputBuilder { + pub(crate) value: ::std::option::Option<::aws_smithy_types::Blob>, +} +impl GetBlobOutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { + &self.value +} + /// Consumes the builder and constructs a [`GetBlobOutput`](crate::operation::operation::GetBlobOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_blob_known_value_test::GetBlobOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_blob_known_value_test::GetBlobOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/builders.rs new file mode 100644 index 0000000000..b7ef06d065 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/operation/get_blob_known_value_test/builders.rs @@ -0,0 +1,74 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_blob_known_value_test::_get_blob_output::GetBlobOutputBuilder; + +pub use crate::operation::get_blob_known_value_test::_get_blob_input::GetBlobInputBuilder; + +impl GetBlobInputBuilder { + /// Sends a request with this input using the given client. + pub async fn send_with( + self, + client: &crate::Client, + ) -> ::std::result::Result< + crate::operation::get_blob_known_value_test::GetBlobOutput, + crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError, + > { + let mut fluent_builder = client.get_blob_known_value_test(); + fluent_builder.inner = self; + fluent_builder.send().await + } +} +/// Fluent builder constructing a request to `GetBlobKnownValueTest`. +/// +#[derive(::std::clone::Clone, ::std::fmt::Debug)] +pub struct GetBlobKnownValueTestFluentBuilder { + client: crate::client::Client, + pub(crate) inner: crate::operation::get_blob_known_value_test::builders::GetBlobInputBuilder, +} +impl GetBlobKnownValueTestFluentBuilder { + /// Creates a new `GetBlobKnownValueTest`. + pub(crate) fn new(client: crate::client::Client) -> Self { + Self { + client, + inner: ::std::default::Default::default(), + } + } + /// Access the GetBlobKnownValueTest as a reference. + pub fn as_input(&self) -> &crate::operation::get_blob_known_value_test::builders::GetBlobInputBuilder { + &self.inner + } + /// Sends the request and returns the response. + pub async fn send( + self, + ) -> ::std::result::Result< + crate::operation::get_blob_known_value_test::GetBlobOutput, + crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError, + > { + let input = self + .inner + .build() + // Using unhandled since GetBlobKnownValueTest doesn't declare any validation, + // and smithy-rs seems to not generate a ValidationError case unless there is + // (but isn't that a backwards compatibility problem for output structures?) + // Vanilla smithy-rs uses SdkError::construction_failure, + // but we aren't using SdkError. + .map_err(crate::operation::get_blob_known_value_test::GetBlobKnownValueTestError::unhandled)?; + crate::operation::get_blob_known_value_test::GetBlobKnownValueTest::send(&self.client, input).await + } + + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::Blob>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::Blob>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::Blob> { + self.inner.get_value() +} +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types.rs index 1dca219a01..ce57ffa44f 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `SimpleBlobConfig` pub mod simple_blob_config; diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types/simple_blob_config.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types/simple_blob_config.rs index 0709ccb7ee..8386df9739 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types/simple_blob_config.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/types/simple_blob_config.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleBlobConfig {} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..5c03253bfb --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::blob::internaldafny::wrapped::_default { + pub fn WrappedSimpleBlob(config: &::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::SimpleBlobConfig, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..1cfbbbb813 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,119 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::blob::internaldafny::types::ISimpleTypesBlobClient); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::SimpleBlobConfig, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_blob_config::_simple_blob_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::blob::internaldafny::types::ISimpleTypesBlobClient for Client { + fn GetBlob( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_blob::_get_blob_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_blob::GetBlob::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_blob::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_blob::_get_blob_output::to_dafny(client), + }, + ), + } + } + + fn GetBlobKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::blob::internaldafny::types::GetBlobOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_blob_known_value_test::_get_blob_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_blob_known_value_test::GetBlobKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_blob_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_blob_known_value_test::_get_blob_known_value_test_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/tests/simple_blob_test.rs b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/tests/simple_blob_test.rs index bf6ce9675d..b9c9ed9970 100644 --- a/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/tests/simple_blob_test.rs +++ b/TestModels/SimpleTypes/SimpleBlob/runtimes/rust/tests/simple_blob_test.rs @@ -32,11 +32,11 @@ use simple_blob::*; */ #[tokio::test] async fn test_get_blob() { - let s = vec![0x0, 0x1, 0x2]; + let s = aws_smithy_types::Blob::new(vec![0x0, 0x1, 0x2]); let result = client().get_blob().value(s.clone()).send().await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, &s); + assert_eq!(value, s); } /* @@ -64,15 +64,15 @@ async fn test_get_blob() { #[tokio::test] async fn test_get_known_value() { - let s = vec![0x0, 0x2, 0x4]; + let s = aws_smithy_types::Blob::new(vec![0x0, 0x2, 0x4]); let result = client() - .get_blob_known_value() + .get_blob_known_value_test() .value(s.clone()) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, &s); + assert_eq!(value, s); } pub fn client() -> Client { diff --git a/TestModels/SimpleTypes/SimpleBoolean/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleBoolean/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleBoolean/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleDouble/Makefile b/TestModels/SimpleTypes/SimpleDouble/Makefile index 032b8a16ae..2fc8ca1be2 100644 --- a/TestModels/SimpleTypes/SimpleDouble/Makefile +++ b/TestModels/SimpleTypes/SimpleDouble/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/Cargo.toml index 3bb72ebe2d..0135a1e231 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/Cargo.toml @@ -5,13 +5,19 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies.tokio] +[dev-dependencies] +simple_double = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client.rs index 5827083463..a858580317 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -29,7 +30,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client/get_double.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client/get_double.rs index db3ce635ea..a41fdf754f 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client/get_double.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/client/get_double.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetDouble`](crate::operation::get_double::builders::GetDoubleFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(f64)`](crate::operation::get_double::builders::GetDoubleFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_double::builders::GetDoubleFluentBuilder::set_value):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_double::builders::GetDoubleFluentBuilder::value) / [`set_value(Option<::std::primitive::f64>)`](crate::operation::get_double::builders::GetDoubleFluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetDoubleOutput`](crate::operation::get_double::GetDoubleOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_double::GetDoubleOutput::value): (undocumented) + /// - [`value(Option<::std::primitive::f64>)`](crate::operation::get_double::GetDoubleOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_double::GetDoubleError) pub fn get_double(&self) -> crate::operation::get_double::builders::GetDoubleFluentBuilder { crate::operation::get_double::builders::GetDoubleFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions.rs index 08430ee335..f861ad1749 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions.rs @@ -1,4 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_double; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod simple_double_config; + pub mod get_double; + + pub mod simple_double_config; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..1003d3aed9 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::smithydouble::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double.rs index 45f3afc17c..e886c559a7 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double.rs @@ -1,12 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_double::GetDoubleError, -) -> ::std::rc::Rc -{ +) -> ::std::rc::Rc { match value { crate::operation::get_double::GetDoubleError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithydouble::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_input.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_input.rs index 1a6a82f8ef..a0b6588355 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_input.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_input.rs @@ -1,47 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_double::GetDoubleInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::dafny_runtime::Sequence::ArraySequence { - values: std::rc::Rc::new(f64::to_be_bytes(v).to_vec()), - }, - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleInput::GetDoubleInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::odouble_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleInput, >, ) -> crate::operation::get_double::GetDoubleInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - let my_vec = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), - |x| *x, - ); - Some(f64::from_be_bytes( - my_vec.try_into().expect("Error converting Sequence to f64"), - )) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_double::GetDoubleInput { value } + crate::operation::get_double::GetDoubleInput::builder() + .set_value(crate::standard_library_conversions::odouble_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_output.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_output.rs index 5dcd0eb48a..6607d6788e 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_output.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/get_double/_get_double_output.rs @@ -1,47 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_double::GetDoubleOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleOutput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::dafny_runtime::Sequence::ArraySequence { - values: std::rc::Rc::new(f64::to_be_bytes(v).to_vec()), - }, - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleOutput::GetDoubleOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::odouble_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleOutput, >, ) -> crate::operation::get_double::GetDoubleOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - let my_vec = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), - |x| *x, - ); - Some(f64::from_be_bytes( - my_vec.try_into().expect("Error converting Sequence to f64"), - )) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_double::GetDoubleOutput { value } + crate::operation::get_double::GetDoubleOutput::builder() + .set_value(crate::standard_library_conversions::odouble_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config.rs index 52a68a7b0e..4289c31fa4 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_double_config; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config/_simple_double_config.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config/_simple_double_config.rs index f726f08b6d..4dd5aa6c03 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config/_simple_double_config.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/conversions/simple_double_config/_simple_double_config.rs @@ -1,10 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_double_config::SimpleDoubleConfig, ) -> ::std::rc::Rc< - crate::simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig, + crate::r#simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig, > { ::std::rc::Rc::new(crate::r#simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig::SimpleDoubleConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/lib.rs deleted file mode 100644 index 94379fc047..0000000000 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub mod implementation_from_dafny; - -pub use client::Client; -pub use types::simple_double_config::SimpleDoubleConfig; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation.rs index 134175f816..3b489e6c92 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetDouble` operation. pub mod get_double; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double.rs index 8b6d980d91..38c65eb849 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetDouble`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -137,9 +139,9 @@ pub use crate::operation::get_double::_get_double_output::GetDoubleOutput; pub use crate::operation::get_double::_get_double_input::GetDoubleInput; -mod _get_double_input; +pub(crate) mod _get_double_output; -mod _get_double_output; +pub(crate) mod _get_double_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_input.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_input.rs index af1cc4102d..598b2c0b07 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_input.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_input.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetDoubleInput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option<::std::primitive::f64>, } impl GetDoubleInput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&f64> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option<::std::primitive::f64> { + self.value +} } impl GetDoubleInput { /// Creates a new builder-style object to manufacture [`GetDoubleInput`](crate::operation::operation::GetDoubleInput). @@ -25,23 +27,23 @@ impl GetDoubleInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetDoubleInputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option<::std::primitive::f64>, } impl GetDoubleInputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::f64>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::f64>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::f64> { + &self.value +} /// Consumes the builder and constructs a [`GetDoubleInput`](crate::operation::operation::GetDoubleInput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_output.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_output.rs index bf850acd35..20305255c7 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_output.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/_get_double_output.rs @@ -1,19 +1,19 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetDoubleOutput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option<::std::primitive::f64>, } - impl GetDoubleOutput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } +pub fn value(&self) -> ::std::option::Option<::std::primitive::f64> { + self.value +} } - impl GetDoubleOutput { /// Creates a new builder-style object to manufacture [`GetDoubleOutput`](crate::operation::operation::GetDoubleOutput). pub fn builder() -> crate::operation::get_double::builders::GetDoubleOutputBuilder { @@ -27,27 +27,23 @@ impl GetDoubleOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetDoubleOutputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option<::std::primitive::f64>, } - impl GetDoubleOutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } - +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::f64>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::f64>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::f64> { + &self.value +} /// Consumes the builder and constructs a [`GetDoubleOutput`](crate::operation::operation::GetDoubleOutput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/builders.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/builders.rs index ed9fd9a40b..dd6f7e015f 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/builders.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/operation/get_double/builders.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_double::_get_double_output::GetDoubleOutputBuilder; pub use crate::operation::get_double::_get_double_input::GetDoubleInputBuilder; @@ -22,7 +24,7 @@ impl GetDoubleInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetDoubleFluentBuilder { client: crate::client::Client, - inner: crate::operation::get_double::builders::GetDoubleInputBuilder, + pub(crate) inner: crate::operation::get_double::builders::GetDoubleInputBuilder, } impl GetDoubleFluentBuilder { /// Creates a new `GetDouble`. @@ -56,17 +58,17 @@ impl GetDoubleFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: f64) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::f64>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::f64>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::f64> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types.rs index 92447294d0..3154f39ef3 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `SimpleDoubleConfig` pub mod simple_double_config; diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types/simple_double_config.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types/simple_double_config.rs index b776656296..46db0da2e6 100644 --- a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types/simple_double_config.rs +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/types/simple_double_config.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleDoubleConfig {} diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..2b7522dd24 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::smithydouble::internaldafny::wrapped::_default { + pub fn WrappedSimpleDouble(config: &::std::rc::Rc< + crate::r#simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..281878c6a9 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleDouble/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,89 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::smithydouble::internaldafny::types::ISimpleTypesDoubleClient); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::smithydouble::internaldafny::types::SimpleDoubleConfig, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_double_config::_simple_double_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::smithydouble::internaldafny::types::ISimpleTypesDoubleClient for Client { + fn GetDouble( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithydouble::internaldafny::types::GetDoubleOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_double::_get_double_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_double::GetDouble::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_double::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_double::_get_double_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/Makefile b/TestModels/SimpleTypes/SimpleEnum/Makefile index 62c78e49de..01aa866e43 100644 --- a/TestModels/SimpleTypes/SimpleEnum/Makefile +++ b/TestModels/SimpleTypes/SimpleEnum/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/Cargo.toml index a3026b8a68..fb5b567bbf 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/Cargo.toml @@ -5,13 +5,19 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies.tokio] +[dev-dependencies] +simple_enum = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client.rs index 9649346b6f..3357e68544 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -29,7 +30,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } @@ -37,5 +38,7 @@ impl Client { mod get_enum; mod get_enum_first_known_value_test; + mod get_enum_second_known_value_test; + mod get_enum_third_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum.rs index f0c395251e..1f8ad39bc1 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetEnum`](crate::operation::get_enum::builders::GetEnumFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumShape)`](crate::operation::get_enum::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum::builders::GetEnumFluentBuilder::set_value):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_enum::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum::builders::GetEnumFluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum::GetEnumOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_enum::GetEnumOutput::value): (undocumented) + /// - [`value(Option)`](crate::operation::get_enum::GetEnumOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_enum::GetEnumError) pub fn get_enum(&self) -> crate::operation::get_enum::builders::GetEnumFluentBuilder { crate::operation::get_enum::builders::GetEnumFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_first_known_value_test.rs index a169931d82..fe5b423fa2 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_first_known_value_test.rs @@ -1,18 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { - /// Constructs a fluent builder for the [`GetEnum`](crate::operation::get_enum_first_known_value::builders::GetEnumFluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumFirstKnownValueTest`](crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumShape)`](crate::operation::get_enum_first_known_value::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_first_known_value::builders::GetEnumFluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_first_known_value::GetEnumOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_first_known_value::GetEnumOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_first_known_value::GetEnumError) - pub fn get_enum_first_known_value_test( - &self, - ) -> crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder - { - crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder::new( - self.clone(), - ) + /// - [`value(impl Into>)`](crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_first_known_value_test::GetEnumOutput) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_first_known_value_test::GetEnumOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError) + pub fn get_enum_first_known_value_test(&self) -> crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder { + crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_second_known_value_test.rs index 8e4ec068d2..4e9a16e551 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_second_known_value_test.rs @@ -1,18 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { - /// Constructs a fluent builder for the [`GetEnum`](crate::operation::get_enum_second_known_value::builders::GetEnumFluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumSecondKnownValueTest`](crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumShape)`](crate::operation::get_enum_second_known_value::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_second_known_value::builders::GetEnumFluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_second_known_value::GetEnumOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_second_known_value::GetEnumOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_second_known_value::GetEnumError) - pub fn get_enum_second_known_value_test( - &self, - ) -> crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder - { - crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder::new( - self.clone(), - ) + /// - [`value(impl Into>)`](crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_second_known_value_test::GetEnumOutput) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_second_known_value_test::GetEnumOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError) + pub fn get_enum_second_known_value_test(&self) -> crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder { + crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_third_known_value_test.rs index 47bdeb2fd5..01060bfee7 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/client/get_enum_third_known_value_test.rs @@ -1,18 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { - /// Constructs a fluent builder for the [`GetEnum`](crate::operation::get_enum_third_known_value::builders::GetEnumFluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumThirdKnownValueTest`](crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumShape)`](crate::operation::get_enum_third_known_value::builders::GetEnumFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_third_known_value::builders::GetEnumFluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_third_known_value::GetEnumOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_third_known_value::GetEnumOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_third_known_value::GetEnumError) - pub fn get_enum_third_known_value_test( - &self, - ) -> crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder - { - crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder::new( - self.clone(), - ) + /// - [`value(impl Into>)`](crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetEnumOutput`](crate::operation::get_enum_third_known_value_test::GetEnumOutput) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_third_known_value_test::GetEnumOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError) + pub fn get_enum_third_known_value_test(&self) -> crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder { + crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions.rs index 7361ee56f3..23444400ba 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions.rs @@ -1,9 +1,16 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_enum; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod get_enum_first_known_value_test; -pub mod get_enum_second_known_value_test; -pub mod get_enum_third_known_value_test; + pub mod get_enum; -pub mod simple_enum_config; -pub mod simple_enum_shape; + pub mod get_enum_first_known_value_test; + + pub mod get_enum_second_known_value_test; + + pub mod get_enum_third_known_value_test; + + pub mod simple_enum_config; + + pub mod simple_enum_shape; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..b16869c834 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::smithyenum::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum.rs index ef493d1195..6d75d851f5 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_input.rs index 3bbf16021f..6d65b89526 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_input.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_enum::GetEnumInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput::GetEnumInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, >, ) -> crate::operation::get_enum::GetEnumInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum::GetEnumInput { value } + crate::operation::get_enum::GetEnumInput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_output.rs index 1ae04378cc..8511c2d0ba 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum/_get_enum_output.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_enum::GetEnumOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput::GetEnumOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, >, ) -> crate::operation::get_enum::GetEnumOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum::GetEnumOutput { value } + crate::operation::get_enum::GetEnumOutput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test.rs index 5e3e946f36..51b4ad7bd9 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs index 453989647e..bd024fe5c6 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput, + value: crate::operation::get_enum_first_known_value_test::GetEnumInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput::GetEnumInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, >, -) -> crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput { value } +) -> crate::operation::get_enum_first_known_value_test::GetEnumInput { + crate::operation::get_enum_first_known_value_test::GetEnumInput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs index c31403c9c8..0b94ed08ad 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, + value: crate::operation::get_enum_first_known_value_test::GetEnumOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput::GetEnumOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, >, -) -> crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput { value } +) -> crate::operation::get_enum_first_known_value_test::GetEnumOutput { + crate::operation::get_enum_first_known_value_test::GetEnumOutput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test.rs index afa0c42cd6..37724a3683 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs index c73d8a6308..0124095fbf 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput, + value: crate::operation::get_enum_second_known_value_test::GetEnumInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput::GetEnumInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, >, -) -> crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput { value } +) -> crate::operation::get_enum_second_known_value_test::GetEnumInput { + crate::operation::get_enum_second_known_value_test::GetEnumInput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs index fbb2809ed3..6f9b39a9ab 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, + value: crate::operation::get_enum_second_known_value_test::GetEnumOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput::GetEnumOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, >, -) -> crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput { value } +) -> crate::operation::get_enum_second_known_value_test::GetEnumOutput { + crate::operation::get_enum_second_known_value_test::GetEnumOutput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test.rs index b3d8d1186e..8860c8548a 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs index 73c9d9b6f0..bf7ce0415c 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput, + value: crate::operation::get_enum_third_known_value_test::GetEnumInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput::GetEnumInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, >, -) -> crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput { value } +) -> crate::operation::get_enum_third_known_value_test::GetEnumInput { + crate::operation::get_enum_third_known_value_test::GetEnumInput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs index aafc1403e6..0199b60a8e 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, + value: crate::operation::get_enum_third_known_value_test::GetEnumOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_shape::_simple_enum_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput::GetEnumOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, >, -) -> crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_shape::_simple_enum_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput { value } +) -> crate::operation::get_enum_third_known_value_test::GetEnumOutput { + crate::operation::get_enum_third_known_value_test::GetEnumOutput::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config.rs index 973679ee23..6b6b7d9e31 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_enum_config; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config/_simple_enum_config.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config/_simple_enum_config.rs index a1e48e7f0e..3fcaeb06a4 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config/_simple_enum_config.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_config/_simple_enum_config.rs @@ -1,10 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_enum_config::SimpleEnumConfig, ) -> ::std::rc::Rc< - crate::simple::types::smithyenum::internaldafny::types::SimpleEnumConfig, + crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumConfig, > { ::std::rc::Rc::new(crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumConfig::SimpleEnumConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape.rs index f531b5531f..994d63ed8a 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape.rs @@ -1,3 +1,25 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] -pub mod _simple_enum_shape; +pub fn to_dafny( + value: crate::types::SimpleEnumShape, +) -> ::std::rc::Rc{ + ::std::rc::Rc::new(match value { + crate::types::SimpleEnumShape::First => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::FIRST {}, +crate::types::SimpleEnumShape::Second => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::SECOND {}, +crate::types::SimpleEnumShape::Third => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::THIRD {}, + _ => panic!("Unknown enum variant: {}", value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: &crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape, +) -> crate::types::SimpleEnumShape { + match dafny_value { + crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::FIRST {} => crate::types::SimpleEnumShape::First, +crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::SECOND {} => crate::types::SimpleEnumShape::Second, +crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::THIRD {} => crate::types::SimpleEnumShape::Third, + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape/_simple_enum_shape.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape/_simple_enum_shape.rs deleted file mode 100644 index 8519605a7c..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/conversions/simple_enum_shape/_simple_enum_shape.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] - -pub fn to_dafny( - value: &crate::types::simple_enum_shape::SimpleEnumShape, -) -> crate::simple::types::smithyenum::internaldafny::types::SimpleEnumShape { - match value { - crate::types::simple_enum_shape::SimpleEnumShape::FIRST => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::FIRST {}, - crate::types::simple_enum_shape::SimpleEnumShape::SECOND => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::SECOND {}, - crate::types::simple_enum_shape::SimpleEnumShape::THIRD => crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::THIRD {}, - } -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: &crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape, -) -> crate::types::simple_enum_shape::SimpleEnumShape { - match dafny_value { - crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::FIRST {} => crate::types::simple_enum_shape::SimpleEnumShape::FIRST, - crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::SECOND {} => crate::types::simple_enum_shape::SimpleEnumShape::SECOND, - crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumShape::THIRD {} => crate::types::simple_enum_shape::SimpleEnumShape::THIRD, - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/lib.rs deleted file mode 100644 index f914e7ba96..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub mod implementation_from_dafny; - -pub use client::Client; -pub use types::simple_enum_config::SimpleEnumConfig; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation.rs index 560af2715d..febf44fb04 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation.rs @@ -1,9 +1,14 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetEnum` operation. pub mod get_enum; -/// Types for the `GetEnumKnownValue` operation. +/// Types for the `GetEnumFirstKnownValueTest` operation. pub mod get_enum_first_known_value_test; + +/// Types for the `GetEnumSecondKnownValueTest` operation. pub mod get_enum_second_known_value_test; + +/// Types for the `GetEnumThirdKnownValueTest` operation. pub mod get_enum_third_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum.rs index d75b5ac448..58f7c64109 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnum`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -16,14 +18,17 @@ impl GetEnum { crate::operation::get_enum::GetEnumError, > { let inner_input = crate::conversions::get_enum::_get_enum_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - Ok(crate::conversions::get_enum::_get_enum_output::from_dafny( - inner_result.value().clone(), - )) + Ok( + crate::conversions::get_enum::_get_enum_output::from_dafny( + inner_result.value().clone(), + ), + ) } else { Err(crate::conversions::get_enum::from_dafny_error( inner_result.error().clone(), @@ -134,9 +139,9 @@ pub use crate::operation::get_enum::_get_enum_output::GetEnumOutput; pub use crate::operation::get_enum::_get_enum_input::GetEnumInput; -mod _get_enum_input; +pub(crate) mod _get_enum_output; -mod _get_enum_output; +pub(crate) mod _get_enum_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_input.rs index 37b1f16c17..5308a7b969 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_input.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_input.rs @@ -1,19 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetEnumInput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option, } impl GetEnumInput { #[allow(missing_docs)] // documentation missing in model - pub fn message( - &self, - ) -> ::std::option::Option<&crate::types::simple_enum_shape::SimpleEnumShape> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} } impl GetEnumInput { /// Creates a new builder-style object to manufacture [`GetEnumInput`](crate::operation::operation::GetEnumInput). @@ -28,31 +27,23 @@ impl GetEnumInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetEnumInputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option, } impl GetEnumInputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} /// Consumes the builder and constructs a [`GetEnumInput`](crate::operation::operation::GetEnumInput). pub fn build( self, @@ -60,6 +51,8 @@ impl GetEnumInputBuilder { crate::operation::get_enum::GetEnumInput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_enum::GetEnumInput { value: self.value }) + ::std::result::Result::Ok(crate::operation::get_enum::GetEnumInput { + value: self.value, + }) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_output.rs index 9675cc2c25..7a05b95d39 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_output.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/_get_enum_output.rs @@ -1,20 +1,19 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetEnumOutput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option, } - impl GetEnumOutput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} } - impl GetEnumOutput { /// Creates a new builder-style object to manufacture [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). pub fn builder() -> crate::operation::get_enum::builders::GetEnumOutputBuilder { @@ -28,35 +27,23 @@ impl GetEnumOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetEnumOutputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option, } - impl GetEnumOutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} /// Consumes the builder and constructs a [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). pub fn build( self, @@ -64,6 +51,8 @@ impl GetEnumOutputBuilder { crate::operation::get_enum::GetEnumOutput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_enum::GetEnumOutput { value: self.value }) + ::std::result::Result::Ok(crate::operation::get_enum::GetEnumOutput { + value: self.value, + }) } } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/builders.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/builders.rs index 11e371c133..34ee4503e4 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum/builders.rs @@ -1,7 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum::_get_enum_input::GetEnumInputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_enum::_get_enum_output::GetEnumOutputBuilder; +pub use crate::operation::get_enum::_get_enum_input::GetEnumInputBuilder; + impl GetEnumInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( @@ -21,7 +24,7 @@ impl GetEnumInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumFluentBuilder { client: crate::client::Client, - inner: crate::operation::get_enum::builders::GetEnumInputBuilder, + pub(crate) inner: crate::operation::get_enum::builders::GetEnumInputBuilder, } impl GetEnumFluentBuilder { /// Creates a new `GetEnum`. @@ -55,22 +58,17 @@ impl GetEnumFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_shape::SimpleEnumShape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test.rs index 106ec1702c..43bf7cd236 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnumFirstKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,14 +12,14 @@ impl GetEnumFirstKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput, + input: crate::operation::get_enum_first_known_value_test::GetEnumInput, ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, + crate::operation::get_enum_first_known_value_test::GetEnumOutput, crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError, > { - let inner_input = - crate::conversions::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); + let inner_input = crate::conversions::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::to_dafny(input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumFirstKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -28,11 +30,9 @@ impl GetEnumFirstKnownValueTest { ), ) } else { - Err( - crate::conversions::get_enum_first_known_value_test::from_dafny_error( - inner_result.error().clone(), - ), - ) + Err(crate::conversions::get_enum_first_known_value_test::from_dafny_error( + inner_result.error().clone(), + )) } } } @@ -41,7 +41,7 @@ impl GetEnumFirstKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumFirstKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unfirst_known error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -121,9 +121,7 @@ impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumFirstK } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError - for GetEnumFirstKnownValueTestError -{ +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumFirstKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -137,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError } } -pub use crate::operation::get_enum_first_known_value_test::_get_enum_first_known_value_test_output::GetEnumFirstKnownValueTestOutput; +pub use crate::operation::get_enum_first_known_value_test::_get_enum_output::GetEnumOutput; -pub use crate::operation::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::GetEnumFirstKnownValueTestInput; +pub use crate::operation::get_enum_first_known_value_test::_get_enum_input::GetEnumInput; -mod _get_enum_first_known_value_test_input; +pub(crate) mod _get_enum_output; -mod _get_enum_first_known_value_test_output; +pub(crate) mod _get_enum_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs deleted file mode 100644 index 866727550e..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_input.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumFirstKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumFirstKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetEnumFirstKnownValueTestInput { - /// Creates a new builder-style object to manufacture [`GetEnumFirstKnownValueTestInput`](crate::operation::operation::GetEnumFirstKnownValueTestInput). - pub fn builder( - ) -> crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestInputBuilder - { - crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestInputBuilder::default() - } -} - -/// A builder for [`GetEnumFirstKnownValueTestInput`](crate::operation::operation::GetEnumFirstKnownValueTestInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumFirstKnownValueTestInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumFirstKnownValueTestInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumFirstKnownValueTestInput`](crate::operation::operation::GetEnumFirstKnownValueTestInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs deleted file mode 100644 index 65154c9626..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_first_known_value_test_output.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumFirstKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumFirstKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetEnumFirstKnownValueTestOutput { - /// Creates a new builder-style object to manufacture [`GetEnumFirstKnownValueTestOutput`](crate::operation::operation::GetEnumFirstKnownValueTestOutput). - pub fn builder( - ) -> crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestOutputBuilder - { - crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestOutputBuilder::default() - } -} - -/// A builder for [`GetEnumFirstKnownValueTestOutput`](crate::operation::operation::GetEnumFirstKnownValueTestOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumFirstKnownValueTestOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumFirstKnownValueTestOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumFirstKnownValueTestOutput`](crate::operation::operation::GetEnumFirstKnownValueTestOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_input.rs new file mode 100644 index 0000000000..9ebdf0a653 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumInput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumInput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumInput { + /// Creates a new builder-style object to manufacture [`GetEnumInput`](crate::operation::operation::GetEnumInput). + pub fn builder() -> crate::operation::get_enum_first_known_value_test::builders::GetEnumInputBuilder { + crate::operation::get_enum_first_known_value_test::builders::GetEnumInputBuilder::default() + } +} + +/// A builder for [`GetEnumInput`](crate::operation::operation::GetEnumInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumInputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumInputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumInput`](crate::operation::operation::GetEnumInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_first_known_value_test::GetEnumInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_first_known_value_test::GetEnumInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_output.rs new file mode 100644 index 0000000000..78d1bf2081 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/_get_enum_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumOutput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumOutput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumOutput { + /// Creates a new builder-style object to manufacture [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). + pub fn builder() -> crate::operation::get_enum_first_known_value_test::builders::GetEnumOutputBuilder { + crate::operation::get_enum_first_known_value_test::builders::GetEnumOutputBuilder::default() + } +} + +/// A builder for [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumOutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumOutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_first_known_value_test::GetEnumOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_first_known_value_test::GetEnumOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/builders.rs index ca84c9774f..4da9155d3b 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_first_known_value_test/builders.rs @@ -1,14 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::GetEnumFirstKnownValueTestInputBuilder; -pub use crate::operation::get_enum_first_known_value_test::_get_enum_first_known_value_test_output::GetEnumFirstKnownValueTestOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_enum_first_known_value_test::_get_enum_output::GetEnumOutputBuilder; -impl GetEnumFirstKnownValueTestInputBuilder { +pub use crate::operation::get_enum_first_known_value_test::_get_enum_input::GetEnumInputBuilder; + +impl GetEnumInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, + crate::operation::get_enum_first_known_value_test::GetEnumOutput, crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError, > { let mut fluent_builder = client.get_enum_first_known_value_test(); @@ -21,8 +24,7 @@ impl GetEnumFirstKnownValueTestInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumFirstKnownValueTestFluentBuilder { client: crate::client::Client, - inner: - crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestInputBuilder, + pub(crate) inner: crate::operation::get_enum_first_known_value_test::builders::GetEnumInputBuilder, } impl GetEnumFirstKnownValueTestFluentBuilder { /// Creates a new `GetEnumFirstKnownValueTest`. @@ -33,52 +35,40 @@ impl GetEnumFirstKnownValueTestFluentBuilder { } } /// Access the GetEnumFirstKnownValueTest as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_enum_first_known_value_test::builders::GetEnumFirstKnownValueTestInputBuilder - { + pub fn as_input(&self) -> &crate::operation::get_enum_first_known_value_test::builders::GetEnumInputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestOutput, + crate::operation::get_enum_first_known_value_test::GetEnumOutput, crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnum doesn't declare any validation, + // Using unhandled since GetEnumFirstKnownValueTest doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTestError::unhandled)?; - crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTest::send( - &self.client, - input, - ) - .await + crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTest::send(&self.client, input).await } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_shape::SimpleEnumShape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test.rs index b59e0ce569..af28939f9c 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnumSecondKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,14 +12,14 @@ impl GetEnumSecondKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput, + input: crate::operation::get_enum_second_known_value_test::GetEnumInput, ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, + crate::operation::get_enum_second_known_value_test::GetEnumOutput, crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError, > { - let inner_input = - crate::conversions::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); + let inner_input = crate::conversions::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::to_dafny(input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumSecondKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -28,11 +30,9 @@ impl GetEnumSecondKnownValueTest { ), ) } else { - Err( - crate::conversions::get_enum_second_known_value_test::from_dafny_error( - inner_result.error().clone(), - ), - ) + Err(crate::conversions::get_enum_second_known_value_test::from_dafny_error( + inner_result.error().clone(), + )) } } } @@ -41,7 +41,7 @@ impl GetEnumSecondKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumSecondKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unsecond_known error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -114,18 +114,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetEnumSecondKnownValueTest ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata - for GetEnumSecondKnownValueTestError -{ +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumSecondKnownValueTestError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError - for GetEnumSecondKnownValueTestError -{ +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumSecondKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -139,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError } } -pub use crate::operation::get_enum_second_known_value_test::_get_enum_second_known_value_test_output::GetEnumSecondKnownValueTestOutput; +pub use crate::operation::get_enum_second_known_value_test::_get_enum_output::GetEnumOutput; -pub use crate::operation::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::GetEnumSecondKnownValueTestInput; +pub use crate::operation::get_enum_second_known_value_test::_get_enum_input::GetEnumInput; -mod _get_enum_second_known_value_test_input; +pub(crate) mod _get_enum_output; -mod _get_enum_second_known_value_test_output; +pub(crate) mod _get_enum_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_input.rs new file mode 100644 index 0000000000..494cb01579 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumInput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumInput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumInput { + /// Creates a new builder-style object to manufacture [`GetEnumInput`](crate::operation::operation::GetEnumInput). + pub fn builder() -> crate::operation::get_enum_second_known_value_test::builders::GetEnumInputBuilder { + crate::operation::get_enum_second_known_value_test::builders::GetEnumInputBuilder::default() + } +} + +/// A builder for [`GetEnumInput`](crate::operation::operation::GetEnumInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumInputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumInputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumInput`](crate::operation::operation::GetEnumInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_second_known_value_test::GetEnumInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_second_known_value_test::GetEnumInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_output.rs new file mode 100644 index 0000000000..355865e935 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumOutput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumOutput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumOutput { + /// Creates a new builder-style object to manufacture [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). + pub fn builder() -> crate::operation::get_enum_second_known_value_test::builders::GetEnumOutputBuilder { + crate::operation::get_enum_second_known_value_test::builders::GetEnumOutputBuilder::default() + } +} + +/// A builder for [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumOutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumOutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_second_known_value_test::GetEnumOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_second_known_value_test::GetEnumOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs deleted file mode 100644 index 3fb03429b0..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_input.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumSecondKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumSecondKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetEnumSecondKnownValueTestInput { - /// Creates a new builder-style object to manufacture [`GetEnumSecondKnownValueTestInput`](crate::operation::operation::GetEnumSecondKnownValueTestInput). - pub fn builder( - ) -> crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestInputBuilder - { - crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestInputBuilder::default() - } -} - -/// A builder for [`GetEnumSecondKnownValueTestInput`](crate::operation::operation::GetEnumSecondKnownValueTestInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumSecondKnownValueTestInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumSecondKnownValueTestInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumSecondKnownValueTestInput`](crate::operation::operation::GetEnumSecondKnownValueTestInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs deleted file mode 100644 index 6937025052..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/_get_enum_second_known_value_test_output.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumSecondKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumSecondKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetEnumSecondKnownValueTestOutput { - /// Creates a new builder-style object to manufacture [`GetEnumSecondKnownValueTestOutput`](crate::operation::operation::GetEnumSecondKnownValueTestOutput). - pub fn builder( - ) -> crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestOutputBuilder - { - crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestOutputBuilder::default() - } -} - -/// A builder for [`GetEnumSecondKnownValueTestOutput`](crate::operation::operation::GetEnumSecondKnownValueTestOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumSecondKnownValueTestOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumSecondKnownValueTestOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumSecondKnownValueTestOutput`](crate::operation::operation::GetEnumSecondKnownValueTestOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/builders.rs index e54348b361..1d0afa3fc5 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_second_known_value_test/builders.rs @@ -1,14 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::GetEnumSecondKnownValueTestInputBuilder; -pub use crate::operation::get_enum_second_known_value_test::_get_enum_second_known_value_test_output::GetEnumSecondKnownValueTestOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_enum_second_known_value_test::_get_enum_output::GetEnumOutputBuilder; -impl GetEnumSecondKnownValueTestInputBuilder { +pub use crate::operation::get_enum_second_known_value_test::_get_enum_input::GetEnumInputBuilder; + +impl GetEnumInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, + crate::operation::get_enum_second_known_value_test::GetEnumOutput, crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError, > { let mut fluent_builder = client.get_enum_second_known_value_test(); @@ -21,7 +24,7 @@ impl GetEnumSecondKnownValueTestInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumSecondKnownValueTestFluentBuilder { client: crate::client::Client, - inner: crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestInputBuilder, + pub(crate) inner: crate::operation::get_enum_second_known_value_test::builders::GetEnumInputBuilder, } impl GetEnumSecondKnownValueTestFluentBuilder { /// Creates a new `GetEnumSecondKnownValueTest`. @@ -32,52 +35,40 @@ impl GetEnumSecondKnownValueTestFluentBuilder { } } /// Access the GetEnumSecondKnownValueTest as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_enum_second_known_value_test::builders::GetEnumSecondKnownValueTestInputBuilder - { + pub fn as_input(&self) -> &crate::operation::get_enum_second_known_value_test::builders::GetEnumInputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestOutput, + crate::operation::get_enum_second_known_value_test::GetEnumOutput, crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnum doesn't declare any validation, + // Using unhandled since GetEnumSecondKnownValueTest doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTestError::unhandled)?; - crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTest::send( - &self.client, - input, - ) - .await + crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTest::send(&self.client, input).await } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_shape::SimpleEnumShape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test.rs index d5def6ff29..0b3f627823 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnumThirdKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,14 +12,14 @@ impl GetEnumThirdKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput, + input: crate::operation::get_enum_third_known_value_test::GetEnumInput, ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, + crate::operation::get_enum_third_known_value_test::GetEnumOutput, crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError, > { - let inner_input = - crate::conversions::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetEnum(&inner_input); + let inner_input = crate::conversions::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::to_dafny(input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumThirdKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -28,11 +30,9 @@ impl GetEnumThirdKnownValueTest { ), ) } else { - Err( - crate::conversions::get_enum_third_known_value_test::from_dafny_error( - inner_result.error().clone(), - ), - ) + Err(crate::conversions::get_enum_third_known_value_test::from_dafny_error( + inner_result.error().clone(), + )) } } } @@ -41,7 +41,7 @@ impl GetEnumThirdKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumThirdKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unthird_known error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -121,9 +121,7 @@ impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumThirdK } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError - for GetEnumThirdKnownValueTestError -{ +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumThirdKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -137,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError } } -pub use crate::operation::get_enum_third_known_value_test::_get_enum_third_known_value_test_output::GetEnumThirdKnownValueTestOutput; +pub use crate::operation::get_enum_third_known_value_test::_get_enum_output::GetEnumOutput; -pub use crate::operation::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::GetEnumThirdKnownValueTestInput; +pub use crate::operation::get_enum_third_known_value_test::_get_enum_input::GetEnumInput; -mod _get_enum_third_known_value_test_input; +pub(crate) mod _get_enum_output; -mod _get_enum_third_known_value_test_output; +pub(crate) mod _get_enum_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_input.rs new file mode 100644 index 0000000000..5529bb5f1d --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumInput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumInput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumInput { + /// Creates a new builder-style object to manufacture [`GetEnumInput`](crate::operation::operation::GetEnumInput). + pub fn builder() -> crate::operation::get_enum_third_known_value_test::builders::GetEnumInputBuilder { + crate::operation::get_enum_third_known_value_test::builders::GetEnumInputBuilder::default() + } +} + +/// A builder for [`GetEnumInput`](crate::operation::operation::GetEnumInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumInputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumInputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumInput`](crate::operation::operation::GetEnumInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_third_known_value_test::GetEnumInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_third_known_value_test::GetEnumInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_output.rs new file mode 100644 index 0000000000..87d794f537 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumOutput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumOutput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumOutput { + /// Creates a new builder-style object to manufacture [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). + pub fn builder() -> crate::operation::get_enum_third_known_value_test::builders::GetEnumOutputBuilder { + crate::operation::get_enum_third_known_value_test::builders::GetEnumOutputBuilder::default() + } +} + +/// A builder for [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumOutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumOutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumOutput`](crate::operation::operation::GetEnumOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_third_known_value_test::GetEnumOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_third_known_value_test::GetEnumOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs deleted file mode 100644 index 275d472c06..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_input.rs +++ /dev/null @@ -1,68 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumThirdKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumThirdKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetEnumThirdKnownValueTestInput { - /// Creates a new builder-style object to manufacture [`GetEnumThirdKnownValueTestInput`](crate::operation::operation::GetEnumThirdKnownValueTestInput). - pub fn builder( - ) -> crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestInputBuilder - { - crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestInputBuilder::default() - } -} - -/// A builder for [`GetEnumThirdKnownValueTestInput`](crate::operation::operation::GetEnumThirdKnownValueTestInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumThirdKnownValueTestInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumThirdKnownValueTestInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumThirdKnownValueTestInput`](crate::operation::operation::GetEnumThirdKnownValueTestInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs deleted file mode 100644 index e1d498d3e5..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/_get_enum_third_known_value_test_output.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumThirdKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumThirdKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetEnumThirdKnownValueTestOutput { - /// Creates a new builder-style object to manufacture [`GetEnumThirdKnownValueTestOutput`](crate::operation::operation::GetEnumThirdKnownValueTestOutput). - pub fn builder( - ) -> crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestOutputBuilder - { - crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestOutputBuilder::default() - } -} - -/// A builder for [`GetEnumThirdKnownValueTestOutput`](crate::operation::operation::GetEnumThirdKnownValueTestOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumThirdKnownValueTestOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumThirdKnownValueTestOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumThirdKnownValueTestOutput`](crate::operation::operation::GetEnumThirdKnownValueTestOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/builders.rs index db835240b0..f51c94119c 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/operation/get_enum_third_known_value_test/builders.rs @@ -1,14 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::GetEnumThirdKnownValueTestInputBuilder; -pub use crate::operation::get_enum_third_known_value_test::_get_enum_third_known_value_test_output::GetEnumThirdKnownValueTestOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_enum_third_known_value_test::_get_enum_output::GetEnumOutputBuilder; -impl GetEnumThirdKnownValueTestInputBuilder { +pub use crate::operation::get_enum_third_known_value_test::_get_enum_input::GetEnumInputBuilder; + +impl GetEnumInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, + crate::operation::get_enum_third_known_value_test::GetEnumOutput, crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError, > { let mut fluent_builder = client.get_enum_third_known_value_test(); @@ -21,8 +24,7 @@ impl GetEnumThirdKnownValueTestInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumThirdKnownValueTestFluentBuilder { client: crate::client::Client, - inner: - crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestInputBuilder, + pub(crate) inner: crate::operation::get_enum_third_known_value_test::builders::GetEnumInputBuilder, } impl GetEnumThirdKnownValueTestFluentBuilder { /// Creates a new `GetEnumThirdKnownValueTest`. @@ -33,52 +35,40 @@ impl GetEnumThirdKnownValueTestFluentBuilder { } } /// Access the GetEnumThirdKnownValueTest as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_enum_third_known_value_test::builders::GetEnumThirdKnownValueTestInputBuilder - { + pub fn as_input(&self) -> &crate::operation::get_enum_third_known_value_test::builders::GetEnumInputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestOutput, + crate::operation::get_enum_third_known_value_test::GetEnumOutput, crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnum doesn't declare any validation, + // Using unhandled since GetEnumThirdKnownValueTest doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTestError::unhandled)?; - crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTest::send( - &self.client, - input, - ) - .await + crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTest::send(&self.client, input).await } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_shape::SimpleEnumShape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types.rs index de39101208..0f9d2788bd 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types.rs @@ -1,5 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -/// Types for the `SimpleIntegerConfig` +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +/// Types for the `SimpleEnumConfig` pub mod simple_enum_config; -pub mod simple_enum_shape; + +mod _simple_enum_shape; +pub use crate::types::_simple_enum_shape::SimpleEnumShape; diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/_simple_enum_shape.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/_simple_enum_shape.rs new file mode 100644 index 0000000000..fd2b3fdce2 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/_simple_enum_shape.rs @@ -0,0 +1,19 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[derive(Debug, PartialEq, Copy, Clone)] +pub enum SimpleEnumShape { + First, +Second, +Third, +} + +impl ::std::fmt::Display for SimpleEnumShape { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match self { + SimpleEnumShape::First => write!(f, "FIRST"), +SimpleEnumShape::Second => write!(f, "SECOND"), +SimpleEnumShape::Third => write!(f, "THIRD"), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_config.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_config.rs index fd3ea0e14c..7fd6368cb2 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_config.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_config.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleEnumConfig {} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_shape.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_shape.rs deleted file mode 100644 index dba3140596..0000000000 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/types/simple_enum_shape.rs +++ /dev/null @@ -1,6 +0,0 @@ -#[derive(Debug, PartialEq, Copy, Clone)] -pub enum SimpleEnumShape { - FIRST, - SECOND, - THIRD, -} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..fe5929068a --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::smithyenum::internaldafny::wrapped::_default { + pub fn WrappedSimpleEnum(config: &::std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumConfig, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..d35f39e8c1 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,179 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::smithyenum::internaldafny::types::ISimpleTypesEnumClient); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::SimpleEnumConfig, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_enum_config::_simple_enum_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::smithyenum::internaldafny::types::ISimpleTypesEnumClient for Client { + fn GetEnum( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum::_get_enum_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum::GetEnum::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum::_get_enum_output::to_dafny(client), + }, + ), + } + } + + fn GetEnumFirstKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum_first_known_value_test::_get_enum_first_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum_first_known_value_test::GetEnumFirstKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum_first_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum_first_known_value_test::_get_enum_first_known_value_test_output::to_dafny(client), + }, + ), + } + } + + fn GetEnumSecondKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum_second_known_value_test::_get_enum_second_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum_second_known_value_test::GetEnumSecondKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum_second_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum_second_known_value_test::_get_enum_second_known_value_test_output::to_dafny(client), + }, + ), + } + } + + fn GetEnumThirdKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithyenum::internaldafny::types::GetEnumOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum_third_known_value_test::_get_enum_third_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum_third_known_value_test::GetEnumThirdKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum_third_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum_third_known_value_test::_get_enum_third_known_value_test_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/tests/simple_enum_test.rs b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/tests/simple_enum_test.rs index 8e53533ea3..0e8259e737 100644 --- a/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/tests/simple_enum_test.rs +++ b/TestModels/SimpleTypes/SimpleEnum/runtimes/rust/tests/simple_enum_test.rs @@ -1,48 +1,48 @@ -use simple_enum::types::simple_enum_shape::SimpleEnumShape::*; +use simple_enum::types::SimpleEnumShape::*; use simple_enum::*; #[tokio::test] async fn test_get_enum() { - let result = client().get_enum().value(SECOND).send().await; + let result = client().get_enum().value(Second).send().await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, SECOND); + assert_eq!(value, Second); } #[tokio::test] async fn test_get_first_known_value() { let result = client() .get_enum_first_known_value_test() - .value(FIRST) + .value(First) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, FIRST); + assert_eq!(value, First); } #[tokio::test] async fn test_get_second_known_value() { let result = client() .get_enum_second_known_value_test() - .value(SECOND) + .value(Second) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, SECOND); + assert_eq!(value, Second); } #[tokio::test] async fn test_get_third_known_value() { let result = client() .get_enum_third_known_value_test() - .value(THIRD) + .value(Third) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, THIRD); + assert_eq!(value, Third); } pub fn client() -> Client { diff --git a/TestModels/SimpleTypes/SimpleEnumV2/Makefile b/TestModels/SimpleTypes/SimpleEnumV2/Makefile index 51615d0785..1cd07bb145 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/Makefile +++ b/TestModels/SimpleTypes/SimpleEnumV2/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/Cargo.toml index dbaad13bfd..291c1fd915 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/Cargo.toml @@ -5,13 +5,19 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies.tokio] +[dev-dependencies] +simple_enum_v2 = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client.rs index f7bbdbfacb..83490767ce 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -29,7 +30,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } @@ -37,5 +38,7 @@ impl Client { mod get_enum_v2; mod get_enum_v2_first_known_value_test; + mod get_enum_v2_second_known_value_test; + mod get_enum_v2_third_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2.rs index c9a688bd85..7cc559b930 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetEnumV2`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumV2Shape)`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::set_value):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2::GetEnumV2Output) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_v2::GetEnumV2Output::value): (undocumented) + /// - [`value(Option)`](crate::operation::get_enum_v2::GetEnumV2Output::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2::GetEnumV2Error) pub fn get_enum_v2(&self) -> crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder { crate::operation::get_enum_v2::builders::GetEnumV2FluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_first_known_value_test.rs index ebde767b2c..896b404709 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_first_known_value_test.rs @@ -1,18 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { - /// Constructs a fluent builder for the [`GetEnumV2`](crate::operation::get_enum_v2_first_known_value::builders::GetEnumV2FluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumV2FirstKnownValueTest`](crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumV2Shape)`](crate::operation::get_enum_v2_first_known_value::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_first_known_value::builders::GetEnumV2FluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_first_known_value::GetEnumV2Output) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_v2_first_known_value::GetEnumV2Output::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_first_known_value::GetEnumV2Error) - pub fn get_enum_v2_first_known_value_test( - &self, - ) -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder - { - crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder::new( - self.clone(), - ) + /// - [`value(impl Into>)`](crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError) + pub fn get_enum_v2_first_known_value_test(&self) -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder { + crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_second_known_value_test.rs index f4981c29d3..3bbcda3c1f 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_second_known_value_test.rs @@ -1,18 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { - /// Constructs a fluent builder for the [`GetEnumV2`](crate::operation::get_enum_v2_second_known_value::builders::GetEnumV2FluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumV2SecondKnownValueTest`](crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumV2Shape)`](crate::operation::get_enum_v2_second_known_value::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_second_known_value::builders::GetEnumV2FluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_second_known_value::GetEnumV2Output) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_v2_second_known_value::GetEnumV2Output::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_second_known_value::GetEnumV2Error) - pub fn get_enum_v2_second_known_value_test( - &self, - ) -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder - { - crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder::new( - self.clone(), - ) + /// - [`value(impl Into>)`](crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError) + pub fn get_enum_v2_second_known_value_test(&self) -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder { + crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_third_known_value_test.rs index afc875f376..c37fe8c75e 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/client/get_enum_v2_third_known_value_test.rs @@ -1,18 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { - /// Constructs a fluent builder for the [`GetEnumV2`](crate::operation::get_enum_v2_third_known_value::builders::GetEnumV2FluentBuilder) operation. + /// Constructs a fluent builder for the [`GetEnumV2ThirdKnownValueTest`](crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(SimpleEnumV2Shape)`](crate::operation::get_enum_v2_third_known_value::builders::GetEnumV2FluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_third_known_value::builders::GetEnumV2FluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_third_known_value::GetEnumV2Output) with field(s): - /// - [`value(Option)`](crate::operation::get_enum_v2_third_known_value::GetEnumV2Output::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_third_known_value::GetEnumV2Error) - pub fn get_enum_v2_third_known_value_test( - &self, - ) -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder - { - crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder::new( - self.clone(), - ) + /// - [`value(impl Into>)`](crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetEnumV2Output`](crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output) with field(s): + /// - [`value(Option)`](crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError) + pub fn get_enum_v2_third_known_value_test(&self) -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder { + crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions.rs index 323761ef25..ae84ee4f2d 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions.rs @@ -1,9 +1,16 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_enum_v2; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod get_enum_v2_first_known_value_test; -pub mod get_enum_v2_second_known_value_test; -pub mod get_enum_v2_third_known_value_test; + pub mod get_enum_v2; -pub mod simple_enum_v2_config; -pub mod simple_enum_v2_shape; + pub mod get_enum_v2_first_known_value_test; + + pub mod get_enum_v2_second_known_value_test; + + pub mod get_enum_v2_third_known_value_test; + + pub mod simple_enum_v2_config; + + pub mod simple_enum_v2_shape; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..fd8f69459c --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::enumv2::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2.rs index e9b9909b5d..b6ad1638f4 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] @@ -7,14 +8,9 @@ pub fn to_dafny_error( value: crate::operation::get_enum_v2::GetEnumV2Error, ) -> ::std::rc::Rc { match value { - crate::operation::get_enum_v2::GetEnumV2Error::Unhandled(unhandled) => ::std::rc::Rc::new( - crate::r#simple::types::enumv2::internaldafny::types::Error::Opaque { - obj: ::dafny_runtime::upcast_object()( - ::dafny_runtime::object::new(unhandled), - ), - }, - ), - } + crate::operation::get_enum_v2::GetEnumV2Error::Unhandled(unhandled) => + ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) + } } #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_input.rs index 236bf35509..00959d1e89 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_input.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_enum_v2::GetEnumV2Input, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input::GetEnumV2Input { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, >, ) -> crate::operation::get_enum_v2::GetEnumV2Input { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2::GetEnumV2Input { value } + crate::operation::get_enum_v2::GetEnumV2Input::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_output.rs index 84d950d915..08130c3e9b 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2/_get_enum_v2_output.rs @@ -1,45 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_enum_v2::GetEnumV2Output, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output::GetEnumV2Output { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, >, ) -> crate::operation::get_enum_v2::GetEnumV2Output { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2::GetEnumV2Output { value } + crate::operation::get_enum_v2::GetEnumV2Output::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test.rs index 9e85094466..e7bfe032d6 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs index 043d693333..96fe41e22f 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs @@ -1,47 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput, + value: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input::GetEnumV2Input { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, >, -) -> crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput { - value, - } +) -> crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input { + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs index 7378e11786..268a2afa6b 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs @@ -1,47 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, + value: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output::GetEnumV2Output { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, >, -) -> crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput { - value, - } +) -> crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output { + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test.rs index b6de63fad1..e64c315050 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs index a7a40bf49c..74e95d15a7 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs @@ -1,47 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput, + value: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input::GetEnumV2Input { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, >, -) -> crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput { - value, - } +) -> crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input { + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs index 07bec26645..0b68410110 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs @@ -1,47 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, + value: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output::GetEnumV2Output { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, >, -) -> crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput { - value, - } +) -> crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output { + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test.rs index a1ddd7dab5..d190f09074 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs index 8adc054b04..1b60f1e579 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs @@ -1,47 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput, + value: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&v), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input::GetEnumV2Input { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, >, -) -> crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput { - value, - } +) -> crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input { + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs index 1607c8003e..ca7d68c38a 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs @@ -1,47 +1,34 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, + value: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, ) -> ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: ::std::rc::Rc::new( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::to_dafny(&b), - ), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output::GetEnumV2Output { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match &value.value { + Some(x) => crate::_Wrappers_Compile::Option::Some { value: crate::conversions::simple_enum_v2_shape::to_dafny(x.clone()) }, + None => crate::_Wrappers_Compile::Option::None { } +}) +, + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, >, -) -> crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - crate::conversions::simple_enum_v2_shape::_simple_enum_v2_shape::from_dafny( - &*dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput { - value, - } +) -> crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output { + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output::builder() + .set_value(match &**dafny_value.value() { + crate::r#_Wrappers_Compile::Option::Some { value } => Some( + crate::conversions::simple_enum_v2_shape::from_dafny(value) + ), + _ => None, +} +) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config.rs index 3eaacd610f..e280adea26 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_enum_v2_config; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config/_simple_enum_v2_config.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config/_simple_enum_v2_config.rs index f0a6804513..005e3ea6e6 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config/_simple_enum_v2_config.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_config/_simple_enum_v2_config.rs @@ -1,10 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_enum_v2_config::SimpleEnumV2Config, ) -> ::std::rc::Rc< - crate::simple::types::enumv2::internaldafny::types::SimpleEnumV2Config, + crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Config, > { ::std::rc::Rc::new(crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Config::SimpleEnumV2Config {}) } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape.rs index b4f4a50f80..d2e61a3673 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape.rs @@ -1,3 +1,25 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] -pub mod _simple_enum_v2_shape; +pub fn to_dafny( + value: crate::types::SimpleEnumV2Shape, +) -> ::std::rc::Rc{ + ::std::rc::Rc::new(match value { + crate::types::SimpleEnumV2Shape::First => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::FIRST {}, +crate::types::SimpleEnumV2Shape::Second => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::SECOND {}, +crate::types::SimpleEnumV2Shape::Third => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::THIRD {}, + _ => panic!("Unknown enum variant: {}", value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: &crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape, +) -> crate::types::SimpleEnumV2Shape { + match dafny_value { + crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::FIRST {} => crate::types::SimpleEnumV2Shape::First, +crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::SECOND {} => crate::types::SimpleEnumV2Shape::Second, +crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::THIRD {} => crate::types::SimpleEnumV2Shape::Third, + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape/_simple_enum_v2_shape.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape/_simple_enum_v2_shape.rs deleted file mode 100644 index d48a6337b0..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/conversions/simple_enum_v2_shape/_simple_enum_v2_shape.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] - -pub fn to_dafny( - value: &crate::types::simple_enum_v2_shape::SimpleEnumV2Shape, -) -> crate::simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape { - match value { - crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::FIRST => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::FIRST {}, - crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::SECOND => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::SECOND {}, - crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::THIRD => crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::THIRD {}, - } -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: &crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape, -) -> crate::types::simple_enum_v2_shape::SimpleEnumV2Shape { - match dafny_value { - crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::FIRST {} => crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::FIRST, - crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::SECOND {} => crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::SECOND, - crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Shape::THIRD {} => crate::types::simple_enum_v2_shape::SimpleEnumV2Shape::THIRD, - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/lib.rs deleted file mode 100644 index fcb015ba30..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub mod implementation_from_dafny; - -pub use client::Client; -pub use types::simple_enum_v2_config::SimpleEnumV2Config; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation.rs index 565298a1a7..a4dc395b89 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation.rs @@ -1,9 +1,14 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetEnumV2` operation. pub mod get_enum_v2; -/// Types for the `GetEnumV2KnownValue` operation. +/// Types for the `GetEnumV2FirstKnownValueTest` operation. pub mod get_enum_v2_first_known_value_test; + +/// Types for the `GetEnumV2SecondKnownValueTest` operation. pub mod get_enum_v2_second_known_value_test; + +/// Types for the `GetEnumV2ThirdKnownValueTest` operation. pub mod get_enum_v2_third_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2.rs index f556fbe3ec..d35d560f15 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnumV2`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -137,9 +139,9 @@ pub use crate::operation::get_enum_v2::_get_enum_v2_output::GetEnumV2Output; pub use crate::operation::get_enum_v2::_get_enum_v2_input::GetEnumV2Input; -mod _get_enum_v2_input; +pub(crate) mod _get_enum_v2_output; -mod _get_enum_v2_output; +pub(crate) mod _get_enum_v2_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_input.rs index a842022680..dfb86df68c 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_input.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_input.rs @@ -1,19 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetEnumV2Input { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option, } impl GetEnumV2Input { #[allow(missing_docs)] // documentation missing in model - pub fn message( - &self, - ) -> ::std::option::Option<&crate::types::simple_enum_v2_shape::SimpleEnumV2Shape> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} } impl GetEnumV2Input { /// Creates a new builder-style object to manufacture [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). @@ -28,31 +27,23 @@ impl GetEnumV2Input { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetEnumV2InputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option, } impl GetEnumV2InputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} /// Consumes the builder and constructs a [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_output.rs index 002769f657..3037a73e7d 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_output.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/_get_enum_v2_output.rs @@ -1,22 +1,19 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetEnumV2Output { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option, } - impl GetEnumV2Output { #[allow(missing_docs)] // documentation missing in model - pub fn value( - &self, - ) -> ::std::option::Option { - self.value - } +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} } - impl GetEnumV2Output { /// Creates a new builder-style object to manufacture [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). pub fn builder() -> crate::operation::get_enum_v2::builders::GetEnumV2OutputBuilder { @@ -30,35 +27,23 @@ impl GetEnumV2Output { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetEnumV2OutputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option, } - impl GetEnumV2OutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} /// Consumes the builder and constructs a [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/builders.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/builders.rs index e742b3d97c..89b6e6ef12 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2/builders.rs @@ -1,7 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum_v2::_get_enum_v2_input::GetEnumV2InputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_enum_v2::_get_enum_v2_output::GetEnumV2OutputBuilder; +pub use crate::operation::get_enum_v2::_get_enum_v2_input::GetEnumV2InputBuilder; + impl GetEnumV2InputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( @@ -21,7 +24,7 @@ impl GetEnumV2InputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumV2FluentBuilder { client: crate::client::Client, - inner: crate::operation::get_enum_v2::builders::GetEnumV2InputBuilder, + pub(crate) inner: crate::operation::get_enum_v2::builders::GetEnumV2InputBuilder, } impl GetEnumV2FluentBuilder { /// Creates a new `GetEnumV2`. @@ -55,22 +58,17 @@ impl GetEnumV2FluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_v2_shape::SimpleEnumV2Shape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test.rs index 57c67e00bc..eae709de44 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnumV2FirstKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,15 +12,14 @@ impl GetEnumV2FirstKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput, + input: crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input, ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError, > { - let inner_input = - crate::conversions::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::to_dafny(input); + let inner_input = crate::conversions::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::to_dafny(input); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2FirstKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -29,11 +30,9 @@ impl GetEnumV2FirstKnownValueTest { ), ) } else { - Err( - crate::conversions::get_enum_v2_first_known_value_test::from_dafny_error( - inner_result.error().clone(), - ), - ) + Err(crate::conversions::get_enum_v2_first_known_value_test::from_dafny_error( + inner_result.error().clone(), + )) } } } @@ -42,7 +41,7 @@ impl GetEnumV2FirstKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumV2FirstKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unfirst_known error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -115,18 +114,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetEnumV2FirstKnownValueTes ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata - for GetEnumV2FirstKnownValueTestError -{ +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumV2FirstKnownValueTestError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError - for GetEnumV2FirstKnownValueTestError -{ +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumV2FirstKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -140,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError } } -pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_output::GetEnumV2FirstKnownValueTestOutput; +pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_output::GetEnumV2Output; -pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::GetEnumV2FirstKnownValueTestInput; +pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_input::GetEnumV2Input; -mod _get_enum_v2_first_known_value_test_input; +pub(crate) mod _get_enum_v2_output; -mod _get_enum_v2_first_known_value_test_output; +pub(crate) mod _get_enum_v2_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs deleted file mode 100644 index a367fd776e..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_input.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2FirstKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumV2FirstKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - &self, - ) -> ::std::option::Option { - self.value - } -} -impl GetEnumV2FirstKnownValueTestInput { - /// Creates a new builder-style object to manufacture [`GetEnumV2FirstKnownValueTestInput`](crate::operation::operation::GetEnumV2FirstKnownValueTestInput). - pub fn builder( - ) -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestInputBuilder - { - crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestInputBuilder::default() - } -} - -/// A builder for [`GetEnumV2FirstKnownValueTestInput`](crate::operation::operation::GetEnumV2FirstKnownValueTestInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2FirstKnownValueTestInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2FirstKnownValueTestInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumV2FirstKnownValueTestInput`](crate::operation::operation::GetEnumV2FirstKnownValueTestInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs deleted file mode 100644 index f665704ab0..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_first_known_value_test_output.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2FirstKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumV2FirstKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - &self, - ) -> ::std::option::Option { - self.value - } -} -impl GetEnumV2FirstKnownValueTestOutput { - /// Creates a new builder-style object to manufacture [`GetEnumV2FirstKnownValueTestOutput`](crate::operation::operation::GetEnumV2FirstKnownValueTestOutput). - pub fn builder( - ) -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestOutputBuilder - { - crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestOutputBuilder::default() - } -} - -/// A builder for [`GetEnumV2FirstKnownValueTestOutput`](crate::operation::operation::GetEnumV2FirstKnownValueTestOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2FirstKnownValueTestOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2FirstKnownValueTestOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumV2FirstKnownValueTestOutput`](crate::operation::operation::GetEnumV2FirstKnownValueTestOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_input.rs new file mode 100644 index 0000000000..fab2d07d14 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2Input { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumV2Input { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumV2Input { + /// Creates a new builder-style object to manufacture [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). + pub fn builder() -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2InputBuilder { + crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2InputBuilder::default() + } +} + +/// A builder for [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2InputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2InputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Input { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_output.rs new file mode 100644 index 0000000000..ee11f4792d --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/_get_enum_v2_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2Output { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumV2Output { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumV2Output { + /// Creates a new builder-style object to manufacture [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). + pub fn builder() -> crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2OutputBuilder { + crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2OutputBuilder::default() + } +} + +/// A builder for [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2OutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2OutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/builders.rs index c88ff6efee..548fdeb7d2 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_first_known_value_test/builders.rs @@ -1,14 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::GetEnumV2FirstKnownValueTestInputBuilder; -pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_output::GetEnumV2FirstKnownValueTestOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_output::GetEnumV2OutputBuilder; -impl GetEnumV2FirstKnownValueTestInputBuilder { +pub use crate::operation::get_enum_v2_first_known_value_test::_get_enum_v2_input::GetEnumV2InputBuilder; + +impl GetEnumV2InputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError, > { let mut fluent_builder = client.get_enum_v2_first_known_value_test(); @@ -21,8 +24,7 @@ impl GetEnumV2FirstKnownValueTestInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumV2FirstKnownValueTestFluentBuilder { client: crate::client::Client, - inner: - crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestInputBuilder, + pub(crate) inner: crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2InputBuilder, } impl GetEnumV2FirstKnownValueTestFluentBuilder { /// Creates a new `GetEnumV2FirstKnownValueTest`. @@ -33,52 +35,40 @@ impl GetEnumV2FirstKnownValueTestFluentBuilder { } } /// Access the GetEnumV2FirstKnownValueTest as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2FirstKnownValueTestInputBuilder - { + pub fn as_input(&self) -> &crate::operation::get_enum_v2_first_known_value_test::builders::GetEnumV2InputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestOutput, + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnumV2 doesn't declare any validation, + // Using unhandled since GetEnumV2FirstKnownValueTest doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTestError::unhandled)?; - crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTest::send( - &self.client, - input, - ) - .await + crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTest::send(&self.client, input).await } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_v2_shape::SimpleEnumV2Shape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test.rs index 9fecf26d24..915d3dd2c7 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnumV2SecondKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,15 +12,14 @@ impl GetEnumV2SecondKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput, + input: crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input, ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError, > { - let inner_input = - crate::conversions::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::to_dafny(input); + let inner_input = crate::conversions::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::to_dafny(input); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2SecondKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -29,11 +30,9 @@ impl GetEnumV2SecondKnownValueTest { ), ) } else { - Err( - crate::conversions::get_enum_v2_second_known_value_test::from_dafny_error( - inner_result.error().clone(), - ), - ) + Err(crate::conversions::get_enum_v2_second_known_value_test::from_dafny_error( + inner_result.error().clone(), + )) } } } @@ -42,7 +41,7 @@ impl GetEnumV2SecondKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumV2SecondKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unsecond_known error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -115,18 +114,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetEnumV2SecondKnownValueTe ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata - for GetEnumV2SecondKnownValueTestError -{ +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumV2SecondKnownValueTestError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError - for GetEnumV2SecondKnownValueTestError -{ +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumV2SecondKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -140,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError } } -pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_output::GetEnumV2SecondKnownValueTestOutput; +pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_output::GetEnumV2Output; -pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::GetEnumV2SecondKnownValueTestInput; +pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_input::GetEnumV2Input; -mod _get_enum_v2_second_known_value_test_input; +pub(crate) mod _get_enum_v2_output; -mod _get_enum_v2_second_known_value_test_output; +pub(crate) mod _get_enum_v2_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_input.rs new file mode 100644 index 0000000000..925024a036 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2Input { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumV2Input { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumV2Input { + /// Creates a new builder-style object to manufacture [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). + pub fn builder() -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2InputBuilder { + crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2InputBuilder::default() + } +} + +/// A builder for [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2InputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2InputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Input { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_output.rs new file mode 100644 index 0000000000..2e6fc555ed --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2Output { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumV2Output { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumV2Output { + /// Creates a new builder-style object to manufacture [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). + pub fn builder() -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2OutputBuilder { + crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2OutputBuilder::default() + } +} + +/// A builder for [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2OutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2OutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs deleted file mode 100644 index d13dfd188e..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_input.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2SecondKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumV2SecondKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - &self, - ) -> ::std::option::Option { - self.value - } -} -impl GetEnumV2SecondKnownValueTestInput { - /// Creates a new builder-style object to manufacture [`GetEnumV2SecondKnownValueTestInput`](crate::operation::operation::GetEnumV2SecondKnownValueTestInput). - pub fn builder( - ) -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestInputBuilder - { - crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestInputBuilder::default() - } -} - -/// A builder for [`GetEnumV2SecondKnownValueTestInput`](crate::operation::operation::GetEnumV2SecondKnownValueTestInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2SecondKnownValueTestInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2SecondKnownValueTestInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumV2SecondKnownValueTestInput`](crate::operation::operation::GetEnumV2SecondKnownValueTestInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs deleted file mode 100644 index 39218e3ad0..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/_get_enum_v2_second_known_value_test_output.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2SecondKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumV2SecondKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - &self, - ) -> ::std::option::Option { - self.value - } -} -impl GetEnumV2SecondKnownValueTestOutput { - /// Creates a new builder-style object to manufacture [`GetEnumV2SecondKnownValueTestOutput`](crate::operation::operation::GetEnumV2SecondKnownValueTestOutput). - pub fn builder( - ) -> crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestOutputBuilder - { - crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestOutputBuilder::default() - } -} - -/// A builder for [`GetEnumV2SecondKnownValueTestOutput`](crate::operation::operation::GetEnumV2SecondKnownValueTestOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2SecondKnownValueTestOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2SecondKnownValueTestOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumV2SecondKnownValueTestOutput`](crate::operation::operation::GetEnumV2SecondKnownValueTestOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/builders.rs index 5137b217e9..13b3676202 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_second_known_value_test/builders.rs @@ -1,14 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::GetEnumV2SecondKnownValueTestInputBuilder; -pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_output::GetEnumV2SecondKnownValueTestOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_output::GetEnumV2OutputBuilder; -impl GetEnumV2SecondKnownValueTestInputBuilder { +pub use crate::operation::get_enum_v2_second_known_value_test::_get_enum_v2_input::GetEnumV2InputBuilder; + +impl GetEnumV2InputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError, > { let mut fluent_builder = client.get_enum_v2_second_known_value_test(); @@ -21,7 +24,7 @@ impl GetEnumV2SecondKnownValueTestInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumV2SecondKnownValueTestFluentBuilder { client: crate::client::Client, - inner: crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestInputBuilder, + pub(crate) inner: crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2InputBuilder, } impl GetEnumV2SecondKnownValueTestFluentBuilder { /// Creates a new `GetEnumV2SecondKnownValueTest`. @@ -32,52 +35,40 @@ impl GetEnumV2SecondKnownValueTestFluentBuilder { } } /// Access the GetEnumV2SecondKnownValueTest as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2SecondKnownValueTestInputBuilder - { + pub fn as_input(&self) -> &crate::operation::get_enum_v2_second_known_value_test::builders::GetEnumV2InputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestOutput, + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnumV2 doesn't declare any validation, + // Using unhandled since GetEnumV2SecondKnownValueTest doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTestError::unhandled)?; - crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTest::send( - &self.client, - input, - ) - .await + crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTest::send(&self.client, input).await } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_v2_shape::SimpleEnumV2Shape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test.rs index bf5efb30b6..188442ad28 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetEnumV2ThirdKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,15 +12,14 @@ impl GetEnumV2ThirdKnownValueTest { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput, + input: crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input, ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError, > { - let inner_input = - crate::conversions::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::to_dafny(input); + let inner_input = crate::conversions::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::to_dafny(input); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetEnumV2ThirdKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } @@ -29,11 +30,9 @@ impl GetEnumV2ThirdKnownValueTest { ), ) } else { - Err( - crate::conversions::get_enum_v2_third_known_value_test::from_dafny_error( - inner_result.error().clone(), - ), - ) + Err(crate::conversions::get_enum_v2_third_known_value_test::from_dafny_error( + inner_result.error().clone(), + )) } } } @@ -42,7 +41,7 @@ impl GetEnumV2ThirdKnownValueTest { #[non_exhaustive] #[derive(::std::fmt::Debug)] pub enum GetEnumV2ThirdKnownValueTestError { - /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unthird_known error code). + /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ variable wildcard pattern and check `.code()`: @@ -115,18 +114,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetEnumV2ThirdKnownValueTes ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata - for GetEnumV2ThirdKnownValueTestError -{ +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetEnumV2ThirdKnownValueTestError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError - for GetEnumV2ThirdKnownValueTestError -{ +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetEnumV2ThirdKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -140,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError } } -pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_output::GetEnumV2ThirdKnownValueTestOutput; +pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_output::GetEnumV2Output; -pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::GetEnumV2ThirdKnownValueTestInput; +pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_input::GetEnumV2Input; -mod _get_enum_v2_third_known_value_test_input; +pub(crate) mod _get_enum_v2_output; -mod _get_enum_v2_third_known_value_test_output; +pub(crate) mod _get_enum_v2_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_input.rs new file mode 100644 index 0000000000..cdfce6ed40 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2Input { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumV2Input { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumV2Input { + /// Creates a new builder-style object to manufacture [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). + pub fn builder() -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2InputBuilder { + crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2InputBuilder::default() + } +} + +/// A builder for [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2InputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2InputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumV2Input`](crate::operation::operation::GetEnumV2Input). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Input { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_output.rs new file mode 100644 index 0000000000..1799bb2d27 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetEnumV2Output { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option, +} +impl GetEnumV2Output { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option { + self.value.clone() +} +} +impl GetEnumV2Output { + /// Creates a new builder-style object to manufacture [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). + pub fn builder() -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2OutputBuilder { + crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2OutputBuilder::default() + } +} + +/// A builder for [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetEnumV2OutputBuilder { + pub(crate) value: ::std::option::Option, +} +impl GetEnumV2OutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + &self.value +} + /// Consumes the builder and constructs a [`GetEnumV2Output`](crate::operation::operation::GetEnumV2Output). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs deleted file mode 100644 index 573fb3c14b..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_input.rs +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2ThirdKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumV2ThirdKnownValueTestInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - &self, - ) -> ::std::option::Option { - self.value - } -} -impl GetEnumV2ThirdKnownValueTestInput { - /// Creates a new builder-style object to manufacture [`GetEnumV2ThirdKnownValueTestInput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestInput). - pub fn builder( - ) -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestInputBuilder - { - crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestInputBuilder::default() - } -} - -/// A builder for [`GetEnumV2ThirdKnownValueTestInput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2ThirdKnownValueTestInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2ThirdKnownValueTestInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumV2ThirdKnownValueTestInput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs deleted file mode 100644 index 588e636c9c..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/_get_enum_v2_third_known_value_test_output.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetEnumV2ThirdKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetEnumV2ThirdKnownValueTestOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - &self, - ) -> ::std::option::Option { - self.value - } -} -impl GetEnumV2ThirdKnownValueTestOutput { - /// Creates a new builder-style object to manufacture [`GetEnumV2ThirdKnownValueTestOutput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestOutput). - pub fn builder( - ) -> crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestOutputBuilder - { - crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestOutputBuilder::default() - } -} - -/// A builder for [`GetEnumV2ThirdKnownValueTestOutput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetEnumV2ThirdKnownValueTestOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetEnumV2ThirdKnownValueTestOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value( - mut self, - input: impl ::std::convert::Into, - ) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetEnumV2ThirdKnownValueTestOutput`](crate::operation::operation::GetEnumV2ThirdKnownValueTestOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/builders.rs index f1bbbe0581..84838695de 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/builders.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/operation/get_enum_v2_third_known_value_test/builders.rs @@ -1,14 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::GetEnumV2ThirdKnownValueTestInputBuilder; -pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_output::GetEnumV2ThirdKnownValueTestOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_output::GetEnumV2OutputBuilder; -impl GetEnumV2ThirdKnownValueTestInputBuilder { +pub use crate::operation::get_enum_v2_third_known_value_test::_get_enum_v2_input::GetEnumV2InputBuilder; + +impl GetEnumV2InputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError, > { let mut fluent_builder = client.get_enum_v2_third_known_value_test(); @@ -21,8 +24,7 @@ impl GetEnumV2ThirdKnownValueTestInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetEnumV2ThirdKnownValueTestFluentBuilder { client: crate::client::Client, - inner: - crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestInputBuilder, + pub(crate) inner: crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2InputBuilder, } impl GetEnumV2ThirdKnownValueTestFluentBuilder { /// Creates a new `GetEnumV2ThirdKnownValueTest`. @@ -33,52 +35,40 @@ impl GetEnumV2ThirdKnownValueTestFluentBuilder { } } /// Access the GetEnumV2ThirdKnownValueTest as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2ThirdKnownValueTestInputBuilder - { + pub fn as_input(&self) -> &crate::operation::get_enum_v2_third_known_value_test::builders::GetEnumV2InputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestOutput, + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2Output, crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError, > { let input = self .inner .build() - // Using unhandled since GetEnumV2 doesn't declare any validation, + // Using unhandled since GetEnumV2ThirdKnownValueTest doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. .map_err(crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTestError::unhandled)?; - crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTest::send( - &self.client, - input, - ) - .await + crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTest::send(&self.client, input).await } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: crate::types::simple_enum_v2_shape::SimpleEnumV2Shape) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value( - mut self, - input: ::std::option::Option, - ) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value( - &self, - ) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types.rs index 951f1e5c4a..bd9720ed21 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types.rs @@ -1,5 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -/// Types for the `SimpleIntegerConfig` +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +/// Types for the `SimpleEnumV2Config` pub mod simple_enum_v2_config; -pub mod simple_enum_v2_shape; + +mod _simple_enum_v2_shape; +pub use crate::types::_simple_enum_v2_shape::SimpleEnumV2Shape; diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/_simple_enum_v2_shape.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/_simple_enum_v2_shape.rs new file mode 100644 index 0000000000..6747128c1b --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/_simple_enum_v2_shape.rs @@ -0,0 +1,19 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[derive(Debug, PartialEq, Copy, Clone)] +pub enum SimpleEnumV2Shape { + First, +Second, +Third, +} + +impl ::std::fmt::Display for SimpleEnumV2Shape { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match self { + SimpleEnumV2Shape::First => write!(f, "FIRST"), +SimpleEnumV2Shape::Second => write!(f, "SECOND"), +SimpleEnumV2Shape::Third => write!(f, "THIRD"), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_config.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_config.rs index 37b2d81ac2..d03031da87 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_config.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_config.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleEnumV2Config {} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_shape.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_shape.rs deleted file mode 100644 index b1eb347281..0000000000 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/types/simple_enum_v2_shape.rs +++ /dev/null @@ -1,6 +0,0 @@ -#[derive(Debug, PartialEq, Copy, Clone)] -pub enum SimpleEnumV2Shape { - FIRST, - SECOND, - THIRD, -} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..4bcdd7d0f8 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::enumv2::internaldafny::wrapped::_default { + pub fn WrappedSimpleEnumV2(config: &::std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Config, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..5beee2ab3f --- /dev/null +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,179 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::enumv2::internaldafny::types::ISimpleTypesEnumV2Client); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::SimpleEnumV2Config, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_enum_v2_config::_simple_enum_v2_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::enumv2::internaldafny::types::ISimpleTypesEnumV2Client for Client { + fn GetEnumV2( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum_v2::_get_enum_v2_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum_v2::GetEnumV2::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum_v2::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum_v2::_get_enum_v2_output::to_dafny(client), + }, + ), + } + } + + fn GetEnumV2FirstKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum_v2_first_known_value_test::GetEnumV2FirstKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum_v2_first_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum_v2_first_known_value_test::_get_enum_v2_first_known_value_test_output::to_dafny(client), + }, + ), + } + } + + fn GetEnumV2SecondKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum_v2_second_known_value_test::GetEnumV2SecondKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum_v2_second_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum_v2_second_known_value_test::_get_enum_v2_second_known_value_test_output::to_dafny(client), + }, + ), + } + } + + fn GetEnumV2ThirdKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Input, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::enumv2::internaldafny::types::GetEnumV2Output, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_enum_v2_third_known_value_test::GetEnumV2ThirdKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_enum_v2_third_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_enum_v2_third_known_value_test::_get_enum_v2_third_known_value_test_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/tests/simple_enum_v2_test.rs b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/tests/simple_enum_v2_test.rs index ddf89e15e4..4ce5192c09 100644 --- a/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/tests/simple_enum_v2_test.rs +++ b/TestModels/SimpleTypes/SimpleEnumV2/runtimes/rust/tests/simple_enum_v2_test.rs @@ -1,48 +1,48 @@ -use simple_enum_v2::types::simple_enum_v2_shape::SimpleEnumV2Shape::*; +use simple_enum_v2::types::SimpleEnumV2Shape::*; use simple_enum_v2::*; #[tokio::test] async fn test_get_enum() { - let result = client().get_enum_v2().value(SECOND).send().await; + let result = client().get_enum_v2().value(Second).send().await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, SECOND); + assert_eq!(value, Second); } #[tokio::test] async fn test_get_first_known_value() { let result = client() .get_enum_v2_first_known_value_test() - .value(FIRST) + .value(First) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, FIRST); + assert_eq!(value, First); } #[tokio::test] async fn test_get_second_known_value() { let result = client() .get_enum_v2_second_known_value_test() - .value(SECOND) + .value(Second) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, SECOND); + assert_eq!(value, Second); } #[tokio::test] async fn test_get_third_known_value() { let result = client() .get_enum_v2_third_known_value_test() - .value(THIRD) + .value(Third) .send() .await; let output = result.unwrap(); let value = output.value().unwrap(); - assert_eq!(value, THIRD); + assert_eq!(value, Third); } pub fn client() -> Client { diff --git a/TestModels/SimpleTypes/SimpleInteger/Makefile b/TestModels/SimpleTypes/SimpleInteger/Makefile index bd4715b6cd..3f522f1305 100644 --- a/TestModels/SimpleTypes/SimpleInteger/Makefile +++ b/TestModels/SimpleTypes/SimpleInteger/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/Cargo.toml index d14ad003b2..3ef7587f62 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/Cargo.toml @@ -5,13 +5,19 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies.tokio] +[dev-dependencies] +simple_integer = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client.rs index a82eefe997..077a869866 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -29,11 +30,11 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } mod get_integer; -mod get_integer_known_value; +mod get_integer_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer.rs index ac241528f2..11767e3f95 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetInteger`](crate::operation::get_integer::builders::GetIntegerFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(i32)`](crate::operation::get_integer::builders::GetIntegerFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_integer::builders::GetIntegerFluentBuilder::set_value):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_integer::builders::GetIntegerFluentBuilder::value) / [`set_value(Option<::std::primitive::i32>)`](crate::operation::get_integer::builders::GetIntegerFluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetIntegerOutput`](crate::operation::get_integer::GetIntegerOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_integer::GetIntegerOutput::value): (undocumented) + /// - [`value(Option<::std::primitive::i32>)`](crate::operation::get_integer::GetIntegerOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_integer::GetIntegerError) pub fn get_integer(&self) -> crate::operation::get_integer::builders::GetIntegerFluentBuilder { crate::operation::get_integer::builders::GetIntegerFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value.rs deleted file mode 100644 index 82695c20fe..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -impl super::Client { - /// Constructs a fluent builder for the [`GetInteger`](crate::operation::get_integer_known_value::builders::GetIntegerFluentBuilder) operation. - /// - /// - The fluent builder is configurable: - /// - [`value(i32)`](crate::operation::get_integer_known_value::builders::GetIntegerFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_integer_known_value::builders::GetIntegerFluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetIntegerOutput`](crate::operation::get_integer_known_value::GetIntegerOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_integer_known_value::GetIntegerOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_integer_known_value::GetIntegerError) - pub fn get_integer_known_value( - &self, - ) -> crate::operation::get_integer_known_value::builders::GetIntegerKnownValueFluentBuilder - { - crate::operation::get_integer_known_value::builders::GetIntegerKnownValueFluentBuilder::new( - self.clone(), - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value_test.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value_test.rs new file mode 100644 index 0000000000..7612ae9e55 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/client/get_integer_known_value_test.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +impl super::Client { + /// Constructs a fluent builder for the [`GetIntegerKnownValueTest`](crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder) operation. + /// + /// - The fluent builder is configurable: + /// - [`value(impl Into>)`](crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder::value) / [`set_value(Option<::std::primitive::i32>)`](crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetIntegerOutput`](crate::operation::get_integer_known_value_test::GetIntegerOutput) with field(s): + /// - [`value(Option<::std::primitive::i32>)`](crate::operation::get_integer_known_value_test::GetIntegerOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError) + pub fn get_integer_known_value_test(&self) -> crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder { + crate::operation::get_integer_known_value_test::builders::GetIntegerKnownValueTestFluentBuilder::new(self.clone()) + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions.rs index 9d397cd054..0af6bf6b95 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions.rs @@ -1,6 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_integer; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod get_integer_known_value; + pub mod get_integer; -pub mod simple_integer_config; + pub mod get_integer_known_value_test; + + pub mod simple_integer_config; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..77c44d4372 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::integer::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer.rs index 3637ac26fa..465334c3ec 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_input.rs index 9b5403e088..03797dbbe0 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_input.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_input.rs @@ -1,37 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_integer::GetIntegerInput, ) -> ::std::rc::Rc< crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { value: v }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerInput::GetIntegerInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::oint_to_dafny(value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, >, ) -> crate::operation::get_integer::GetIntegerInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_integer::GetIntegerInput { value } + crate::operation::get_integer::GetIntegerInput::builder() + .set_value(crate::standard_library_conversions::oint_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_output.rs index 0883177221..9b8946b2ba 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_output.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer/_get_integer_output.rs @@ -1,37 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_integer::GetIntegerOutput, ) -> ::std::rc::Rc< crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput::GetIntegerOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::oint_to_dafny(value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, >, ) -> crate::operation::get_integer::GetIntegerOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_integer::GetIntegerOutput { value } + crate::operation::get_integer::GetIntegerOutput::builder() + .set_value(crate::standard_library_conversions::oint_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value.rs deleted file mode 100644 index 15c6b7c8b2..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -use std::any::Any; - -#[allow(dead_code)] -pub fn to_dafny_error( - value: crate::operation::get_integer_known_value::GetIntegerKnownValueError, -) -> ::std::rc::Rc { - match value { - crate::operation::get_integer_known_value::GetIntegerKnownValueError::Unhandled(unhandled) => - ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) - } -} - -#[allow(dead_code)] -pub fn from_dafny_error( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::Error, - >, -) -> crate::operation::get_integer_known_value::GetIntegerKnownValueError { - // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error - if matches!(&dafny_value.as_ref(), crate::r#simple::types::integer::internaldafny::types::Error::CollectionOfErrors { .. }) { - let error_message = "TODO: can't get message yet"; - crate::operation::get_integer_known_value::GetIntegerKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) - } else { - crate::operation::get_integer_known_value::GetIntegerKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) - } -} - -pub mod _get_integer_known_value_input; - -pub mod _get_integer_known_value_output; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_input.rs deleted file mode 100644 index 40db6820d4..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_input.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_integer_known_value::GetIntegerKnownValueInput, -) -> ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { value: v }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerInput::GetIntegerInput { - value: ::std::rc::Rc::new(dafny_value) - }) -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, - >, -) -> crate::operation::get_integer_known_value::GetIntegerKnownValueInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_integer_known_value::GetIntegerKnownValueInput { value } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_output.rs deleted file mode 100644 index c122e6bee4..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value/_get_integer_known_value_output.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, -) -> ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput::GetIntegerOutput { - value: ::std::rc::Rc::new(dafny_value) - }) -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, - >, -) -> crate::operation::get_integer_known_value::GetIntegerKnownValueOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_integer_known_value::GetIntegerKnownValueOutput { value } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test.rs new file mode 100644 index 0000000000..553b0b3725 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test.rs @@ -0,0 +1,33 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +#[allow(dead_code)] +pub fn to_dafny_error( + value: crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError, +) -> ::std::rc::Rc { + match value { + crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError::Unhandled(unhandled) => + ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) + } +} + +#[allow(dead_code)] +pub fn from_dafny_error( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::Error, + >, +) -> crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError { + // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error + if matches!(&dafny_value.as_ref(), crate::r#simple::types::integer::internaldafny::types::Error::CollectionOfErrors { .. }) { + let error_message = "TODO: can't get message yet"; + crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) + } else { + crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) + } +} + +pub mod _get_integer_known_value_test_input; + +pub mod _get_integer_known_value_test_output; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_input.rs new file mode 100644 index 0000000000..0b004b785b --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_input.rs @@ -0,0 +1,24 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_integer_known_value_test::GetIntegerInput, +) -> ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, +>{ + ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerInput::GetIntegerInput { + value: crate::standard_library_conversions::oint_to_dafny(value.value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, + >, +) -> crate::operation::get_integer_known_value_test::GetIntegerInput { + crate::operation::get_integer_known_value_test::GetIntegerInput::builder() + .set_value(crate::standard_library_conversions::oint_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_output.rs new file mode 100644 index 0000000000..19f8b437b6 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/get_integer_known_value_test/_get_integer_known_value_test_output.rs @@ -0,0 +1,24 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_integer_known_value_test::GetIntegerOutput, +) -> ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, +>{ + ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput::GetIntegerOutput { + value: crate::standard_library_conversions::oint_to_dafny(value.value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, + >, +) -> crate::operation::get_integer_known_value_test::GetIntegerOutput { + crate::operation::get_integer_known_value_test::GetIntegerOutput::builder() + .set_value(crate::standard_library_conversions::oint_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config.rs index f3cdb7384b..f25f66bfec 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_integer_config; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config/_simple_integer_config.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config/_simple_integer_config.rs index 360d19898b..a712be2fba 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config/_simple_integer_config.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/conversions/simple_integer_config/_simple_integer_config.rs @@ -1,10 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_integer_config::SimpleIntegerConfig, ) -> ::std::rc::Rc< - crate::simple::types::integer::internaldafny::types::SimpleIntegerConfig, + crate::r#simple::types::integer::internaldafny::types::SimpleIntegerConfig, > { ::std::rc::Rc::new(crate::r#simple::types::integer::internaldafny::types::SimpleIntegerConfig::SimpleIntegerConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/lib.rs deleted file mode 100644 index e427bffab8..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub mod implementation_from_dafny; - -pub use client::Client; -pub use types::simple_integer_config::SimpleIntegerConfig; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation.rs index faaa994cb8..94588bbdb2 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation.rs @@ -1,7 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetInteger` operation. pub mod get_integer; -/// Types for the `GetIntegerKnownValue` operation. -pub mod get_integer_known_value; +/// Types for the `GetIntegerKnownValueTest` operation. +pub mod get_integer_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer.rs index 3cb49535a7..1887a2158b 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetInteger`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -137,9 +139,9 @@ pub use crate::operation::get_integer::_get_integer_output::GetIntegerOutput; pub use crate::operation::get_integer::_get_integer_input::GetIntegerInput; -mod _get_integer_input; +pub(crate) mod _get_integer_output; -mod _get_integer_output; +pub(crate) mod _get_integer_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_input.rs index ab0c63e080..ae911475a7 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_input.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_input.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetIntegerInput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option<::std::primitive::i32>, } impl GetIntegerInput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&i32> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option<::std::primitive::i32> { + self.value +} } impl GetIntegerInput { /// Creates a new builder-style object to manufacture [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). @@ -25,23 +27,23 @@ impl GetIntegerInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetIntegerInputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option<::std::primitive::i32>, } impl GetIntegerInputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { + &self.value +} /// Consumes the builder and constructs a [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_output.rs index 49ae58c834..354b4fb6af 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_output.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/_get_integer_output.rs @@ -1,19 +1,19 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetIntegerOutput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option<::std::primitive::i32>, } - impl GetIntegerOutput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } +pub fn value(&self) -> ::std::option::Option<::std::primitive::i32> { + self.value +} } - impl GetIntegerOutput { /// Creates a new builder-style object to manufacture [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). pub fn builder() -> crate::operation::get_integer::builders::GetIntegerOutputBuilder { @@ -27,27 +27,23 @@ impl GetIntegerOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetIntegerOutputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option<::std::primitive::i32>, } - impl GetIntegerOutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } - +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { + &self.value +} /// Consumes the builder and constructs a [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/builders.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/builders.rs index 74d985a93a..f96df4a71d 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/builders.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer/builders.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_integer::_get_integer_output::GetIntegerOutputBuilder; pub use crate::operation::get_integer::_get_integer_input::GetIntegerInputBuilder; @@ -21,8 +23,8 @@ impl GetIntegerInputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetIntegerFluentBuilder { - client: crate::Client, - inner: crate::operation::get_integer::builders::GetIntegerInputBuilder, + client: crate::client::Client, + pub(crate) inner: crate::operation::get_integer::builders::GetIntegerInputBuilder, } impl GetIntegerFluentBuilder { /// Creates a new `GetInteger`. @@ -56,17 +58,17 @@ impl GetIntegerFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: i32) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_input.rs deleted file mode 100644 index 83a4b82918..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_input.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetIntegerKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetIntegerKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetIntegerKnownValueInput { - /// Creates a new builder-style object to manufacture [`GetIntegerKnownValueInput`](crate::operation::operation::GetIntegerKnownValueInput). - pub fn builder( - ) -> crate::operation::get_integer_known_value::builders::GetIntegerKnownValueInputBuilder { - crate::operation::get_integer_known_value::builders::GetIntegerKnownValueInputBuilder::default() - } -} - -/// A builder for [`GetIntegerKnownValueInput`](crate::operation::operation::GetIntegerKnownValueInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetIntegerKnownValueInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetIntegerKnownValueInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetIntegerKnownValueInput`](crate::operation::operation::GetIntegerKnownValueInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_integer_known_value::GetIntegerKnownValueInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_integer_known_value::GetIntegerKnownValueInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_output.rs deleted file mode 100644 index f80e3163bf..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/_get_integer_known_value_output.rs +++ /dev/null @@ -1,60 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetIntegerKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetIntegerKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetIntegerKnownValueOutput { - /// Creates a new builder-style object to manufacture [`GetIntegerKnownValueOutput`](crate::operation::operation::GetIntegerKnownValueOutput). - pub fn builder( - ) -> crate::operation::get_integer_known_value::builders::GetIntegerKnownValueOutputBuilder - { - crate::operation::get_integer_known_value::builders::GetIntegerKnownValueOutputBuilder::default() - } -} - -/// A builder for [`GetIntegerKnownValueOutput`](crate::operation::operation::GetIntegerKnownValueOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetIntegerKnownValueOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetIntegerKnownValueOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetIntegerKnownValueOutput`](crate::operation::operation::GetIntegerKnownValueOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_integer_known_value::GetIntegerKnownValueOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/builders.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/builders.rs deleted file mode 100644 index 9cfc99ee3a..0000000000 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value/builders.rs +++ /dev/null @@ -1,78 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_integer_known_value::_get_integer_known_value_output::GetIntegerKnownValueOutputBuilder; - -pub use crate::operation::get_integer_known_value::_get_integer_known_value_input::GetIntegerKnownValueInputBuilder; - -impl GetIntegerKnownValueInputBuilder { - /// Sends a request with this input using the given client. - pub async fn send_with( - self, - client: &crate::Client, - ) -> ::std::result::Result< - crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, - crate::operation::get_integer_known_value::GetIntegerKnownValueError, - > { - let mut fluent_builder = client.get_integer_known_value(); - fluent_builder.inner = self; - fluent_builder.send().await - } -} -/// Fluent builder constructing a request to `GetIntegerKnownValue`. -/// -#[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct GetIntegerKnownValueFluentBuilder { - client: crate::client::Client, - inner: crate::operation::get_integer_known_value::builders::GetIntegerKnownValueInputBuilder, -} -impl GetIntegerKnownValueFluentBuilder { - /// Creates a new `GetIntegerKnownValue`. - pub(crate) fn new(client: crate::client::Client) -> Self { - Self { - client, - inner: ::std::default::Default::default(), - } - } - /// Access the GetIntegerKnownValue as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_integer_known_value::builders::GetIntegerKnownValueInputBuilder - { - &self.inner - } - /// Sends the request and returns the response. - pub async fn send( - self, - ) -> ::std::result::Result< - crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, - crate::operation::get_integer_known_value::GetIntegerKnownValueError, - > { - let input = self - .inner - .build() - // Using unhandled since GetInteger doesn't declare any validation, - // and smithy-rs seems to not generate a ValidationError case unless there is - // (but isn't that a backwards compatibility problem for output structures?) - // Vanilla smithy-rs uses SdkError::construction_failure, - // but we aren't using SdkError. - .map_err( - crate::operation::get_integer_known_value::GetIntegerKnownValueError::unhandled, - )?; - crate::operation::get_integer_known_value::GetIntegerKnownValue::send(&self.client, input) - .await - } - - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: i32) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() - } -} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test.rs similarity index 67% rename from TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value.rs rename to TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test.rs index 06e0fa0cb4..0a0f7a5080 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test.rs @@ -1,49 +1,46 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -/// Orchestration and serialization glue logic for `GetIntegerKnownValue`. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +/// Orchestration and serialization glue logic for `GetIntegerKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] -pub struct GetIntegerKnownValue; -impl GetIntegerKnownValue { - /// Creates a new `GetIntegerKnownValue` +pub struct GetIntegerKnownValueTest; +impl GetIntegerKnownValueTest { + /// Creates a new `GetIntegerKnownValueTest` pub fn new() -> Self { Self } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_integer_known_value::GetIntegerKnownValueInput, + input: crate::operation::get_integer_known_value_test::GetIntegerInput, ) -> ::std::result::Result< - crate::operation::get_integer_known_value::GetIntegerKnownValueOutput, - crate::operation::get_integer_known_value::GetIntegerKnownValueError, + crate::operation::get_integer_known_value_test::GetIntegerOutput, + crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError, > { - let inner_input = - crate::conversions::get_integer_known_value::_get_integer_known_value_input::to_dafny( - input, - ); + let inner_input = crate::conversions::get_integer_known_value_test::_get_integer_known_value_test_input::to_dafny(input); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetInteger(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetIntegerKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { Ok( - crate::conversions::get_integer_known_value::_get_integer_known_value_output::from_dafny( + crate::conversions::get_integer_known_value_test::_get_integer_known_value_test_output::from_dafny( inner_result.value().clone(), ), ) } else { - Err( - crate::conversions::get_integer_known_value::from_dafny_error( - inner_result.error().clone(), - ), - ) + Err(crate::conversions::get_integer_known_value_test::from_dafny_error( + inner_result.error().clone(), + )) } } } -/// Error type for the `GetIntegerKnownValue` operation. +/// Error type for the `GetIntegerKnownValueTest` operation. #[non_exhaustive] #[derive(::std::fmt::Debug)] -pub enum GetIntegerKnownValueError { +pub enum GetIntegerKnownValueTestError { /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ @@ -51,12 +48,12 @@ pub enum GetIntegerKnownValueError { \    `err if err.code() == Some(\"SpecificExceptionCode\") => { /* handle the error */ }` \ - See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetIntegerKnownValueError) for what information is available for the error." + See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetIntegerKnownValueTestError) for what information is available for the error." )] Unhandled(crate::error::sealed_unhandled::Unhandled), } -impl GetIntegerKnownValueError { - /// Creates the `GetIntegerKnownValueError::Unhandled` variant from any error type. +impl GetIntegerKnownValueTestError { + /// Creates the `GetIntegerKnownValueTestError::Unhandled` variant from any error type. pub fn unhandled( err: impl ::std::convert::Into< ::std::boxed::Box< @@ -70,7 +67,7 @@ impl GetIntegerKnownValueError { }) } - /// Creates the `GetIntegerKnownValueError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). + /// Creates the `GetIntegerKnownValueTestError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). pub fn generic(err: ::aws_smithy_types::error::ErrorMetadata) -> Self { Self::Unhandled(crate::error::sealed_unhandled::Unhandled { source: err.clone().into(), @@ -87,14 +84,14 @@ impl GetIntegerKnownValueError { } } } -impl ::std::error::Error for GetIntegerKnownValueError { +impl ::std::error::Error for GetIntegerKnownValueTestError { fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> { match self { Self::Unhandled(_inner) => ::std::option::Option::Some(&*_inner.source), } } } -impl ::std::fmt::Display for GetIntegerKnownValueError { +impl ::std::fmt::Display for GetIntegerKnownValueTestError { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self { Self::Unhandled(_inner) => { @@ -109,7 +106,7 @@ impl ::std::fmt::Display for GetIntegerKnownValueError { } } } -impl ::aws_smithy_types::retry::ProvideErrorKind for GetIntegerKnownValueError { +impl ::aws_smithy_types::retry::ProvideErrorKind for GetIntegerKnownValueTestError { fn code(&self) -> ::std::option::Option<&str> { ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self) } @@ -117,14 +114,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetIntegerKnownValueError { ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetIntegerKnownValueError { +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetIntegerKnownValueTestError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetIntegerKnownValueError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetIntegerKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -138,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetInteg } } -pub use crate::operation::get_integer_known_value::_get_integer_known_value_output::GetIntegerKnownValueOutput; +pub use crate::operation::get_integer_known_value_test::_get_integer_output::GetIntegerOutput; -pub use crate::operation::get_integer_known_value::_get_integer_known_value_input::GetIntegerKnownValueInput; +pub use crate::operation::get_integer_known_value_test::_get_integer_input::GetIntegerInput; -mod _get_integer_known_value_input; +pub(crate) mod _get_integer_output; -mod _get_integer_known_value_output; +pub(crate) mod _get_integer_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_input.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_input.rs new file mode 100644 index 0000000000..43e834f3de --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetIntegerInput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::primitive::i32>, +} +impl GetIntegerInput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::primitive::i32> { + self.value +} +} +impl GetIntegerInput { + /// Creates a new builder-style object to manufacture [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). + pub fn builder() -> crate::operation::get_integer_known_value_test::builders::GetIntegerInputBuilder { + crate::operation::get_integer_known_value_test::builders::GetIntegerInputBuilder::default() + } +} + +/// A builder for [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetIntegerInputBuilder { + pub(crate) value: ::std::option::Option<::std::primitive::i32>, +} +impl GetIntegerInputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { + &self.value +} + /// Consumes the builder and constructs a [`GetIntegerInput`](crate::operation::operation::GetIntegerInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_integer_known_value_test::GetIntegerInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_integer_known_value_test::GetIntegerInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_output.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_output.rs new file mode 100644 index 0000000000..c1c00f46eb --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/_get_integer_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetIntegerOutput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::primitive::i32>, +} +impl GetIntegerOutput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::primitive::i32> { + self.value +} +} +impl GetIntegerOutput { + /// Creates a new builder-style object to manufacture [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). + pub fn builder() -> crate::operation::get_integer_known_value_test::builders::GetIntegerOutputBuilder { + crate::operation::get_integer_known_value_test::builders::GetIntegerOutputBuilder::default() + } +} + +/// A builder for [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetIntegerOutputBuilder { + pub(crate) value: ::std::option::Option<::std::primitive::i32>, +} +impl GetIntegerOutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { + &self.value +} + /// Consumes the builder and constructs a [`GetIntegerOutput`](crate::operation::operation::GetIntegerOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_integer_known_value_test::GetIntegerOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_integer_known_value_test::GetIntegerOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/builders.rs new file mode 100644 index 0000000000..a7554ca939 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/operation/get_integer_known_value_test/builders.rs @@ -0,0 +1,74 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_integer_known_value_test::_get_integer_output::GetIntegerOutputBuilder; + +pub use crate::operation::get_integer_known_value_test::_get_integer_input::GetIntegerInputBuilder; + +impl GetIntegerInputBuilder { + /// Sends a request with this input using the given client. + pub async fn send_with( + self, + client: &crate::Client, + ) -> ::std::result::Result< + crate::operation::get_integer_known_value_test::GetIntegerOutput, + crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError, + > { + let mut fluent_builder = client.get_integer_known_value_test(); + fluent_builder.inner = self; + fluent_builder.send().await + } +} +/// Fluent builder constructing a request to `GetIntegerKnownValueTest`. +/// +#[derive(::std::clone::Clone, ::std::fmt::Debug)] +pub struct GetIntegerKnownValueTestFluentBuilder { + client: crate::client::Client, + pub(crate) inner: crate::operation::get_integer_known_value_test::builders::GetIntegerInputBuilder, +} +impl GetIntegerKnownValueTestFluentBuilder { + /// Creates a new `GetIntegerKnownValueTest`. + pub(crate) fn new(client: crate::client::Client) -> Self { + Self { + client, + inner: ::std::default::Default::default(), + } + } + /// Access the GetIntegerKnownValueTest as a reference. + pub fn as_input(&self) -> &crate::operation::get_integer_known_value_test::builders::GetIntegerInputBuilder { + &self.inner + } + /// Sends the request and returns the response. + pub async fn send( + self, + ) -> ::std::result::Result< + crate::operation::get_integer_known_value_test::GetIntegerOutput, + crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError, + > { + let input = self + .inner + .build() + // Using unhandled since GetIntegerKnownValueTest doesn't declare any validation, + // and smithy-rs seems to not generate a ValidationError case unless there is + // (but isn't that a backwards compatibility problem for output structures?) + // Vanilla smithy-rs uses SdkError::construction_failure, + // but we aren't using SdkError. + .map_err(crate::operation::get_integer_known_value_test::GetIntegerKnownValueTestError::unhandled)?; + crate::operation::get_integer_known_value_test::GetIntegerKnownValueTest::send(&self.client, input).await + } + + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i32>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i32>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i32> { + self.inner.get_value() +} +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types.rs index 0ab755433a..646cdced26 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `SimpleIntegerConfig` pub mod simple_integer_config; diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types/simple_integer_config.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types/simple_integer_config.rs index 15a5df4737..4851f5748c 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types/simple_integer_config.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/types/simple_integer_config.rs @@ -1,9 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct SimpleIntegerConfig { - // XXX : ::std::option::Option -} +pub struct SimpleIntegerConfig {} impl SimpleIntegerConfig { pub fn builder() -> SimpleIntegerConfigBuilder { @@ -12,17 +11,12 @@ impl SimpleIntegerConfig { } #[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct SimpleIntegerConfigBuilder { - // XXX : ::std::option::Option -} +pub struct SimpleIntegerConfigBuilder {} impl SimpleIntegerConfigBuilder { /// Creates a new `SimpleIntegerConfigBuilder`. pub(crate) fn new() -> Self { - Self { - // XXX = ::std::option::Option::None - // somewhere get default values for things? - } + Self {} } pub fn build( self, @@ -30,19 +24,4 @@ impl SimpleIntegerConfigBuilder { { ::std::result::Result::Ok(SimpleIntegerConfig {}) } - /* - pub fn XXX(mut self, input: impl ::std::convert::Into) -> Self { - self.XXX = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_XXX(mut self, input: ::std::option::Option) -> Self { - self.XXX = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_XXX(&self) -> &::std::option::Option { - &self.XXX - } - */ } diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..77a3cb4cd4 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::integer::internaldafny::wrapped::_default { + pub fn WrappedSimpleInteger(config: &::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::SimpleIntegerConfig, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..2df771a408 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,119 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::integer::internaldafny::types::ISimpleTypesIntegerClient); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::SimpleIntegerConfig, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_integer_config::_simple_integer_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::integer::internaldafny::types::ISimpleTypesIntegerClient for Client { + fn GetInteger( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_integer::_get_integer_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_integer::GetInteger::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_integer::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_integer::_get_integer_output::to_dafny(client), + }, + ), + } + } + + fn GetIntegerKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::integer::internaldafny::types::GetIntegerOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_integer_known_value_test::_get_integer_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_integer_known_value_test::GetIntegerKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_integer_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_integer_known_value_test::_get_integer_known_value_test_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/tests/simple_integer_test.rs b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/tests/simple_integer_test.rs index 432eb5450c..a48b2d5df6 100644 --- a/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/tests/simple_integer_test.rs +++ b/TestModels/SimpleTypes/SimpleInteger/runtimes/rust/tests/simple_integer_test.rs @@ -10,7 +10,7 @@ async fn test_get_integer() { #[tokio::test] async fn test_get_known_value() { - let result = client().get_integer_known_value().value(20).send().await; + let result = client().get_integer_known_value_test().value(20).send().await; let output = result.unwrap(); let value = output.value().unwrap(); assert_eq!(value, 20); diff --git a/TestModels/SimpleTypes/SimpleLong/Makefile b/TestModels/SimpleTypes/SimpleLong/Makefile index ff21e566bb..30f5ebd1a4 100644 --- a/TestModels/SimpleTypes/SimpleLong/Makefile +++ b/TestModels/SimpleTypes/SimpleLong/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/Cargo.toml index 6fa3747d29..9c0ced7f0a 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/Cargo.toml @@ -5,13 +5,19 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies.tokio] +[dev-dependencies] +simple_long = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] version = "1.26.0" features = ["full"] diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client.rs index 0529ead1f9..6ec9bcc3e4 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -29,11 +30,11 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } mod get_long; -mod get_long_known_value; +mod get_long_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long.rs index acd51ffb21..d420786f93 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetLong`](crate::operation::get_long::builders::GetLongFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(i64)`](crate::operation::get_long::builders::GetLongFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_long::builders::GetLongFluentBuilder::set_value):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_long::builders::GetLongFluentBuilder::value) / [`set_value(Option<::std::primitive::i64>)`](crate::operation::get_long::builders::GetLongFluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetLongOutput`](crate::operation::get_long::GetLongOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_long::GetLongOutput::value): (undocumented) + /// - [`value(Option<::std::primitive::i64>)`](crate::operation::get_long::GetLongOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_long::GetLongError) pub fn get_long(&self) -> crate::operation::get_long::builders::GetLongFluentBuilder { crate::operation::get_long::builders::GetLongFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value.rs deleted file mode 100644 index 197e3f5bef..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value.rs +++ /dev/null @@ -1,17 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -impl super::Client { - /// Constructs a fluent builder for the [`GetLong`](crate::operation::get_long_known_value::builders::GetLongFluentBuilder) operation. - /// - /// - The fluent builder is configurable: - /// - [`value(i64)`](crate::operation::get_long_known_value::builders::GetLongFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_long_known_value::builders::GetLongFluentBuilder::set_value):(undocumented)
- /// - On success, responds with [`GetLongOutput`](crate::operation::get_long_known_value::GetLongOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_long_known_value::GetLongOutput::value): (undocumented) - /// - On failure, responds with [`SdkError`](crate::operation::get_long_known_value::GetLongError) - pub fn get_long_known_value( - &self, - ) -> crate::operation::get_long_known_value::builders::GetLongKnownValueFluentBuilder { - crate::operation::get_long_known_value::builders::GetLongKnownValueFluentBuilder::new( - self.clone(), - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value_test.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value_test.rs new file mode 100644 index 0000000000..d0cc474cc5 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/client/get_long_known_value_test.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +impl super::Client { + /// Constructs a fluent builder for the [`GetLongKnownValueTest`](crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder) operation. + /// + /// - The fluent builder is configurable: + /// - [`value(impl Into>)`](crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder::value) / [`set_value(Option<::std::primitive::i64>)`](crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetLongOutput`](crate::operation::get_long_known_value_test::GetLongOutput) with field(s): + /// - [`value(Option<::std::primitive::i64>)`](crate::operation::get_long_known_value_test::GetLongOutput::value): (undocumented) + /// - On failure, responds with [`SdkError`](crate::operation::get_long_known_value_test::GetLongKnownValueTestError) + pub fn get_long_known_value_test(&self) -> crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder { + crate::operation::get_long_known_value_test::builders::GetLongKnownValueTestFluentBuilder::new(self.clone()) + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions.rs index 4ff5bcbc92..a0cb33c551 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions.rs @@ -1,6 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_long; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod get_long_known_value; + pub mod get_long; -pub mod simple_long_config; + pub mod get_long_known_value_test; + + pub mod simple_long_config; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..4d0aeedd1a --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::smithylong::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long.rs index 59558ca19b..210e9a6d0d 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_input.rs index 8392959724..9b4211a3da 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_input.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_input.rs @@ -1,37 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_long::GetLongInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { value: v }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongInput::GetLongInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::olong_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, >, ) -> crate::operation::get_long::GetLongInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_long::GetLongInput { value } + crate::operation::get_long::GetLongInput::builder() + .set_value(crate::standard_library_conversions::olong_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_output.rs index 68ff34defe..4bbf353650 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_output.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long/_get_long_output.rs @@ -1,37 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_long::GetLongOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput::GetLongOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::olong_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, >, ) -> crate::operation::get_long::GetLongOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_long::GetLongOutput { value } + crate::operation::get_long::GetLongOutput::builder() + .set_value(crate::standard_library_conversions::olong_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value.rs deleted file mode 100644 index f4c90a3a2b..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -use std::any::Any; - -#[allow(dead_code)] -pub fn to_dafny_error( - value: crate::operation::get_long_known_value::GetLongKnownValueError, -) -> ::std::rc::Rc { - match value { - crate::operation::get_long_known_value::GetLongKnownValueError::Unhandled(unhandled) => - ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) - } -} - -#[allow(dead_code)] -pub fn from_dafny_error( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::Error, - >, -) -> crate::operation::get_long_known_value::GetLongKnownValueError { - // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error - if matches!(&dafny_value.as_ref(), crate::r#simple::types::smithylong::internaldafny::types::Error::CollectionOfErrors { .. }) { - let error_message = "TODO: can't get message yet"; - crate::operation::get_long_known_value::GetLongKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) - } else { - crate::operation::get_long_known_value::GetLongKnownValueError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) - } -} - -pub mod _get_long_known_value_input; - -pub mod _get_long_known_value_output; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_input.rs deleted file mode 100644 index aae399058f..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_input.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_long_known_value::GetLongKnownValueInput, -) -> ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, -> { - let dafny_value = match value.value { - Some(v) => crate::_Wrappers_Compile::Option::Some { value: v }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongInput::GetLongInput { - value: ::std::rc::Rc::new(dafny_value) - }) -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, - >, -) -> crate::operation::get_long_known_value::GetLongKnownValueInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_long_known_value::GetLongKnownValueInput { value } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_output.rs deleted file mode 100644 index bdc927aae1..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value/_get_long_known_value_output.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(dead_code)] -pub fn to_dafny( - value: crate::operation::get_long_known_value::GetLongKnownValueOutput, -) -> ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, -> { - let dafny_value = match value.value { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput::GetLongOutput { - value: ::std::rc::Rc::new(dafny_value) - }) -} - -#[allow(dead_code)] -pub fn from_dafny( - dafny_value: ::std::rc::Rc< - crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, - >, -) -> crate::operation::get_long_known_value::GetLongKnownValueOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some(dafny_value.value().Extract()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_long_known_value::GetLongKnownValueOutput { value } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test.rs new file mode 100644 index 0000000000..5550a2e767 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test.rs @@ -0,0 +1,33 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +#[allow(dead_code)] +pub fn to_dafny_error( + value: crate::operation::get_long_known_value_test::GetLongKnownValueTestError, +) -> ::std::rc::Rc { + match value { + crate::operation::get_long_known_value_test::GetLongKnownValueTestError::Unhandled(unhandled) => + ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) + } +} + +#[allow(dead_code)] +pub fn from_dafny_error( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::Error, + >, +) -> crate::operation::get_long_known_value_test::GetLongKnownValueTestError { + // TODO: Losing information here, but we have to figure out how to wrap an arbitrary Dafny value as std::error::Error + if matches!(&dafny_value.as_ref(), crate::r#simple::types::smithylong::internaldafny::types::Error::CollectionOfErrors { .. }) { + let error_message = "TODO: can't get message yet"; + crate::operation::get_long_known_value_test::GetLongKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message(error_message).build()) + } else { + crate::operation::get_long_known_value_test::GetLongKnownValueTestError::generic(::aws_smithy_types::error::metadata::ErrorMetadata::builder().message("Opaque error").build()) + } +} + +pub mod _get_long_known_value_test_input; + +pub mod _get_long_known_value_test_output; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_input.rs new file mode 100644 index 0000000000..67c44ec3c3 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_input.rs @@ -0,0 +1,24 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_long_known_value_test::GetLongInput, +) -> ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, +>{ + ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongInput::GetLongInput { + value: crate::standard_library_conversions::olong_to_dafny(&value.value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, + >, +) -> crate::operation::get_long_known_value_test::GetLongInput { + crate::operation::get_long_known_value_test::GetLongInput::builder() + .set_value(crate::standard_library_conversions::olong_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_output.rs new file mode 100644 index 0000000000..859142fbf6 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/get_long_known_value_test/_get_long_known_value_test_output.rs @@ -0,0 +1,24 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(dead_code)] +pub fn to_dafny( + value: crate::operation::get_long_known_value_test::GetLongOutput, +) -> ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, +>{ + ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput::GetLongOutput { + value: crate::standard_library_conversions::olong_to_dafny(&value.value), + }) +} + #[allow(dead_code)] +pub fn from_dafny( + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, + >, +) -> crate::operation::get_long_known_value_test::GetLongOutput { + crate::operation::get_long_known_value_test::GetLongOutput::builder() + .set_value(crate::standard_library_conversions::olong_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config.rs index 129c7eb442..644ecd05da 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_long_config; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config/_simple_long_config.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config/_simple_long_config.rs index 4bb610c4d2..1371539ba8 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config/_simple_long_config.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/conversions/simple_long_config/_simple_long_config.rs @@ -1,10 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_long_config::SimpleLongConfig, ) -> ::std::rc::Rc< - crate::simple::types::smithylong::internaldafny::types::SimpleLongConfig, + crate::r#simple::types::smithylong::internaldafny::types::SimpleLongConfig, > { ::std::rc::Rc::new(crate::r#simple::types::smithylong::internaldafny::types::SimpleLongConfig::SimpleLongConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/lib.rs deleted file mode 100644 index 1248f58305..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub mod implementation_from_dafny; - -pub use client::Client; -pub use types::simple_long_config::SimpleLongConfig; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation.rs index 9378720071..4584907aea 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation.rs @@ -1,7 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetLong` operation. pub mod get_long; -/// Types for the `GetLongKnownValue` operation. -pub mod get_long_known_value; +/// Types for the `GetLongKnownValueTest` operation. +pub mod get_long_known_value_test; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long.rs index 44259e5ba4..a7387cce96 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetLong`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -16,14 +18,17 @@ impl GetLong { crate::operation::get_long::GetLongError, > { let inner_input = crate::conversions::get_long::_get_long_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetLong(&inner_input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetLong(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - Ok(crate::conversions::get_long::_get_long_output::from_dafny( - inner_result.value().clone(), - )) + Ok( + crate::conversions::get_long::_get_long_output::from_dafny( + inner_result.value().clone(), + ), + ) } else { Err(crate::conversions::get_long::from_dafny_error( inner_result.error().clone(), @@ -134,9 +139,9 @@ pub use crate::operation::get_long::_get_long_output::GetLongOutput; pub use crate::operation::get_long::_get_long_input::GetLongInput; -mod _get_long_input; +pub(crate) mod _get_long_output; -mod _get_long_output; +pub(crate) mod _get_long_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_input.rs index cf4ca97a0f..0f9e90cd9c 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_input.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_input.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetLongInput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option<::std::primitive::i64>, } impl GetLongInput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&i64> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option<::std::primitive::i64> { + self.value +} } impl GetLongInput { /// Creates a new builder-style object to manufacture [`GetLongInput`](crate::operation::operation::GetLongInput). @@ -25,23 +27,23 @@ impl GetLongInput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetLongInputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option<::std::primitive::i64>, } impl GetLongInputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { + &self.value +} /// Consumes the builder and constructs a [`GetLongInput`](crate::operation::operation::GetLongInput). pub fn build( self, @@ -49,6 +51,8 @@ impl GetLongInputBuilder { crate::operation::get_long::GetLongInput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_long::GetLongInput { value: self.value }) + ::std::result::Result::Ok(crate::operation::get_long::GetLongInput { + value: self.value, + }) } } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_output.rs index 5a2814c686..86950e84ce 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_output.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/_get_long_output.rs @@ -1,19 +1,19 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetLongOutput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, +pub value: ::std::option::Option<::std::primitive::i64>, } - impl GetLongOutput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } +pub fn value(&self) -> ::std::option::Option<::std::primitive::i64> { + self.value +} } - impl GetLongOutput { /// Creates a new builder-style object to manufacture [`GetLongOutput`](crate::operation::operation::GetLongOutput). pub fn builder() -> crate::operation::get_long::builders::GetLongOutputBuilder { @@ -27,27 +27,23 @@ impl GetLongOutput { ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, )] pub struct GetLongOutputBuilder { - pub(crate) value: ::std::option::Option, + pub(crate) value: ::std::option::Option<::std::primitive::i64>, } - impl GetLongOutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } - +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { + &self.value +} /// Consumes the builder and constructs a [`GetLongOutput`](crate::operation::operation::GetLongOutput). pub fn build( self, @@ -55,6 +51,8 @@ impl GetLongOutputBuilder { crate::operation::get_long::GetLongOutput, ::aws_smithy_types::error::operation::BuildError, > { - ::std::result::Result::Ok(crate::operation::get_long::GetLongOutput { value: self.value }) + ::std::result::Result::Ok(crate::operation::get_long::GetLongOutput { + value: self.value, + }) } } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/builders.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/builders.rs index cf89d6b34d..5cdbbd256e 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/builders.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long/builders.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_long::_get_long_output::GetLongOutputBuilder; pub use crate::operation::get_long::_get_long_input::GetLongInputBuilder; @@ -22,7 +24,7 @@ impl GetLongInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetLongFluentBuilder { client: crate::client::Client, - inner: crate::operation::get_long::builders::GetLongInputBuilder, + pub(crate) inner: crate::operation::get_long::builders::GetLongInputBuilder, } impl GetLongFluentBuilder { /// Creates a new `GetLong`. @@ -56,17 +58,17 @@ impl GetLongFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: i64) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_input.rs deleted file mode 100644 index b1b4d3bece..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_input.rs +++ /dev/null @@ -1,57 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetLongKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetLongKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetLongKnownValueInput { - /// Creates a new builder-style object to manufacture [`GetLongKnownValueInput`](crate::operation::operation::GetLongKnownValueInput). - pub fn builder( - ) -> crate::operation::get_long_known_value::builders::GetLongKnownValueInputBuilder { - crate::operation::get_long_known_value::builders::GetLongKnownValueInputBuilder::default() - } -} - -/// A builder for [`GetLongKnownValueInput`](crate::operation::operation::GetLongKnownValueInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetLongKnownValueInputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetLongKnownValueInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetLongKnownValueInput`](crate::operation::operation::GetLongKnownValueInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_long_known_value::GetLongKnownValueInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_long_known_value::GetLongKnownValueInput { value: self.value }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_output.rs deleted file mode 100644 index b18b9c89a4..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/_get_long_known_value_output.rs +++ /dev/null @@ -1,57 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetLongKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option, -} -impl GetLongKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option { - self.value - } -} -impl GetLongKnownValueOutput { - /// Creates a new builder-style object to manufacture [`GetLongKnownValueOutput`](crate::operation::operation::GetLongKnownValueOutput). - pub fn builder( - ) -> crate::operation::get_long_known_value::builders::GetLongKnownValueOutputBuilder { - crate::operation::get_long_known_value::builders::GetLongKnownValueOutputBuilder::default() - } -} - -/// A builder for [`GetLongKnownValueOutput`](crate::operation::operation::GetLongKnownValueOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetLongKnownValueOutputBuilder { - pub(crate) value: ::std::option::Option, -} -impl GetLongKnownValueOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - &self.value - } - /// Consumes the builder and constructs a [`GetLongKnownValueOutput`](crate::operation::operation::GetLongKnownValueOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_long_known_value::GetLongKnownValueOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_long_known_value::GetLongKnownValueOutput { value: self.value }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/builders.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/builders.rs deleted file mode 100644 index 46a4de5e36..0000000000 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value/builders.rs +++ /dev/null @@ -1,74 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_long_known_value::_get_long_known_value_output::GetLongKnownValueOutputBuilder; - -pub use crate::operation::get_long_known_value::_get_long_known_value_input::GetLongKnownValueInputBuilder; - -impl GetLongKnownValueInputBuilder { - /// Sends a request with this input using the given client. - pub async fn send_with( - self, - client: &crate::Client, - ) -> ::std::result::Result< - crate::operation::get_long_known_value::GetLongKnownValueOutput, - crate::operation::get_long_known_value::GetLongKnownValueError, - > { - let mut fluent_builder = client.get_long_known_value(); - fluent_builder.inner = self; - fluent_builder.send().await - } -} -/// Fluent builder constructing a request to `GetLongKnownValue`. -/// -#[derive(::std::clone::Clone, ::std::fmt::Debug)] -pub struct GetLongKnownValueFluentBuilder { - client: crate::client::Client, - inner: crate::operation::get_long_known_value::builders::GetLongKnownValueInputBuilder, -} -impl GetLongKnownValueFluentBuilder { - /// Creates a new `GetLongKnownValue`. - pub(crate) fn new(client: crate::client::Client) -> Self { - Self { - client, - inner: ::std::default::Default::default(), - } - } - /// Access the GetLongKnownValue as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_long_known_value::builders::GetLongKnownValueInputBuilder { - &self.inner - } - /// Sends the request and returns the response. - pub async fn send( - self, - ) -> ::std::result::Result< - crate::operation::get_long_known_value::GetLongKnownValueOutput, - crate::operation::get_long_known_value::GetLongKnownValueError, - > { - let input = self - .inner - .build() - // Using unhandled since GetLong doesn't declare any validation, - // and smithy-rs seems to not generate a ValidationError case unless there is - // (but isn't that a backwards compatibility problem for output structures?) - // Vanilla smithy-rs uses SdkError::construction_failure, - // but we aren't using SdkError. - .map_err(crate::operation::get_long_known_value::GetLongKnownValueError::unhandled)?; - crate::operation::get_long_known_value::GetLongKnownValue::send(&self.client, input).await - } - - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: i64) -> Self { - self.inner = self.inner.value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option { - self.inner.get_value() - } -} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test.rs similarity index 67% rename from TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value.rs rename to TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test.rs index b434182d0d..ce1f24b47b 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test.rs @@ -1,44 +1,46 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -/// Orchestration and serialization glue logic for `GetLongKnownValue`. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +/// Orchestration and serialization glue logic for `GetLongKnownValueTest`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] -pub struct GetLongKnownValue; -impl GetLongKnownValue { - /// Creates a new `GetLongKnownValue` +pub struct GetLongKnownValueTest; +impl GetLongKnownValueTest { + /// Creates a new `GetLongKnownValueTest` pub fn new() -> Self { Self } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_long_known_value::GetLongKnownValueInput, + input: crate::operation::get_long_known_value_test::GetLongInput, ) -> ::std::result::Result< - crate::operation::get_long_known_value::GetLongKnownValueOutput, - crate::operation::get_long_known_value::GetLongKnownValueError, + crate::operation::get_long_known_value_test::GetLongOutput, + crate::operation::get_long_known_value_test::GetLongKnownValueTestError, > { - let inner_input = - crate::conversions::get_long_known_value::_get_long_known_value_input::to_dafny(input); - let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetLong(&inner_input); + let inner_input = crate::conversions::get_long_known_value_test::_get_long_known_value_test_input::to_dafny(input); + let inner_result = + ::dafny_runtime::md!(client.dafny_client.clone()).GetLongKnownValueTest(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { Ok( - crate::conversions::get_long_known_value::_get_long_known_value_output::from_dafny( + crate::conversions::get_long_known_value_test::_get_long_known_value_test_output::from_dafny( inner_result.value().clone(), ), ) } else { - Err(crate::conversions::get_long_known_value::from_dafny_error( + Err(crate::conversions::get_long_known_value_test::from_dafny_error( inner_result.error().clone(), )) } } } -/// Error type for the `GetLongKnownValue` operation. +/// Error type for the `GetLongKnownValueTest` operation. #[non_exhaustive] #[derive(::std::fmt::Debug)] -pub enum GetLongKnownValueError { +pub enum GetLongKnownValueTestError { /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). #[deprecated( note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \ @@ -46,12 +48,12 @@ pub enum GetLongKnownValueError { \    `err if err.code() == Some(\"SpecificExceptionCode\") => { /* handle the error */ }` \ - See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetLongKnownValueError) for what information is available for the error." + See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetLongKnownValueTestError) for what information is available for the error." )] Unhandled(crate::error::sealed_unhandled::Unhandled), } -impl GetLongKnownValueError { - /// Creates the `GetLongKnownValueError::Unhandled` variant from any error type. +impl GetLongKnownValueTestError { + /// Creates the `GetLongKnownValueTestError::Unhandled` variant from any error type. pub fn unhandled( err: impl ::std::convert::Into< ::std::boxed::Box< @@ -65,7 +67,7 @@ impl GetLongKnownValueError { }) } - /// Creates the `GetLongKnownValueError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). + /// Creates the `GetLongKnownValueTestError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata). pub fn generic(err: ::aws_smithy_types::error::ErrorMetadata) -> Self { Self::Unhandled(crate::error::sealed_unhandled::Unhandled { source: err.clone().into(), @@ -82,14 +84,14 @@ impl GetLongKnownValueError { } } } -impl ::std::error::Error for GetLongKnownValueError { +impl ::std::error::Error for GetLongKnownValueTestError { fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> { match self { Self::Unhandled(_inner) => ::std::option::Option::Some(&*_inner.source), } } } -impl ::std::fmt::Display for GetLongKnownValueError { +impl ::std::fmt::Display for GetLongKnownValueTestError { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self { Self::Unhandled(_inner) => { @@ -104,7 +106,7 @@ impl ::std::fmt::Display for GetLongKnownValueError { } } } -impl ::aws_smithy_types::retry::ProvideErrorKind for GetLongKnownValueError { +impl ::aws_smithy_types::retry::ProvideErrorKind for GetLongKnownValueTestError { fn code(&self) -> ::std::option::Option<&str> { ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self) } @@ -112,14 +114,14 @@ impl ::aws_smithy_types::retry::ProvideErrorKind for GetLongKnownValueError { ::std::option::Option::None } } -impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetLongKnownValueError { +impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetLongKnownValueTestError { fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::Unhandled(_inner) => &_inner.meta, } } } -impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetLongKnownValueError { +impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetLongKnownValueTestError { fn create_unhandled_error( source: ::std::boxed::Box< dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static, @@ -133,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetLongK } } -pub use crate::operation::get_long_known_value::_get_long_known_value_output::GetLongKnownValueOutput; +pub use crate::operation::get_long_known_value_test::_get_long_output::GetLongOutput; -pub use crate::operation::get_long_known_value::_get_long_known_value_input::GetLongKnownValueInput; +pub use crate::operation::get_long_known_value_test::_get_long_input::GetLongInput; -mod _get_long_known_value_input; +pub(crate) mod _get_long_output; -mod _get_long_known_value_output; +pub(crate) mod _get_long_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_input.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_input.rs new file mode 100644 index 0000000000..3549b72552 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetLongInput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::primitive::i64>, +} +impl GetLongInput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::primitive::i64> { + self.value +} +} +impl GetLongInput { + /// Creates a new builder-style object to manufacture [`GetLongInput`](crate::operation::operation::GetLongInput). + pub fn builder() -> crate::operation::get_long_known_value_test::builders::GetLongInputBuilder { + crate::operation::get_long_known_value_test::builders::GetLongInputBuilder::default() + } +} + +/// A builder for [`GetLongInput`](crate::operation::operation::GetLongInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetLongInputBuilder { + pub(crate) value: ::std::option::Option<::std::primitive::i64>, +} +impl GetLongInputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { + &self.value +} + /// Consumes the builder and constructs a [`GetLongInput`](crate::operation::operation::GetLongInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_long_known_value_test::GetLongInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_long_known_value_test::GetLongInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_output.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_output.rs new file mode 100644 index 0000000000..60d05a1481 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/_get_long_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetLongOutput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::primitive::i64>, +} +impl GetLongOutput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::primitive::i64> { + self.value +} +} +impl GetLongOutput { + /// Creates a new builder-style object to manufacture [`GetLongOutput`](crate::operation::operation::GetLongOutput). + pub fn builder() -> crate::operation::get_long_known_value_test::builders::GetLongOutputBuilder { + crate::operation::get_long_known_value_test::builders::GetLongOutputBuilder::default() + } +} + +/// A builder for [`GetLongOutput`](crate::operation::operation::GetLongOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetLongOutputBuilder { + pub(crate) value: ::std::option::Option<::std::primitive::i64>, +} +impl GetLongOutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { + &self.value +} + /// Consumes the builder and constructs a [`GetLongOutput`](crate::operation::operation::GetLongOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_long_known_value_test::GetLongOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_long_known_value_test::GetLongOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/builders.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/builders.rs new file mode 100644 index 0000000000..a79b8a361b --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/operation/get_long_known_value_test/builders.rs @@ -0,0 +1,74 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_long_known_value_test::_get_long_output::GetLongOutputBuilder; + +pub use crate::operation::get_long_known_value_test::_get_long_input::GetLongInputBuilder; + +impl GetLongInputBuilder { + /// Sends a request with this input using the given client. + pub async fn send_with( + self, + client: &crate::Client, + ) -> ::std::result::Result< + crate::operation::get_long_known_value_test::GetLongOutput, + crate::operation::get_long_known_value_test::GetLongKnownValueTestError, + > { + let mut fluent_builder = client.get_long_known_value_test(); + fluent_builder.inner = self; + fluent_builder.send().await + } +} +/// Fluent builder constructing a request to `GetLongKnownValueTest`. +/// +#[derive(::std::clone::Clone, ::std::fmt::Debug)] +pub struct GetLongKnownValueTestFluentBuilder { + client: crate::client::Client, + pub(crate) inner: crate::operation::get_long_known_value_test::builders::GetLongInputBuilder, +} +impl GetLongKnownValueTestFluentBuilder { + /// Creates a new `GetLongKnownValueTest`. + pub(crate) fn new(client: crate::client::Client) -> Self { + Self { + client, + inner: ::std::default::Default::default(), + } + } + /// Access the GetLongKnownValueTest as a reference. + pub fn as_input(&self) -> &crate::operation::get_long_known_value_test::builders::GetLongInputBuilder { + &self.inner + } + /// Sends the request and returns the response. + pub async fn send( + self, + ) -> ::std::result::Result< + crate::operation::get_long_known_value_test::GetLongOutput, + crate::operation::get_long_known_value_test::GetLongKnownValueTestError, + > { + let input = self + .inner + .build() + // Using unhandled since GetLongKnownValueTest doesn't declare any validation, + // and smithy-rs seems to not generate a ValidationError case unless there is + // (but isn't that a backwards compatibility problem for output structures?) + // Vanilla smithy-rs uses SdkError::construction_failure, + // but we aren't using SdkError. + .map_err(crate::operation::get_long_known_value_test::GetLongKnownValueTestError::unhandled)?; + crate::operation::get_long_known_value_test::GetLongKnownValueTest::send(&self.client, input).await + } + + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::primitive::i64>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::primitive::i64>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::primitive::i64> { + self.inner.get_value() +} +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types.rs index f8ff6d665a..d9223fcb30 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `SimpleLongConfig` pub mod simple_long_config; diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types/simple_long_config.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types/simple_long_config.rs index 7def54c032..5df8e1ebfc 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types/simple_long_config.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/types/simple_long_config.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleLongConfig {} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..ef8910b03c --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::smithylong::internaldafny::wrapped::_default { + pub fn WrappedSimpleLong(config: &::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::SimpleLongConfig, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..5b4a2bf9c4 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,119 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::smithylong::internaldafny::types::ISimpleTypesLongClient); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::SimpleLongConfig, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_long_config::_simple_long_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::smithylong::internaldafny::types::ISimpleTypesLongClient for Client { + fn GetLong( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_long::_get_long_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_long::GetLong::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_long::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_long::_get_long_output::to_dafny(client), + }, + ), + } + } + + fn GetLongKnownValueTest( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithylong::internaldafny::types::GetLongOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_long_known_value_test::_get_long_known_value_test_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_long_known_value_test::GetLongKnownValueTest::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_long_known_value_test::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_long_known_value_test::_get_long_known_value_test_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/tests/simple_long_test.rs b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/tests/simple_long_test.rs index d63548ae69..e48d52d5fd 100644 --- a/TestModels/SimpleTypes/SimpleLong/runtimes/rust/tests/simple_long_test.rs +++ b/TestModels/SimpleTypes/SimpleLong/runtimes/rust/tests/simple_long_test.rs @@ -10,7 +10,7 @@ async fn test_get_long() { #[tokio::test] async fn test_get_known_value() { - let result = client().get_long_known_value().value(33i64).send().await; + let result = client().get_long_known_value_test().value(33i64).send().await; let output = result.unwrap(); let value = output.value().unwrap(); assert_eq!(value, 33i64); diff --git a/TestModels/SimpleTypes/SimpleString/Makefile b/TestModels/SimpleTypes/SimpleString/Makefile index e68e628e37..6ee0d9abff 100644 --- a/TestModels/SimpleTypes/SimpleString/Makefile +++ b/TestModels/SimpleTypes/SimpleString/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleString/runtimes/rust/Cargo.toml index 3f66bd6aa2..65ef7a3960 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/Cargo.toml @@ -5,15 +5,21 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] aws-smithy-runtime = {version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = {version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} -[dev-dependencies.tokio] +[dev-dependencies] +simple_string = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] version = "1.26.0" features = ["full"] [lib] -path = "src/implementation_from_dafny.rs" \ No newline at end of file +path = "src/implementation_from_dafny.rs" diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client.rs index 2d5b76bf25..88a144918b 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -13,8 +14,6 @@ impl Client { pub fn from_conf( conf: crate::types::simple_string_config::SimpleStringConfig, ) -> Result { - // If this service had any configuration properties, - // they would need converting here too. let inner = crate::simple::types::smithystring::internaldafny::_default::SimpleString( &crate::conversions::simple_string_config::_simple_string_config::to_dafny(conf), @@ -31,7 +30,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } @@ -42,4 +41,4 @@ mod get_string_known_value; mod get_string_utf8; -mod get_string_utf8_known_value; \ No newline at end of file +mod get_string_utf8_known_value; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string.rs index da262534e9..fe18db0b8c 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetString`](crate::operation::get_string::builders::GetStringFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_string::builders::GetStringFluentBuilder::name) / [`set_name(Option)`](crate::operation::get_string::builders::GetStringFluentBuilder::set_name):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_string::builders::GetStringFluentBuilder::value) / [`set_value(Option<::std::string::String>)`](crate::operation::get_string::builders::GetStringFluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetStringOutput`](crate::operation::get_string::GetStringOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_string::GetStringOutput::value): (undocumented) + /// - [`value(Option<::std::string::String>)`](crate::operation::get_string::GetStringOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_string::GetStringError) pub fn get_string(&self) -> crate::operation::get_string::builders::GetStringFluentBuilder { crate::operation::get_string::builders::GetStringFluentBuilder::new(self.clone()) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_known_value.rs index 8c13c6ad59..6ddfcadaa5 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_known_value.rs @@ -1,17 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetStringKnownValue`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::name) / [`set_name(Option)`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::set_name):(undocumented)
- /// - On success, responds with [`GetStringKnownValueOutput`](crate::operation::get_string_known_value::GetStringKnownValueOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_string_known_value::GetStringKnownValueOutput::value): (undocumented) + /// - [`value(impl Into>)`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::value) / [`set_value(Option<::std::string::String>)`](crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetStringOutput`](crate::operation::get_string_known_value::GetStringOutput) with field(s): + /// - [`value(Option<::std::string::String>)`](crate::operation::get_string_known_value::GetStringOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_string_known_value::GetStringKnownValueError) - pub fn get_string_known_value( - &self, - ) -> crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder { - crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::new( - self.clone(), - ) + pub fn get_string_known_value(&self) -> crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder { + crate::operation::get_string_known_value::builders::GetStringKnownValueFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8.rs index 3a487be091..010a0547e6 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8.rs @@ -1,15 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetStringUTF8`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::name) / [`set_name(Option)`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::set_name):(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::value) / [`set_value(Option<::std::string::String>)`](crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetStringUTF8Output`](crate::operation::get_string_utf8::GetStringUTF8Output) with field(s): - /// - [`value(Option)`](crate::operation::get_string_utf8::GetStringUTF8Output::value): (undocumented) + /// - [`value(Option<::std::string::String>)`](crate::operation::get_string_utf8::GetStringUTF8Output::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_string_utf8::GetStringUTF8Error) - pub fn get_string_utf8( - &self, - ) -> crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder { + pub fn get_string_utf8(&self) -> crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder { crate::operation::get_string_utf8::builders::GetStringUTF8FluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8_known_value.rs index 205f24ff5f..dab2fd15fb 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/client/get_string_utf8_known_value.rs @@ -1,15 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetStringUTF8KnownValue`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(impl Into>)`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::name) / [`set_name(Option)`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::set_name):(undocumented)
- /// - On success, responds with [`GetStringUTF8KnownValueOutput`](crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput::value): (undocumented) + /// - [`value(impl Into>)`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::value) / [`set_value(Option<::std::string::String>)`](crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::set_value): (undocumented)
+ /// - On success, responds with [`GetStringUTF8Output`](crate::operation::get_string_utf8_known_value::GetStringUTF8Output) with field(s): + /// - [`value(Option<::std::string::String>)`](crate::operation::get_string_utf8_known_value::GetStringUTF8Output::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError) - pub fn get_string_utf8_known_value( - &self, - ) -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder { + pub fn get_string_utf8_known_value(&self) -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder { crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions.rs index e48982f580..c994c2ec1b 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions.rs @@ -1,10 +1,14 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_string; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod get_string_known_value; + pub mod get_string; -pub mod get_string_utf8; + pub mod get_string_known_value; -pub mod get_string_utf8_known_value; + pub mod get_string_utf8; -pub mod simple_string_config; + pub mod get_string_utf8_known_value; + + pub mod simple_string_config; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..ec72eaf961 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string.rs index 4a11ce9324..28eedb4163 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string.rs @@ -1,12 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_string::GetStringError, -) -> ::std::rc::Rc -{ +) -> ::std::rc::Rc { match value { crate::operation::get_string::GetStringError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_input.rs index 2b7ac1e68b..504704b4f8 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_input.rs @@ -1,43 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_string::GetStringInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringInput::GetStringInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::ostring_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, >, ) -> crate::operation::get_string::GetStringInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string::GetStringInput { value } + crate::operation::get_string::GetStringInput::builder() + .set_value(crate::standard_library_conversions::ostring_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_output.rs index 66cfd60615..9f993cd584 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string/_get_string_output.rs @@ -1,41 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_string::GetStringOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::ostring_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( - dafny_value: ::std::rc::Rc, + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, + >, ) -> crate::operation::get_string::GetStringOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string::GetStringOutput { value } + crate::operation::get_string::GetStringOutput::builder() + .set_value(crate::standard_library_conversions::ostring_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value.rs index 680fd6ad86..9f4018f6fa 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value.rs @@ -1,12 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_string_known_value::GetStringKnownValueError, -) -> ::std::rc::Rc -{ +) -> ::std::rc::Rc { match value { crate::operation::get_string_known_value::GetStringKnownValueError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_input.rs index 2a638911d9..cc34124d85 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_input.rs @@ -1,43 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_string_known_value::GetStringKnownValueInput, + value: crate::operation::get_string_known_value::GetStringInput, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringInput::GetStringInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::ostring_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, >, -) -> crate::operation::get_string_known_value::GetStringKnownValueInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string_known_value::GetStringKnownValueInput { value } +) -> crate::operation::get_string_known_value::GetStringInput { + crate::operation::get_string_known_value::GetStringInput::builder() + .set_value(crate::standard_library_conversions::ostring_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_output.rs index 00f53c20bc..1507eeb3f4 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_known_value/_get_string_known_value_output.rs @@ -1,41 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_string_known_value::GetStringKnownValueOutput, + value: crate::operation::get_string_known_value::GetStringOutput, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::ostring_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( - dafny_value: ::std::rc::Rc, -) -> crate::operation::get_string_known_value::GetStringKnownValueOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &dafny_value.value().Extract(), - ), - ) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string_known_value::GetStringKnownValueOutput { value } + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, + >, +) -> crate::operation::get_string_known_value::GetStringOutput { + crate::operation::get_string_known_value::GetStringOutput::builder() + .set_value(crate::standard_library_conversions::ostring_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8.rs index 1f3d581ec4..855e9697cd 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8.rs @@ -1,12 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_string_utf8::GetStringUTF8Error, -) -> ::std::rc::Rc -{ +) -> ::std::rc::Rc { match value { crate::operation::get_string_utf8::GetStringUTF8Error::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_input.rs index c6b8fc2ae2..c70b83f7bf 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_input.rs @@ -1,43 +1,30 @@ -use core::str; - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_string_utf8::GetStringUTF8Input, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input::GetStringUTF8Input { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) }, + None => crate::_Wrappers_Compile::Option::None {}, +}), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, >, ) -> crate::operation::get_string_utf8::GetStringUTF8Input { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - let bytes = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), |b| *b); - Some(String::from_utf8(bytes).unwrap()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string_utf8::GetStringUTF8Input { value } + crate::operation::get_string_utf8::GetStringUTF8Input::builder() + .set_value(match dafny_value.value().as_ref() { + crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&dafny_value.value().Extract(), |b| *b)).unwrap()), + _ => ::std::option::Option::None, +}) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_output.rs index 1ceb81a53a..be225b6181 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8/_get_string_utf8_output.rs @@ -1,39 +1,30 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_string_utf8::GetStringUTF8Output, ) -> ::std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, +>{ + ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output::GetStringUTF8Output { + value: ::std::rc::Rc::new(match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) }, + None => crate::_Wrappers_Compile::Option::None {}, +}), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( - dafny_value: ::std::rc::Rc, + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, + >, ) -> crate::operation::get_string_utf8::GetStringUTF8Output { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - let bytes = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), |b| *b); - Some(String::from_utf8(bytes).unwrap()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string_utf8::GetStringUTF8Output { value } + crate::operation::get_string_utf8::GetStringUTF8Output::builder() + .set_value(match dafny_value.value().as_ref() { + crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&dafny_value.value().Extract(), |b| *b)).unwrap()), + _ => ::std::option::Option::None, +}) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value.rs index f942e0b21e..25e02541ce 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value.rs @@ -1,12 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError, -) -> ::std::rc::Rc -{ +) -> ::std::rc::Rc { match value { crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs index 97719cd80e..233ffd0804 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs @@ -1,43 +1,30 @@ -use core::str; - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput, + value: crate::operation::get_string_utf8_known_value::GetStringUTF8Input, ) -> ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input::GetStringUTF8Input { - value: ::std::rc::Rc::new(dafny_value) - }) + value: ::std::rc::Rc::new(match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) }, + None => crate::_Wrappers_Compile::Option::None {}, +}), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, >, -) -> crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - let bytes = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), |b| *b); - Some(String::from_utf8(bytes).unwrap()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput { value } +) -> crate::operation::get_string_utf8_known_value::GetStringUTF8Input { + crate::operation::get_string_utf8_known_value::GetStringUTF8Input::builder() + .set_value(match dafny_value.value().as_ref() { + crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&dafny_value.value().Extract(), |b| *b)).unwrap()), + _ => ::std::option::Option::None, +}) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs index 2f0ea07136..2aa9d94c0f 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs @@ -1,39 +1,30 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( - value: crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, + value: crate::operation::get_string_utf8_known_value::GetStringUTF8Output, ) -> ::std::rc::Rc< - crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { - value: dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, +>{ + ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output::GetStringUTF8Output { + value: ::std::rc::Rc::new(match value.value { + Some(s) => crate::_Wrappers_Compile::Option::Some { value: dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&s.as_bytes().to_vec(), |b| *b) }, + None => crate::_Wrappers_Compile::Option::None {}, +}), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( - dafny_value: ::std::rc::Rc, -) -> crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput { - let value = if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::Some { .. } - ) { - let bytes = dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec( - &dafny_value.value().Extract(), |b| *b); - Some(String::from_utf8(bytes).unwrap()) - } else if matches!( - dafny_value.value().as_ref(), - crate::_Wrappers_Compile::Option::None { .. } - ) { - None - } else { - panic!("Unreachable") - }; - crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput { value } + dafny_value: ::std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, + >, +) -> crate::operation::get_string_utf8_known_value::GetStringUTF8Output { + crate::operation::get_string_utf8_known_value::GetStringUTF8Output::builder() + .set_value(match dafny_value.value().as_ref() { + crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&dafny_value.value().Extract(), |b| *b)).unwrap()), + _ => ::std::option::Option::None, +}) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config.rs index 286313ae8b..d8734a9d1d 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_string_config; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config/_simple_string_config.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config/_simple_string_config.rs index 95d7da8d43..71f90a271c 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config/_simple_string_config.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/conversions/simple_string_config/_simple_string_config.rs @@ -1,10 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_string_config::SimpleStringConfig, ) -> ::std::rc::Rc< - crate::simple::types::smithystring::internaldafny::types::SimpleStringConfig, + crate::r#simple::types::smithystring::internaldafny::types::SimpleStringConfig, > { ::std::rc::Rc::new(crate::r#simple::types::smithystring::internaldafny::types::SimpleStringConfig::SimpleStringConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/implementation_from_dafny.rs-e b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/implementation_from_dafny.rs-e deleted file mode 100644 index 0c57116297..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/implementation_from_dafny.rs-e +++ /dev/null @@ -1,1880 +0,0 @@ -#![allow(warnings, unconditional_panic)] -#![allow(nonstandard_style)] - -pub mod _module { - -} -pub mod simple { - pub mod types { - pub mod smithystring { - pub mod internaldafny { - pub use ::dafny_runtime::UpcastObject; - pub use ::std::any::Any; - pub use crate::simple::types::smithystring::internaldafny::types::ISimpleTypesStringClient; - - pub struct _default {} - - impl _default { - pub fn DefaultSimpleStringConfig() -> ::std::rc::Rc { - ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::SimpleStringConfig::SimpleStringConfig {}) - } - pub fn SimpleString(config: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut res = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut client = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object>::new(); - let mut _nw0: ::dafny_runtime::Object = crate::simple::types::smithystring::internaldafny::SimpleStringClient::_allocate_object(); - crate::simple::types::smithystring::internaldafny::SimpleStringClient::_ctor(&_nw0, &::std::rc::Rc::new(crate::r#_SimpleStringImpl_Compile::Config::Config {})); - client = ::dafny_runtime::MaybePlacebo::from(_nw0.clone()); - res = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Success { - value: client.read() - })); - return res.read(); - } - pub fn CreateSuccessOfClient(client: &::dafny_runtime::Object) -> ::std::rc::Rc, ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Success { - value: client.clone() - }) - } - pub fn CreateFailureOfError(error: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Object, ::std::rc::Rc>::Failure { - error: error.clone() - }) - } - } - - pub struct SimpleStringClient { - pub r#__i_config: ::std::rc::Rc - } - - impl SimpleStringClient { - pub fn _allocate_object() -> ::dafny_runtime::Object { - ::dafny_runtime::allocate_object::() - } - pub fn _ctor(this: &::dafny_runtime::Object, config: &::std::rc::Rc) -> () { - let mut _set__i_config: bool = false; - ::dafny_runtime::update_field_uninit_object!(this.clone(), r#__i_config, _set__i_config, config.clone()); - return (); - } - pub fn config(&self) -> ::std::rc::Rc { - self.r#__i_config.clone() - } - } - - impl UpcastObject - for crate::simple::types::smithystring::internaldafny::SimpleStringClient { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); - } - - impl ISimpleTypesStringClient - for crate::simple::types::smithystring::internaldafny::SimpleStringClient { - fn GetString(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut _out0 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - _out0 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleStringImpl_Compile::_default::GetString(&self.config().clone(), input)); - output = ::dafny_runtime::MaybePlacebo::from(_out0.read()); - return output.read(); - } - fn GetStringKnownValue(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut _out1 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - _out1 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleStringImpl_Compile::_default::GetStringKnownValue(&self.config().clone(), input)); - output = ::dafny_runtime::MaybePlacebo::from(_out1.read()); - return output.read(); - } - fn GetStringUTF8(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut _out2 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - _out2 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleStringImpl_Compile::_default::GetStringUTF8(&self.config().clone(), input)); - output = ::dafny_runtime::MaybePlacebo::from(_out2.read()); - return output.read(); - } - fn GetStringUTF8KnownValue(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut _out3 = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - _out3 = ::dafny_runtime::MaybePlacebo::from(crate::r#_SimpleStringImpl_Compile::_default::GetStringUTF8KnownValue(&self.config().clone(), input)); - output = ::dafny_runtime::MaybePlacebo::from(_out3.read()); - return output.read(); - } - } - - impl UpcastObject - for crate::simple::types::smithystring::internaldafny::SimpleStringClient { - ::dafny_runtime::UpcastObjectFn!(dyn crate::simple::types::smithystring::internaldafny::types::ISimpleTypesStringClient); - } - - pub mod types { - pub use ::std::fmt::Debug; - pub use ::dafny_runtime::DafnyPrint; - pub use ::std::cmp::Eq; - pub use ::std::hash::Hash; - pub use ::std::default::Default; - pub use ::std::convert::AsRef; - pub use ::dafny_runtime::UpcastObject; - pub use ::std::any::Any; - - #[derive(PartialEq, Clone)] - pub enum DafnyCallEvent { - DafnyCallEvent { - input: I, - output: O - } - } - - impl DafnyCallEvent { - pub fn input(&self) -> &I { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => input, - } - } - pub fn output(&self) -> &O { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => output, - } - } - } - - impl Debug - for DafnyCallEvent { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for DafnyCallEvent { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.DafnyCallEvent.DafnyCallEvent(")?; - ::dafny_runtime::DafnyPrint::fmt_print(input, _formatter, false)?; - write!(_formatter, ", ")?; - ::dafny_runtime::DafnyPrint::fmt_print(output, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for DafnyCallEvent {} - - impl Hash - for DafnyCallEvent { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - DafnyCallEvent::DafnyCallEvent{input, output, } => { - ::std::hash::Hash::hash(input, _state); - ::std::hash::Hash::hash(output, _state) - }, - } - } - } - - impl Default - for DafnyCallEvent { - fn default() -> DafnyCallEvent { - DafnyCallEvent::DafnyCallEvent { - input: ::std::default::Default::default(), - output: ::std::default::Default::default() - } - } - } - - impl AsRef> - for &DafnyCallEvent { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum GetStringInput { - GetStringInput { - value: ::std::rc::Rc>> - } - } - - impl GetStringInput { - pub fn value(&self) -> &::std::rc::Rc>> { - match self { - GetStringInput::GetStringInput{value, } => value, - } - } - } - - impl Debug - for GetStringInput { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for GetStringInput { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - GetStringInput::GetStringInput{value, } => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.GetStringInput.GetStringInput(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for GetStringInput {} - - impl Hash - for GetStringInput { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - GetStringInput::GetStringInput{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for GetStringInput { - fn default() -> GetStringInput { - GetStringInput::GetStringInput { - value: ::std::default::Default::default() - } - } - } - - impl AsRef - for &GetStringInput { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum GetStringOutput { - GetStringOutput { - value: ::std::rc::Rc>> - } - } - - impl GetStringOutput { - pub fn value(&self) -> &::std::rc::Rc>> { - match self { - GetStringOutput::GetStringOutput{value, } => value, - } - } - } - - impl Debug - for GetStringOutput { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for GetStringOutput { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - GetStringOutput::GetStringOutput{value, } => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.GetStringOutput.GetStringOutput(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for GetStringOutput {} - - impl Hash - for GetStringOutput { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - GetStringOutput::GetStringOutput{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for GetStringOutput { - fn default() -> GetStringOutput { - GetStringOutput::GetStringOutput { - value: ::std::default::Default::default() - } - } - } - - impl AsRef - for &GetStringOutput { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum GetStringUTF8Input { - GetStringUTF8Input { - value: ::std::rc::Rc> - } - } - - impl GetStringUTF8Input { - pub fn value(&self) -> &::std::rc::Rc> { - match self { - GetStringUTF8Input::GetStringUTF8Input{value, } => value, - } - } - } - - impl Debug - for GetStringUTF8Input { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for GetStringUTF8Input { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - GetStringUTF8Input::GetStringUTF8Input{value, } => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.GetStringUTF8Input.GetStringUTF8Input(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for GetStringUTF8Input {} - - impl Hash - for GetStringUTF8Input { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - GetStringUTF8Input::GetStringUTF8Input{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for GetStringUTF8Input { - fn default() -> GetStringUTF8Input { - GetStringUTF8Input::GetStringUTF8Input { - value: ::std::default::Default::default() - } - } - } - - impl AsRef - for &GetStringUTF8Input { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum GetStringUTF8Output { - GetStringUTF8Output { - value: ::std::rc::Rc> - } - } - - impl GetStringUTF8Output { - pub fn value(&self) -> &::std::rc::Rc> { - match self { - GetStringUTF8Output::GetStringUTF8Output{value, } => value, - } - } - } - - impl Debug - for GetStringUTF8Output { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for GetStringUTF8Output { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - GetStringUTF8Output::GetStringUTF8Output{value, } => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.GetStringUTF8Output.GetStringUTF8Output(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for GetStringUTF8Output {} - - impl Hash - for GetStringUTF8Output { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - GetStringUTF8Output::GetStringUTF8Output{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for GetStringUTF8Output { - fn default() -> GetStringUTF8Output { - GetStringUTF8Output::GetStringUTF8Output { - value: ::std::default::Default::default() - } - } - } - - impl AsRef - for &GetStringUTF8Output { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum SimpleStringConfig { - SimpleStringConfig {} - } - - impl SimpleStringConfig {} - - impl Debug - for SimpleStringConfig { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for SimpleStringConfig { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - SimpleStringConfig::SimpleStringConfig{} => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.SimpleStringConfig.SimpleStringConfig")?; - Ok(()) - }, - } - } - } - - impl SimpleStringConfig { - pub fn _AllSingletonConstructors() -> ::dafny_runtime::SequenceIter<::std::rc::Rc> { - ::dafny_runtime::seq![::std::rc::Rc::new(SimpleStringConfig::SimpleStringConfig {})].iter() - } - } - - impl Eq - for SimpleStringConfig {} - - impl Hash - for SimpleStringConfig { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - SimpleStringConfig::SimpleStringConfig{} => { - - }, - } - } - } - - impl Default - for SimpleStringConfig { - fn default() -> SimpleStringConfig { - SimpleStringConfig::SimpleStringConfig {} - } - } - - impl AsRef - for &SimpleStringConfig { - fn as_ref(&self) -> Self { - self - } - } - - pub struct ISimpleTypesStringClientCallHistory {} - - impl ISimpleTypesStringClientCallHistory { - pub fn _allocate_object() -> ::dafny_runtime::Object { - ::dafny_runtime::allocate_object::() - } - } - - impl UpcastObject - for crate::simple::types::smithystring::internaldafny::types::ISimpleTypesStringClientCallHistory { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); - } - - pub trait ISimpleTypesStringClient: ::std::any::Any + ::dafny_runtime::UpcastObject { - fn GetString(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; - fn GetStringKnownValue(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; - fn GetStringUTF8(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; - fn GetStringUTF8KnownValue(&mut self, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>>; - } - - #[derive(PartialEq, Clone)] - pub enum Error { - CollectionOfErrors { - list: ::dafny_runtime::Sequence<::std::rc::Rc>, - message: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> - }, - Opaque { - obj: ::dafny_runtime::Object - } - } - - impl Error { - pub fn list(&self) -> &::dafny_runtime::Sequence<::std::rc::Rc> { - match self { - Error::CollectionOfErrors{list, message, } => list, - Error::Opaque{obj, } => panic!("field does not exist on this variant"), - } - } - pub fn message(&self) -> &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - match self { - Error::CollectionOfErrors{list, message, } => message, - Error::Opaque{obj, } => panic!("field does not exist on this variant"), - } - } - pub fn obj(&self) -> &::dafny_runtime::Object { - match self { - Error::CollectionOfErrors{list, message, } => panic!("field does not exist on this variant"), - Error::Opaque{obj, } => obj, - } - } - } - - impl Debug - for Error { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Error { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Error::CollectionOfErrors{list, message, } => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.Error.CollectionOfErrors(")?; - ::dafny_runtime::DafnyPrint::fmt_print(list, _formatter, false)?; - write!(_formatter, ", ")?; - ::dafny_runtime::DafnyPrint::fmt_print(message, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - Error::Opaque{obj, } => { - write!(_formatter, "simple.types.smithystring.internaldafny.types.Error.Opaque(")?; - ::dafny_runtime::DafnyPrint::fmt_print(obj, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for Error {} - - impl Hash - for Error { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Error::CollectionOfErrors{list, message, } => { - ::std::hash::Hash::hash(list, _state); - ::std::hash::Hash::hash(message, _state) - }, - Error::Opaque{obj, } => { - ::std::hash::Hash::hash(obj, _state) - }, - } - } - } - - impl Default - for Error { - fn default() -> Error { - Error::CollectionOfErrors { - list: ::std::default::Default::default(), - message: ::std::default::Default::default() - } - } - } - - impl AsRef - for &Error { - fn as_ref(&self) -> Self { - self - } - } - - pub type OpaqueError = ::std::rc::Rc; - } - } - } - } -} -pub mod r#_SimpleStringImpl_Compile { - pub use ::std::fmt::Debug; - pub use ::dafny_runtime::DafnyPrint; - pub use ::std::cmp::Eq; - pub use ::std::hash::Hash; - pub use ::std::default::Default; - pub use ::std::convert::AsRef; - - pub struct _default {} - - impl _default { - pub fn GetString(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { - value: input.value().clone() - }); - output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Success { - value: res.clone() - })); - return output.read(); - } - pub fn GetStringKnownValue(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { - panic!("Halt") - }; - let mut _e00: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> = input.value().value().clone(); - let mut _e10: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> = ::dafny_runtime::string_utf16_of("TEST_SIMPLE_STRING_KNOWN_VALUE"); - if !(_e00.clone() == _e10.clone()) { - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&::dafny_runtime::string_utf16_of("Left:\n"))); - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&_e00)); - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&::dafny_runtime::string_utf16_of("Right:\n"))); - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&_e10)); - panic!("Halt") - }; - let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::GetStringOutput::GetStringOutput { - value: input.value().clone() - }); - output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Success { - value: res.clone() - })); - return output.read(); - } - pub fn GetStringUTF8(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { - panic!("Halt") - }; - let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::GetStringUTF8Output::GetStringUTF8Output { - value: input.value().clone() - }); - output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Success { - value: res.clone() - })); - return output.read(); - } - pub fn GetStringUTF8KnownValue(config: &::std::rc::Rc, input: &::std::rc::Rc) -> ::std::rc::Rc, ::std::rc::Rc>> { - let mut output = ::dafny_runtime::MaybePlacebo::<::std::rc::Rc, ::std::rc::Rc>>>::new(); - if !matches!(input.value().as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { - panic!("Halt") - }; - let mut expected: ::dafny_runtime::Sequence = ::dafny_runtime::seq![72, 101, 108, 108, 111]; - let mut _e01: crate::UTF8::ValidUTF8Bytes = input.value().value().clone(); - let mut _e11: ::dafny_runtime::Sequence = expected.clone(); - if !(_e01.clone() == _e11.clone()) { - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&::dafny_runtime::string_utf16_of("Left:\n"))); - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&_e01)); - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&::dafny_runtime::string_utf16_of("Right:\n"))); - print!("{}", ::dafny_runtime::DafnyPrintWrapper(&_e11)); - panic!("Halt") - }; - let mut res: ::std::rc::Rc = ::std::rc::Rc::new(crate::simple::types::smithystring::internaldafny::types::GetStringUTF8Output::GetStringUTF8Output { - value: input.value().clone() - }); - output = ::dafny_runtime::MaybePlacebo::from(::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::std::rc::Rc, ::std::rc::Rc>::Success { - value: res.clone() - })); - return output.read(); - } - } - - #[derive(PartialEq, Clone)] - pub enum Config { - Config {} - } - - impl Config {} - - impl Debug - for Config { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Config { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Config::Config{} => { - write!(_formatter, "SimpleStringImpl_Compile.Config.Config")?; - Ok(()) - }, - } - } - } - - impl Config { - pub fn _AllSingletonConstructors() -> ::dafny_runtime::SequenceIter<::std::rc::Rc> { - ::dafny_runtime::seq![::std::rc::Rc::new(Config::Config {})].iter() - } - } - - impl Eq - for Config {} - - impl Hash - for Config { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Config::Config{} => { - - }, - } - } - } - - impl Default - for Config { - fn default() -> Config { - Config::Config {} - } - } - - impl AsRef - for &Config { - fn as_ref(&self) -> Self { - self - } - } -} -pub mod r#_StandardLibrary_Compile { - pub struct _default {} - - impl _default { - pub fn Join<_T: ::dafny_runtime::DafnyType>(ss: &::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>, joiner: &::dafny_runtime::Sequence<_T>) -> ::dafny_runtime::Sequence<_T> { - let mut _accumulator: ::dafny_runtime::Sequence<_T> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>; - let mut _r0 = ss.clone(); - let mut _r1 = joiner.clone(); - 'TAIL_CALL_START: loop { - let ss = _r0; - let joiner = _r1; - if ss.cardinality() == ::dafny_runtime::int!(1) { - return _accumulator.concat(&ss.get(&::dafny_runtime::int!(0))); - } else { - _accumulator = _accumulator.concat(&ss.get(&::dafny_runtime::int!(0)).concat(&joiner)); - let mut _in0: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ss.drop(&::dafny_runtime::int!(1)); - let mut _in1: ::dafny_runtime::Sequence<_T> = joiner.clone(); - _r0 = _in0.clone(); - _r1 = _in1.clone(); - continue 'TAIL_CALL_START; - } - } - } - pub fn Split<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> { - let mut _accumulator: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>; - let mut _r0 = s.clone(); - let mut _r1 = delim.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let delim = _r1; - let mut i: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(&s, &delim, &::dafny_runtime::int!(0)); - if matches!((&i).as_ref(), crate::r#_Wrappers_Compile::Option::Some{ .. }) { - _accumulator = _accumulator.concat(&::dafny_runtime::seq![s.take(i.value())]); - let mut _in2: ::dafny_runtime::Sequence<_T> = s.drop(&(i.value().clone() + ::dafny_runtime::int!(1))); - let mut _in3: _T = delim.clone(); - _r0 = _in2.clone(); - _r1 = _in3.clone(); - continue 'TAIL_CALL_START; - } else { - return _accumulator.concat(&::dafny_runtime::seq![s.clone()]); - } - } - } - pub fn SplitOnce<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> (::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>) { - let mut i: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(s, delim, &::dafny_runtime::int!(0)); - ( - s.take(i.value()), - s.drop(&(i.value().clone() + ::dafny_runtime::int!(1))) - ) - } - pub fn r#_SplitOnce_q<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, delim: &_T) -> ::std::rc::Rc, ::dafny_runtime::Sequence<_T>)>> { - let mut valueOrError0: ::std::rc::Rc> = crate::r#_StandardLibrary_Compile::_default::FindIndexMatching::<_T>(s, delim, &::dafny_runtime::int!(0)); - if valueOrError0.IsFailure() { - valueOrError0.PropagateFailure::<(::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>)>() - } else { - let mut i: ::dafny_runtime::_System::nat = valueOrError0.Extract(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<(::dafny_runtime::Sequence<_T>, ::dafny_runtime::Sequence<_T>)>::Some { - value: ( - s.take(&i), - s.drop(&(i.clone() + ::dafny_runtime::int!(1))) - ) - }) - } - } - pub fn FindIndexMatching<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Sequence<_T>, c: &_T, i: &::dafny_runtime::_System::nat) -> ::std::rc::Rc> { - crate::r#_StandardLibrary_Compile::_default::FindIndex::<_T>(s, { - let c: _T = c.clone(); - &({ - let mut c = c.clone(); - ::std::rc::Rc::new(move |x: &_T| -> bool{ - x.clone() == c.clone() - }) - }) - }, i) - } - pub fn FindIndex<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>, f: &::std::rc::Rc bool>, i: &::dafny_runtime::_System::nat) -> ::std::rc::Rc> { - let mut _r0 = s.clone(); - let mut _r1 = f.clone(); - let mut _r2 = i.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let f = _r1; - let i = _r2; - if i.clone() == s.cardinality() { - return ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::_System::nat>::None {}); - } else { - if (&f)(&s.get(&i)) { - return ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::_System::nat>::Some { - value: i.clone() - }); - } else { - let mut _in4: ::dafny_runtime::Sequence<_T> = s.clone(); - let mut _in5: ::std::rc::Rc bool> = f.clone(); - let mut _in6: ::dafny_runtime::DafnyInt = i.clone() + ::dafny_runtime::int!(1); - _r0 = _in4.clone(); - _r1 = _in5.clone(); - _r2 = _in6.clone(); - continue 'TAIL_CALL_START; - } - } - } - } - pub fn Filter<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>, f: &::std::rc::Rc bool>) -> ::dafny_runtime::Sequence<_T> { - let mut _accumulator: ::dafny_runtime::Sequence<_T> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>; - let mut _r0 = s.clone(); - let mut _r1 = f.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let f = _r1; - if s.cardinality() == ::dafny_runtime::int!(0) { - return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence<_T>)); - } else { - if (&f)(&s.get(&::dafny_runtime::int!(0))) { - _accumulator = _accumulator.concat(&::dafny_runtime::seq![s.get(&::dafny_runtime::int!(0))]); - let mut _in7: ::dafny_runtime::Sequence<_T> = s.drop(&::dafny_runtime::int!(1)); - let mut _in8: ::std::rc::Rc bool> = f.clone(); - _r0 = _in7.clone(); - _r1 = _in8.clone(); - continue 'TAIL_CALL_START; - } else { - let mut _in9: ::dafny_runtime::Sequence<_T> = s.drop(&::dafny_runtime::int!(1)); - let mut _in10: ::std::rc::Rc bool> = f.clone(); - _r0 = _in9.clone(); - _r1 = _in10.clone(); - continue 'TAIL_CALL_START; - } - } - } - } - pub fn Min(a: &::dafny_runtime::DafnyInt, b: &::dafny_runtime::DafnyInt) -> ::dafny_runtime::DafnyInt { - if a.clone() < b.clone() { - a.clone() - } else { - b.clone() - } - } - pub fn Fill<_T: ::dafny_runtime::DafnyType>(value: &_T, n: &::dafny_runtime::_System::nat) -> ::dafny_runtime::Sequence<_T> { - { - let _initializer = { - let value: _T = value.clone(); - { - let mut value = value.clone(); - ::std::rc::Rc::new(move |_v0: &::dafny_runtime::DafnyInt| -> _T{ - value.clone() - }) - } - }; - ::dafny_runtime::integer_range(::dafny_runtime::Zero::zero(), n.clone()).map(|i| _initializer(&i)).collect::<::dafny_runtime::Sequence<_>>() - } - } - pub fn SeqToArray<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> ::dafny_runtime::Object<[_T]> { - let mut a = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Object<[_T]>>::new(); - let mut _init0: ::std::rc::Rc _T> = { - let s: ::dafny_runtime::Sequence<_T> = s.clone(); - { - let mut s = s.clone(); - ::std::rc::Rc::new(move |i: &::dafny_runtime::DafnyInt| -> _T{ - s.get(i) - }) - } - }; - let mut _nw1: ::dafny_runtime::Object<[::std::mem::MaybeUninit<_T>]> = ::dafny_runtime::array::placebos_usize_object::<_T>(::dafny_runtime::DafnyUsize::into_usize(s.cardinality())); - for r#__i0_0 in ::dafny_runtime::integer_range(0, ::dafny_runtime::rd!(_nw1.clone()).len()) { - { - let __idx0 = ::dafny_runtime::DafnyUsize::into_usize(r#__i0_0.clone()); - ::dafny_runtime::md!(_nw1)[__idx0] = ::std::mem::MaybeUninit::new((&_init0)(&::dafny_runtime::int!(r#__i0_0.clone()))); - } - } - a = ::dafny_runtime::MaybePlacebo::from(::dafny_runtime::array::construct_object(_nw1.clone())); - return a.read(); - } - pub fn LexicographicLessOrEqual<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, b: &::dafny_runtime::Sequence<_T>, less: &::std::rc::Rc bool>) -> bool { - ::dafny_runtime::integer_range(::dafny_runtime::int!(0), a.cardinality() + ::dafny_runtime::int!(1)).any(({ - let mut a = a.clone(); - let mut b = b.clone(); - let mut less = less.clone(); - ::std::rc::Rc::new(move |r#__exists_var_0: ::dafny_runtime::DafnyInt| -> bool{ - let mut k: ::dafny_runtime::DafnyInt = r#__exists_var_0.clone(); - ::dafny_runtime::int!(0) <= k.clone() && k.clone() <= a.cardinality() && crate::r#_StandardLibrary_Compile::_default::LexicographicLessOrEqualAux::<_T>(&a, &b, &less, &k) - }) - }).as_ref()) - } - pub fn LexicographicLessOrEqualAux<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, b: &::dafny_runtime::Sequence<_T>, less: &::std::rc::Rc bool>, lengthOfCommonPrefix: &::dafny_runtime::_System::nat) -> bool { - lengthOfCommonPrefix.clone() <= b.cardinality() && ::dafny_runtime::integer_range(::dafny_runtime::int!(0), lengthOfCommonPrefix.clone()).all(({ - let mut lengthOfCommonPrefix = lengthOfCommonPrefix.clone(); - let mut a = a.clone(); - let mut b = b.clone(); - ::std::rc::Rc::new(move |r#__forall_var_0: ::dafny_runtime::DafnyInt| -> bool{ - let mut i: ::dafny_runtime::DafnyInt = r#__forall_var_0.clone(); - !(::dafny_runtime::int!(0) <= i.clone() && i.clone() < lengthOfCommonPrefix.clone()) || a.get(&i) == b.get(&i) - }) - }).as_ref()) && (lengthOfCommonPrefix.clone() == a.cardinality() || lengthOfCommonPrefix.clone() < b.cardinality() && less(&a.get(lengthOfCommonPrefix), &b.get(lengthOfCommonPrefix))) - } - pub fn SetToOrderedSequence<_T: ::dafny_runtime::DafnyTypeEq>(s: &::dafny_runtime::Set<::dafny_runtime::Sequence<_T>>, less: &::std::rc::Rc bool>) -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> { - let mut _accumulator: ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>> = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>; - let mut _r0 = s.clone(); - let mut _r1 = less.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - let less = _r1; - if s.clone() == ::dafny_runtime::set!{} { - return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>)); - } else { - return (&({ - let mut s = s.clone(); - let mut less = less.clone(); - ::std::rc::Rc::new(move |r#__let_dummy_0: &::dafny_runtime::DafnyInt| -> ::dafny_runtime::Sequence<::dafny_runtime::Sequence<_T>>{ - let mut a = ::dafny_runtime::MaybePlacebo::<::dafny_runtime::Sequence<_T>>::new(); - 'label_goto__ASSIGN_SUCH_THAT_0: loop { - for r#__assign_such_that_0 in (&s).iter().cloned() { - a = ::dafny_runtime::MaybePlacebo::from(r#__assign_such_that_0.clone()); - if s.contains(&a.read()) && crate::r#_StandardLibrary_Compile::_default::IsMinimum::<_T>(&a.read(), &s, &less) { - break 'label_goto__ASSIGN_SUCH_THAT_0; - } - } - panic!("Halt"); - break; - }; - ::dafny_runtime::seq![a.read()].concat(&crate::r#_StandardLibrary_Compile::_default::SetToOrderedSequence::<_T>(&s.subtract(&::dafny_runtime::set!{a.read()}), &less)) - }) - }))(&::dafny_runtime::int!(0)); - } - } - } - pub fn IsMinimum<_T: ::dafny_runtime::DafnyTypeEq>(a: &::dafny_runtime::Sequence<_T>, s: &::dafny_runtime::Set<::dafny_runtime::Sequence<_T>>, less: &::std::rc::Rc bool>) -> bool { - s.contains(a) && s.iter().all(({ - let mut a = a.clone(); - let mut s = s.clone(); - let mut less = less.clone(); - ::std::rc::Rc::new(move |r#__forall_var_1: &::dafny_runtime::Sequence<_T>| -> bool{ - let mut z: ::dafny_runtime::Sequence<_T> = r#__forall_var_1.clone(); - !s.contains(&z) || crate::r#_StandardLibrary_Compile::_default::LexicographicLessOrEqual::<_T>(&a, &z, &less) - }) - }).as_ref()) - } - } - - pub mod r#_UInt_Compile { - pub use ::std::default::Default; - pub use ::dafny_runtime::DafnyPrint; - - pub struct _default {} - - impl _default { - pub fn UInt8Less(a: u8, b: u8) -> bool { - a < b - } - pub fn HasUint16Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { - s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT16_LIMIT() - } - pub fn HasUint32Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { - s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT32_LIMIT() - } - pub fn HasUint64Len<_T: ::dafny_runtime::DafnyType>(s: &::dafny_runtime::Sequence<_T>) -> bool { - s.cardinality() < crate::r#_StandardLibrary_Compile::r#_UInt_Compile::_default::UINT64_LIMIT() - } - pub fn UInt16ToSeq(x: u16) -> ::dafny_runtime::Sequence { - let mut b0: u8 = (x / 256) as u8; - let mut b1: u8 = (x % 256) as u8; - ::dafny_runtime::seq![b0, b1] - } - pub fn SeqToUInt16(s: &::dafny_runtime::Sequence) -> u16 { - let mut x0: u16 = s.get(&::dafny_runtime::int!(0)) as u16 * 256; - x0 + s.get(&::dafny_runtime::int!(1)) as u16 - } - pub fn UInt32ToSeq(x: u32) -> ::dafny_runtime::Sequence { - let mut b0: u8 = (x / 16777216) as u8; - let mut x0: u32 = x - b0 as u32 * 16777216; - let mut b1: u8 = (x0 / 65536) as u8; - let mut x1: u32 = x0 - b1 as u32 * 65536; - let mut b2: u8 = (x1 / 256) as u8; - let mut b3: u8 = (x1 % 256) as u8; - ::dafny_runtime::seq![b0, b1, b2, b3] - } - pub fn SeqToUInt32(s: &::dafny_runtime::Sequence) -> u32 { - let mut x0: u32 = s.get(&::dafny_runtime::int!(0)) as u32 * 16777216; - let mut x1: u32 = x0 + s.get(&::dafny_runtime::int!(1)) as u32 * 65536; - let mut x2: u32 = x1 + s.get(&::dafny_runtime::int!(2)) as u32 * 256; - x2 + s.get(&::dafny_runtime::int!(3)) as u32 - } - pub fn UInt64ToSeq(x: u64) -> ::dafny_runtime::Sequence { - let mut b0: u8 = (x / 72057594037927936) as u8; - let mut x0: u64 = x - b0 as u64 * 72057594037927936; - let mut b1: u8 = (x0 / 281474976710656) as u8; - let mut x1: u64 = x0 - b1 as u64 * 281474976710656; - let mut b2: u8 = (x1 / 1099511627776) as u8; - let mut x2: u64 = x1 - b2 as u64 * 1099511627776; - let mut b3: u8 = (x2 / 4294967296) as u8; - let mut x3: u64 = x2 - b3 as u64 * 4294967296; - let mut b4: u8 = (x3 / 16777216) as u8; - let mut x4: u64 = x3 - b4 as u64 * 16777216; - let mut b5: u8 = (x4 / 65536) as u8; - let mut x5: u64 = x4 - b5 as u64 * 65536; - let mut b6: u8 = (x5 / 256) as u8; - let mut b7: u8 = (x5 % 256) as u8; - ::dafny_runtime::seq![b0, b1, b2, b3, b4, b5, b6, b7] - } - pub fn SeqToUInt64(s: &::dafny_runtime::Sequence) -> u64 { - let mut x0: u64 = s.get(&::dafny_runtime::int!(0)) as u64 * 72057594037927936; - let mut x1: u64 = x0 + s.get(&::dafny_runtime::int!(1)) as u64 * 281474976710656; - let mut x2: u64 = x1 + s.get(&::dafny_runtime::int!(2)) as u64 * 1099511627776; - let mut x3: u64 = x2 + s.get(&::dafny_runtime::int!(3)) as u64 * 4294967296; - let mut x4: u64 = x3 + s.get(&::dafny_runtime::int!(4)) as u64 * 16777216; - let mut x5: u64 = x4 + s.get(&::dafny_runtime::int!(5)) as u64 * 65536; - let mut x6: u64 = x5 + s.get(&::dafny_runtime::int!(6)) as u64 * 256; - let mut x: u64 = x6 + s.get(&::dafny_runtime::int!(7)) as u64; - x - } - pub fn UINT16_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"65536") - } - pub fn UINT32_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"4294967296") - } - pub fn UINT64_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"18446744073709551616") - } - pub fn INT32_MAX_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"2147483648") - } - pub fn INT64_MAX_LIMIT() -> ::dafny_runtime::DafnyInt { - ::dafny_runtime::int!(b"9223372036854775808") - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint8(pub u8); - - impl uint8 { - pub fn is(_source: u8) -> bool { - return true; - } - } - - impl Default - for uint8 { - fn default() -> Self { - uint8(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint8 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint8 { - type Target = u8; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint16(pub u16); - - impl uint16 { - pub fn is(_source: u16) -> bool { - return true; - } - } - - impl Default - for uint16 { - fn default() -> Self { - uint16(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint16 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint16 { - type Target = u16; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint32(pub u32); - - impl uint32 { - pub fn is(_source: u32) -> bool { - return true; - } - } - - impl Default - for uint32 { - fn default() -> Self { - uint32(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint32 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint32 { - type Target = u32; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct uint64(pub u64); - - impl uint64 { - pub fn is(_source: u64) -> bool { - return true; - } - } - - impl Default - for uint64 { - fn default() -> Self { - uint64(::std::default::Default::default()) - } - } - - impl DafnyPrint - for uint64 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for uint64 { - type Target = u64; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct int32(pub i32); - - impl int32 { - pub fn is(_source: i32) -> bool { - return true; - } - } - - impl Default - for int32 { - fn default() -> Self { - int32(::std::default::Default::default()) - } - } - - impl DafnyPrint - for int32 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for int32 { - type Target = i32; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct int64(pub i64); - - impl int64 { - pub fn is(_source: i64) -> bool { - return true; - } - } - - impl Default - for int64 { - fn default() -> Self { - int64(::std::default::Default::default()) - } - } - - impl DafnyPrint - for int64 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for int64 { - type Target = i64; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - #[derive(Clone, PartialEq)] - #[repr(transparent)] - pub struct posInt64(pub u64); - - impl posInt64 { - pub fn is(_source: u64) -> bool { - let mut x: ::dafny_runtime::DafnyInt = ::std::convert::Into::<::dafny_runtime::DafnyInt>::into(_source.clone()); - return ::dafny_runtime::int!(0) < x.clone() && x.clone() < ::dafny_runtime::int!(b"9223372036854775808"); - } - } - - impl Default - for posInt64 { - fn default() -> Self { - posInt64(1) - } - } - - impl DafnyPrint - for posInt64 { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, in_seq: bool) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(&self.0, _formatter, in_seq) - } - } - - impl ::std::ops::Deref - for posInt64 { - type Target = u64; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - pub type seq16 = ::dafny_runtime::Sequence; - - pub type seq32 = ::dafny_runtime::Sequence; - - pub type seq64 = ::dafny_runtime::Sequence; - } -} -pub mod r#_StandardLibraryInterop_Compile { - pub use ::dafny_runtime::UpcastObject; - pub use ::std::any::Any; - - pub struct WrappersInterop {} - - impl WrappersInterop { - pub fn _allocate_object() -> ::dafny_runtime::Object { - ::dafny_runtime::allocate_object::() - } - pub fn CreateStringSome(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Some { - value: s.clone() - }) - } - pub fn CreateStringNone() -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::None {}) - } - pub fn CreateBooleanSome(b: bool) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::Some { - value: b - }) - } - pub fn CreateBooleanNone() -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::None {}) - } - } - - impl UpcastObject - for WrappersInterop { - ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); - } -} -pub mod UTF8 { - pub struct _default {} - - impl _default { - pub fn CreateEncodeSuccess(bytes: &crate::UTF8::ValidUTF8Bytes) -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Success { - value: bytes.clone() - }) - } - pub fn CreateEncodeFailure(error: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Failure { - error: error.clone() - }) - } - pub fn CreateDecodeSuccess(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { - value: s.clone() - }) - } - pub fn CreateDecodeFailure(error: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> ::std::rc::Rc, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { - error: error.clone() - }) - } - pub fn IsASCIIString(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> bool { - let mut _hresult: bool = ::default(); - let mut _hi0: ::dafny_runtime::DafnyInt = s.cardinality(); - for i in ::dafny_runtime::integer_range(::dafny_runtime::int!(0), _hi0.clone()) { - if !(::dafny_runtime::int!(s.get(&i).0) < ::dafny_runtime::int!(128)) { - _hresult = false; - return _hresult; - } - } - _hresult = true; - return _hresult; - } - pub fn EncodeAscii(s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>) -> crate::UTF8::ValidUTF8Bytes { - let mut _accumulator: crate::UTF8::ValidUTF8Bytes = ::dafny_runtime::seq![] as ::dafny_runtime::Sequence; - let mut _r0 = s.clone(); - 'TAIL_CALL_START: loop { - let s = _r0; - if s.cardinality() == ::dafny_runtime::int!(0) { - return _accumulator.concat(&(::dafny_runtime::seq![] as ::dafny_runtime::Sequence)); - } else { - let mut x: ::dafny_runtime::Sequence = ::dafny_runtime::seq![s.get(&::dafny_runtime::int!(0)).0 as u8]; - _accumulator = _accumulator.concat(&x); - let mut _in11: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> = s.drop(&::dafny_runtime::int!(1)); - _r0 = _in11.clone(); - continue 'TAIL_CALL_START; - } - } - } - pub fn Uses1Byte(s: &::dafny_runtime::Sequence) -> bool { - 0 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 127 - } - pub fn Uses2Bytes(s: &::dafny_runtime::Sequence) -> bool { - 194 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 223 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) - } - pub fn Uses3Bytes(s: &::dafny_runtime::Sequence) -> bool { - s.get(&::dafny_runtime::int!(0)) == 224 && (160 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || 225 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 236 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || s.get(&::dafny_runtime::int!(0)) == 237 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 159) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) || 238 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 239 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) - } - pub fn Uses4Bytes(s: &::dafny_runtime::Sequence) -> bool { - s.get(&::dafny_runtime::int!(0)) == 240 && (144 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) || 241 <= s.get(&::dafny_runtime::int!(0)) && s.get(&::dafny_runtime::int!(0)) <= 243 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) || s.get(&::dafny_runtime::int!(0)) == 244 && (128 <= s.get(&::dafny_runtime::int!(1)) && s.get(&::dafny_runtime::int!(1)) <= 143) && (128 <= s.get(&::dafny_runtime::int!(2)) && s.get(&::dafny_runtime::int!(2)) <= 191) && (128 <= s.get(&::dafny_runtime::int!(3)) && s.get(&::dafny_runtime::int!(3)) <= 191) - } - pub fn ValidUTF8Range(a: &::dafny_runtime::Sequence, lo: &::dafny_runtime::_System::nat, hi: &::dafny_runtime::_System::nat) -> bool { - let mut _r0 = a.clone(); - let mut _r1 = lo.clone(); - let mut _r2 = hi.clone(); - 'TAIL_CALL_START: loop { - let a = _r0; - let lo = _r1; - let hi = _r2; - if lo.clone() == hi.clone() { - return true; - } else { - let mut r: ::dafny_runtime::Sequence = a.slice(&lo, &hi); - if crate::UTF8::_default::Uses1Byte(&r) { - let mut _in12: ::dafny_runtime::Sequence = a.clone(); - let mut _in13: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(1); - let mut _in14: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in12.clone(); - _r1 = _in13.clone(); - _r2 = _in14.clone(); - continue 'TAIL_CALL_START; - } else { - if ::dafny_runtime::int!(2) <= r.cardinality() && crate::UTF8::_default::Uses2Bytes(&r) { - let mut _in15: ::dafny_runtime::Sequence = a.clone(); - let mut _in16: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(2); - let mut _in17: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in15.clone(); - _r1 = _in16.clone(); - _r2 = _in17.clone(); - continue 'TAIL_CALL_START; - } else { - if ::dafny_runtime::int!(3) <= r.cardinality() && crate::UTF8::_default::Uses3Bytes(&r) { - let mut _in18: ::dafny_runtime::Sequence = a.clone(); - let mut _in19: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(3); - let mut _in20: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in18.clone(); - _r1 = _in19.clone(); - _r2 = _in20.clone(); - continue 'TAIL_CALL_START; - } else { - if ::dafny_runtime::int!(4) <= r.cardinality() && crate::UTF8::_default::Uses4Bytes(&r) { - let mut _in21: ::dafny_runtime::Sequence = a.clone(); - let mut _in22: ::dafny_runtime::DafnyInt = lo.clone() + ::dafny_runtime::int!(4); - let mut _in23: ::dafny_runtime::_System::nat = hi.clone(); - _r0 = _in21.clone(); - _r1 = _in22.clone(); - _r2 = _in23.clone(); - continue 'TAIL_CALL_START; - } else { - return false; - } - } - } - } - } - } - } - pub fn ValidUTF8Seq(s: &::dafny_runtime::Sequence) -> bool { - crate::UTF8::_default::ValidUTF8Range(s, &::dafny_runtime::int!(0), &s.cardinality()) - } - } - - pub type ValidUTF8Bytes = ::dafny_runtime::Sequence; - - pub fn r#__init_ValidUTF8Bytes() -> ::dafny_runtime::Sequence { - ::dafny_runtime::seq![] as ::dafny_runtime::Sequence - } -} -pub mod r#_Wrappers_Compile { - pub use ::std::fmt::Debug; - pub use ::dafny_runtime::DafnyPrint; - pub use ::std::cmp::Eq; - pub use ::std::hash::Hash; - pub use ::std::default::Default; - pub use ::std::convert::AsRef; - - pub struct _default {} - - impl _default { - pub fn Need<_E: ::dafny_runtime::DafnyType>(condition: bool, error: &_E) -> ::std::rc::Rc> { - if condition { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Outcome::<_E>::Pass {}) - } else { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Outcome::<_E>::Fail { - error: error.clone() - }) - } - } - } - - #[derive(PartialEq, Clone)] - pub enum Option { - None {}, - Some { - value: T - } - } - - impl Option { - pub fn ToResult(self: &::std::rc::Rc) -> ::std::rc::Rc>> { - let mut _source0: ::std::rc::Rc> = self.clone(); - if matches!((&_source0).as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Failure { - error: ::dafny_runtime::string_utf16_of("Option is None") - }) - } else { - let mut r#___mcc_h0: T = _source0.value().clone(); - let mut v: T = r#___mcc_h0.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::>::Success { - value: v.clone() - }) - } - } - pub fn UnwrapOr(self: &::std::rc::Rc, default: &T) -> T { - let mut _source1: ::std::rc::Rc> = self.clone(); - if matches!((&_source1).as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) { - default.clone() - } else { - let mut r#___mcc_h0: T = _source1.value().clone(); - let mut v: T = r#___mcc_h0.clone(); - v.clone() - } - } - pub fn IsFailure(self: &::std::rc::Rc) -> bool { - matches!(self.as_ref(), crate::r#_Wrappers_Compile::Option::None{ .. }) - } - pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::<_U>::None {}) - } - pub fn Extract(self: &::std::rc::Rc) -> T { - self.value().clone() - } - pub fn value(&self) -> &T { - match self { - Option::None{} => panic!("field does not exist on this variant"), - Option::Some{value, } => value, - } - } - } - - impl Debug - for Option { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Option { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Option::None{} => { - write!(_formatter, "Wrappers_Compile.Option.None")?; - Ok(()) - }, - Option::Some{value, } => { - write!(_formatter, "Wrappers_Compile.Option.Some(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Option { - pub fn coerce(f_0: ::std::rc::Rc r#__T0 + 'static>) -> ::std::rc::Rc) -> Option> { - ::std::rc::Rc::new(move |this: Self| -> Option{ - match this { - Option::None{} => { - Option::None {} - }, - Option::Some{value, } => { - Option::Some { - value: f_0.clone()(value) - } - }, - } - }) - } - } - - impl Eq - for Option {} - - impl Hash - for Option { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Option::None{} => { - - }, - Option::Some{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - } - } - } - - impl Default - for Option { - fn default() -> Option { - Option::None {} - } - } - - impl AsRef> - for &Option { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum Result { - Success { - value: T - }, - Failure { - error: R - } - } - - impl Result { - pub fn ToOption(self: &::std::rc::Rc) -> ::std::rc::Rc> { - let mut _source2: ::std::rc::Rc> = self.clone(); - if matches!((&_source2).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { - let mut r#___mcc_h0: T = _source2.value().clone(); - let mut s: T = r#___mcc_h0.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::Some { - value: s.clone() - }) - } else { - let mut r#___mcc_h1: R = _source2.error().clone(); - let mut e: R = r#___mcc_h1.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Option::::None {}) - } - } - pub fn UnwrapOr(self: &::std::rc::Rc, default: &T) -> T { - let mut _source3: ::std::rc::Rc> = self.clone(); - if matches!((&_source3).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { - let mut r#___mcc_h0: T = _source3.value().clone(); - let mut s: T = r#___mcc_h0.clone(); - s.clone() - } else { - let mut r#___mcc_h1: R = _source3.error().clone(); - let mut e: R = r#___mcc_h1.clone(); - default.clone() - } - } - pub fn IsFailure(self: &::std::rc::Rc) -> bool { - matches!(self.as_ref(), crate::r#_Wrappers_Compile::Result::Failure{ .. }) - } - pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<_U, R>::Failure { - error: self.error().clone() - }) - } - pub fn MapFailure<_NewR: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc, reWrap: &::std::rc::Rc _NewR>) -> ::std::rc::Rc> { - let mut _source4: ::std::rc::Rc> = self.clone(); - if matches!((&_source4).as_ref(), crate::r#_Wrappers_Compile::Result::Success{ .. }) { - let mut r#___mcc_h0: T = _source4.value().clone(); - let mut s: T = r#___mcc_h0.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::::Success { - value: s.clone() - }) - } else { - let mut r#___mcc_h1: R = _source4.error().clone(); - let mut e: R = r#___mcc_h1.clone(); - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::::Failure { - error: reWrap(&e) - }) - } - } - pub fn Extract(self: &::std::rc::Rc) -> T { - self.value().clone() - } - pub fn value(&self) -> &T { - match self { - Result::Success{value, } => value, - Result::Failure{error, } => panic!("field does not exist on this variant"), - } - } - pub fn error(&self) -> &R { - match self { - Result::Success{value, } => panic!("field does not exist on this variant"), - Result::Failure{error, } => error, - } - } - } - - impl Debug - for Result { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Result { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Result::Success{value, } => { - write!(_formatter, "Wrappers_Compile.Result.Success(")?; - ::dafny_runtime::DafnyPrint::fmt_print(value, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - Result::Failure{error, } => { - write!(_formatter, "Wrappers_Compile.Result.Failure(")?; - ::dafny_runtime::DafnyPrint::fmt_print(error, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Result { - pub fn coerce(f_0: ::std::rc::Rc r#__T0 + 'static>, f_1: ::std::rc::Rc r#__T1 + 'static>) -> ::std::rc::Rc) -> Result> { - ::std::rc::Rc::new(move |this: Self| -> Result{ - match this { - Result::Success{value, } => { - Result::Success { - value: f_0.clone()(value) - } - }, - Result::Failure{error, } => { - Result::Failure { - error: f_1.clone()(error) - } - }, - } - }) - } - } - - impl Eq - for Result {} - - impl Hash - for Result { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Result::Success{value, } => { - ::std::hash::Hash::hash(value, _state) - }, - Result::Failure{error, } => { - ::std::hash::Hash::hash(error, _state) - }, - } - } - } - - impl Default - for Result { - fn default() -> Result { - Result::Success { - value: ::std::default::Default::default() - } - } - } - - impl AsRef> - for &Result { - fn as_ref(&self) -> Self { - self - } - } - - #[derive(PartialEq, Clone)] - pub enum Outcome { - Pass {}, - Fail { - error: E - } - } - - impl Outcome { - pub fn IsFailure(self: &::std::rc::Rc) -> bool { - matches!(self.as_ref(), crate::r#_Wrappers_Compile::Outcome::Fail{ .. }) - } - pub fn PropagateFailure<_U: ::dafny_runtime::DafnyType>(self: &::std::rc::Rc) -> ::std::rc::Rc> { - ::std::rc::Rc::new(crate::r#_Wrappers_Compile::Result::<_U, E>::Failure { - error: self.error().clone() - }) - } - pub fn error(&self) -> &E { - match self { - Outcome::Pass{} => panic!("field does not exist on this variant"), - Outcome::Fail{error, } => error, - } - } - } - - impl Debug - for Outcome { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - ::dafny_runtime::DafnyPrint::fmt_print(self, f, true) - } - } - - impl DafnyPrint - for Outcome { - fn fmt_print(&self, _formatter: &mut ::std::fmt::Formatter, _in_seq: bool) -> std::fmt::Result { - match self { - Outcome::Pass{} => { - write!(_formatter, "Wrappers_Compile.Outcome.Pass")?; - Ok(()) - }, - Outcome::Fail{error, } => { - write!(_formatter, "Wrappers_Compile.Outcome.Fail(")?; - ::dafny_runtime::DafnyPrint::fmt_print(error, _formatter, false)?; - write!(_formatter, ")")?; - Ok(()) - }, - } - } - } - - impl Eq - for Outcome {} - - impl Hash - for Outcome { - fn hash<_H: ::std::hash::Hasher>(&self, _state: &mut _H) { - match self { - Outcome::Pass{} => { - - }, - Outcome::Fail{error, } => { - ::std::hash::Hash::hash(error, _state) - }, - } - } - } - - impl Default - for Outcome { - fn default() -> Outcome { - Outcome::Pass {} - } - } - - impl AsRef> - for &Outcome { - fn as_ref(&self) -> Self { - self - } - } -} \ No newline at end of file diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/lib.rs deleted file mode 100644 index 4315dacf41..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,17 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub use client::Client; -pub use types::simple_string_config::SimpleStringConfig; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation.rs index 11a6156789..1220a72598 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetString` operation. pub mod get_string; @@ -11,4 +12,3 @@ pub mod get_string_utf8; /// Types for the `GetStringUTF8KnownValue` operation. pub mod get_string_utf8_known_value; - diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string.rs index 813f2280e3..2ac87c12d5 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetString`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -137,9 +139,9 @@ pub use crate::operation::get_string::_get_string_output::GetStringOutput; pub use crate::operation::get_string::_get_string_input::GetStringInput; -mod _get_string_input; +pub(crate) mod _get_string_output; -mod _get_string_output; +pub(crate) mod _get_string_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_input.rs index 9c0d47f5f2..b775cb1bfa 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_input.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetStringInput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, +pub value: ::std::option::Option<::std::string::String>, } impl GetStringInput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} } impl GetStringInput { /// Creates a new builder-style object to manufacture [`GetStringInput`](crate::operation::operation::GetStringInput). @@ -29,19 +31,19 @@ pub struct GetStringInputBuilder { } impl GetStringInputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} /// Consumes the builder and constructs a [`GetStringInput`](crate::operation::operation::GetStringInput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_output.rs index ab6b1fa3cd..0f89443a9b 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/_get_string_output.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetStringOutput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, +pub value: ::std::option::Option<::std::string::String>, } impl GetStringOutput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} } impl GetStringOutput { /// Creates a new builder-style object to manufacture [`GetStringOutput`](crate::operation::operation::GetStringOutput). @@ -29,19 +31,19 @@ pub struct GetStringOutputBuilder { } impl GetStringOutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} /// Consumes the builder and constructs a [`GetStringOutput`](crate::operation::operation::GetStringOutput). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/builders.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/builders.rs index ec32b2e2ce..e0c6cd015e 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/builders.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string/builders.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_string::_get_string_output::GetStringOutputBuilder; pub use crate::operation::get_string::_get_string_input::GetStringInputBuilder; @@ -21,12 +23,12 @@ impl GetStringInputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetStringFluentBuilder { - client: crate::Client, - inner: crate::operation::get_string::builders::GetStringInputBuilder, + client: crate::client::Client, + pub(crate) inner: crate::operation::get_string::builders::GetStringInputBuilder, } impl GetStringFluentBuilder { /// Creates a new `GetString`. - pub(crate) fn new(client: crate::Client) -> Self { + pub(crate) fn new(client: crate::client::Client) -> Self { Self { client, inner: ::std::default::Default::default(), @@ -56,17 +58,17 @@ impl GetStringFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.inner = self.inner.value(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value.rs index d6abc77c74..0d9960be0e 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetStringKnownValue`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,28 +12,27 @@ impl GetStringKnownValue { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_string_known_value::GetStringKnownValueInput, + input: crate::operation::get_string_known_value::GetStringInput, ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringKnownValueOutput, + crate::operation::get_string_known_value::GetStringOutput, crate::operation::get_string_known_value::GetStringKnownValueError, > { - let inner_input = - crate::conversions::get_string_known_value::_get_string_known_value_input::to_dafny( - input, - ); + let inner_input = crate::conversions::get_string_known_value::_get_string_known_value_input::to_dafny(input); let inner_result = - ::dafny_runtime::md!(client.dafny_client.clone()).GetString(&inner_input); + ::dafny_runtime::md!(client.dafny_client.clone()).GetStringKnownValue(&inner_input); if matches!( inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - Ok(crate::conversions::get_string_known_value::_get_string_known_value_output::from_dafny(inner_result.value().clone())) - } else { - Err( - crate::conversions::get_string_known_value::from_dafny_error( - inner_result.error().clone(), + Ok( + crate::conversions::get_string_known_value::_get_string_known_value_output::from_dafny( + inner_result.value().clone(), ), ) + } else { + Err(crate::conversions::get_string_known_value::from_dafny_error( + inner_result.error().clone(), + )) } } } @@ -134,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetStrin } } -pub use crate::operation::get_string_known_value::_get_string_known_value_output::GetStringKnownValueOutput; +pub use crate::operation::get_string_known_value::_get_string_output::GetStringOutput; -pub use crate::operation::get_string_known_value::_get_string_known_value_input::GetStringKnownValueInput; +pub use crate::operation::get_string_known_value::_get_string_input::GetStringInput; -mod _get_string_known_value_input; +pub(crate) mod _get_string_output; -mod _get_string_known_value_output; +pub(crate) mod _get_string_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_input.rs new file mode 100644 index 0000000000..2eedc4c6b9 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetStringInput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::string::String>, +} +impl GetStringInput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} +} +impl GetStringInput { + /// Creates a new builder-style object to manufacture [`GetStringInput`](crate::operation::operation::GetStringInput). + pub fn builder() -> crate::operation::get_string_known_value::builders::GetStringInputBuilder { + crate::operation::get_string_known_value::builders::GetStringInputBuilder::default() + } +} + +/// A builder for [`GetStringInput`](crate::operation::operation::GetStringInput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetStringInputBuilder { + pub(crate) value: ::std::option::Option<::std::string::String>, +} +impl GetStringInputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} + /// Consumes the builder and constructs a [`GetStringInput`](crate::operation::operation::GetStringInput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_string_known_value::GetStringInput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_string_known_value::GetStringInput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_input.rs deleted file mode 100644 index b67c3effad..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_input.rs +++ /dev/null @@ -1,60 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetStringKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, -} -impl GetStringKnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } -} -impl GetStringKnownValueInput { - /// Creates a new builder-style object to manufacture [`GetStringKnownValueInput`](crate::operation::operation::GetStringKnownValueInput). - pub fn builder( - ) -> crate::operation::get_string_known_value::builders::GetStringKnownValueInputBuilder { - crate::operation::get_string_known_value::builders::GetStringKnownValueInputBuilder::default( - ) - } -} - -/// A builder for [`GetStringKnownValueInput`](crate::operation::operation::GetStringKnownValueInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetStringKnownValueInputBuilder { - pub(crate) value: ::std::option::Option<::std::string::String>, -} -impl GetStringKnownValueInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } - /// Consumes the builder and constructs a [`GetStringKnownValueInput`](crate::operation::operation::GetStringKnownValueInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringKnownValueInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_string_known_value::GetStringKnownValueInput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_output.rs deleted file mode 100644 index 291e692c5a..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_known_value_output.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetStringKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, -} -impl GetStringKnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } -} -impl GetStringKnownValueOutput { - /// Creates a new builder-style object to manufacture [`GetStringKnownValueOutput`](crate::operation::operation::GetStringKnownValueOutput). - pub fn builder( - ) -> crate::operation::get_string_known_value::builders::GetStringKnownValueOutputBuilder { - crate::operation::get_string_known_value::builders::GetStringKnownValueOutputBuilder::default() - } -} - -/// A builder for [`GetStringKnownValueOutput`](crate::operation::operation::GetStringKnownValueOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetStringKnownValueOutputBuilder { - pub(crate) value: ::std::option::Option<::std::string::String>, -} -impl GetStringKnownValueOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } - /// Consumes the builder and constructs a [`GetStringKnownValueOutput`](crate::operation::operation::GetStringKnownValueOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringKnownValueOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok( - crate::operation::get_string_known_value::GetStringKnownValueOutput { - value: self.value, - }, - ) - } -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_output.rs new file mode 100644 index 0000000000..dd7b2a2ebc --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/_get_string_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetStringOutput { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::string::String>, +} +impl GetStringOutput { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} +} +impl GetStringOutput { + /// Creates a new builder-style object to manufacture [`GetStringOutput`](crate::operation::operation::GetStringOutput). + pub fn builder() -> crate::operation::get_string_known_value::builders::GetStringOutputBuilder { + crate::operation::get_string_known_value::builders::GetStringOutputBuilder::default() + } +} + +/// A builder for [`GetStringOutput`](crate::operation::operation::GetStringOutput). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetStringOutputBuilder { + pub(crate) value: ::std::option::Option<::std::string::String>, +} +impl GetStringOutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} + /// Consumes the builder and constructs a [`GetStringOutput`](crate::operation::operation::GetStringOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_string_known_value::GetStringOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_string_known_value::GetStringOutput { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/builders.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/builders.rs index 82b4c7fb37..0d379f9cad 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/builders.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_known_value/builders.rs @@ -1,15 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_string_known_value::_get_string_known_value_output::GetStringKnownValueOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_string_known_value::_get_string_output::GetStringOutputBuilder; -pub use crate::operation::get_string_known_value::_get_string_known_value_input::GetStringKnownValueInputBuilder; +pub use crate::operation::get_string_known_value::_get_string_input::GetStringInputBuilder; -impl GetStringKnownValueInputBuilder { +impl GetStringInputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringKnownValueOutput, + crate::operation::get_string_known_value::GetStringOutput, crate::operation::get_string_known_value::GetStringKnownValueError, > { let mut fluent_builder = client.get_string_known_value(); @@ -21,57 +23,52 @@ impl GetStringKnownValueInputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetStringKnownValueFluentBuilder { - client: crate::Client, - inner: crate::operation::get_string_known_value::builders::GetStringKnownValueInputBuilder, + client: crate::client::Client, + pub(crate) inner: crate::operation::get_string_known_value::builders::GetStringInputBuilder, } impl GetStringKnownValueFluentBuilder { /// Creates a new `GetStringKnownValue`. - pub(crate) fn new(client: crate::Client) -> Self { + pub(crate) fn new(client: crate::client::Client) -> Self { Self { client, inner: ::std::default::Default::default(), } } /// Access the GetStringKnownValue as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_string_known_value::builders::GetStringKnownValueInputBuilder { + pub fn as_input(&self) -> &crate::operation::get_string_known_value::builders::GetStringInputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_string_known_value::GetStringKnownValueOutput, + crate::operation::get_string_known_value::GetStringOutput, crate::operation::get_string_known_value::GetStringKnownValueError, > { let input = self .inner .build() - // Using unhandled since GetString doesn't declare any validation, + // Using unhandled since GetStringKnownValue doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, // but we aren't using SdkError. - .map_err( - crate::operation::get_string_known_value::GetStringKnownValueError::unhandled, - )?; - crate::operation::get_string_known_value::GetStringKnownValue::send(&self.client, input) - .await + .map_err(crate::operation::get_string_known_value::GetStringKnownValueError::unhandled)?; + crate::operation::get_string_known_value::GetStringKnownValue::send(&self.client, input).await } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.inner = self.inner.value(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8.rs index 966f215250..d27e047855 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetStringUTF8`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -15,8 +17,7 @@ impl GetStringUTF8 { crate::operation::get_string_utf8::GetStringUTF8Output, crate::operation::get_string_utf8::GetStringUTF8Error, > { - let inner_input = - crate::conversions::get_string_utf8::_get_string_utf8_input::to_dafny(input); + let inner_input = crate::conversions::get_string_utf8::_get_string_utf8_input::to_dafny(input); let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetStringUTF8(&inner_input); if matches!( @@ -138,9 +139,9 @@ pub use crate::operation::get_string_utf8::_get_string_utf8_output::GetStringUTF pub use crate::operation::get_string_utf8::_get_string_utf8_input::GetStringUTF8Input; -mod _get_string_utf8_input; +pub(crate) mod _get_string_utf8_output; -mod _get_string_utf8_output; +pub(crate) mod _get_string_utf8_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_input.rs index a448688ed3..8950b2a8c0 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_input.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_input.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetStringUTF8Input { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, +pub value: ::std::option::Option<::std::string::String>, } impl GetStringUTF8Input { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} } impl GetStringUTF8Input { /// Creates a new builder-style object to manufacture [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). @@ -29,19 +31,19 @@ pub struct GetStringUTF8InputBuilder { } impl GetStringUTF8InputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} /// Consumes the builder and constructs a [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_output.rs index 2c8dca6a85..bb7220129d 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_output.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/_get_string_utf8_output.rs @@ -1,16 +1,18 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetStringUTF8Output { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, +pub value: ::std::option::Option<::std::string::String>, } impl GetStringUTF8Output { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} } impl GetStringUTF8Output { /// Creates a new builder-style object to manufacture [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). @@ -29,19 +31,19 @@ pub struct GetStringUTF8OutputBuilder { } impl GetStringUTF8OutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} /// Consumes the builder and constructs a [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). pub fn build( self, diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/builders.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/builders.rs index 26bf3d9e26..2291919ec3 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/builders.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8/builders.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_string_utf8::_get_string_utf8_output::GetStringUTF8OutputBuilder; pub use crate::operation::get_string_utf8::_get_string_utf8_input::GetStringUTF8InputBuilder; @@ -21,21 +23,19 @@ impl GetStringUTF8InputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetStringUTF8FluentBuilder { - client: crate::Client, - inner: crate::operation::get_string_utf8::builders::GetStringUTF8InputBuilder, + client: crate::client::Client, + pub(crate) inner: crate::operation::get_string_utf8::builders::GetStringUTF8InputBuilder, } impl GetStringUTF8FluentBuilder { /// Creates a new `GetStringUTF8`. - pub(crate) fn new(client: crate::Client) -> Self { + pub(crate) fn new(client: crate::client::Client) -> Self { Self { client, inner: ::std::default::Default::default(), } } /// Access the GetStringUTF8 as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_string_utf8::builders::GetStringUTF8InputBuilder { + pub fn as_input(&self) -> &crate::operation::get_string_utf8::builders::GetStringUTF8InputBuilder { &self.inner } /// Sends the request and returns the response. @@ -48,7 +48,7 @@ impl GetStringUTF8FluentBuilder { let input = self .inner .build() - // Using unhandled since GetString doesn't declare any validation, + // Using unhandled since GetStringUTF8 doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, @@ -58,17 +58,17 @@ impl GetStringUTF8FluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.inner = self.inner.value(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value.rs index 16b06252a3..47bb6d9ea5 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetStringUTF8KnownValue`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -10,13 +12,12 @@ impl GetStringUTF8KnownValue { } pub(crate) async fn send( client: &crate::client::Client, - input: crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput, + input: crate::operation::get_string_utf8_known_value::GetStringUTF8Input, ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, + crate::operation::get_string_utf8_known_value::GetStringUTF8Output, crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError, > { - let inner_input = - crate::conversions::get_string_utf8_known_value::_get_string_utf8_known_value_input::to_dafny(input); + let inner_input = crate::conversions::get_string_utf8_known_value::_get_string_utf8_known_value_input::to_dafny(input); let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).GetStringUTF8KnownValue(&inner_input); if matches!( @@ -134,13 +135,13 @@ impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetStrin } } -pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_known_value_output::GetStringUTF8KnownValueOutput; +pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_output::GetStringUTF8Output; -pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_known_value_input::GetStringUTF8KnownValueInput; +pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_input::GetStringUTF8Input; -mod _get_string_utf8_known_value_input; +pub(crate) mod _get_string_utf8_output; -mod _get_string_utf8_known_value_output; +pub(crate) mod _get_string_utf8_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_input.rs new file mode 100644 index 0000000000..6e21c111bd --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_input.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetStringUTF8Input { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::string::String>, +} +impl GetStringUTF8Input { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} +} +impl GetStringUTF8Input { + /// Creates a new builder-style object to manufacture [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). + pub fn builder() -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8InputBuilder { + crate::operation::get_string_utf8_known_value::builders::GetStringUTF8InputBuilder::default() + } +} + +/// A builder for [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetStringUTF8InputBuilder { + pub(crate) value: ::std::option::Option<::std::string::String>, +} +impl GetStringUTF8InputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} + /// Consumes the builder and constructs a [`GetStringUTF8Input`](crate::operation::operation::GetStringUTF8Input). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_string_utf8_known_value::GetStringUTF8Input, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_string_utf8_known_value::GetStringUTF8Input { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs deleted file mode 100644 index 6b73af0d8f..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_input.rs +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetStringUTF8KnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, -} -impl GetStringUTF8KnownValueInput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } -} -impl GetStringUTF8KnownValueInput { - /// Creates a new builder-style object to manufacture [`GetStringUTF8KnownValueInput`](crate::operation::operation::GetStringUTF8KnownValueInput). - pub fn builder() -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueInputBuilder { - crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueInputBuilder::default() - } -} - -/// A builder for [`GetStringUTF8KnownValueInput`](crate::operation::operation::GetStringUTF8KnownValueInput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetStringUTF8KnownValueInputBuilder { - pub(crate) value: ::std::option::Option<::std::string::String>, -} -impl GetStringUTF8KnownValueInputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } - /// Consumes the builder and constructs a [`GetStringUTF8KnownValueInput`](crate::operation::operation::GetStringUTF8KnownValueInput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueInput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs deleted file mode 100644 index 8c77126081..0000000000 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_known_value_output.rs +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -#[allow(missing_docs)] // documentation missing in model -#[non_exhaustive] -#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] -pub struct GetStringUTF8KnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::std::string::String>, -} -impl GetStringUTF8KnownValueOutput { - #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&str> { - self.value.as_deref() - } -} -impl GetStringUTF8KnownValueOutput { - /// Creates a new builder-style object to manufacture [`GetStringUTF8KnownValueOutput`](crate::operation::operation::GetStringUTF8KnownValueOutput). - pub fn builder() -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueOutputBuilder { - crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueOutputBuilder::default() - } -} - -/// A builder for [`GetStringUTF8KnownValueOutput`](crate::operation::operation::GetStringUTF8KnownValueOutput). -#[non_exhaustive] -#[derive( - ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, -)] -pub struct GetStringUTF8KnownValueOutputBuilder { - pub(crate) value: ::std::option::Option<::std::string::String>, -} -impl GetStringUTF8KnownValueOutputBuilder { - #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.value = ::std::option::Option::Some(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - &self.value - } - /// Consumes the builder and constructs a [`GetStringUTF8KnownValueOutput`](crate::operation::operation::GetStringUTF8KnownValueOutput). - pub fn build( - self, - ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, - ::aws_smithy_types::error::operation::BuildError, - > { - ::std::result::Result::Ok(crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput { - value: self.value, - }) - } -} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_output.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_output.rs new file mode 100644 index 0000000000..f1dfb24b67 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/_get_string_utf8_output.rs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +#[allow(missing_docs)] // documentation missing in model +#[non_exhaustive] +#[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] +pub struct GetStringUTF8Output { + #[allow(missing_docs)] // documentation missing in model +pub value: ::std::option::Option<::std::string::String>, +} +impl GetStringUTF8Output { + #[allow(missing_docs)] // documentation missing in model +pub fn value(&self) -> ::std::option::Option<::std::string::String> { + self.value.clone() +} +} +impl GetStringUTF8Output { + /// Creates a new builder-style object to manufacture [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). + pub fn builder() -> crate::operation::get_string_utf8_known_value::builders::GetStringUTF8OutputBuilder { + crate::operation::get_string_utf8_known_value::builders::GetStringUTF8OutputBuilder::default() + } +} + +/// A builder for [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). +#[non_exhaustive] +#[derive( + ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, +)] +pub struct GetStringUTF8OutputBuilder { + pub(crate) value: ::std::option::Option<::std::string::String>, +} +impl GetStringUTF8OutputBuilder { + #[allow(missing_docs)] // documentation missing in model +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + &self.value +} + /// Consumes the builder and constructs a [`GetStringUTF8Output`](crate::operation::operation::GetStringUTF8Output). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_string_utf8_known_value::GetStringUTF8Output, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_string_utf8_known_value::GetStringUTF8Output { + value: self.value, + }) + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/builders.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/builders.rs index 0b29a00e10..c6e957eee6 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/builders.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/operation/get_string_utf8_known_value/builders.rs @@ -1,15 +1,17 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_known_value_output::GetStringUTF8KnownValueOutputBuilder; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_output::GetStringUTF8OutputBuilder; -pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_known_value_input::GetStringUTF8KnownValueInputBuilder; +pub use crate::operation::get_string_utf8_known_value::_get_string_utf8_input::GetStringUTF8InputBuilder; -impl GetStringUTF8KnownValueInputBuilder { +impl GetStringUTF8InputBuilder { /// Sends a request with this input using the given client. pub async fn send_with( self, client: &crate::Client, ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, + crate::operation::get_string_utf8_known_value::GetStringUTF8Output, crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError, > { let mut fluent_builder = client.get_string_utf8_known_value(); @@ -21,34 +23,32 @@ impl GetStringUTF8KnownValueInputBuilder { /// #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetStringUTF8KnownValueFluentBuilder { - client: crate::Client, - inner: crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueInputBuilder, + client: crate::client::Client, + pub(crate) inner: crate::operation::get_string_utf8_known_value::builders::GetStringUTF8InputBuilder, } impl GetStringUTF8KnownValueFluentBuilder { /// Creates a new `GetStringUTF8KnownValue`. - pub(crate) fn new(client: crate::Client) -> Self { + pub(crate) fn new(client: crate::client::Client) -> Self { Self { client, inner: ::std::default::Default::default(), } } /// Access the GetStringUTF8KnownValue as a reference. - pub fn as_input( - &self, - ) -> &crate::operation::get_string_utf8_known_value::builders::GetStringUTF8KnownValueInputBuilder { + pub fn as_input(&self) -> &crate::operation::get_string_utf8_known_value::builders::GetStringUTF8InputBuilder { &self.inner } /// Sends the request and returns the response. pub async fn send( self, ) -> ::std::result::Result< - crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueOutput, + crate::operation::get_string_utf8_known_value::GetStringUTF8Output, crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValueError, > { let input = self .inner .build() - // Using unhandled since GetString doesn't declare any validation, + // Using unhandled since GetStringUTF8KnownValue doesn't declare any validation, // and smithy-rs seems to not generate a ValidationError case unless there is // (but isn't that a backwards compatibility problem for output structures?) // Vanilla smithy-rs uses SdkError::construction_failure, @@ -58,17 +58,17 @@ impl GetStringUTF8KnownValueFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { - self.inner = self.inner.value(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::std::string::String>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::std::string::String> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types.rs index 7ec7460923..9e117395c3 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `SimpleStringConfig` pub mod simple_string_config; diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types/simple_string_config.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types/simple_string_config.rs index 6b9ec61a06..94d186d226 100644 --- a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types/simple_string_config.rs +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/types/simple_string_config.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleStringConfig {} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..4f32d02ae7 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::smithystring::internaldafny::wrapped::_default { + pub fn WrappedSimpleString(config: &::std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::SimpleStringConfig, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..f89535dd13 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleString/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,179 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::smithystring::internaldafny::types::ISimpleTypesStringClient); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::SimpleStringConfig, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_string_config::_simple_string_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::smithystring::internaldafny::types::ISimpleTypesStringClient for Client { + fn GetString( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_string::_get_string_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_string::GetString::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_string::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_string::_get_string_output::to_dafny(client), + }, + ), + } + } + + fn GetStringKnownValue( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_string_known_value::_get_string_known_value_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_string_known_value::GetStringKnownValue::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_string_known_value::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_string_known_value::_get_string_known_value_output::to_dafny(client), + }, + ), + } + } + + fn GetStringUTF8( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_string_utf8::_get_string_utf8_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_string_utf8::GetStringUTF8::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_string_utf8::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_string_utf8::_get_string_utf8_output::to_dafny(client), + }, + ), + } + } + + fn GetStringUTF8KnownValue( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Input, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::smithystring::internaldafny::types::GetStringUTF8Output, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_string_utf8_known_value::_get_string_utf8_known_value_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_string_utf8_known_value::GetStringUTF8KnownValue::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_string_utf8_known_value::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_string_utf8_known_value::_get_string_utf8_known_value_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/Makefile b/TestModels/SimpleTypes/SimpleTimestamp/Makefile index 6575072c56..55d0f10c8b 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/Makefile +++ b/TestModels/SimpleTypes/SimpleTimestamp/Makefile @@ -3,8 +3,9 @@ CORES=2 +TRANSPILE_TESTS_IN_RUST=1 + ENABLE_EXTERN_PROCESSING=1 -RUST_BENERATED=1 include ../../SharedMakefile.mk @@ -22,10 +23,8 @@ SMITHY_DEPS=dafny-dependencies/Model/traits.smithy # This project has no dependencies # DEPENDENT-MODELS:= - POLYMORPH_OPTIONS=--generate client-constructors,project-files - # Constants for languages that drop extern names (Python, Go) TYPES_FILE_PATH=Model/SimpleTypesTimestampTypes.dfy diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/Cargo.toml b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/Cargo.toml index 94927ac487..de5d419467 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/Cargo.toml +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/Cargo.toml @@ -5,14 +5,21 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +wrapped-client = [] + [dependencies] -dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} aws-smithy-runtime = { version = "1.6.0", features = ["client"] } aws-smithy-runtime-api = { version = "1.7.0", features = ["client"] } aws-smithy-types = "1.2.0" +dafny_runtime = { path = "../../../../dafny-dependencies/dafny_runtime_rust"} [dev-dependencies] -tokio = { version = "1.26.0", features = ["full"] } +simple_timestamp = { path = ".", features = ["wrapped-client"] } + +[dependencies.tokio] +version = "1.26.0" +features = ["full"] [lib] path = "src/implementation_from_dafny.rs" diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client.rs index 1691812f17..c87832fe22 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use aws_smithy_types::error::operation::BuildError; #[derive(::std::clone::Clone, ::std::fmt::Debug)] @@ -29,7 +30,7 @@ impl Client { )); } Ok(Self { - dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()), + dafny_client: ::dafny_runtime::upcast_object()(inner.Extract()) }) } } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client/get_timestamp.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client/get_timestamp.rs index 9004f4f30c..e272f76759 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client/get_timestamp.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/client/get_timestamp.rs @@ -1,15 +1,15 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. impl super::Client { /// Constructs a fluent builder for the [`GetTimestamp`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder) operation. /// /// - The fluent builder is configurable: - /// - [`value(DateTime)`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::value) / [`set_value(Option)`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::set_value):
required: **false**
(undocumented)
+ /// - [`value(impl Into>)`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::value) / [`set_value(Option<::aws_smithy_types::DateTime>)`](crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::set_value): (undocumented)
/// - On success, responds with [`GetTimestampOutput`](crate::operation::get_timestamp::GetTimestampOutput) with field(s): - /// - [`value(Option)`](crate::operation::get_timestamp::GetTimestampOutput::value): (undocumented) + /// - [`value(Option<::aws_smithy_types::DateTime>)`](crate::operation::get_timestamp::GetTimestampOutput::value): (undocumented) /// - On failure, responds with [`SdkError`](crate::operation::get_timestamp::GetTimestampError) - pub fn get_timestamp( - &self, - ) -> crate::operation::get_timestamp::builders::GetTimestampFluentBuilder { + pub fn get_timestamp(&self) -> crate::operation::get_timestamp::builders::GetTimestampFluentBuilder { crate::operation::get_timestamp::builders::GetTimestampFluentBuilder::new(self.clone()) } } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions.rs index 6c19c684d4..85c9ba3aa5 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions.rs @@ -1,4 +1,8 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. -pub mod get_timestamp; +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod error; -pub mod simple_timestamp_config; + pub mod get_timestamp; + + pub mod simple_timestamp_config; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/error.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/error.rs new file mode 100644 index 0000000000..255fc97000 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/error.rs @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + /// Wraps up an arbitrary Rust Error value as a Dafny Error +pub fn to_opaque_error(value: E) -> + ::std::rc::Rc +{ + let error_obj: ::dafny_runtime::Object = ::dafny_runtime::Object(Some( + ::std::rc::Rc::new(::std::cell::UnsafeCell::new(value)), + )); + ::std::rc::Rc::new( + crate::r#simple::types::timestamp::internaldafny::types::Error::Opaque { + obj: error_obj, + }, + ) +} + +/// Wraps up an arbitrary Rust Error value as a Dafny Result.Failure +pub fn to_opaque_error_result(value: E) -> + ::std::rc::Rc< + crate::_Wrappers_Compile::Result< + T, + ::std::rc::Rc + > + > +{ + ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: to_opaque_error(value), + }, + ) +} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp.rs index 64d9cf3a17..e96799af63 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp.rs @@ -1,12 +1,12 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. use std::any::Any; #[allow(dead_code)] pub fn to_dafny_error( value: crate::operation::get_timestamp::GetTimestampError, -) -> ::std::rc::Rc -{ +) -> ::std::rc::Rc { match value { crate::operation::get_timestamp::GetTimestampError::Unhandled(unhandled) => ::std::rc::Rc::new(crate::r#simple::types::timestamp::internaldafny::types::Error::Opaque { obj: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(unhandled)) }) diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_input.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_input.rs index ec1fde893a..b42a091567 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_input.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_input.rs @@ -1,39 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_timestamp::GetTimestampInput, ) -> ::std::rc::Rc< crate::r#simple::types::timestamp::internaldafny::types::GetTimestampInput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s.to_string()) }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::timestamp::internaldafny::types::GetTimestampInput::GetTimestampInput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::otimestamp_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::timestamp::internaldafny::types::GetTimestampInput, >, -) -> Result< - crate::operation::get_timestamp::GetTimestampInput, - aws_smithy_types::date_time::DateTimeParseError, -> { - let value = match dafny_value.value().as_ref() { - crate::_Wrappers_Compile::Option::None {} => None, - crate::_Wrappers_Compile::Option::Some { value } => { - let value = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&value); - let value = ::aws_smithy_types::DateTime::from_str( - &value, - aws_smithy_types::date_time::Format::DateTime, - )?; - Some(value) - } - }; - - Ok(crate::operation::get_timestamp::GetTimestampInput { value }) +) -> crate::operation::get_timestamp::GetTimestampInput { + crate::operation::get_timestamp::GetTimestampInput::builder() + .set_value(crate::standard_library_conversions::otimestamp_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_output.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_output.rs index 958069da06..09e9489bd3 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_output.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/get_timestamp/_get_timestamp_output.rs @@ -1,39 +1,24 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::operation::get_timestamp::GetTimestampOutput, ) -> ::std::rc::Rc< crate::r#simple::types::timestamp::internaldafny::types::GetTimestampOutput, -> { - let dafny_value = match value.value { - Some(s) => crate::_Wrappers_Compile::Option::Some { value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s.to_string()) }, - None => crate::_Wrappers_Compile::Option::None {}, - }; +>{ ::std::rc::Rc::new(crate::r#simple::types::timestamp::internaldafny::types::GetTimestampOutput::GetTimestampOutput { - value: ::std::rc::Rc::new(dafny_value) - }) + value: crate::standard_library_conversions::otimestamp_to_dafny(&value.value), + }) } - -#[allow(dead_code)] + #[allow(dead_code)] pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#simple::types::timestamp::internaldafny::types::GetTimestampOutput, >, -) -> Result< - crate::operation::get_timestamp::GetTimestampOutput, - aws_smithy_types::date_time::DateTimeParseError, -> { - let value = match dafny_value.value().as_ref() { - crate::_Wrappers_Compile::Option::None {} => None, - crate::_Wrappers_Compile::Option::Some { value } => { - let value = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&value); - let value = ::aws_smithy_types::DateTime::from_str( - &value, - aws_smithy_types::date_time::Format::DateTime, - )?; - Some(value) - } - }; - - Ok(crate::operation::get_timestamp::GetTimestampOutput { value }) +) -> crate::operation::get_timestamp::GetTimestampOutput { + crate::operation::get_timestamp::GetTimestampOutput::builder() + .set_value(crate::standard_library_conversions::otimestamp_from_dafny(dafny_value.value().clone())) + .build() + .unwrap() } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config.rs index 3ab1449023..f4c49447c2 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config.rs @@ -1,3 +1,4 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub mod _simple_timestamp_config; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config/_simple_timestamp_config.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config/_simple_timestamp_config.rs index 7a6ad17f9b..65be65a356 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config/_simple_timestamp_config.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/conversions/simple_timestamp_config/_simple_timestamp_config.rs @@ -1,11 +1,13 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(dead_code)] pub fn to_dafny( value: crate::types::simple_timestamp_config::SimpleTimestampConfig, ) -> ::std::rc::Rc< - crate::simple::types::timestamp::internaldafny::types::SimpleTimestampConfig, ->{ + crate::r#simple::types::timestamp::internaldafny::types::SimpleTimestampConfig, +> { ::std::rc::Rc::new(crate::r#simple::types::timestamp::internaldafny::types::SimpleTimestampConfig::SimpleTimestampConfig {}) } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error.rs index ec89cbecc9..4cddaa7c39 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use ::aws_smithy_runtime_api::box_error::BoxError; /// Error type returned by the client. diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error/sealed_unhandled.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error/sealed_unhandled.rs index cce22d1cfd..eae8007292 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error/sealed_unhandled.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/error/sealed_unhandled.rs @@ -1,4 +1,10 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use std::any::Any; + +use dafny_runtime::UpcastObject; + /// This struct is not intended to be used. /// /// This struct holds information about an unhandled error, @@ -21,6 +27,6 @@ pub struct Unhandled { pub(crate) meta: ::aws_smithy_types::error::metadata::ErrorMetadata, } -impl ::dafny_runtime::UpcastObject for Unhandled { +impl UpcastObject for Unhandled { ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/lib.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/lib.rs deleted file mode 100644 index 4e55b724cc..0000000000 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![allow(deprecated)] - -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - -pub mod client; -pub mod types; - -/// Common errors and error handling utilities. -pub mod error; - -/// All operations that this crate can perform. -pub mod operation; - -mod conversions; - -pub mod implementation_from_dafny; - -pub use client::Client; -pub use types::simple_timestamp_config::SimpleTimestampConfig; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation.rs index 14ae6ca55a..e1bae12748 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `GetTimestamp` operation. pub mod get_timestamp; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp.rs index 27f406c721..a393c9880c 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Orchestration and serialization glue logic for `GetTimestamp`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] @@ -22,10 +24,11 @@ impl GetTimestamp { inner_result.as_ref(), crate::r#_Wrappers_Compile::Result::Success { .. } ) { - crate::conversions::get_timestamp::_get_timestamp_output::from_dafny( - inner_result.value().clone(), + Ok( + crate::conversions::get_timestamp::_get_timestamp_output::from_dafny( + inner_result.value().clone(), + ), ) - .map_err(crate::operation::get_timestamp::GetTimestampError::unhandled) } else { Err(crate::conversions::get_timestamp::from_dafny_error( inner_result.error().clone(), @@ -136,9 +139,9 @@ pub use crate::operation::get_timestamp::_get_timestamp_output::GetTimestampOutp pub use crate::operation::get_timestamp::_get_timestamp_input::GetTimestampInput; -mod _get_timestamp_input; +pub(crate) mod _get_timestamp_output; -mod _get_timestamp_output; +pub(crate) mod _get_timestamp_input; /// Builders pub mod builders; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_input.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_input.rs index acf259d313..1155b34c91 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_input.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_input.rs @@ -1,25 +1,27 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetTimestampInput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::aws_smithy_types::DateTime>, +pub value: ::std::option::Option<::aws_smithy_types::DateTime>, } impl GetTimestampInput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&::aws_smithy_types::DateTime> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::DateTime> { + self.value +} } impl GetTimestampInput { - /// Creates a new builder-style object to manufacture [`GetTimestampInput`](crate::operation::get_timestamp::GetTimestampInput). + /// Creates a new builder-style object to manufacture [`GetTimestampInput`](crate::operation::operation::GetTimestampInput). pub fn builder() -> crate::operation::get_timestamp::builders::GetTimestampInputBuilder { crate::operation::get_timestamp::builders::GetTimestampInputBuilder::default() } } -/// A builder for [`GetTimestampInput`](crate::operation::get_timestamp::GetTimestampInput). +/// A builder for [`GetTimestampInput`](crate::operation::operation::GetTimestampInput). #[non_exhaustive] #[derive( ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, @@ -29,20 +31,20 @@ pub struct GetTimestampInputBuilder { } impl GetTimestampInputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: ::aws_smithy_types::DateTime) -> Self { - self.value = ::std::option::Option::Some(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { - &self.value - } - /// Consumes the builder and constructs a [`GetTimestampInput`](crate::operation::get_timestamp::GetTimestampInput). +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::DateTime>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { + &self.value +} + /// Consumes the builder and constructs a [`GetTimestampInput`](crate::operation::operation::GetTimestampInput). pub fn build( self, ) -> ::std::result::Result< diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_output.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_output.rs index 711324b3a8..c4f3ab84e0 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_output.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/_get_timestamp_output.rs @@ -1,25 +1,27 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetTimestampOutput { #[allow(missing_docs)] // documentation missing in model - pub value: ::std::option::Option<::aws_smithy_types::DateTime>, +pub value: ::std::option::Option<::aws_smithy_types::DateTime>, } impl GetTimestampOutput { #[allow(missing_docs)] // documentation missing in model - pub fn value(&self) -> ::std::option::Option<&::aws_smithy_types::DateTime> { - self.value.as_ref() - } +pub fn value(&self) -> ::std::option::Option<::aws_smithy_types::DateTime> { + self.value +} } impl GetTimestampOutput { - /// Creates a new builder-style object to manufacture [`GetTimestampOutput`](crate::operation::get_timestamp::GetTimestampOutput). + /// Creates a new builder-style object to manufacture [`GetTimestampOutput`](crate::operation::operation::GetTimestampOutput). pub fn builder() -> crate::operation::get_timestamp::builders::GetTimestampOutputBuilder { crate::operation::get_timestamp::builders::GetTimestampOutputBuilder::default() } } -/// A builder for [`GetTimestampOutput`](crate::operation::get_timestamp::GetTimestampOutput). +/// A builder for [`GetTimestampOutput`](crate::operation::operation::GetTimestampOutput). #[non_exhaustive] #[derive( ::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, @@ -29,21 +31,28 @@ pub struct GetTimestampOutputBuilder { } impl GetTimestampOutputBuilder { #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: ::aws_smithy_types::DateTime) -> Self { - self.value = ::std::option::Option::Some(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { - self.value = input; - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { - &self.value - } - /// Consumes the builder and constructs a [`GetTimestampOutput`](crate::operation::get_timestamp::GetTimestampOutput). - pub fn build(self) -> crate::operation::get_timestamp::GetTimestampOutput { - crate::operation::get_timestamp::GetTimestampOutput { value: self.value } +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::DateTime>) -> Self { + self.value = ::std::option::Option::Some(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { + self.value = input; + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { + &self.value +} + /// Consumes the builder and constructs a [`GetTimestampOutput`](crate::operation::operation::GetTimestampOutput). + pub fn build( + self, + ) -> ::std::result::Result< + crate::operation::get_timestamp::GetTimestampOutput, + ::aws_smithy_types::error::operation::BuildError, + > { + ::std::result::Result::Ok(crate::operation::get_timestamp::GetTimestampOutput { + value: self.value, + }) } } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/builders.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/builders.rs index 6097f5dc0d..4f9282db2a 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/builders.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/operation/get_timestamp/builders.rs @@ -1,4 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. pub use crate::operation::get_timestamp::_get_timestamp_output::GetTimestampOutputBuilder; pub use crate::operation::get_timestamp::_get_timestamp_input::GetTimestampInputBuilder; @@ -22,7 +24,7 @@ impl GetTimestampInputBuilder { #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct GetTimestampFluentBuilder { client: crate::client::Client, - inner: crate::operation::get_timestamp::builders::GetTimestampInputBuilder, + pub(crate) inner: crate::operation::get_timestamp::builders::GetTimestampInputBuilder, } impl GetTimestampFluentBuilder { /// Creates a new `GetTimestamp`. @@ -56,17 +58,17 @@ impl GetTimestampFluentBuilder { } #[allow(missing_docs)] // documentation missing in model - pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::DateTime>) -> Self { - self.inner = self.inner.value(input.into()); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { - self.inner = self.inner.set_value(input); - self - } - #[allow(missing_docs)] // documentation missing in model - pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { - self.inner.get_value() - } +pub fn value(mut self, input: impl ::std::convert::Into<::aws_smithy_types::DateTime>) -> Self { + self.inner = self.inner.value(input.into()); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn set_value(mut self, input: ::std::option::Option<::aws_smithy_types::DateTime>) -> Self { + self.inner = self.inner.set_value(input); + self +} +#[allow(missing_docs)] // documentation missing in model +pub fn get_value(&self) -> &::std::option::Option<::aws_smithy_types::DateTime> { + self.inner.get_value() +} } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_conversions.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_conversions.rs index 3a51134c6e..6bf8297d8a 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_conversions.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_conversions.rs @@ -1,246 +1,266 @@ pub fn ostring_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, > { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) - }, - None => crate::_Wrappers_Compile::Option::None {}, + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&b) + }, + None => crate::_Wrappers_Compile::Option::None {}, }; - ::std::rc::Rc::new(dafny_value) + ::std::rc::Rc::new(dafny_value) } pub fn ostring_from_dafny( - input: ::std::rc::Rc< - crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, - >, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some( - dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( - &input.Extract(), - ), - ) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some( + dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input.Extract(), + ), + ) + } else { + None + } } -pub fn obool_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn obool_to_dafny( + input: &Option, +) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn obool_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn obool_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } pub fn oint_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn oint_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn olong_to_dafny(input: Option) -> ::std::rc::Rc> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { value: b }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) +pub fn olong_to_dafny(input: &Option) -> ::std::rc::Rc> { + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { value: *b }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn olong_from_dafny(input: ::std::rc::Rc>) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(input.Extract()) - } else { - None - } +pub fn olong_from_dafny( + input: ::std::rc::Rc>, +) -> Option { + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(input.Extract()) + } else { + None + } } -pub fn blob_to_dafny( - input: &::aws_smithy_types::Blob, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) +pub fn blob_to_dafny(input: &::aws_smithy_types::Blob) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&input.clone().into_inner(), |x| *x) } pub fn oblob_to_dafny( - input: &Option<::aws_smithy_types::Blob>, + input: &Option<::aws_smithy_types::Blob>, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(b) => crate::_Wrappers_Compile::Option::Some { - value: blob_to_dafny(&b), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(b) => crate::_Wrappers_Compile::Option::Some { + value: blob_to_dafny(&b), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn blob_from_dafny( - input: ::dafny_runtime::Sequence, -) -> ::aws_smithy_types::Blob { - - ::aws_smithy_types::Blob::new( - ::std::rc::Rc::try_unwrap(input.to_array()) - .unwrap_or_else(|rc| (*rc).clone()), - ) +pub fn blob_from_dafny(input: ::dafny_runtime::Sequence) -> ::aws_smithy_types::Blob { + ::aws_smithy_types::Blob::new( + ::std::rc::Rc::try_unwrap(input.to_array()).unwrap_or_else(|rc| (*rc).clone()), + ) } pub fn oblob_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option<::aws_smithy_types::Blob> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(blob_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(blob_from_dafny(input.Extract())) + } else { + None + } } -pub fn double_to_dafny( - input: f64, -) -> ::dafny_runtime::Sequence { - ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( - &f64::to_be_bytes(input).to_vec(), - |x| *x) +pub fn double_to_dafny(input: f64) -> ::dafny_runtime::Sequence { + ::dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence( + &f64::to_be_bytes(input).to_vec(), + |x| *x, + ) } pub fn odouble_to_dafny( - input: &Option, + input: &Option, ) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: double_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: double_to_dafny(*f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } -pub fn double_from_dafny( - input: &::dafny_runtime::Sequence, -) -> f64 { - let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); - f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) +pub fn double_from_dafny(input: &::dafny_runtime::Sequence) -> f64 { + let v = ::dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(input, |x| *x); + f64::from_be_bytes(v.try_into().expect("Error converting Sequence to f64")) } pub fn odouble_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc>>, ) -> Option { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(double_from_dafny(&input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(double_from_dafny(&input.Extract())) + } else { + None + } } pub fn timestamp_to_dafny( - input: ::aws_smithy_types::DateTime, + input: &::aws_smithy_types::DateTime, ) -> ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16> { - ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&input.to_string()) + ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &input.to_string(), + ) } pub fn otimestamp_to_dafny( - input: &Option<::aws_smithy_types::DateTime>, -) -> ::std::rc::Rc>> { - let dafny_value = match input { - Some(f) => crate::_Wrappers_Compile::Option::Some { - value: timestamp_to_dafny(*f), - }, - None => crate::_Wrappers_Compile::Option::None {}, - }; - ::std::rc::Rc::new(dafny_value) + input: &Option<::aws_smithy_types::DateTime>, +) -> ::std::rc::Rc< + crate::_Wrappers_Compile::Option<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>, +> { + let dafny_value = match input { + Some(f) => crate::_Wrappers_Compile::Option::Some { + value: timestamp_to_dafny(f), + }, + None => crate::_Wrappers_Compile::Option::None {}, + }; + ::std::rc::Rc::new(dafny_value) } pub fn timestamp_from_dafny( - input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + input: ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, ) -> ::aws_smithy_types::DateTime { - let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string(&input); - ::aws_smithy_types::DateTime::from_str( - &s, - aws_smithy_types::date_time::Format::DateTime, - ).unwrap() + let s = dafny_runtime::dafny_runtime_conversions::unicode_chars_false::dafny_string_to_string( + &input, + ); + ::aws_smithy_types::DateTime::from_str(&s, aws_smithy_types::date_time::Format::DateTime) + .unwrap() } pub fn otimestamp_from_dafny( - input: ::std::rc::Rc>>, + input: ::std::rc::Rc< + crate::_Wrappers_Compile::Option< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + >, ) -> Option<::aws_smithy_types::DateTime> { - if matches!(input.as_ref(), crate::_Wrappers_Compile::Option::Some { .. }) { - Some(timestamp_from_dafny(input.Extract())) - } else { - None - } + if matches!( + input.as_ref(), + crate::_Wrappers_Compile::Option::Some { .. } + ) { + Some(timestamp_from_dafny(input.Extract())) + } else { + None + } } pub fn option_from_dafny( - input: ::std::rc::Rc>, - converter: fn(&T) -> TR, + input: ::std::rc::Rc>, + converter: fn(&T) -> TR, ) -> Option { - match &*input { - crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), - crate::_Wrappers_Compile::Option::None { } => None, - } + match &*input { + crate::_Wrappers_Compile::Option::Some { value } => Some(converter(value)), + crate::_Wrappers_Compile::Option::None {} => None, + } } pub fn option_to_dafny( - input: &Option, - converter: fn(&TR) -> T, + input: &Option, + converter: fn(&TR) -> T, ) -> ::std::rc::Rc> { - match input { - Some(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::Some { - value: converter(&value) - } - ), - None => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Option::None {} - ), - } + match input { + Some(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::Some { + value: converter(&value), + }), + None => ::std::rc::Rc::new(crate::_Wrappers_Compile::Option::None {}), + } } pub fn result_from_dafny( - input: ::std::rc::Rc>, - converter_t: fn(&T) -> TR, - converter_e: fn(&E) -> ER, + input: ::std::rc::Rc>, + converter_t: fn(&T) -> TR, + converter_e: fn(&E) -> ER, ) -> Result { - match &*input { - crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), - crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), - } + match &*input { + crate::_Wrappers_Compile::Result::Success { value } => Ok(converter_t(value)), + crate::_Wrappers_Compile::Result::Failure { error } => Err(converter_e(error)), + } } pub fn result_to_dafny( - input: &Result, - converter_t: fn(&TR) -> T, - converter_e: fn(&ER) -> E, + input: &Result, + converter_t: fn(&TR) -> T, + converter_e: fn(&ER) -> E, ) -> ::std::rc::Rc> { - match input { - Ok(value) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Success { - value: converter_t(&value) - } - ), - Err(error) => ::std::rc::Rc::new( - crate::_Wrappers_Compile::Result::Failure { - error: converter_e(&error) - } - ), - } -} \ No newline at end of file + match input { + Ok(value) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Success { + value: converter_t(&value), + }), + Err(error) => ::std::rc::Rc::new(crate::_Wrappers_Compile::Result::Failure { + error: converter_e(&error), + }), + } +} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_externs.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types.rs index b22d67ccbb..7eff17a000 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types.rs @@ -1,4 +1,5 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. /// Types for the `SimpleTimestampConfig` pub mod simple_timestamp_config; diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types/simple_timestamp_config.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types/simple_timestamp_config.rs index 611191c990..678b4ac557 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types/simple_timestamp_config.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/types/simple_timestamp_config.rs @@ -1,5 +1,6 @@ -// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. - +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. #[derive(::std::clone::Clone, ::std::fmt::Debug)] pub struct SimpleTimestampConfig {} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped.rs new file mode 100644 index 0000000000..cefeb4517d --- /dev/null +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped.rs @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +pub mod client; + +impl crate::r#simple::types::timestamp::internaldafny::wrapped::_default { + pub fn WrappedSimpleTimestamp(config: &::std::rc::Rc< + crate::r#simple::types::timestamp::internaldafny::types::SimpleTimestampConfig, + >) -> ::std::rc::Rc, + ::std::rc::Rc + >>{ + crate::wrapped::client::Client::from_conf(config) + } +} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped/client.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped/client.rs new file mode 100644 index 0000000000..c33b27e948 --- /dev/null +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/src/wrapped/client.rs @@ -0,0 +1,89 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +use tokio::runtime::Runtime; + +pub struct Client { + wrapped: crate::client::Client, + + /// A `current_thread` runtime for executing operations on the + /// asynchronous client in a blocking manner. + rt: Runtime +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn crate::r#simple::types::timestamp::internaldafny::types::ISimpleTypesTimestampClient); +} + +impl dafny_runtime::UpcastObject for Client { + ::dafny_runtime::UpcastObjectFn!(dyn ::std::any::Any); +} + +impl Client { + pub fn from_conf(config: &::std::rc::Rc< + crate::r#simple::types::timestamp::internaldafny::types::SimpleTimestampConfig, + >) -> +::std::rc::Rc, + ::std::rc::Rc +>> { + let rt_result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let rt = match rt_result { + Ok(x) => x, + Err(error) => return crate::conversions::error::to_opaque_error_result(error), + }; + let result = crate::client::Client::from_conf( + crate::conversions::simple_timestamp_config::_simple_timestamp_config::from_dafny( + config.clone(), + ), + ); + match result { + Ok(client) => { + let wrap = crate::wrapped::client::Client { + wrapped: client, + rt + }; + std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: ::dafny_runtime::upcast_object()(::dafny_runtime::object::new(wrap)) + } + ) + }, + Err(error) => crate::conversions::error::to_opaque_error_result(error) + } + } +} + +impl crate::r#simple::types::timestamp::internaldafny::types::ISimpleTypesTimestampClient for Client { + fn GetTimestamp( + &mut self, + input: &std::rc::Rc< + crate::r#simple::types::timestamp::internaldafny::types::GetTimestampInput, + >, + ) -> std::rc::Rc< + crate::r#_Wrappers_Compile::Result< + std::rc::Rc< + crate::r#simple::types::timestamp::internaldafny::types::GetTimestampOutput, + >, + std::rc::Rc, + >, + >{ + let inner_input = + crate::conversions::get_timestamp::_get_timestamp_input::from_dafny(input.clone()); + let result = self.rt.block_on(crate::operation::get_timestamp::GetTimestamp::send(&self.wrapped, inner_input)); + match result { + Err(error) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Failure { + error: crate::conversions::get_timestamp::to_dafny_error(error), + }, + ), + Ok(client) => ::std::rc::Rc::new( + crate::_Wrappers_Compile::Result::Success { + value: crate::conversions::get_timestamp::_get_timestamp_output::to_dafny(client), + }, + ), + } + } +} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/tests/simple_timestamp_test.rs b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/tests/simple_timestamp_test.rs index b6b60a0483..f45eb0c6ee 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/tests/simple_timestamp_test.rs +++ b/TestModels/SimpleTypes/SimpleTimestamp/runtimes/rust/tests/simple_timestamp_test.rs @@ -28,7 +28,7 @@ async fn test_get_timestamp() { .unwrap(); let result = client().get_timestamp().value(ts).send().await.unwrap(); let value = result.value().unwrap(); - assert_eq!(value, &ts); + assert_eq!(value, ts); } pub fn client() -> Client { diff --git a/TestModels/SimpleTypes/SimpleTimestamp/src/WrappedSimpleTypesTimestampImpl.dfy b/TestModels/SimpleTypes/SimpleTimestamp/src/WrappedSimpleTypesTimestampImpl.dfy new file mode 100644 index 0000000000..ce9fc36dbc --- /dev/null +++ b/TestModels/SimpleTypes/SimpleTimestamp/src/WrappedSimpleTypesTimestampImpl.dfy @@ -0,0 +1,10 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/SimpleTypesTimestampTypesWrapped.dfy" + +module {:options "--function-syntax:4"} {:extern "simple.types.timestamp.internaldafny.wrapped"} WrappedSimpleTypesTimestampService refines WrappedAbstractSimpleTypesTimestampService { + import WrappedService = SimpleTimestamp + function WrappedDefaultSimpleTimestampConfig(): SimpleTimestampConfig { + SimpleTimestampConfig + } +} diff --git a/TestModels/SimpleTypes/SimpleTimestamp/test/SimpleTimestampImplTest.dfy b/TestModels/SimpleTypes/SimpleTimestamp/test/SimpleTimestampImplTest.dfy index 7cd928417e..a30f145cd2 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/test/SimpleTimestampImplTest.dfy +++ b/TestModels/SimpleTypes/SimpleTimestamp/test/SimpleTimestampImplTest.dfy @@ -12,6 +12,7 @@ module SimpleTimestampImplTest { var client :- expect SimpleTimestamp.SimpleTimestamp(); TestGetTimestamp(client); + TestGetTimestampNoMs(client); } method TestGetTimestamp(client: ISimpleTypesTimestampClient) @@ -19,9 +20,26 @@ module SimpleTimestampImplTest { modifies client.Modifies ensures client.ValidState() { - var dafnyTimestamp := "2024-06-11T12:34:56"; - var ret :- expect client.GetTimestamp(SimpleTimestamp.Types.GetTimestampInput(value:= Some(dafnyTimestamp))); + var dafnyTimestamp := "2024-06-11T12:34:56.789Z"; + var ret :- expect client.GetTimestamp(SimpleTimestamp.Types.GetTimestampInput(value := Some(dafnyTimestamp))); expect ret.value == Some(dafnyTimestamp); print ret; } + + method TestGetTimestampNoMs(client: ISimpleTypesTimestampClient) + requires client.ValidState() + modifies client.Modifies + ensures client.ValidState() + { + var dafnyTimestamp := "2024-06-11T12:34:56Z"; + var ret :- expect client.GetTimestamp(SimpleTimestamp.Types.GetTimestampInput(value := Some(dafnyTimestamp))); + expect ret.value.Some?; + var retTimestamp := ret.value.value; + + // It's okay if milliseconds are serialized, so only check for prefix + expect |retTimestamp| > 0; + expect retTimestamp[|retTimestamp| - 1] == 'Z'; + expect dafnyTimestamp[|dafnyTimestamp| - 1] <= retTimestamp[|retTimestamp| - 1]; + print ret; + } } diff --git a/TestModels/SimpleTypes/SimpleTimestamp/test/WrappedSimpleTimestampTest.dfy b/TestModels/SimpleTypes/SimpleTimestamp/test/WrappedSimpleTimestampTest.dfy index 3e741368ff..d51eb599bc 100644 --- a/TestModels/SimpleTypes/SimpleTimestamp/test/WrappedSimpleTimestampTest.dfy +++ b/TestModels/SimpleTypes/SimpleTimestamp/test/WrappedSimpleTimestampTest.dfy @@ -11,5 +11,6 @@ module WrappedSimpleTypesTimestampTest { var client :- expect WrappedSimpleTypesTimestampService.WrappedSimpleTimestamp(); SimpleTimestampImplTest.TestGetTimestamp(client); + SimpleTimestampImplTest.TestGetTimestampNoMs(client); } } diff --git a/TestModels/Union/runtimes/rust/src/standard_library_externs.rs b/TestModels/Union/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/Union/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/attribute_action.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/attribute_action.rs index 3b4bb95a5e..86959a17b6 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/attribute_action.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/attribute_action.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::AttributeAction, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::AttributeAction::Add => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::ADD {}, - aws_sdk_dynamodb::types::AttributeAction::Put => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::PUT {}, - aws_sdk_dynamodb::types::AttributeAction::Delete => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::DELETE {}, + aws_sdk_dynamodb::types::AttributeAction::Add => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::ADD {}, +aws_sdk_dynamodb::types::AttributeAction::Put => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::PUT {}, +aws_sdk_dynamodb::types::AttributeAction::Delete => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::DELETE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction, ) -> aws_sdk_dynamodb::types::AttributeAction { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::ADD {} => aws_sdk_dynamodb::types::AttributeAction::Add, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::PUT {} => aws_sdk_dynamodb::types::AttributeAction::Put, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::DELETE {} => aws_sdk_dynamodb::types::AttributeAction::Delete, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::ADD {} => aws_sdk_dynamodb::types::AttributeAction::Add, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::PUT {} => aws_sdk_dynamodb::types::AttributeAction::Put, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::AttributeAction::DELETE {} => aws_sdk_dynamodb::types::AttributeAction::Delete, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/batch_statement_error_code_enum.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/batch_statement_error_code_enum.rs index 93746fece8..fd53a818a3 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/batch_statement_error_code_enum.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/batch_statement_error_code_enum.rs @@ -7,17 +7,17 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::RequestLimitExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::RequestLimitExceeded {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ValidationError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ValidationError {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::TransactionConflict => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::TransactionConflict {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ThrottlingError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ThrottlingError {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::InternalServerError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::InternalServerError {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ResourceNotFound => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ResourceNotFound {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::AccessDenied => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::AccessDenied {}, - aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::DuplicateItem => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::DuplicateItem {}, + aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::RequestLimitExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::RequestLimitExceeded {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ValidationError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ValidationError {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::TransactionConflict => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::TransactionConflict {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ThrottlingError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ThrottlingError {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::InternalServerError => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::InternalServerError {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ResourceNotFound => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ResourceNotFound {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::AccessDenied => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::AccessDenied {}, +aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::DuplicateItem => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::DuplicateItem {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -26,16 +26,16 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum, ) -> aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::RequestLimitExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::RequestLimitExceeded, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ValidationError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ValidationError, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::TransactionConflict {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::TransactionConflict, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ThrottlingError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ThrottlingError, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::InternalServerError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::InternalServerError, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ResourceNotFound {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ResourceNotFound, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::AccessDenied {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::AccessDenied, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::DuplicateItem {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::DuplicateItem, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ConditionalCheckFailed, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ItemCollectionSizeLimitExceeded, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::RequestLimitExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::RequestLimitExceeded, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ValidationError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ValidationError, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ProvisionedThroughputExceeded, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::TransactionConflict {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::TransactionConflict, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ThrottlingError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ThrottlingError, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::InternalServerError {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::InternalServerError, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::ResourceNotFound {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::ResourceNotFound, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::AccessDenied {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::AccessDenied, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BatchStatementErrorCodeEnum::DuplicateItem {} => aws_sdk_dynamodb::types::BatchStatementErrorCodeEnum::DuplicateItem, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/billing_mode.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/billing_mode.rs index 5304c2abc0..a29d5b3565 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/billing_mode.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/billing_mode.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::BillingMode, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::BillingMode::Provisioned => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PROVISIONED {}, - aws_sdk_dynamodb::types::BillingMode::PayPerRequest => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PAY_PER_REQUEST {}, + aws_sdk_dynamodb::types::BillingMode::Provisioned => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PROVISIONED {}, +aws_sdk_dynamodb::types::BillingMode::PayPerRequest => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PAY_PER_REQUEST {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode, ) -> aws_sdk_dynamodb::types::BillingMode { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PROVISIONED {} => aws_sdk_dynamodb::types::BillingMode::Provisioned, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PAY_PER_REQUEST {} => aws_sdk_dynamodb::types::BillingMode::PayPerRequest, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PROVISIONED {} => aws_sdk_dynamodb::types::BillingMode::Provisioned, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::BillingMode::PAY_PER_REQUEST {} => aws_sdk_dynamodb::types::BillingMode::PayPerRequest, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/comparison_operator.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/comparison_operator.rs index 0c75159bda..a18dec568f 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/comparison_operator.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/comparison_operator.rs @@ -7,19 +7,19 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ComparisonOperator, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ComparisonOperator::Eq => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::EQ {}, - aws_sdk_dynamodb::types::ComparisonOperator::Ne => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NE {}, - aws_sdk_dynamodb::types::ComparisonOperator::In => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::IN {}, - aws_sdk_dynamodb::types::ComparisonOperator::Le => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LE {}, - aws_sdk_dynamodb::types::ComparisonOperator::Lt => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LT {}, - aws_sdk_dynamodb::types::ComparisonOperator::Ge => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GE {}, - aws_sdk_dynamodb::types::ComparisonOperator::Gt => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GT {}, - aws_sdk_dynamodb::types::ComparisonOperator::Between => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BETWEEN {}, - aws_sdk_dynamodb::types::ComparisonOperator::NotNull => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_NULL {}, - aws_sdk_dynamodb::types::ComparisonOperator::Null => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NULL {}, - aws_sdk_dynamodb::types::ComparisonOperator::Contains => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::CONTAINS {}, - aws_sdk_dynamodb::types::ComparisonOperator::NotContains => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_CONTAINS {}, - aws_sdk_dynamodb::types::ComparisonOperator::BeginsWith => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BEGINS_WITH {}, + aws_sdk_dynamodb::types::ComparisonOperator::Eq => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::EQ {}, +aws_sdk_dynamodb::types::ComparisonOperator::Ne => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NE {}, +aws_sdk_dynamodb::types::ComparisonOperator::In => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::IN {}, +aws_sdk_dynamodb::types::ComparisonOperator::Le => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LE {}, +aws_sdk_dynamodb::types::ComparisonOperator::Lt => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LT {}, +aws_sdk_dynamodb::types::ComparisonOperator::Ge => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GE {}, +aws_sdk_dynamodb::types::ComparisonOperator::Gt => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GT {}, +aws_sdk_dynamodb::types::ComparisonOperator::Between => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BETWEEN {}, +aws_sdk_dynamodb::types::ComparisonOperator::NotNull => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_NULL {}, +aws_sdk_dynamodb::types::ComparisonOperator::Null => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NULL {}, +aws_sdk_dynamodb::types::ComparisonOperator::Contains => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::CONTAINS {}, +aws_sdk_dynamodb::types::ComparisonOperator::NotContains => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_CONTAINS {}, +aws_sdk_dynamodb::types::ComparisonOperator::BeginsWith => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BEGINS_WITH {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -28,18 +28,18 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator, ) -> aws_sdk_dynamodb::types::ComparisonOperator { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::EQ {} => aws_sdk_dynamodb::types::ComparisonOperator::Eq, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NE {} => aws_sdk_dynamodb::types::ComparisonOperator::Ne, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::IN {} => aws_sdk_dynamodb::types::ComparisonOperator::In, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LE {} => aws_sdk_dynamodb::types::ComparisonOperator::Le, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LT {} => aws_sdk_dynamodb::types::ComparisonOperator::Lt, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GE {} => aws_sdk_dynamodb::types::ComparisonOperator::Ge, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GT {} => aws_sdk_dynamodb::types::ComparisonOperator::Gt, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BETWEEN {} => aws_sdk_dynamodb::types::ComparisonOperator::Between, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_NULL {} => aws_sdk_dynamodb::types::ComparisonOperator::NotNull, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NULL {} => aws_sdk_dynamodb::types::ComparisonOperator::Null, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::CONTAINS {} => aws_sdk_dynamodb::types::ComparisonOperator::Contains, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_CONTAINS {} => aws_sdk_dynamodb::types::ComparisonOperator::NotContains, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BEGINS_WITH {} => aws_sdk_dynamodb::types::ComparisonOperator::BeginsWith, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::EQ {} => aws_sdk_dynamodb::types::ComparisonOperator::Eq, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NE {} => aws_sdk_dynamodb::types::ComparisonOperator::Ne, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::IN {} => aws_sdk_dynamodb::types::ComparisonOperator::In, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LE {} => aws_sdk_dynamodb::types::ComparisonOperator::Le, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::LT {} => aws_sdk_dynamodb::types::ComparisonOperator::Lt, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GE {} => aws_sdk_dynamodb::types::ComparisonOperator::Ge, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::GT {} => aws_sdk_dynamodb::types::ComparisonOperator::Gt, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BETWEEN {} => aws_sdk_dynamodb::types::ComparisonOperator::Between, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_NULL {} => aws_sdk_dynamodb::types::ComparisonOperator::NotNull, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NULL {} => aws_sdk_dynamodb::types::ComparisonOperator::Null, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::CONTAINS {} => aws_sdk_dynamodb::types::ComparisonOperator::Contains, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::NOT_CONTAINS {} => aws_sdk_dynamodb::types::ComparisonOperator::NotContains, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ComparisonOperator::BEGINS_WITH {} => aws_sdk_dynamodb::types::ComparisonOperator::BeginsWith, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/conditional_operator.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/conditional_operator.rs index 64208da483..216ac006fb 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/conditional_operator.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/conditional_operator.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ConditionalOperator, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ConditionalOperator::And => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::AND {}, - aws_sdk_dynamodb::types::ConditionalOperator::Or => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::OR {}, + aws_sdk_dynamodb::types::ConditionalOperator::And => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::AND {}, +aws_sdk_dynamodb::types::ConditionalOperator::Or => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::OR {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator, ) -> aws_sdk_dynamodb::types::ConditionalOperator { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::AND {} => aws_sdk_dynamodb::types::ConditionalOperator::And, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::OR {} => aws_sdk_dynamodb::types::ConditionalOperator::Or, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::AND {} => aws_sdk_dynamodb::types::ConditionalOperator::And, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ConditionalOperator::OR {} => aws_sdk_dynamodb::types::ConditionalOperator::Or, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/index_status.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/index_status.rs index cd99dab3d6..df88cdcb2c 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/index_status.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/index_status.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::IndexStatus, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::IndexStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::CREATING {}, - aws_sdk_dynamodb::types::IndexStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::UPDATING {}, - aws_sdk_dynamodb::types::IndexStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::DELETING {}, - aws_sdk_dynamodb::types::IndexStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::ACTIVE {}, + aws_sdk_dynamodb::types::IndexStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::CREATING {}, +aws_sdk_dynamodb::types::IndexStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::UPDATING {}, +aws_sdk_dynamodb::types::IndexStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::DELETING {}, +aws_sdk_dynamodb::types::IndexStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::ACTIVE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus, ) -> aws_sdk_dynamodb::types::IndexStatus { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::CREATING {} => aws_sdk_dynamodb::types::IndexStatus::Creating, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::UPDATING {} => aws_sdk_dynamodb::types::IndexStatus::Updating, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::DELETING {} => aws_sdk_dynamodb::types::IndexStatus::Deleting, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::ACTIVE {} => aws_sdk_dynamodb::types::IndexStatus::Active, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::CREATING {} => aws_sdk_dynamodb::types::IndexStatus::Creating, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::UPDATING {} => aws_sdk_dynamodb::types::IndexStatus::Updating, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::DELETING {} => aws_sdk_dynamodb::types::IndexStatus::Deleting, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::IndexStatus::ACTIVE {} => aws_sdk_dynamodb::types::IndexStatus::Active, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/key_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/key_type.rs index 0d5d59c569..ea86df5b0e 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/key_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/key_type.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::KeyType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::KeyType::Hash => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::HASH {}, - aws_sdk_dynamodb::types::KeyType::Range => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::RANGE {}, + aws_sdk_dynamodb::types::KeyType::Hash => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::HASH {}, +aws_sdk_dynamodb::types::KeyType::Range => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::RANGE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType, ) -> aws_sdk_dynamodb::types::KeyType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::HASH {} => aws_sdk_dynamodb::types::KeyType::Hash, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::RANGE {} => aws_sdk_dynamodb::types::KeyType::Range, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::HASH {} => aws_sdk_dynamodb::types::KeyType::Hash, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::KeyType::RANGE {} => aws_sdk_dynamodb::types::KeyType::Range, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/projection_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/projection_type.rs index d242c07d48..28b89124fa 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/projection_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/projection_type.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ProjectionType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ProjectionType::All => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::ALL {}, - aws_sdk_dynamodb::types::ProjectionType::KeysOnly => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::KEYS_ONLY {}, - aws_sdk_dynamodb::types::ProjectionType::Include => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::INCLUDE {}, + aws_sdk_dynamodb::types::ProjectionType::All => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::ALL {}, +aws_sdk_dynamodb::types::ProjectionType::KeysOnly => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::KEYS_ONLY {}, +aws_sdk_dynamodb::types::ProjectionType::Include => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::INCLUDE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType, ) -> aws_sdk_dynamodb::types::ProjectionType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::ALL {} => aws_sdk_dynamodb::types::ProjectionType::All, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::KEYS_ONLY {} => aws_sdk_dynamodb::types::ProjectionType::KeysOnly, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::INCLUDE {} => aws_sdk_dynamodb::types::ProjectionType::Include, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::ALL {} => aws_sdk_dynamodb::types::ProjectionType::All, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::KEYS_ONLY {} => aws_sdk_dynamodb::types::ProjectionType::KeysOnly, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ProjectionType::INCLUDE {} => aws_sdk_dynamodb::types::ProjectionType::Include, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/replica_status.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/replica_status.rs index 11e2638d48..fd626473a6 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/replica_status.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/replica_status.rs @@ -7,13 +7,13 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReplicaStatus, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReplicaStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATING {}, - aws_sdk_dynamodb::types::ReplicaStatus::CreationFailed => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATION_FAILED {}, - aws_sdk_dynamodb::types::ReplicaStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::UPDATING {}, - aws_sdk_dynamodb::types::ReplicaStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::DELETING {}, - aws_sdk_dynamodb::types::ReplicaStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::ACTIVE {}, - aws_sdk_dynamodb::types::ReplicaStatus::RegionDisabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::REGION_DISABLED {}, - aws_sdk_dynamodb::types::ReplicaStatus::InaccessibleEncryptionCredentials => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {}, + aws_sdk_dynamodb::types::ReplicaStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATING {}, +aws_sdk_dynamodb::types::ReplicaStatus::CreationFailed => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATION_FAILED {}, +aws_sdk_dynamodb::types::ReplicaStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::UPDATING {}, +aws_sdk_dynamodb::types::ReplicaStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::DELETING {}, +aws_sdk_dynamodb::types::ReplicaStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::ACTIVE {}, +aws_sdk_dynamodb::types::ReplicaStatus::RegionDisabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::REGION_DISABLED {}, +aws_sdk_dynamodb::types::ReplicaStatus::InaccessibleEncryptionCredentials => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -22,12 +22,12 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus, ) -> aws_sdk_dynamodb::types::ReplicaStatus { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATING {} => aws_sdk_dynamodb::types::ReplicaStatus::Creating, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATION_FAILED {} => aws_sdk_dynamodb::types::ReplicaStatus::CreationFailed, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::UPDATING {} => aws_sdk_dynamodb::types::ReplicaStatus::Updating, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::DELETING {} => aws_sdk_dynamodb::types::ReplicaStatus::Deleting, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::ACTIVE {} => aws_sdk_dynamodb::types::ReplicaStatus::Active, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::REGION_DISABLED {} => aws_sdk_dynamodb::types::ReplicaStatus::RegionDisabled, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {} => aws_sdk_dynamodb::types::ReplicaStatus::InaccessibleEncryptionCredentials, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATING {} => aws_sdk_dynamodb::types::ReplicaStatus::Creating, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::CREATION_FAILED {} => aws_sdk_dynamodb::types::ReplicaStatus::CreationFailed, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::UPDATING {} => aws_sdk_dynamodb::types::ReplicaStatus::Updating, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::DELETING {} => aws_sdk_dynamodb::types::ReplicaStatus::Deleting, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::ACTIVE {} => aws_sdk_dynamodb::types::ReplicaStatus::Active, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::REGION_DISABLED {} => aws_sdk_dynamodb::types::ReplicaStatus::RegionDisabled, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReplicaStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {} => aws_sdk_dynamodb::types::ReplicaStatus::InaccessibleEncryptionCredentials, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_consumed_capacity.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_consumed_capacity.rs index fbfeeb4e61..b2526611f3 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_consumed_capacity.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_consumed_capacity.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReturnConsumedCapacity, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReturnConsumedCapacity::Indexes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::INDEXES {}, - aws_sdk_dynamodb::types::ReturnConsumedCapacity::Total => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::TOTAL {}, - aws_sdk_dynamodb::types::ReturnConsumedCapacity::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::NONE {}, + aws_sdk_dynamodb::types::ReturnConsumedCapacity::Indexes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::INDEXES {}, +aws_sdk_dynamodb::types::ReturnConsumedCapacity::Total => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::TOTAL {}, +aws_sdk_dynamodb::types::ReturnConsumedCapacity::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::NONE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity, ) -> aws_sdk_dynamodb::types::ReturnConsumedCapacity { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::INDEXES {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::Indexes, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::TOTAL {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::Total, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::NONE {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::None, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::INDEXES {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::Indexes, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::TOTAL {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::Total, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnConsumedCapacity::NONE {} => aws_sdk_dynamodb::types::ReturnConsumedCapacity::None, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_item_collection_metrics.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_item_collection_metrics.rs index 0896dc4cd3..6857387303 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_item_collection_metrics.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_item_collection_metrics.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReturnItemCollectionMetrics, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::Size => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::SIZE {}, - aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::NONE {}, + aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::Size => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::SIZE {}, +aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::NONE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics, ) -> aws_sdk_dynamodb::types::ReturnItemCollectionMetrics { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::SIZE {} => aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::Size, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::NONE {} => aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::None, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::SIZE {} => aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::Size, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnItemCollectionMetrics::NONE {} => aws_sdk_dynamodb::types::ReturnItemCollectionMetrics::None, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_value.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_value.rs index 21983ab80f..df8085df33 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_value.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_value.rs @@ -7,11 +7,11 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReturnValue, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReturnValue::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::NONE {}, - aws_sdk_dynamodb::types::ReturnValue::AllOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_OLD {}, - aws_sdk_dynamodb::types::ReturnValue::UpdatedOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_OLD {}, - aws_sdk_dynamodb::types::ReturnValue::AllNew => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_NEW {}, - aws_sdk_dynamodb::types::ReturnValue::UpdatedNew => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_NEW {}, + aws_sdk_dynamodb::types::ReturnValue::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::NONE {}, +aws_sdk_dynamodb::types::ReturnValue::AllOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_OLD {}, +aws_sdk_dynamodb::types::ReturnValue::UpdatedOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_OLD {}, +aws_sdk_dynamodb::types::ReturnValue::AllNew => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_NEW {}, +aws_sdk_dynamodb::types::ReturnValue::UpdatedNew => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_NEW {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -20,10 +20,10 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue, ) -> aws_sdk_dynamodb::types::ReturnValue { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::NONE {} => aws_sdk_dynamodb::types::ReturnValue::None, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_OLD {} => aws_sdk_dynamodb::types::ReturnValue::AllOld, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_OLD {} => aws_sdk_dynamodb::types::ReturnValue::UpdatedOld, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_NEW {} => aws_sdk_dynamodb::types::ReturnValue::AllNew, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_NEW {} => aws_sdk_dynamodb::types::ReturnValue::UpdatedNew, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::NONE {} => aws_sdk_dynamodb::types::ReturnValue::None, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_OLD {} => aws_sdk_dynamodb::types::ReturnValue::AllOld, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_OLD {} => aws_sdk_dynamodb::types::ReturnValue::UpdatedOld, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::ALL_NEW {} => aws_sdk_dynamodb::types::ReturnValue::AllNew, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValue::UPDATED_NEW {} => aws_sdk_dynamodb::types::ReturnValue::UpdatedNew, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_values_on_condition_check_failure.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_values_on_condition_check_failure.rs index b185462326..7d3380d942 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_values_on_condition_check_failure.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/return_values_on_condition_check_failure.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::AllOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::ALL_OLD {}, - aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::NONE {}, + aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::AllOld => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::ALL_OLD {}, +aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::None => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::NONE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure, ) -> aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::ALL_OLD {} => aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::AllOld, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::NONE {} => aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::None, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::ALL_OLD {} => aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::AllOld, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ReturnValuesOnConditionCheckFailure::NONE {} => aws_sdk_dynamodb::types::ReturnValuesOnConditionCheckFailure::None, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/scalar_attribute_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/scalar_attribute_type.rs index 7a16ac8159..f921f603f0 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/scalar_attribute_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/scalar_attribute_type.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::ScalarAttributeType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::ScalarAttributeType::S => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::S {}, - aws_sdk_dynamodb::types::ScalarAttributeType::N => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::N {}, - aws_sdk_dynamodb::types::ScalarAttributeType::B => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::B {}, + aws_sdk_dynamodb::types::ScalarAttributeType::S => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::S {}, +aws_sdk_dynamodb::types::ScalarAttributeType::N => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::N {}, +aws_sdk_dynamodb::types::ScalarAttributeType::B => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::B {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType, ) -> aws_sdk_dynamodb::types::ScalarAttributeType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::S {} => aws_sdk_dynamodb::types::ScalarAttributeType::S, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::N {} => aws_sdk_dynamodb::types::ScalarAttributeType::N, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::B {} => aws_sdk_dynamodb::types::ScalarAttributeType::B, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::S {} => aws_sdk_dynamodb::types::ScalarAttributeType::S, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::N {} => aws_sdk_dynamodb::types::ScalarAttributeType::N, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::ScalarAttributeType::B {} => aws_sdk_dynamodb::types::ScalarAttributeType::B, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/select.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/select.rs index 52afedb1c3..c52b7a634b 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/select.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/select.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::Select, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::Select::AllAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_ATTRIBUTES {}, - aws_sdk_dynamodb::types::Select::AllProjectedAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_PROJECTED_ATTRIBUTES {}, - aws_sdk_dynamodb::types::Select::SpecificAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::SPECIFIC_ATTRIBUTES {}, - aws_sdk_dynamodb::types::Select::Count => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::COUNT {}, + aws_sdk_dynamodb::types::Select::AllAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_ATTRIBUTES {}, +aws_sdk_dynamodb::types::Select::AllProjectedAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_PROJECTED_ATTRIBUTES {}, +aws_sdk_dynamodb::types::Select::SpecificAttributes => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::SPECIFIC_ATTRIBUTES {}, +aws_sdk_dynamodb::types::Select::Count => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::COUNT {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select, ) -> aws_sdk_dynamodb::types::Select { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::AllAttributes, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_PROJECTED_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::AllProjectedAttributes, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::SPECIFIC_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::SpecificAttributes, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::COUNT {} => aws_sdk_dynamodb::types::Select::Count, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::AllAttributes, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::ALL_PROJECTED_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::AllProjectedAttributes, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::SPECIFIC_ATTRIBUTES {} => aws_sdk_dynamodb::types::Select::SpecificAttributes, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::Select::COUNT {} => aws_sdk_dynamodb::types::Select::Count, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_status.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_status.rs index fd0a2e7a4b..a4f20bf1cf 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_status.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_status.rs @@ -7,11 +7,11 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::SseStatus, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::SseStatus::Enabling => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLING {}, - aws_sdk_dynamodb::types::SseStatus::Enabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLED {}, - aws_sdk_dynamodb::types::SseStatus::Disabling => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLING {}, - aws_sdk_dynamodb::types::SseStatus::Disabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLED {}, - aws_sdk_dynamodb::types::SseStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::UPDATING {}, + aws_sdk_dynamodb::types::SseStatus::Enabling => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLING {}, +aws_sdk_dynamodb::types::SseStatus::Enabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLED {}, +aws_sdk_dynamodb::types::SseStatus::Disabling => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLING {}, +aws_sdk_dynamodb::types::SseStatus::Disabled => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLED {}, +aws_sdk_dynamodb::types::SseStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::UPDATING {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -20,10 +20,10 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus, ) -> aws_sdk_dynamodb::types::SseStatus { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLING {} => aws_sdk_dynamodb::types::SseStatus::Enabling, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLED {} => aws_sdk_dynamodb::types::SseStatus::Enabled, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLING {} => aws_sdk_dynamodb::types::SseStatus::Disabling, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLED {} => aws_sdk_dynamodb::types::SseStatus::Disabled, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::UPDATING {} => aws_sdk_dynamodb::types::SseStatus::Updating, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLING {} => aws_sdk_dynamodb::types::SseStatus::Enabling, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::ENABLED {} => aws_sdk_dynamodb::types::SseStatus::Enabled, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLING {} => aws_sdk_dynamodb::types::SseStatus::Disabling, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::DISABLED {} => aws_sdk_dynamodb::types::SseStatus::Disabled, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEStatus::UPDATING {} => aws_sdk_dynamodb::types::SseStatus::Updating, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_type.rs index 6a6dfd122e..56f69062bc 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/sse_type.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::SseType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::SseType::Aes256 => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::AES256 {}, - aws_sdk_dynamodb::types::SseType::Kms => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::KMS {}, + aws_sdk_dynamodb::types::SseType::Aes256 => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::AES256 {}, +aws_sdk_dynamodb::types::SseType::Kms => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::KMS {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType, ) -> aws_sdk_dynamodb::types::SseType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::AES256 {} => aws_sdk_dynamodb::types::SseType::Aes256, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::KMS {} => aws_sdk_dynamodb::types::SseType::Kms, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::AES256 {} => aws_sdk_dynamodb::types::SseType::Aes256, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::SSEType::KMS {} => aws_sdk_dynamodb::types::SseType::Kms, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/stream_view_type.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/stream_view_type.rs index df3a0c2b7b..718b38e764 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/stream_view_type.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/stream_view_type.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::StreamViewType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::StreamViewType::NewImage => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_IMAGE {}, - aws_sdk_dynamodb::types::StreamViewType::OldImage => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::OLD_IMAGE {}, - aws_sdk_dynamodb::types::StreamViewType::NewAndOldImages => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_AND_OLD_IMAGES {}, - aws_sdk_dynamodb::types::StreamViewType::KeysOnly => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::KEYS_ONLY {}, + aws_sdk_dynamodb::types::StreamViewType::NewImage => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_IMAGE {}, +aws_sdk_dynamodb::types::StreamViewType::OldImage => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::OLD_IMAGE {}, +aws_sdk_dynamodb::types::StreamViewType::NewAndOldImages => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_AND_OLD_IMAGES {}, +aws_sdk_dynamodb::types::StreamViewType::KeysOnly => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::KEYS_ONLY {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType, ) -> aws_sdk_dynamodb::types::StreamViewType { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_IMAGE {} => aws_sdk_dynamodb::types::StreamViewType::NewImage, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::OLD_IMAGE {} => aws_sdk_dynamodb::types::StreamViewType::OldImage, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_AND_OLD_IMAGES {} => aws_sdk_dynamodb::types::StreamViewType::NewAndOldImages, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::KEYS_ONLY {} => aws_sdk_dynamodb::types::StreamViewType::KeysOnly, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_IMAGE {} => aws_sdk_dynamodb::types::StreamViewType::NewImage, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::OLD_IMAGE {} => aws_sdk_dynamodb::types::StreamViewType::OldImage, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::NEW_AND_OLD_IMAGES {} => aws_sdk_dynamodb::types::StreamViewType::NewAndOldImages, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::StreamViewType::KEYS_ONLY {} => aws_sdk_dynamodb::types::StreamViewType::KeysOnly, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_class.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_class.rs index dba3a71daa..f0a717fc91 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_class.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_class.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::TableClass, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::TableClass::Standard => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD {}, - aws_sdk_dynamodb::types::TableClass::StandardInfrequentAccess => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD_INFREQUENT_ACCESS {}, + aws_sdk_dynamodb::types::TableClass::Standard => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD {}, +aws_sdk_dynamodb::types::TableClass::StandardInfrequentAccess => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD_INFREQUENT_ACCESS {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass, ) -> aws_sdk_dynamodb::types::TableClass { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD {} => aws_sdk_dynamodb::types::TableClass::Standard, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD_INFREQUENT_ACCESS {} => aws_sdk_dynamodb::types::TableClass::StandardInfrequentAccess, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD {} => aws_sdk_dynamodb::types::TableClass::Standard, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableClass::STANDARD_INFREQUENT_ACCESS {} => aws_sdk_dynamodb::types::TableClass::StandardInfrequentAccess, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_status.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_status.rs index 444e0c5411..e996bc8805 100644 --- a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_status.rs +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/conversions/table_status.rs @@ -7,13 +7,13 @@ pub fn to_dafny( value: aws_sdk_dynamodb::types::TableStatus, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_dynamodb::types::TableStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::CREATING {}, - aws_sdk_dynamodb::types::TableStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::UPDATING {}, - aws_sdk_dynamodb::types::TableStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::DELETING {}, - aws_sdk_dynamodb::types::TableStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ACTIVE {}, - aws_sdk_dynamodb::types::TableStatus::InaccessibleEncryptionCredentials => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {}, - aws_sdk_dynamodb::types::TableStatus::Archiving => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVING {}, - aws_sdk_dynamodb::types::TableStatus::Archived => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVED {}, + aws_sdk_dynamodb::types::TableStatus::Creating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::CREATING {}, +aws_sdk_dynamodb::types::TableStatus::Updating => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::UPDATING {}, +aws_sdk_dynamodb::types::TableStatus::Deleting => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::DELETING {}, +aws_sdk_dynamodb::types::TableStatus::Active => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ACTIVE {}, +aws_sdk_dynamodb::types::TableStatus::InaccessibleEncryptionCredentials => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {}, +aws_sdk_dynamodb::types::TableStatus::Archiving => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVING {}, +aws_sdk_dynamodb::types::TableStatus::Archived => crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVED {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -22,12 +22,12 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus, ) -> aws_sdk_dynamodb::types::TableStatus { match dafny_value { - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::CREATING {} => aws_sdk_dynamodb::types::TableStatus::Creating, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::UPDATING {} => aws_sdk_dynamodb::types::TableStatus::Updating, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::DELETING {} => aws_sdk_dynamodb::types::TableStatus::Deleting, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ACTIVE {} => aws_sdk_dynamodb::types::TableStatus::Active, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {} => aws_sdk_dynamodb::types::TableStatus::InaccessibleEncryptionCredentials, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVING {} => aws_sdk_dynamodb::types::TableStatus::Archiving, - crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVED {} => aws_sdk_dynamodb::types::TableStatus::Archived, + crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::CREATING {} => aws_sdk_dynamodb::types::TableStatus::Creating, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::UPDATING {} => aws_sdk_dynamodb::types::TableStatus::Updating, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::DELETING {} => aws_sdk_dynamodb::types::TableStatus::Deleting, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ACTIVE {} => aws_sdk_dynamodb::types::TableStatus::Active, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::INACCESSIBLE_ENCRYPTION_CREDENTIALS {} => aws_sdk_dynamodb::types::TableStatus::InaccessibleEncryptionCredentials, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVING {} => aws_sdk_dynamodb::types::TableStatus::Archiving, +crate::r#software::amazon::cryptography::services::dynamodb::internaldafny::types::TableStatus::ARCHIVED {} => aws_sdk_dynamodb::types::TableStatus::Archived, } } diff --git a/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/standard_library_externs.rs b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/aws-sdks/ddb-lite/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/customer_master_key_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/customer_master_key_spec.rs index 3115f64a3a..d00e07390b 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/customer_master_key_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/customer_master_key_spec.rs @@ -7,19 +7,19 @@ pub fn to_dafny( value: aws_sdk_kms::types::CustomerMasterKeySpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::CustomerMasterKeySpec::Rsa2048 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_2048 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::Rsa3072 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_3072 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::Rsa4096 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_4096 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P256 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P384 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP521 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P521 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::EccSecgP256K1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_SECG_P256K1 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SYMMETRIC_DEFAULT {}, - aws_sdk_kms::types::CustomerMasterKeySpec::Hmac224 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_224 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::Hmac256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_256 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::Hmac384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_384 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::Hmac512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_512 {}, - aws_sdk_kms::types::CustomerMasterKeySpec::Sm2 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SM2 {}, + aws_sdk_kms::types::CustomerMasterKeySpec::Rsa2048 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_2048 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::Rsa3072 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_3072 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::Rsa4096 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_4096 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P256 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P384 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP521 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P521 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::EccSecgP256K1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_SECG_P256K1 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SYMMETRIC_DEFAULT {}, +aws_sdk_kms::types::CustomerMasterKeySpec::Hmac224 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_224 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::Hmac256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_256 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::Hmac384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_384 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::Hmac512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_512 {}, +aws_sdk_kms::types::CustomerMasterKeySpec::Sm2 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SM2 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -28,18 +28,18 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec, ) -> aws_sdk_kms::types::CustomerMasterKeySpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_2048 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa2048, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_3072 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa3072, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_4096 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa4096, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P256 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P384 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP384, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P521 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP521, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_SECG_P256K1 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccSecgP256K1, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::CustomerMasterKeySpec::SymmetricDefault, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_224 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac224, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_256 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_384 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac384, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_512 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac512, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SM2 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Sm2, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_2048 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa2048, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_3072 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa3072, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::RSA_4096 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Rsa4096, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P256 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P384 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP384, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_NIST_P521 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccNistP521, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::ECC_SECG_P256K1 {} => aws_sdk_kms::types::CustomerMasterKeySpec::EccSecgP256K1, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::CustomerMasterKeySpec::SymmetricDefault, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_224 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac224, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_256 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_384 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac384, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::HMAC_512 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Hmac512, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::CustomerMasterKeySpec::SM2 {} => aws_sdk_kms::types::CustomerMasterKeySpec::Sm2, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/data_key_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/data_key_spec.rs index aa96da51cb..f26b83c132 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/data_key_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/data_key_spec.rs @@ -7,8 +7,8 @@ pub fn to_dafny( value: aws_sdk_kms::types::DataKeySpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::DataKeySpec::Aes256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_256 {}, - aws_sdk_kms::types::DataKeySpec::Aes128 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_128 {}, + aws_sdk_kms::types::DataKeySpec::Aes256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_256 {}, +aws_sdk_kms::types::DataKeySpec::Aes128 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_128 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -17,7 +17,7 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec, ) -> aws_sdk_kms::types::DataKeySpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_256 {} => aws_sdk_kms::types::DataKeySpec::Aes256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_128 {} => aws_sdk_kms::types::DataKeySpec::Aes128, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_256 {} => aws_sdk_kms::types::DataKeySpec::Aes256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::DataKeySpec::AES_128 {} => aws_sdk_kms::types::DataKeySpec::Aes128, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/encryption_algorithm_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/encryption_algorithm_spec.rs index 8cc859bad9..af802a8f42 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/encryption_algorithm_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/encryption_algorithm_spec.rs @@ -7,9 +7,9 @@ pub fn to_dafny( value: aws_sdk_kms::types::EncryptionAlgorithmSpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::EncryptionAlgorithmSpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::SYMMETRIC_DEFAULT {}, - aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_1 {}, - aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_256 {}, + aws_sdk_kms::types::EncryptionAlgorithmSpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::SYMMETRIC_DEFAULT {}, +aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_1 {}, +aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_256 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -18,8 +18,8 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec, ) -> aws_sdk_kms::types::EncryptionAlgorithmSpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::SymmetricDefault, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_1 {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha1, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_256 {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::SymmetricDefault, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_1 {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha1, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::EncryptionAlgorithmSpec::RSAES_OAEP_SHA_256 {} => aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_agreement_algorithm_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_agreement_algorithm_spec.rs index ab964fd2f7..1693266fff 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_agreement_algorithm_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_agreement_algorithm_spec.rs @@ -7,7 +7,7 @@ pub fn to_dafny( value: aws_sdk_kms::types::KeyAgreementAlgorithmSpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::KeyAgreementAlgorithmSpec::Ecdh => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec::ECDH {}, + aws_sdk_kms::types::KeyAgreementAlgorithmSpec::Ecdh => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec::ECDH {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -16,6 +16,6 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec, ) -> aws_sdk_kms::types::KeyAgreementAlgorithmSpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec::ECDH {} => aws_sdk_kms::types::KeyAgreementAlgorithmSpec::Ecdh, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyAgreementAlgorithmSpec::ECDH {} => aws_sdk_kms::types::KeyAgreementAlgorithmSpec::Ecdh, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_encryption_mechanism.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_encryption_mechanism.rs index 1dd9d0e9d8..80c4b4d9b9 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_encryption_mechanism.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_encryption_mechanism.rs @@ -7,7 +7,7 @@ pub fn to_dafny( value: aws_sdk_kms::types::KeyEncryptionMechanism, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::KeyEncryptionMechanism::RsaesOaepSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism::RSAES_OAEP_SHA_256 {}, + aws_sdk_kms::types::KeyEncryptionMechanism::RsaesOaepSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism::RSAES_OAEP_SHA_256 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -16,6 +16,6 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism, ) -> aws_sdk_kms::types::KeyEncryptionMechanism { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism::RSAES_OAEP_SHA_256 {} => aws_sdk_kms::types::KeyEncryptionMechanism::RsaesOaepSha256, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyEncryptionMechanism::RSAES_OAEP_SHA_256 {} => aws_sdk_kms::types::KeyEncryptionMechanism::RsaesOaepSha256, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_spec.rs index 66ae3f0dc7..14c6136fc9 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_spec.rs @@ -7,19 +7,19 @@ pub fn to_dafny( value: aws_sdk_kms::types::KeySpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::KeySpec::Rsa2048 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_2048 {}, - aws_sdk_kms::types::KeySpec::Rsa3072 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_3072 {}, - aws_sdk_kms::types::KeySpec::Rsa4096 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_4096 {}, - aws_sdk_kms::types::KeySpec::EccNistP256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P256 {}, - aws_sdk_kms::types::KeySpec::EccNistP384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P384 {}, - aws_sdk_kms::types::KeySpec::EccNistP521 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P521 {}, - aws_sdk_kms::types::KeySpec::EccSecgP256K1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_SECG_P256K1 {}, - aws_sdk_kms::types::KeySpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SYMMETRIC_DEFAULT {}, - aws_sdk_kms::types::KeySpec::Hmac224 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_224 {}, - aws_sdk_kms::types::KeySpec::Hmac256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_256 {}, - aws_sdk_kms::types::KeySpec::Hmac384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_384 {}, - aws_sdk_kms::types::KeySpec::Hmac512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_512 {}, - aws_sdk_kms::types::KeySpec::Sm2 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SM2 {}, + aws_sdk_kms::types::KeySpec::Rsa2048 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_2048 {}, +aws_sdk_kms::types::KeySpec::Rsa3072 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_3072 {}, +aws_sdk_kms::types::KeySpec::Rsa4096 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_4096 {}, +aws_sdk_kms::types::KeySpec::EccNistP256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P256 {}, +aws_sdk_kms::types::KeySpec::EccNistP384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P384 {}, +aws_sdk_kms::types::KeySpec::EccNistP521 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P521 {}, +aws_sdk_kms::types::KeySpec::EccSecgP256K1 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_SECG_P256K1 {}, +aws_sdk_kms::types::KeySpec::SymmetricDefault => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SYMMETRIC_DEFAULT {}, +aws_sdk_kms::types::KeySpec::Hmac224 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_224 {}, +aws_sdk_kms::types::KeySpec::Hmac256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_256 {}, +aws_sdk_kms::types::KeySpec::Hmac384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_384 {}, +aws_sdk_kms::types::KeySpec::Hmac512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_512 {}, +aws_sdk_kms::types::KeySpec::Sm2 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SM2 {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -28,18 +28,18 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec, ) -> aws_sdk_kms::types::KeySpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_2048 {} => aws_sdk_kms::types::KeySpec::Rsa2048, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_3072 {} => aws_sdk_kms::types::KeySpec::Rsa3072, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_4096 {} => aws_sdk_kms::types::KeySpec::Rsa4096, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P256 {} => aws_sdk_kms::types::KeySpec::EccNistP256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P384 {} => aws_sdk_kms::types::KeySpec::EccNistP384, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P521 {} => aws_sdk_kms::types::KeySpec::EccNistP521, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_SECG_P256K1 {} => aws_sdk_kms::types::KeySpec::EccSecgP256K1, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::KeySpec::SymmetricDefault, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_224 {} => aws_sdk_kms::types::KeySpec::Hmac224, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_256 {} => aws_sdk_kms::types::KeySpec::Hmac256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_384 {} => aws_sdk_kms::types::KeySpec::Hmac384, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_512 {} => aws_sdk_kms::types::KeySpec::Hmac512, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SM2 {} => aws_sdk_kms::types::KeySpec::Sm2, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_2048 {} => aws_sdk_kms::types::KeySpec::Rsa2048, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_3072 {} => aws_sdk_kms::types::KeySpec::Rsa3072, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::RSA_4096 {} => aws_sdk_kms::types::KeySpec::Rsa4096, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P256 {} => aws_sdk_kms::types::KeySpec::EccNistP256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P384 {} => aws_sdk_kms::types::KeySpec::EccNistP384, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_NIST_P521 {} => aws_sdk_kms::types::KeySpec::EccNistP521, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::ECC_SECG_P256K1 {} => aws_sdk_kms::types::KeySpec::EccSecgP256K1, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SYMMETRIC_DEFAULT {} => aws_sdk_kms::types::KeySpec::SymmetricDefault, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_224 {} => aws_sdk_kms::types::KeySpec::Hmac224, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_256 {} => aws_sdk_kms::types::KeySpec::Hmac256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_384 {} => aws_sdk_kms::types::KeySpec::Hmac384, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::HMAC_512 {} => aws_sdk_kms::types::KeySpec::Hmac512, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeySpec::SM2 {} => aws_sdk_kms::types::KeySpec::Sm2, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_usage_type.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_usage_type.rs index fdf182c6dd..8d2db6b3ca 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_usage_type.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/key_usage_type.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_kms::types::KeyUsageType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::KeyUsageType::SignVerify => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::SIGN_VERIFY {}, - aws_sdk_kms::types::KeyUsageType::EncryptDecrypt => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::ENCRYPT_DECRYPT {}, - aws_sdk_kms::types::KeyUsageType::GenerateVerifyMac => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::GENERATE_VERIFY_MAC {}, - aws_sdk_kms::types::KeyUsageType::KeyAgreement => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::KEY_AGREEMENT {}, + aws_sdk_kms::types::KeyUsageType::SignVerify => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::SIGN_VERIFY {}, +aws_sdk_kms::types::KeyUsageType::EncryptDecrypt => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::ENCRYPT_DECRYPT {}, +aws_sdk_kms::types::KeyUsageType::GenerateVerifyMac => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::GENERATE_VERIFY_MAC {}, +aws_sdk_kms::types::KeyUsageType::KeyAgreement => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::KEY_AGREEMENT {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType, ) -> aws_sdk_kms::types::KeyUsageType { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::SIGN_VERIFY {} => aws_sdk_kms::types::KeyUsageType::SignVerify, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::ENCRYPT_DECRYPT {} => aws_sdk_kms::types::KeyUsageType::EncryptDecrypt, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::GENERATE_VERIFY_MAC {} => aws_sdk_kms::types::KeyUsageType::GenerateVerifyMac, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::KEY_AGREEMENT {} => aws_sdk_kms::types::KeyUsageType::KeyAgreement, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::SIGN_VERIFY {} => aws_sdk_kms::types::KeyUsageType::SignVerify, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::ENCRYPT_DECRYPT {} => aws_sdk_kms::types::KeyUsageType::EncryptDecrypt, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::GENERATE_VERIFY_MAC {} => aws_sdk_kms::types::KeyUsageType::GenerateVerifyMac, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::KeyUsageType::KEY_AGREEMENT {} => aws_sdk_kms::types::KeyUsageType::KeyAgreement, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/origin_type.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/origin_type.rs index 79b60c37bd..8878e10fa2 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/origin_type.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/origin_type.rs @@ -7,10 +7,10 @@ pub fn to_dafny( value: aws_sdk_kms::types::OriginType, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::OriginType::AwsKms => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_KMS {}, - aws_sdk_kms::types::OriginType::External => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL {}, - aws_sdk_kms::types::OriginType::AwsCloudhsm => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_CLOUDHSM {}, - aws_sdk_kms::types::OriginType::ExternalKeyStore => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL_KEY_STORE {}, + aws_sdk_kms::types::OriginType::AwsKms => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_KMS {}, +aws_sdk_kms::types::OriginType::External => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL {}, +aws_sdk_kms::types::OriginType::AwsCloudhsm => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_CLOUDHSM {}, +aws_sdk_kms::types::OriginType::ExternalKeyStore => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL_KEY_STORE {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -19,9 +19,9 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType, ) -> aws_sdk_kms::types::OriginType { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_KMS {} => aws_sdk_kms::types::OriginType::AwsKms, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL {} => aws_sdk_kms::types::OriginType::External, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_CLOUDHSM {} => aws_sdk_kms::types::OriginType::AwsCloudhsm, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL_KEY_STORE {} => aws_sdk_kms::types::OriginType::ExternalKeyStore, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_KMS {} => aws_sdk_kms::types::OriginType::AwsKms, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL {} => aws_sdk_kms::types::OriginType::External, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::AWS_CLOUDHSM {} => aws_sdk_kms::types::OriginType::AwsCloudhsm, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::OriginType::EXTERNAL_KEY_STORE {} => aws_sdk_kms::types::OriginType::ExternalKeyStore, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/signing_algorithm_spec.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/signing_algorithm_spec.rs index bc9cbeb90b..4fcc04f841 100644 --- a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/signing_algorithm_spec.rs +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/conversions/signing_algorithm_spec.rs @@ -7,16 +7,16 @@ pub fn to_dafny( value: aws_sdk_kms::types::SigningAlgorithmSpec, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_256 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_384 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_512 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_256 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_384 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_512 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_256 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_384 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_512 {}, - aws_sdk_kms::types::SigningAlgorithmSpec::Sm2Dsa => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::SM2DSA {}, + aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_256 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_384 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_512 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_256 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_384 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_512 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha256 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_256 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha384 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_384 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha512 => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_512 {}, +aws_sdk_kms::types::SigningAlgorithmSpec::Sm2Dsa => crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::SM2DSA {}, _ => panic!("Unknown enum variant: {}", value), }) } @@ -25,15 +25,15 @@ pub fn from_dafny( dafny_value: &crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec, ) -> aws_sdk_kms::types::SigningAlgorithmSpec { match dafny_value { - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha384, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha512, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha384, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha512, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha256, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha384, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha512, - crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::SM2DSA {} => aws_sdk_kms::types::SigningAlgorithmSpec::Sm2Dsa, + crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha384, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PSS_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPssSha512, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha384, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::RSASSA_PKCS1_V1_5_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::RsassaPkcs1V15Sha512, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_256 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha256, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_384 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha384, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::ECDSA_SHA_512 {} => aws_sdk_kms::types::SigningAlgorithmSpec::EcdsaSha512, +crate::r#software::amazon::cryptography::services::kms::internaldafny::types::SigningAlgorithmSpec::SM2DSA {} => aws_sdk_kms::types::SigningAlgorithmSpec::Sm2Dsa, } } diff --git a/TestModels/aws-sdks/kms-lite/runtimes/rust/src/standard_library_externs.rs b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/TestModels/aws-sdks/kms-lite/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/codegen/smithy-dafny-codegen-cli/src/main/java/software/amazon/polymorph/CodegenCli.java b/codegen/smithy-dafny-codegen-cli/src/main/java/software/amazon/polymorph/CodegenCli.java index 253f589759..4e12ab1308 100644 --- a/codegen/smithy-dafny-codegen-cli/src/main/java/software/amazon/polymorph/CodegenCli.java +++ b/codegen/smithy-dafny-codegen-cli/src/main/java/software/amazon/polymorph/CodegenCli.java @@ -21,13 +21,11 @@ import org.apache.commons.cli.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - -import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.loader.ModelAssembler; - import software.amazon.polymorph.CodegenEngine.TargetLanguage; import software.amazon.polymorph.smithydafny.DafnyVersion; import software.amazon.polymorph.smithyjava.generator.CodegenSubject.AwsSdkVersion; +import software.amazon.smithy.model.Model; +import software.amazon.smithy.model.loader.ModelAssembler; import software.amazon.smithy.model.validation.ValidatedResult; import software.amazon.smithy.model.validation.ValidationEvent; @@ -235,12 +233,12 @@ private static Options getCliOptionsForBuild() { .build() ) .addOption( - Option - .builder() - .longOpt("output-go") - .desc(" output directory for generated Go files") - .hasArg() - .build() + Option + .builder() + .longOpt("output-go") + .desc(" output directory for generated Go files") + .hasArg() + .build() ) .addOption( Option @@ -354,8 +352,7 @@ private static Options getCliOptionsForBuild() { .valueSeparator(',') .build() ); - } - + } private static Options getCliOptionsForPatchAfterTranspile() { return new Options() @@ -557,8 +554,8 @@ static Optional parse(String[] args) throws ParseException { .ofNullable(commandLine.getOptionValue("output-dotnet")) .map(Paths::get); final Optional outputGoDir = Optional - .ofNullable(commandLine.getOptionValue("output-go")) - .map(Paths::get); + .ofNullable(commandLine.getOptionValue("output-go")) + .map(Paths::get); final Optional outputRustDir = Optional .ofNullable(commandLine.getOptionValue("output-rust")) .map(Paths::get); diff --git a/codegen/smithy-dafny-codegen-test/src/test/java/software/amazon/polymorph/smithygo/GoTestModels.java b/codegen/smithy-dafny-codegen-test/src/test/java/software/amazon/polymorph/smithygo/GoTestModels.java new file mode 100644 index 0000000000..07bf4bce64 --- /dev/null +++ b/codegen/smithy-dafny-codegen-test/src/test/java/software/amazon/polymorph/smithygo/GoTestModels.java @@ -0,0 +1,47 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package software.amazon.polymorph.smithygo; + +import java.nio.file.Path; +import java.util.HashSet; +import java.util.Set; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import software.amazon.polymorph.TestModelTest; + +class GoTestModels extends TestModelTest { + + private static final Set DISABLED_TESTS = new HashSet<>(); + + static { + DISABLED_TESTS.add("AggregateReferences"); + DISABLED_TESTS.add("LanguageSpecificLogic"); + DISABLED_TESTS.add("SimpleTypes/BigDecimal"); + DISABLED_TESTS.add("SimpleTypes/BigInteger"); + DISABLED_TESTS.add("SimpleTypes/SimpleByte"); + DISABLED_TESTS.add("SimpleTypes/SimpleFloat"); + DISABLED_TESTS.add("SimpleTypes/SimpleShort"); + DISABLED_TESTS.add("SimpleTypes/SimpleTimestamp"); + DISABLED_TESTS.add("aws-sdks/ddb-lite"); + DISABLED_TESTS.add("aws-sdks/glue"); + DISABLED_TESTS.add("aws-sdks/lakeformation"); + DISABLED_TESTS.add("aws-sdks/kms-lite"); + DISABLED_TESTS.add("aws-sdks/sqs"); + DISABLED_TESTS.add("aws-sdks/sqs-via-cli"); + } + + @ParameterizedTest + @MethodSource("discoverTestModels") + void testModelsForJava(String relativeTestModelPath) { + Assumptions.assumeFalse(DISABLED_TESTS.contains(relativeTestModelPath)); + + Path testModelPath = getTestModelPath(relativeTestModelPath); + make(testModelPath, "setup_prettier"); + make(testModelPath, "polymorph_dafny"); + make(testModelPath, "polymorph_go"); + make(testModelPath, "transpile_go"); + make(testModelPath, "test_go"); + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java index ccd4bec72d..e3a234f9f3 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/CodegenEngine.java @@ -43,6 +43,7 @@ import software.amazon.polymorph.smithydotnet.localServiceWrapper.LocalServiceWrappedConversionCodegen; import software.amazon.polymorph.smithydotnet.localServiceWrapper.LocalServiceWrappedShimCodegen; import software.amazon.polymorph.smithygo.awssdk.DafnyGoAwsSdkClientCodegenPlugin; +import software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceCodegenPlugin; import software.amazon.polymorph.smithyjava.generator.CodegenSubject.AwsSdkVersion; import software.amazon.polymorph.smithyjava.generator.awssdk.v1.JavaAwsSdkV1; import software.amazon.polymorph.smithyjava.generator.awssdk.v2.JavaAwsSdkV2; @@ -66,7 +67,6 @@ import software.amazon.smithy.model.node.ObjectNode; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.utils.IoUtils; -import software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceCodegenPlugin; import software.amazon.smithy.utils.Pair; public class CodegenEngine { @@ -246,15 +246,7 @@ private void generateDafny(final Path outputDir) { dafnyOtherGeneratedAspects(outputDir); - LOGGER.info("Formatting Dafny code in {}", outputDir); - runCommand( - outputDir, - "dafny", - "format", - "--function-syntax:3", - "--unicode-char:false", - "." - ); + formatDafnyCode(outputDir); handlePatching(TargetLanguage.DAFNY, outputDir); } @@ -315,16 +307,29 @@ private void dafnyOtherGeneratedAspects(final Path outputDir) { // Perhaps we can make a `smithy init` template for that instead? if (!generationAspects.isEmpty()) { - Path srcDir = outputDir.resolve("../src"); - LOGGER.info("Formatting Dafny code in {}", srcDir); - runCommand( - srcDir, - "dafny", - "format", - "--function-syntax:3", - "--unicode-char:false", - "." - ); + formatDafnyCode(outputDir.resolve("../src")); + } + } + + /** + * Formats the Dafny code in the given path using {@code dafny format}, + * but does not throw an exception if the command fails. + *

+ * This enables generating interdependent Dafny files + * across multiple smithy-dafny-codegen invocations. + */ + private void formatDafnyCode(final Path path) { + LOGGER.info("Formatting Dafny code in {}", path); + final CommandResult formatResult = runCommand( + path, + "dafny", + "format", + "--function-syntax:3", + "--unicode-char:false", + "." + ); + if (formatResult.exitCode != 0) { + LOGGER.warn("Formatting failed:\n{}", formatResult.output); } } @@ -360,7 +365,7 @@ private void generateJava(final Path outputDir, final Path testOutputDir) { javaOtherGeneratedAspects(); LOGGER.info("Formatting Java code in {}", outputDir); - runCommand( + runCommandOrThrow( outputDir, "npm", "i", @@ -368,7 +373,7 @@ private void generateJava(final Path outputDir, final Path testOutputDir) { "prettier@3", "prettier-plugin-java@2.5" ); - runCommand( + runCommandOrThrow( outputDir, "npx", "prettier@3", @@ -544,7 +549,7 @@ private void generateDotnet(final Path outputDir) { .filter(path -> path.toFile().getName().endsWith(".csproj")) .map(Path::toString) ); - runCommand(dotnetRoot, args.toArray(String[]::new)); + runCommandOrThrow(dotnetRoot, args.toArray(String[]::new)); } catch (IOException e) { throw new RuntimeException(e); } @@ -721,13 +726,17 @@ private void generateRust(final Path outputDir) { generator.generate(outputDir); } - // TODO: This should be part of the StandardLibrary instead, + // TODO: These should be part of the StandardLibrary instead, // but since the Dafny Rust code generator doesn't yet support multiple crates, // we have to inline it instead. writeTemplatedFile( "runtimes/rust/src/standard_library_conversions.rs", Map.of() ); + writeTemplatedFile( + "runtimes/rust/src/standard_library_externs.rs", + Map.of() + ); handlePatching(TargetLanguage.RUST, outputDir); } @@ -765,13 +774,14 @@ private void handlePatching(TargetLanguage targetLanguage, Path outputDir) { ); Path outputDirRelative = libraryRoot.relativize(outputDir); // Need to ignore the exit code because diff will return 1 if there is a diff - String patchContent = runCommandIgnoringExitCode( + String patchContent = runCommand( libraryRoot, "git", "diff", "-R", outputDirRelative.toString() - ); + ) + .output; if (!patchContent.isBlank()) { IOUtils.writeToFile(patchContent, patchFile.toFile()); } @@ -787,7 +797,13 @@ private void handlePatching(TargetLanguage targetLanguage, Path outputDir) { if (dafnyVersion.compareTo(patchFilePair.getKey()) >= 0) { Path patchFile = patchFilePair.getValue(); LOGGER.info("Applying patch file {}", patchFile); - runCommand(libraryRoot, "git", "apply", "-v", patchFile.toString()); + runCommandOrThrow( + libraryRoot, + "git", + "apply", + "-v", + patchFile.toString() + ); return; } } @@ -799,25 +815,36 @@ private void handlePatching(TargetLanguage targetLanguage, Path outputDir) { private void generateGo() { if (libraryName.isEmpty()) { - throw new IllegalArgumentException("Python codegen requires a module name"); + throw new IllegalArgumentException("Go codegen requires a library name"); } - ObjectNode.Builder goSettingsBuilder = ObjectNode.builder() - .withMember("service", serviceShape.getId().toString()) - .withMember("moduleName", libraryName.get()); + ObjectNode.Builder goSettingsBuilder = ObjectNode + .builder() + .withMember("service", serviceShape.getId().toString()) + .withMember("moduleName", libraryName.get()); - final PluginContext pluginContext = PluginContext.builder() - .model(model) - .fileManifest(FileManifest.create(targetLangOutputDirs.get(TargetLanguage.GO))) - .settings(goSettingsBuilder.build()) - .build(); + final PluginContext pluginContext = PluginContext + .builder() + .model(model) + .fileManifest( + FileManifest.create(targetLangOutputDirs.get(TargetLanguage.GO)) + ) + .settings(goSettingsBuilder.build()) + .build(); - final Map smithyNamespaceToGoModuleNameMap = new HashMap<>(dependencyLibraryNames); - smithyNamespaceToGoModuleNameMap.put(serviceShape.getId().getNamespace(), libraryName.get()); + final Map smithyNamespaceToGoModuleNameMap = new HashMap<>( + dependencyLibraryNames + ); + smithyNamespaceToGoModuleNameMap.put( + serviceShape.getId().getNamespace(), + libraryName.get() + ); if (this.awsSdkStyle) { - new DafnyGoAwsSdkClientCodegenPlugin(smithyNamespaceToGoModuleNameMap).run(pluginContext); + new DafnyGoAwsSdkClientCodegenPlugin(smithyNamespaceToGoModuleNameMap) + .run(pluginContext); } else { - new DafnyLocalServiceCodegenPlugin(smithyNamespaceToGoModuleNameMap).run(pluginContext); + new DafnyLocalServiceCodegenPlugin(smithyNamespaceToGoModuleNameMap) + .run(pluginContext); } } @@ -941,7 +968,10 @@ private String extraDeclarationsForLocalService() { pub mod operation; mod conversions; + + /// Copied from StandardLibrary mod standard_library_conversions; + mod standard_library_externs; #[cfg(feature = "wrapped-client")] pub mod wrapped; @@ -959,26 +989,34 @@ private String extraDeclarationsForLocalService() { ); } - private String runCommand(Path workingDir, String... args) { - List argsList = List.of(args); - StringBuilder output = new StringBuilder(); - int exitCode = IoUtils.runCommand( + private record CommandResult(int exitCode, String output) {} + + /** + * Runs the given command and throws an exception if the exit code is nonzero. + */ + private String runCommandOrThrow(Path workingDir, String... args) { + final CommandResult result = runCommand(workingDir, args); + if (result.exitCode != 0) { + throw new RuntimeException( + "Command failed: " + List.of(args) + "\n" + result.output + ); + } + return result.output; + } + + /** + * Runs the given command. + */ + private CommandResult runCommand(Path workingDir, String... args) { + final List argsList = List.of(args); + final StringBuilder output = new StringBuilder(); + final int exitCode = IoUtils.runCommand( argsList, workingDir, output, Collections.emptyMap() ); - if (exitCode != 0) { - throw new RuntimeException("Command failed: " + argsList + "\n" + output); - } - return output.toString(); - } - - private String runCommandIgnoringExitCode(Path workingDir, String... args) { - List argsList = List.of(args); - StringBuilder output = new StringBuilder(); - IoUtils.runCommand(argsList, workingDir, output, Collections.emptyMap()); - return output.toString(); + return new CommandResult(exitCode, output.toString()); } private Path standardLibraryPath() { diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithydotnet/TypeConversionCodegen.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithydotnet/TypeConversionCodegen.java index c955b48e2f..05494838e1 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithydotnet/TypeConversionCodegen.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithydotnet/TypeConversionCodegen.java @@ -114,6 +114,7 @@ public Map generate() { Stream.of(typeConverter.fromDafny, typeConverter.toDafny) ) ) + .prepend(conversionConstants()) .lineSeparated() .braced(); final TokenTree conversionClass = conversionClassBody @@ -122,6 +123,16 @@ public Map generate() { return Map.of(TYPE_CONVERSION_CLASS_PATH, conversionClass.prepend(prelude)); } + private static TokenTree conversionConstants() { + return TokenTree.of( + """ + private const string ISO8601DateFormat = "yyyy-MM-dd\\\\THH:mm:ss.fff\\\\Z"; + + private const string ISO8601DateFormatNoMS = "yyyy-MM-dd\\\\THH:mm:ss\\\\Z"; + """ + ); + } + /** * Returns a stream of type converters for synthetic types (types that aren't defined in the model). */ @@ -383,15 +394,13 @@ public TypeConverter generateTimestampConverter( ) { final TokenTree fromDafnyBody = Token.of( """ - System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(""); string timestampString = new string(value.Elements); - return System.DateTime.ParseExact(timestampString, "s", culture); + return System.DateTime.ParseExact(timestampString, new[] {ISO8601DateFormat, ISO8601DateFormatNoMS}, System.Globalization.CultureInfo.InvariantCulture); """ ); final TokenTree toDafnyBody = Token.of( """ - System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(""); - string timestampString = value.ToString("s", culture); + string timestampString = value.ToString(ISO8601DateFormat, System.Globalization.CultureInfo.InvariantCulture); return Dafny.Sequence.FromString(timestampString); """ ); diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/AwsSdkGoPointableIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/AwsSdkGoPointableIndex.java index c57767d9c8..a6524a8a24 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/AwsSdkGoPointableIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/AwsSdkGoPointableIndex.java @@ -20,226 +20,262 @@ import software.amazon.smithy.utils.SetUtils; public class AwsSdkGoPointableIndex implements KnowledgeIndex { - public static final NullableIndex.CheckMode DEFAULT_CHECKMODE = - NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1_NO_INPUT; - - private static final Logger LOGGER = Logger.getLogger(AwsSdkGoPointableIndex.class.getName()); - - // All types that are Go value types - private static final Set INHERENTLY_VALUE = SetUtils.of( - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - ShapeType.UNION, - ShapeType.DOCUMENT - ); - - // All types that are Go pointer types - private static final Set INHERENTLY_POINTABLE = SetUtils.of( - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - // All types that cannot be dereferenced - private static final Set INHERENTLY_NONDEREFERENCABLE = SetUtils.of( - // built in slice/map - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - - // Interfaces - ShapeType.UNION, - ShapeType.DOCUMENT, - - // known pointer types. - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER + public static final NullableIndex.CheckMode DEFAULT_CHECKMODE = + NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1_NO_INPUT; + + private static final Logger LOGGER = Logger.getLogger( + AwsSdkGoPointableIndex.class.getName() + ); + + // All types that are Go value types + private static final Set INHERENTLY_VALUE = SetUtils.of( + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + ShapeType.UNION, + ShapeType.DOCUMENT + ); + + // All types that are Go pointer types + private static final Set INHERENTLY_POINTABLE = SetUtils.of( + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + // All types that cannot be dereferenced + private static final Set INHERENTLY_NONDEREFERENCABLE = + SetUtils.of( + // built in slice/map + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + // Interfaces + ShapeType.UNION, + ShapeType.DOCUMENT, + // known pointer types. + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER ); - // All types types that are comparable to nil - private static final Set INHERENTLY_NILLABLE = SetUtils.of( - // built in slice/map - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - - // Interfaces - ShapeType.UNION, - ShapeType.DOCUMENT, - - // known pointer types. - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - - - - private final Model model; - private final NullableIndex nullableIndex; - private final NullableIndex.CheckMode checkMode; - private final Set pointableShapes = new HashSet<>(); - private final Set nillableShapes = new HashSet<>(); - private final Set dereferencableShapes = new HashSet<>(); - - public AwsSdkGoPointableIndex(Model model, NullableIndex.CheckMode checkMode) { - this.model = model; - this.nullableIndex = NullableIndex.of(model); - this.checkMode = checkMode; - - for (Shape shape : model.toSet()) { - if (shape.asMemberShape().isPresent()) { - MemberShape member = shape.asMemberShape().get(); - Shape targetShape = model.expectShape(member.getTarget()); - - if (isMemberPointable(member, targetShape)) { - pointableShapes.add(shape.getId()); - } - if (isMemberNillable(member, targetShape)) { - nillableShapes.add(shape.getId()); - } - if (isMemberDereferencable(member, targetShape)) { - dereferencableShapes.add(shape.getId()); - } - } else { - if (isShapePointable(shape)) { - pointableShapes.add(shape.getId()); - nillableShapes.add(shape.getId()); - } - if (isShapeNillable(shape)) { - nillableShapes.add(shape.getId()); - } - if (isShapeDereferencable(shape)) { - dereferencableShapes.add(shape.getId()); - } - } + // All types types that are comparable to nil + private static final Set INHERENTLY_NILLABLE = SetUtils.of( + // built in slice/map + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + // Interfaces + ShapeType.UNION, + ShapeType.DOCUMENT, + // known pointer types. + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + private final Model model; + private final NullableIndex nullableIndex; + private final NullableIndex.CheckMode checkMode; + private final Set pointableShapes = new HashSet<>(); + private final Set nillableShapes = new HashSet<>(); + private final Set dereferencableShapes = new HashSet<>(); + + public AwsSdkGoPointableIndex( + Model model, + NullableIndex.CheckMode checkMode + ) { + this.model = model; + this.nullableIndex = NullableIndex.of(model); + this.checkMode = checkMode; + + for (Shape shape : model.toSet()) { + if (shape.asMemberShape().isPresent()) { + MemberShape member = shape.asMemberShape().get(); + Shape targetShape = model.expectShape(member.getTarget()); + + if (isMemberPointable(member, targetShape)) { + pointableShapes.add(shape.getId()); + } + if (isMemberNillable(member, targetShape)) { + nillableShapes.add(shape.getId()); + } + if (isMemberDereferencable(member, targetShape)) { + dereferencableShapes.add(shape.getId()); + } + } else { + if (isShapePointable(shape)) { + pointableShapes.add(shape.getId()); + nillableShapes.add(shape.getId()); + } + if (isShapeNillable(shape)) { + nillableShapes.add(shape.getId()); } + if (isShapeDereferencable(shape)) { + dereferencableShapes.add(shape.getId()); + } + } } + } - public AwsSdkGoPointableIndex(Model model) { - this(model, DEFAULT_CHECKMODE); - } + public AwsSdkGoPointableIndex(Model model) { + this(model, DEFAULT_CHECKMODE); + } - public static AwsSdkGoPointableIndex of(Model model) { - return model.getKnowledge(AwsSdkGoPointableIndex.class, AwsSdkGoPointableIndex::new); - } + public static AwsSdkGoPointableIndex of(Model model) { + return model.getKnowledge( + AwsSdkGoPointableIndex.class, + AwsSdkGoPointableIndex::new + ); + } + + public static AwsSdkGoPointableIndex of( + Model model, + NullableIndex.CheckMode checkMode + ) { + return model.getKnowledge( + AwsSdkGoPointableIndex.class, + model1 -> new AwsSdkGoPointableIndex(model1, checkMode) + ); + } + + private boolean isMemberDereferencable( + MemberShape member, + Shape targetShape + ) { + return ( + !INHERENTLY_NONDEREFERENCABLE.contains(targetShape.getType()) && + isMemberPointable(member, targetShape) + ); + } - public static AwsSdkGoPointableIndex of(Model model, NullableIndex.CheckMode checkMode) { - return model.getKnowledge(AwsSdkGoPointableIndex.class, (model1) -> new AwsSdkGoPointableIndex(model1, checkMode)); - } + private boolean isMemberNillable(MemberShape member, Shape targetShape) { + return ( + INHERENTLY_NILLABLE.contains(targetShape.getType()) || + isMemberPointable(member, targetShape) + ); + } - private boolean isMemberDereferencable(MemberShape member, Shape targetShape) { - return !INHERENTLY_NONDEREFERENCABLE.contains(targetShape.getType()) && isMemberPointable(member, targetShape); + private boolean isMemberPointable(MemberShape member, Shape targetShape) { + // Streamed blob shapes are never pointers because they are interfaces + if (isBlobStream(targetShape)) { + return false; } - private boolean isMemberNillable(MemberShape member, Shape targetShape) { - return INHERENTLY_NILLABLE.contains(targetShape.getType()) || isMemberPointable(member, targetShape); + if ( + INHERENTLY_VALUE.contains(targetShape.getType()) || + isShapeEnum(targetShape) + ) { + return false; } - private boolean isMemberPointable(MemberShape member, Shape targetShape) { + return nullableIndex.isMemberNullable(member, checkMode); + } - // Streamed blob shapes are never pointers because they are interfaces - if (isBlobStream(targetShape)) { - return false; - } + private boolean isShapeDereferencable(Shape shape) { + return ( + !INHERENTLY_NONDEREFERENCABLE.contains(shape.getType()) && + isShapePointable(shape) + ); + } - if (INHERENTLY_VALUE.contains(targetShape.getType()) || isShapeEnum(targetShape)) { - return false; - } + private boolean isShapeNillable(Shape shape) { + return ( + INHERENTLY_NILLABLE.contains(shape.getType()) || isShapePointable(shape) + ); + } - return nullableIndex.isMemberNullable(member, checkMode); + private boolean isShapePointable(Shape shape) { + // All operation input and output shapes are pointable. + if (isOperationStruct(shape)) { + return true; } - private boolean isShapeDereferencable(Shape shape) { - return !INHERENTLY_NONDEREFERENCABLE.contains(shape.getType()) && isShapePointable(shape); + // Streamed blob shapes are never pointers because they are interfaces + if (isBlobStream(shape)) { + return false; } - private boolean isShapeNillable(Shape shape) { - return INHERENTLY_NILLABLE.contains(shape.getType()) || isShapePointable(shape); + if (shape.isServiceShape()) { + return true; } - private boolean isShapePointable(Shape shape) { - // All operation input and output shapes are pointable. - if (isOperationStruct(shape)) { - return true; - } - - // Streamed blob shapes are never pointers because they are interfaces - if (isBlobStream(shape)) { - return false; - } - - if (shape.isServiceShape()) { - return true; - } - - // This is odd because its not a go type but a function with receiver - if (shape.isOperationShape()) { - return false; - } - - if (INHERENTLY_POINTABLE.contains(shape.getType())) { - return true; - } - - if (INHERENTLY_VALUE.contains(shape.getType()) || isShapeEnum(shape)) { - return false; - } - - return nullableIndex.isNullable(shape); + // This is odd because its not a go type but a function with receiver + if (shape.isOperationShape()) { + return false; } - private boolean isShapeEnum(Shape shape) { - return shape.getType() == ShapeType.STRING && shape.hasTrait(EnumTrait.class) - || shape.getType() == ShapeType.ENUM - || shape.getType() == ShapeType.INT_ENUM; + if (INHERENTLY_POINTABLE.contains(shape.getType())) { + return true; } - private boolean isBlobStream(Shape shape) { - return shape.getType() == ShapeType.BLOB && shape.hasTrait(StreamingTrait.ID); + if (INHERENTLY_VALUE.contains(shape.getType()) || isShapeEnum(shape)) { + return false; } - public boolean isOperationStruct(Shape shape) { - NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); - for (Relationship relationship : provider.getNeighbors(shape)) { - RelationshipType relationshipType = relationship.getRelationshipType(); - if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { - return true; - } - } - - return false; - } + return nullableIndex.isNullable(shape); + } - /** - * Returns if the shape should be generated as a Go pointer type or not. - * - * @param shape the shape to check if should be pointable type. - * @return if the shape is should be a Go pointer type. - */ - public final boolean isPointable(ToShapeId shape) { - return pointableShapes.contains(shape.toShapeId()); - } + private boolean isShapeEnum(Shape shape) { + return ( + (shape.getType() == ShapeType.STRING && + shape.hasTrait(EnumTrait.class)) || + shape.getType() == ShapeType.ENUM || + shape.getType() == ShapeType.INT_ENUM + ); + } - /** - * Returns if the Go type generated for the shape is comparable to nil. - * - * @param shape the shape to check - * @return if the shape's go type is comparable to nil - */ - public final boolean isNillable(ToShapeId shape) { - return nillableShapes.contains(shape.toShapeId()); + private boolean isBlobStream(Shape shape) { + return ( + shape.getType() == ShapeType.BLOB && shape.hasTrait(StreamingTrait.ID) + ); + } + + public boolean isOperationStruct(Shape shape) { + NeighborProvider provider = NeighborProviderIndex + .of(model) + .getReverseProvider(); + for (Relationship relationship : provider.getNeighbors(shape)) { + RelationshipType relationshipType = relationship.getRelationshipType(); + if ( + relationshipType == RelationshipType.INPUT || + relationshipType == RelationshipType.OUTPUT + ) { + return true; + } } - /** - * Returns if the Go type generated for the shape can be dereferenced. - * - * @param shape the shape to check - * @return if the shape's go type is dereferencable - */ - public final boolean isDereferencable(ToShapeId shape) { - return dereferencableShapes.contains(shape.toShapeId()); - } -} \ No newline at end of file + return false; + } + + /** + * Returns if the shape should be generated as a Go pointer type or not. + * + * @param shape the shape to check if should be pointable type. + * @return if the shape is should be a Go pointer type. + */ + public final boolean isPointable(ToShapeId shape) { + return pointableShapes.contains(shape.toShapeId()); + } + + /** + * Returns if the Go type generated for the shape is comparable to nil. + * + * @param shape the shape to check + * @return if the shape's go type is comparable to nil + */ + public final boolean isNillable(ToShapeId shape) { + return nillableShapes.contains(shape.toShapeId()); + } + + /** + * Returns if the Go type generated for the shape can be dereferenced. + * + * @param shape the shape to check + * @return if the shape's go type is dereferencable + */ + public final boolean isDereferencable(ToShapeId shape) { + return dereferencableShapes.contains(shape.toShapeId()); + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientShimGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientShimGenerator.java index f0116ce4fc..a9835297ae 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientShimGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientShimGenerator.java @@ -15,91 +15,174 @@ public class DafnyAwsSdkClientShimGenerator implements Runnable { - private final GenerationContext context; - private final ServiceShape service; - private final GoDelegator writerDelegator; - private final Model dafnyNonNormalizedModel; - private final Model awsNormalizedModel; - private final SymbolProvider symbolProvider; + private final GenerationContext context; + private final ServiceShape service; + private final GoDelegator writerDelegator; + private final Model dafnyNonNormalizedModel; + private final Model awsNormalizedModel; + private final SymbolProvider symbolProvider; - public DafnyAwsSdkClientShimGenerator(GenerationContext context, ServiceShape service) { - this.context = context; - this.service = service; - dafnyNonNormalizedModel = context.model(); - awsNormalizedModel = AddOperationShapes.execute(context.model(), service.toShapeId()); - writerDelegator = context.writerDelegator(); - symbolProvider = context.symbolProvider(); - } + public DafnyAwsSdkClientShimGenerator( + GenerationContext context, + ServiceShape service + ) { + this.context = context; + this.service = service; + dafnyNonNormalizedModel = context.model(); + awsNormalizedModel = + AddOperationShapes.execute(context.model(), service.toShapeId()); + writerDelegator = context.writerDelegator(); + symbolProvider = context.symbolProvider(); + } - @Override - public void run() { - generateShim(); - } + @Override + public void run() { + generateShim(); + } - void generateShim() { - final var namespace = "%swrapped".formatted(DafnyNameResolver.dafnyNamespace(service)); + void generateShim() { + final var namespace = + "%swrapped".formatted(DafnyNameResolver.dafnyNamespace(service)); - writerDelegator.useFileWriter("%s/shim.go".formatted(namespace), namespace, writer -> { + writerDelegator.useFileWriter( + "%s/shim.go".formatted(namespace), + namespace, + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(service) + ); + writer.addImport( + SmithyNameResolver.getGoModuleNameForSdkNamespace( + awsNormalizedModel + .expectShape(service.toShapeId(), ServiceShape.class) + .toShapeId() + .getNamespace() + ) + ); + writer.addImportFromModule( + "github.com/dafny-lang/DafnyStandardLibGo", + "Wrappers" + ); + writer.addUseImports(SmithyGoDependency.CONTEXT); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + SmithyNameResolver.shapeNamespace(service) + ); + writer.write( + """ + type Shim struct { + $L + Client *$L + } + """, + DafnyNameResolver.getDafnyInterfaceClient( + service, + service.expectTrait(ServiceTrait.class) + ), + SmithyNameResolver.getAwsServiceClient( + service.expectTrait(ServiceTrait.class) + ) + ); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(service)); - writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedModel.expectShape(service.toShapeId(), ServiceShape.class).toShapeId().getNamespace())); - writer.addImportFromModule("github.com/dafny-lang/DafnyStandardLibGo", "Wrappers"); - writer.addUseImports(SmithyGoDependency.CONTEXT); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.shapeNamespace(service)); - writer.write(""" - type Shim struct { - $L - Client *$L - } - """, - DafnyNameResolver.getDafnyInterfaceClient(service, service.expectTrait(ServiceTrait.class)), - SmithyNameResolver.getAwsServiceClient(service.expectTrait(ServiceTrait.class)) + service + .getOperations() + .forEach(operation -> { + final var awsNormalizedOperation = awsNormalizedModel.expectShape( + operation, + OperationShape.class + ); + final var awsNormalizedInputShape = awsNormalizedModel.expectShape( + awsNormalizedOperation.getInputShape() + ); + final var awsNormalizedOutputShape = awsNormalizedModel.expectShape( + awsNormalizedOperation.getOutputShape() ); + final var operationShape = dafnyNonNormalizedModel.expectShape( + operation, + OperationShape.class + ); + final var inputShape = dafnyNonNormalizedModel.expectShape( + operationShape.getInputShape() + ); + final var outputShape = dafnyNonNormalizedModel.expectShape( + operationShape.getOutputShape() + ); + final var inputType = awsNormalizedInputShape.hasTrait( + UnitTypeTrait.class + ) + ? "" + : "input %s".formatted( + DafnyNameResolver.getDafnyType( + inputShape, + symbolProvider.toSymbol(inputShape) + ) + ); - service.getOperations().forEach(operation -> { - final var awsNormalizedOperation = awsNormalizedModel.expectShape(operation, OperationShape.class); - final var awsNormalizedInputShape = awsNormalizedModel.expectShape(awsNormalizedOperation.getInputShape()); - final var awsNormalizedOutputShape = awsNormalizedModel.expectShape(awsNormalizedOperation.getOutputShape()); - - final var operationShape = dafnyNonNormalizedModel.expectShape(operation, OperationShape.class); - final var inputShape = dafnyNonNormalizedModel.expectShape(operationShape.getInputShape()); - final var outputShape = dafnyNonNormalizedModel.expectShape(operationShape.getOutputShape()); - final var inputType = awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) ? "" - : "input %s".formatted(DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(inputShape))); + final var typeConversion = awsNormalizedInputShape.hasTrait( + UnitTypeTrait.class + ) + ? "" + : "var native_request = %s(input)".formatted( + SmithyNameResolver.getFromDafnyMethodName( + awsNormalizedInputShape, + "" + ) + ); - final var typeConversion = awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) ? "" - : "var native_request = %s(input)".formatted(SmithyNameResolver.getFromDafnyMethodName(awsNormalizedInputShape, "")); + final var clientCall = + "shim.Client.%s(context.Background() %s)".formatted( + operationShape.getId().getName(), + awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) + ? "" + : ", &native_request" + ); - final var clientCall = "shim.Client.%s(context.Background() %s)".formatted(operationShape.getId().getName(), - awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) ? "" : ", &native_request"); + String clientResponse, returnResponse; + if (awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class)) { + clientResponse = "var _, native_error"; + returnResponse = "dafny.TupleOf()"; + writer.addImportFromModule( + "github.com/dafny-lang/DafnyRuntimeGo", + "dafny" + ); + } else { + clientResponse = "var native_response, native_error"; + returnResponse = + "%s(*native_response)".formatted( + SmithyNameResolver.getToDafnyMethodName( + awsNormalizedOutputShape, + "" + ) + ); + } - String clientResponse, returnResponse; - if (awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class)) { - clientResponse = "var _, native_error"; - returnResponse = "dafny.TupleOf()"; - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - } else { - clientResponse = "var native_response, native_error"; - returnResponse = "%s(*native_response)".formatted(SmithyNameResolver.getToDafnyMethodName(awsNormalizedOutputShape, "")); + writer.write( + """ + func (shim *Shim) $L($L) Wrappers.Result { + $L + $L = $L + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_($L.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_($L) } - - writer.write(""" - func (shim *Shim) $L($L) Wrappers.Result { - $L - $L = $L - if native_error != nil { - return Wrappers.Companion_Result_.Create_Failure_($L.Error_ToDafny(native_error)) - } - return Wrappers.Companion_Result_.Create_Success_($L) - } - """, - operationShape.getId().getName(), - inputType, typeConversion, clientResponse, clientCall, - SmithyNameResolver.shapeNamespace(service), - returnResponse - ); - }); - }); - } + """, + operationShape.getId().getName(), + inputType, + typeConversion, + clientResponse, + clientCall, + SmithyNameResolver.shapeNamespace(service), + returnResponse + ); + }); + } + ); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientTypeConversionProtocol.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientTypeConversionProtocol.java index 0b50402b28..3a82903637 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientTypeConversionProtocol.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyAwsSdkClientTypeConversionProtocol.java @@ -1,5 +1,10 @@ package software.amazon.polymorph.smithygo.awssdk; +import static software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceTypeConversionProtocol.TO_DAFNY; +import static software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceTypeConversionProtocol.TO_NATIVE; + +import java.util.HashSet; +import java.util.Set; import software.amazon.polymorph.smithygo.awssdk.shapevisitor.AwsSdkToDafnyShapeVisitor; import software.amazon.polymorph.smithygo.awssdk.shapevisitor.DafnyToAwsSdkShapeVisitor; import software.amazon.polymorph.smithygo.codegen.AddOperationShapes; @@ -18,359 +23,744 @@ import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.UnitTypeTrait; -import java.util.HashSet; -import java.util.Set; - -import static software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceTypeConversionProtocol.TO_DAFNY; -import static software.amazon.polymorph.smithygo.localservice.DafnyLocalServiceTypeConversionProtocol.TO_NATIVE; - -public class DafnyAwsSdkClientTypeConversionProtocol implements ProtocolGenerator { - final Model dafnyNonNormalizedModel; - final Model awsNormalizedModel; - final ServiceShape serviceShape; - public DafnyAwsSdkClientTypeConversionProtocol(Model model, ServiceShape serviceShape) { - dafnyNonNormalizedModel = model; - awsNormalizedModel = AddOperationShapes.execute(model, serviceShape.toShapeId()); - - this.serviceShape = serviceShape; - } +public class DafnyAwsSdkClientTypeConversionProtocol + implements ProtocolGenerator { + + final Model dafnyNonNormalizedModel; + final Model awsNormalizedModel; + final ServiceShape serviceShape; + + public DafnyAwsSdkClientTypeConversionProtocol( + Model model, + ServiceShape serviceShape + ) { + dafnyNonNormalizedModel = model; + awsNormalizedModel = + AddOperationShapes.execute(model, serviceShape.toShapeId()); + + this.serviceShape = serviceShape; + } + + @Override + public ShapeId getProtocol() { + return null; + } + + @Override + public ApplicationProtocol getApplicationProtocol() { + return null; + } + + @Override + public void generateSerializers(GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var symbolProvider = context.symbolProvider(); + final var writerDelegator = context.writerDelegator(); + serviceShape + .getOperations() + .forEach(eachOperation -> { + final var awsNormalizedOperation = awsNormalizedModel.expectShape( + eachOperation, + OperationShape.class + ); + final var awsNormalizedInputShape = awsNormalizedModel.expectShape( + awsNormalizedOperation.getInputShape() + ); + if (!alreadyVisited.contains(awsNormalizedInputShape.toShapeId())) { + alreadyVisited.add(awsNormalizedInputShape.toShapeId()); + if ( + !awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) && + awsNormalizedInputShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var awsNormalizedInputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName( + serviceShape, + awsNormalizedInputShape, + "" + ); + final var awsNormalizedInputSymbol = symbolProvider.toSymbol( + awsNormalizedInputShape + ); + final var dafnyInput = dafnyNonNormalizedModel + .expectShape(eachOperation, OperationShape.class) + .getInputShape(); + final var dafnyInputSymbol = symbolProvider.toSymbol( + dafnyNonNormalizedModel.expectShape(dafnyInput) + ); + writerDelegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImport( + SmithyNameResolver.getGoModuleNameForSdkNamespace( + awsNormalizedInputShape.toShapeId().getNamespace() + ) + ); + writer.write( + """ + func $L(nativeInput $L)($L) { + ${C|} + }""", + awsNormalizedInputToDafnyMethodName, + SmithyNameResolver.getSmithyTypeAws( + serviceShape.expectTrait(ServiceTrait.class), + awsNormalizedInputSymbol, + false + ), + DafnyNameResolver.getDafnyType( + dafnyNonNormalizedModel.expectShape(dafnyInput), + dafnyInputSymbol + ), + writer.consumer(w -> + generateRequestSerializer( + context, + awsNormalizedOperation, + context.writerDelegator() + ) + ) + ); + } + ); + } + } - @Override - public ShapeId getProtocol() { - return null; - } + final var awsNormalizedOutputShape = awsNormalizedModel.expectShape( + awsNormalizedOperation.getOutputShape() + ); + if (!alreadyVisited.contains(awsNormalizedOutputShape.toShapeId())) { + alreadyVisited.add(awsNormalizedOutputShape.toShapeId()); + if ( + !awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class) && + awsNormalizedOutputShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var awsNormalizedOutputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName( + serviceShape, + awsNormalizedOutputShape, + "" + ); + final var awsNormalizedOutputSymbol = symbolProvider.toSymbol( + awsNormalizedOutputShape + ); + final var dafnyOutput = dafnyNonNormalizedModel + .expectShape(eachOperation, OperationShape.class) + .getOutputShape(); + final var dafnyOutputSymbol = symbolProvider.toSymbol( + dafnyNonNormalizedModel.expectShape(dafnyOutput) + ); + writerDelegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImport( + SmithyNameResolver.getGoModuleNameForSdkNamespace( + awsNormalizedInputShape.toShapeId().getNamespace() + ) + ); + writer.write( + """ + func $L(nativeOutput $L)($L) { + ${C|} + }""", + awsNormalizedOutputToDafnyMethodName, + SmithyNameResolver.getSmithyTypeAws( + serviceShape.expectTrait(ServiceTrait.class), + awsNormalizedOutputSymbol, + false + ), + DafnyNameResolver.getDafnyType( + dafnyNonNormalizedModel.expectShape(dafnyOutput), + dafnyOutputSymbol + ), + writer.consumer(w -> + generateResponseSerializer( + context, + awsNormalizedOperation, + context.writerDelegator() + ) + ) + ); + } + ); + } + } + }); + generateErrorSerializer(context); + } + + @Override + public void generateDeserializers(GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var symbolProvider = context.symbolProvider(); + final var delegator = context.writerDelegator(); + + serviceShape + .getOperations() + .forEach(eachOperation -> { + final var awsNormalizedOperationShape = awsNormalizedModel.expectShape( + eachOperation, + OperationShape.class + ); + final var awsNormalizedInputShape = awsNormalizedModel.expectShape( + awsNormalizedOperationShape.getInputShape() + ); + if (!alreadyVisited.contains(awsNormalizedInputShape.toShapeId())) { + alreadyVisited.add(awsNormalizedInputShape.toShapeId()); + if ( + !awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) && + awsNormalizedInputShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var awsNormalizedInputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + awsNormalizedInputShape, + "" + ); + final var awsNormalizedInputSymbol = symbolProvider.toSymbol( + awsNormalizedInputShape + ); + final var dafnyInput = dafnyNonNormalizedModel + .expectShape(eachOperation, OperationShape.class) + .getInputShape(); + final var dafnyInputSymbol = symbolProvider.toSymbol( + dafnyNonNormalizedModel.expectShape(dafnyInput) + ); + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImport( + SmithyNameResolver.getGoModuleNameForSdkNamespace( + awsNormalizedInputShape.toShapeId().getNamespace() + ) + ); + writer.write( + """ + func $L(dafnyInput $L)($L) { + ${C|} + }""", + awsNormalizedInputFromDafnyMethodName, + DafnyNameResolver.getDafnyType( + dafnyNonNormalizedModel.expectShape(dafnyInput), + dafnyInputSymbol + ), + SmithyNameResolver.getSmithyTypeAws( + serviceShape.expectTrait(ServiceTrait.class), + awsNormalizedInputSymbol, + false + ), + writer.consumer(w -> + generateRequestDeserializer( + context, + awsNormalizedOperationShape, + context.writerDelegator() + ) + ) + ); + } + ); + } + } - @Override - public ApplicationProtocol getApplicationProtocol() { - return null; - } + final var awsNormalizedOutputShape = awsNormalizedModel.expectShape( + awsNormalizedOperationShape.getOutputShape() + ); + if (!alreadyVisited.contains(awsNormalizedOutputShape.toShapeId())) { + alreadyVisited.add(awsNormalizedOutputShape.toShapeId()); + if ( + !awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class) && + awsNormalizedOutputShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var awsNormalizedOutputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + awsNormalizedOutputShape, + "" + ); + final var awsNormalizedOutputSymbol = context + .symbolProvider() + .toSymbol(awsNormalizedOutputShape); + final var dafnyOutput = dafnyNonNormalizedModel + .expectShape(eachOperation, OperationShape.class) + .getOutputShape(); + final var dafnyOutputSymbol = symbolProvider.toSymbol( + dafnyNonNormalizedModel.expectShape(dafnyOutput) + ); + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImport( + SmithyNameResolver.getGoModuleNameForSdkNamespace( + awsNormalizedInputShape.toShapeId().getNamespace() + ) + ); + writer.write( + """ + func $L(dafnyOutput $L)($L) { + ${C|} + }""", + awsNormalizedOutputFromDafnyMethodName, + DafnyNameResolver.getDafnyType( + dafnyNonNormalizedModel.expectShape(dafnyOutput), + dafnyOutputSymbol + ), + SmithyNameResolver.getSmithyTypeAws( + serviceShape.expectTrait(ServiceTrait.class), + awsNormalizedOutputSymbol, + false + ), + writer.consumer(w -> + generateResponseDeserializer( + context, + awsNormalizedOperationShape, + context.writerDelegator() + ) + ) + ); + } + ); + } + } + }); + + generateErrorDeserializer(context); + } + + private void generateRequestSerializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + final var nonNormalizedOperation = dafnyNonNormalizedModel.expectShape( + operation.toShapeId(), + OperationShape.class + ); + final var targetShape = dafnyNonNormalizedModel.expectShape( + nonNormalizedOperation.getInputShape() + ); + delegator.useFileWriter( + "%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var input = targetShape.accept( + new AwsSdkToDafnyShapeVisitor( + context, + "nativeInput", + writer, + false, + false, + false + ) + ); + writer.write( + """ + return $L + """, + input + ); + } + ); + } + + private void generateResponseSerializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + final var nonNormalizedOperation = dafnyNonNormalizedModel.expectShape( + operation.toShapeId(), + OperationShape.class + ); + final var targetShape = dafnyNonNormalizedModel.expectShape( + nonNormalizedOperation.getOutputShape() + ); + delegator.useFileWriter( + "%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var input = targetShape.accept( + new AwsSdkToDafnyShapeVisitor( + context, + "nativeOutput", + writer, + false, + false, + false + ) + ); + writer.write( + """ + return $L + """, + input + ); + } + ); + } + + private void generateRequestDeserializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(operation), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var inputShape = operation.getInputShape(); + + final var targetShape = awsNormalizedModel.expectShape(inputShape); + final var input = targetShape.accept( + new DafnyToAwsSdkShapeVisitor(context, "dafnyInput", writer) + ); - @Override - public void generateSerializers(GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var symbolProvider = context.symbolProvider(); - final var writerDelegator = context.writerDelegator(); - serviceShape.getOperations().forEach(eachOperation -> { - final var awsNormalizedOperation = awsNormalizedModel.expectShape(eachOperation, OperationShape.class); - final var awsNormalizedInputShape = awsNormalizedModel.expectShape(awsNormalizedOperation.getInputShape()); - if (!alreadyVisited.contains(awsNormalizedInputShape.toShapeId())) { - alreadyVisited.add(awsNormalizedInputShape.toShapeId()); - if (!awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) && awsNormalizedInputShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var awsNormalizedInputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, awsNormalizedInputShape, ""); - final var awsNormalizedInputSymbol = symbolProvider.toSymbol(awsNormalizedInputShape); - final var dafnyInput = dafnyNonNormalizedModel.expectShape(eachOperation, OperationShape.class).getInputShape(); - final var dafnyInputSymbol = symbolProvider.toSymbol(dafnyNonNormalizedModel.expectShape(dafnyInput)); - writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedInputShape.toShapeId().getNamespace())); - writer.write(""" - func $L(nativeInput $L)($L) { - ${C|} - }""", awsNormalizedInputToDafnyMethodName, SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), awsNormalizedInputSymbol, false), - DafnyNameResolver.getDafnyType(dafnyNonNormalizedModel.expectShape(dafnyInput), dafnyInputSymbol), - writer.consumer(w -> generateRequestSerializer(context, awsNormalizedOperation, context.writerDelegator()))); - }); - } - } + writer.write( + """ + return $L + """, + input + ); + } + ); + } + + private void generateResponseDeserializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(operation), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var outputShape = operation.getOutputShape(); + + final var targetShape = awsNormalizedModel.expectShape(outputShape); + final var output = targetShape.accept( + new DafnyToAwsSdkShapeVisitor(context, "dafnyOutput", writer) + ); - final var awsNormalizedOutputShape = awsNormalizedModel.expectShape(awsNormalizedOperation.getOutputShape()); - if (!alreadyVisited.contains(awsNormalizedOutputShape.toShapeId())) { - alreadyVisited.add(awsNormalizedOutputShape.toShapeId()); - if (!awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class) && awsNormalizedOutputShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var awsNormalizedOutputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, awsNormalizedOutputShape, ""); - final var awsNormalizedOutputSymbol = symbolProvider.toSymbol(awsNormalizedOutputShape); - final var dafnyOutput = dafnyNonNormalizedModel.expectShape(eachOperation, OperationShape.class).getOutputShape(); - final var dafnyOutputSymbol = symbolProvider.toSymbol(dafnyNonNormalizedModel.expectShape(dafnyOutput)); - writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedInputShape.toShapeId().getNamespace())); - writer.write(""" - func $L(nativeOutput $L)($L) { - ${C|} - }""", awsNormalizedOutputToDafnyMethodName, - SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), awsNormalizedOutputSymbol, false), - DafnyNameResolver.getDafnyType(dafnyNonNormalizedModel.expectShape(dafnyOutput), dafnyOutputSymbol), - writer.consumer(w -> generateResponseSerializer(context, awsNormalizedOperation, context.writerDelegator()))); - }); - } + writer.write( + """ + return $L + """, + output + ); + } + ); + } + + private void generateErrorSerializer(final GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var errorShapes = awsNormalizedModel.getShapesWithTrait( + ErrorTrait.class + ); + + for (final var errorShape : errorShapes) { + if ( + !errorShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + continue; + } + if (!alreadyVisited.contains(errorShape.toShapeId())) { + alreadyVisited.add(errorShape.toShapeId()); + final var getInputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName(serviceShape, errorShape, ""); + + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(errorShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(errorShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSdkNamespace( + errorShape.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespaceAws( + serviceShape.expectTrait(ServiceTrait.class), + true + ) + ); + writer.write( + """ + func $L(nativeInput types.$L)($L) { + ${C|} + }""", + getInputToDafnyMethodName, + context.symbolProvider().toSymbol(errorShape).getName(), + DafnyNameResolver.getDafnyBaseErrorType(errorShape), + writer.consumer(w -> { + String output = errorShape.accept( + new AwsSdkToDafnyShapeVisitor( + context, + "nativeInput", + writer, + false, + false, + false + ) + ); + writer.write( + """ + return $L + """, + output + ); + }) + ); } - }); - generateErrorSerializer(context); + ); + } } - @Override - public void generateDeserializers(GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var symbolProvider = context.symbolProvider(); - final var delegator = context.writerDelegator(); - - serviceShape.getOperations().forEach(eachOperation -> { - final var awsNormalizedOperationShape = awsNormalizedModel.expectShape(eachOperation, OperationShape.class); - final var awsNormalizedInputShape = awsNormalizedModel.expectShape(awsNormalizedOperationShape.getInputShape()); - if (!alreadyVisited.contains(awsNormalizedInputShape.toShapeId())) { - alreadyVisited.add(awsNormalizedInputShape.toShapeId()); - if (!awsNormalizedInputShape.hasTrait(UnitTypeTrait.class) && awsNormalizedInputShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var awsNormalizedInputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, awsNormalizedInputShape, ""); - final var awsNormalizedInputSymbol = symbolProvider.toSymbol(awsNormalizedInputShape); - final var dafnyInput = dafnyNonNormalizedModel.expectShape(eachOperation, OperationShape.class).getInputShape(); - final var dafnyInputSymbol = symbolProvider.toSymbol(dafnyNonNormalizedModel.expectShape(dafnyInput)); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedInputShape.toShapeId().getNamespace())); - writer.write(""" - func $L(dafnyInput $L)($L) { - ${C|} - }""", awsNormalizedInputFromDafnyMethodName, DafnyNameResolver.getDafnyType(dafnyNonNormalizedModel.expectShape(dafnyInput), dafnyInputSymbol), - SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), awsNormalizedInputSymbol, false), - writer.consumer(w -> generateRequestDeserializer(context, awsNormalizedOperationShape, context.writerDelegator()))); - }); + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.write( + """ + func OpaqueError_Input_ToDafny(nativeInput error)($L.Error) { + return $L.Companion_Error_.Create_Opaque_(nativeInput) + }""", + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape) + ); + } + ); + + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.write( + """ + func Error_ToDafny(err error)($L.Error) { + switch err.(type) { + // Service Errors + ${C|} + + default: + return OpaqueError_Input_ToDafny(err) } } - - final var awsNormalizedOutputShape = awsNormalizedModel.expectShape(awsNormalizedOperationShape.getOutputShape()); - if (!alreadyVisited.contains(awsNormalizedOutputShape.toShapeId())) { - alreadyVisited.add(awsNormalizedOutputShape.toShapeId()); - if (!awsNormalizedOutputShape.hasTrait(UnitTypeTrait.class) && awsNormalizedOutputShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var awsNormalizedOutputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, awsNormalizedOutputShape, ""); - final var awsNormalizedOutputSymbol = context.symbolProvider().toSymbol(awsNormalizedOutputShape); - final var dafnyOutput = dafnyNonNormalizedModel.expectShape(eachOperation, OperationShape.class).getOutputShape(); - final var dafnyOutputSymbol = symbolProvider.toSymbol(dafnyNonNormalizedModel.expectShape(dafnyOutput)); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImport(SmithyNameResolver.getGoModuleNameForSdkNamespace(awsNormalizedInputShape.toShapeId().getNamespace())); - writer.write(""" - func $L(dafnyOutput $L)($L) { - ${C|} - }""", awsNormalizedOutputFromDafnyMethodName, DafnyNameResolver.getDafnyType(dafnyNonNormalizedModel.expectShape(dafnyOutput), dafnyOutputSymbol), - SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), awsNormalizedOutputSymbol, false), - writer.consumer(w -> generateResponseDeserializer(context, awsNormalizedOperationShape, context.writerDelegator()))); - }); - } + """, + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + writer.consumer(w -> { + for (var error : errorShapes) { + w.write( + """ + case *$L: + return $L(*err.(*$L)) + """, + SmithyNameResolver.getSmithyTypeAws( + serviceShape.expectTrait(ServiceTrait.class), + context + .symbolProvider() + .toSymbol( + awsNormalizedModel.expectShape(error.toShapeId()) + ), + true + ), + SmithyNameResolver.getToDafnyMethodName( + serviceShape, + awsNormalizedModel.expectShape(error.toShapeId()), + "" + ), + SmithyNameResolver.getSmithyTypeAws( + serviceShape.expectTrait(ServiceTrait.class), + context + .symbolProvider() + .toSymbol( + awsNormalizedModel.expectShape(error.toShapeId()) + ), + true + ) + ); + } + }) + ); + } + ); + } + + private void generateErrorDeserializer(final GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var errorShapes = awsNormalizedModel.getShapesWithTrait( + ErrorTrait.class + ); + for (final var errorShape : errorShapes) { + if ( + !errorShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + continue; + } + if (!alreadyVisited.contains(errorShape.toShapeId())) { + alreadyVisited.add(errorShape.toShapeId()); + final var getOutputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + errorShape, + "" + ); + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(errorShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(errorShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSdkNamespace( + errorShape.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespaceAws( + serviceShape.expectTrait(ServiceTrait.class), + true + ) + ); + writer.write( + """ + func $L(dafnyOutput $L)(types.$L) { + ${C|} + }""", + getOutputFromDafnyMethodName, + DafnyNameResolver.getDafnyBaseErrorType(errorShape), + context.symbolProvider().toSymbol(errorShape).getName(), + writer.consumer(w -> { + String output = errorShape.accept( + new DafnyToAwsSdkShapeVisitor( + context, + "dafnyOutput", + writer + ) + ); + writer.write( + """ + return $L + """, + output + ); + }) + ); } - }); - - generateErrorDeserializer(context); - - } - - private void generateRequestSerializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - final var nonNormalizedOperation = dafnyNonNormalizedModel.expectShape(operation.toShapeId(), OperationShape.class); - final var targetShape = dafnyNonNormalizedModel.expectShape(nonNormalizedOperation.getInputShape()); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), SmithyNameResolver.shapeNamespace(operation), writer -> { - final var input = targetShape.accept(new AwsSdkToDafnyShapeVisitor( - context, - "nativeInput", - writer, - false, false, false - )); - writer.write(""" - return $L - """, - input); - } - ); - } - - private void generateResponseSerializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - final var nonNormalizedOperation = dafnyNonNormalizedModel.expectShape(operation.toShapeId(), OperationShape.class); - final var targetShape = dafnyNonNormalizedModel.expectShape(nonNormalizedOperation.getOutputShape()); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), SmithyNameResolver.shapeNamespace(operation), writer -> { - final var input = targetShape.accept(new AwsSdkToDafnyShapeVisitor( - context, - "nativeOutput", - writer, - false, false, false - )); - writer.write(""" - return $L - """, - input); - } - ); - } - - private void generateRequestDeserializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_NATIVE), SmithyNameResolver.shapeNamespace(operation), writer -> { - - final var inputShape = operation.getInputShape(); - - final var targetShape = awsNormalizedModel.expectShape(inputShape); - final var input = targetShape.accept(new DafnyToAwsSdkShapeVisitor( - context, - "dafnyInput", - writer - )); - - writer.write(""" - return $L - """, input); - }); + ); + } } - private void generateResponseDeserializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_NATIVE), SmithyNameResolver.shapeNamespace(operation), writer -> { - - final var outputShape = operation.getOutputShape(); - - final var targetShape = awsNormalizedModel.expectShape(outputShape); - final var output = targetShape.accept(new DafnyToAwsSdkShapeVisitor( - context, - "dafnyOutput", - writer - )); - - writer.write(""" - return $L - """, output); - }); - } - - private void generateErrorSerializer(final GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var errorShapes = awsNormalizedModel.getShapesWithTrait(ErrorTrait.class); - - for (final var errorShape : - errorShapes) { - if (!errorShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - continue; - } - if (!alreadyVisited.contains(errorShape.toShapeId())) { - alreadyVisited.add(errorShape.toShapeId()); - final var getInputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, errorShape, ""); - - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(errorShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(errorShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSdkNamespace(errorShape.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespaceAws(serviceShape.expectTrait(ServiceTrait.class), true)); - writer.write(""" - func $L(nativeInput types.$L)($L) { - ${C|} - }""", - getInputToDafnyMethodName, context.symbolProvider().toSymbol(errorShape).getName(), DafnyNameResolver.getDafnyBaseErrorType(errorShape), - writer.consumer(w -> { - String output = errorShape.accept(new AwsSdkToDafnyShapeVisitor( - context, - "nativeInput", - writer, - false, false, false - )); - writer.write(""" - return $L - """, output); - })); - }); - } + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addUseImports(SmithyGoDependency.FMT); + writer.write( + """ + func OpaqueError_Output_FromDafny(dafnyOutput $L.Error)(error) { + return fmt.Errorf(fmt.Sprintf("%v", dafnyOutput.Dtor_obj())) + }""", + DafnyNameResolver.dafnyTypesNamespace(serviceShape) + ); } - - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.write(""" - func OpaqueError_Input_ToDafny(nativeInput error)($L.Error) { - return $L.Companion_Error_.Create_Opaque_(nativeInput) - }""", DafnyNameResolver.dafnyTypesNamespace(serviceShape), DafnyNameResolver.dafnyTypesNamespace(serviceShape)); - }); - - - context.writerDelegator() - .useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), - SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.write(""" - func Error_ToDafny(err error)($L.Error) { - switch err.(type) { - // Service Errors - ${C|} - - default: - return OpaqueError_Input_ToDafny(err) - } - } - """, DafnyNameResolver.dafnyTypesNamespace(serviceShape), - writer.consumer(w -> { - for (var error : errorShapes) { - w.write(""" - case *$L: - return $L(*err.(*$L)) - """, SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), context.symbolProvider().toSymbol(awsNormalizedModel.expectShape(error.toShapeId())), true), - SmithyNameResolver.getToDafnyMethodName(serviceShape, awsNormalizedModel.expectShape(error.toShapeId()), ""), - SmithyNameResolver.getSmithyTypeAws(serviceShape.expectTrait(ServiceTrait.class), context.symbolProvider().toSymbol(awsNormalizedModel.expectShape(error.toShapeId())), true)); - } - }) - ); - }); - } - - private void generateErrorDeserializer(final GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var errorShapes = awsNormalizedModel.getShapesWithTrait(ErrorTrait.class); - for (final var errorShape : - errorShapes) { - if (!errorShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - continue; - } - if (!alreadyVisited.contains(errorShape.toShapeId())) { - alreadyVisited.add(errorShape.toShapeId()); - final var getOutputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, errorShape, ""); - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(errorShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(errorShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSdkNamespace(errorShape.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespaceAws(serviceShape.expectTrait(ServiceTrait.class), true)); - writer.write(""" - func $L(dafnyOutput $L)(types.$L) { - ${C|} - }""", - getOutputFromDafnyMethodName, DafnyNameResolver.getDafnyBaseErrorType(errorShape), context.symbolProvider().toSymbol(errorShape).getName(), - writer.consumer(w -> { - String output = errorShape.accept(new DafnyToAwsSdkShapeVisitor( - context, - "dafnyOutput", - writer - )); - writer.write(""" - return $L - """, output); - })); - }); + ); + + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.write( + """ + func Error_FromDafny(err $L.Error)(error) { + // Service Errors + ${C|} + + return OpaqueError_Output_FromDafny(err) } + """, + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + writer.consumer(w -> { + for (var error : awsNormalizedModel.getShapesWithTrait( + ErrorTrait.class + )) { + w.write( + """ + if err.Is_$L() { + e := $L(err) + return &e + } + """, + error.toShapeId().getName(), + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + awsNormalizedModel.expectShape(error.toShapeId()), + "" + ) + ); + } + }) + ); } - - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addUseImports(SmithyGoDependency.FMT); - writer.write(""" - func OpaqueError_Output_FromDafny(dafnyOutput $L.Error)(error) { - return fmt.Errorf(fmt.Sprintf("%v", dafnyOutput.Dtor_obj())) - }""", - DafnyNameResolver.dafnyTypesNamespace(serviceShape)); - }); - - context.writerDelegator() - .useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), - SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.write(""" - func Error_FromDafny(err $L.Error)(error) { - // Service Errors - ${C|} - - return OpaqueError_Output_FromDafny(err) - } - """, DafnyNameResolver.dafnyTypesNamespace(serviceShape), - writer.consumer(w -> { - for (var error : awsNormalizedModel.getShapesWithTrait(ErrorTrait.class)) { - w.write(""" - if err.Is_$L() { - e := $L(err) - return &e - } - """, error.toShapeId().getName(), SmithyNameResolver.getFromDafnyMethodName(serviceShape, awsNormalizedModel.expectShape(error.toShapeId()), "")); - } - }) - ); - }); - } + ); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkClientCodegenPlugin.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkClientCodegenPlugin.java index a8ef0ae239..1398a55c1c 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkClientCodegenPlugin.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkClientCodegenPlugin.java @@ -1,5 +1,6 @@ package software.amazon.polymorph.smithygo.awssdk; +import java.util.Map; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoSettings; import software.amazon.polymorph.smithygo.codegen.GoWriter; @@ -9,52 +10,59 @@ import software.amazon.smithy.build.SmithyBuildPlugin; import software.amazon.smithy.codegen.core.directed.CodegenDirector; -import java.util.Map; - public class DafnyGoAwsSdkClientCodegenPlugin implements SmithyBuildPlugin { - public DafnyGoAwsSdkClientCodegenPlugin(final Map smithyNamespaceToPythonModuleNameMap) { - super(); - SmithyNameResolver.setSmithyNamespaceToGoModuleNameMap(smithyNamespaceToPythonModuleNameMap); - } + public DafnyGoAwsSdkClientCodegenPlugin( + final Map smithyNamespaceToPythonModuleNameMap + ) { + super(); + SmithyNameResolver.setSmithyNamespaceToGoModuleNameMap( + smithyNamespaceToPythonModuleNameMap + ); + } - @Override - public String getName() { - return "dafny-go-aws-sdk-client-codegen"; } + @Override + public String getName() { + return "dafny-go-aws-sdk-client-codegen"; + } - public void run(PluginContext context) { - CodegenDirector runner - = new CodegenDirector<>(); + public void run(PluginContext context) { + CodegenDirector< + GoWriter, + GoIntegration, + GenerationContext, + GoSettings + > runner = new CodegenDirector<>(); - runner.directedCodegen(new DafnyGoAwsSdkDirectedCodegen()); + runner.directedCodegen(new DafnyGoAwsSdkDirectedCodegen()); - // Set the SmithyIntegration class to look for and apply using SPI. - runner.integrationClass(GoIntegration.class); + // Set the SmithyIntegration class to look for and apply using SPI. + runner.integrationClass(GoIntegration.class); - // Set the FileManifest and Model from the plugin. - runner.fileManifest(context.getFileManifest()); + // Set the FileManifest and Model from the plugin. + runner.fileManifest(context.getFileManifest()); - // Create the GoSettings object from the plugin settings. - GoSettings settings = GoSettings.from(context.getSettings()); - runner.settings(settings); + // Create the GoSettings object from the plugin settings. + GoSettings settings = GoSettings.from(context.getSettings()); + runner.settings(settings); - runner.model(context.getModel()); + runner.model(context.getModel()); - runner.service(settings.getService()); + runner.service(settings.getService()); - // Configure the director to perform some common model transforms. - runner.performDefaultCodegenTransforms(); + // Configure the director to perform some common model transforms. + runner.performDefaultCodegenTransforms(); - // TODO: Not using below because it would break existing AWS SDKs. Maybe it should be configurable - // so generic SDKs call this by default, but AWS SDKs can opt-out of it via a setting. - // runner.createDedicatedInputsAndOutputs(); + // TODO: Not using below because it would break existing AWS SDKs. Maybe it should be configurable + // so generic SDKs call this by default, but AWS SDKs can opt-out of it via a setting. + // runner.createDedicatedInputsAndOutputs(); - // Run it! - runner.run(); - } + // Run it! + runner.run(); + } - @Override - public void execute(PluginContext context) { - this.run(context); - } + @Override + public void execute(PluginContext context) { + this.run(context); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkDirectedCodegen.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkDirectedCodegen.java index 16798586aa..ddbccecbe4 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkDirectedCodegen.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/DafnyGoAwsSdkDirectedCodegen.java @@ -16,62 +16,84 @@ import software.amazon.smithy.codegen.core.directed.GenerateStructureDirective; import software.amazon.smithy.codegen.core.directed.GenerateUnionDirective; -public class DafnyGoAwsSdkDirectedCodegen implements DirectedCodegen { - @Override - public SymbolProvider createSymbolProvider(CreateSymbolProviderDirective directive) { - return new SymbolVisitor(directive.model(), directive.settings()); +public class DafnyGoAwsSdkDirectedCodegen + implements DirectedCodegen { + + @Override + public SymbolProvider createSymbolProvider( + CreateSymbolProviderDirective directive + ) { + return new SymbolVisitor(directive.model(), directive.settings()); + } + + @Override + public GenerationContext createContext( + CreateContextDirective directive + ) { + return GenerationContext + .builder() + .model(directive.model()) + .settings(directive.settings()) + .symbolProvider(directive.symbolProvider()) + .fileManifest(directive.fileManifest()) + .integrations(directive.integrations()) + .writerDelegator( + new GoDelegator(directive.fileManifest(), directive.symbolProvider()) + ) + .protocolGenerator( + new DafnyAwsSdkClientTypeConversionProtocol( + directive.model(), + directive.service() + ) + ) + .build(); + } + + @Override + public void generateService( + GenerateServiceDirective directive + ) { + new DafnyAwsSdkClientShimGenerator(directive.context(), directive.service()) + .run(); + + var protocolGenerator = directive.context().protocolGenerator(); + if (protocolGenerator == null) { + return; } - @Override - public GenerationContext createContext(CreateContextDirective directive) { - return GenerationContext.builder() - .model(directive.model()) - .settings(directive.settings()) - .symbolProvider(directive.symbolProvider()) - .fileManifest(directive.fileManifest()) - .integrations(directive.integrations()) - .writerDelegator(new GoDelegator(directive.fileManifest(), directive.symbolProvider())) - .protocolGenerator(new DafnyAwsSdkClientTypeConversionProtocol(directive.model(), directive.service())) - .build(); - } - - @Override - public void generateService(GenerateServiceDirective directive) { - new DafnyAwsSdkClientShimGenerator(directive.context(), directive.service()).run(); - - var protocolGenerator = directive.context().protocolGenerator(); - if (protocolGenerator == null) { - return; - } - - protocolGenerator.generateSerializers(directive.context()); - - protocolGenerator.generateDeserializers(directive.context()); - - } - - @Override - public void generateStructure(GenerateStructureDirective generateStructureDirective) { - - } - - @Override - public void generateError(GenerateErrorDirective generateErrorDirective) { - - } - - @Override - public void generateUnion(GenerateUnionDirective generateUnionDirective) { - - } - - @Override - public void generateEnumShape(GenerateEnumDirective generateEnumDirective) { - - } - - @Override - public void generateIntEnumShape(GenerateIntEnumDirective generateIntEnumDirective) { - - } + protocolGenerator.generateSerializers(directive.context()); + + protocolGenerator.generateDeserializers(directive.context()); + } + + @Override + public void generateStructure( + GenerateStructureDirective< + GenerationContext, + GoSettings + > generateStructureDirective + ) {} + + @Override + public void generateError( + GenerateErrorDirective generateErrorDirective + ) {} + + @Override + public void generateUnion( + GenerateUnionDirective generateUnionDirective + ) {} + + @Override + public void generateEnumShape( + GenerateEnumDirective generateEnumDirective + ) {} + + @Override + public void generateIntEnumShape( + GenerateIntEnumDirective< + GenerationContext, + GoSettings + > generateIntEnumDirective + ) {} } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/AwsSdkToDafnyShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/AwsSdkToDafnyShapeVisitor.java index 62d13f66b3..d89e542548 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/AwsSdkToDafnyShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/AwsSdkToDafnyShapeVisitor.java @@ -1,5 +1,7 @@ package software.amazon.polymorph.smithygo.awssdk.shapevisitor; +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + import software.amazon.polymorph.smithygo.awssdk.AwsSdkGoPointableIndex; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoWriter; @@ -26,394 +28,538 @@ import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.utils.StringUtils; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - public class AwsSdkToDafnyShapeVisitor extends ShapeVisitor.Default { - private final GenerationContext context; - private final String dataSource; - private final GoWriter writer; - private final boolean isConfigShape; - private final boolean isOptional; - protected boolean isPointerType; - - public void setPointerType() { - this.isPointerType = false; + private final GenerationContext context; + private final String dataSource; + private final GoWriter writer; + private final boolean isConfigShape; + + private final boolean isOptional; + protected boolean isPointerType; + + public void setPointerType() { + this.isPointerType = false; + } + + public AwsSdkToDafnyShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isConfigShape, + final boolean isOptional, + final boolean isPointerType + ) { + this.context = context; + this.dataSource = dataSource; + this.writer = writer; + this.isConfigShape = isConfigShape; + this.isOptional = isOptional; + this.isPointerType = isPointerType; + } + + @Override + protected String getDefault(Shape shape) { + throw new CodegenException( + String.format( + "Unsupported conversion of %s to %s using the %s protocol", + shape, + shape.getType(), + context.protocolGenerator().getName() + ) + ); + } + + @Override + public String blobShape(BlobShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - - public AwsSdkToDafnyShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isConfigShape, - final boolean isOptional, - final boolean isPointerType - ) { - this.context = context; - this.dataSource = dataSource; - this.writer = writer; - this.isConfigShape = isConfigShape; - this.isOptional = isOptional; - this.isPointerType = isPointerType; + return """ + func () %s { + var v []interface{} + if %s == nil {return %s} + for _, e := range %s { + v = append(v, e) + } + return %s; + }()""".formatted( + returnType, + dataSource, + nilWrapIfRequired, + dataSource, + someWrapIfRequired.formatted("dafny.SeqOf(v...)") + ); + } + + @Override + public String structureShape(final StructureShape shape) { + final var builder = new StringBuilder(); + writer.addImportFromModule( + "github.com/dafny-lang/DafnyStandardLibGo", + "Wrappers" + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + shape.toShapeId().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(shape) + ); + + String someWrapIfRequired = "%s"; + + String companionStruct; + String returnType; + if (shape.hasTrait(ErrorTrait.class)) { + companionStruct = + DafnyNameResolver.getDafnyErrorCompanionCreate( + shape, + context.symbolProvider().toSymbol(shape) + ); + returnType = DafnyNameResolver.getDafnyBaseErrorType(shape); + } else { + companionStruct = + DafnyNameResolver.getDafnyCompanionTypeCreate( + shape, + context.symbolProvider().toSymbol(shape) + ); + returnType = + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ); } + String nilWrapIfRequired = returnType.concat("{}"); - @Override - protected String getDefault(Shape shape) { - throw new CodegenException(String.format( - "Unsupported conversion of %s to %s using the %s protocol", - shape, shape.getType(), context.protocolGenerator().getName())); + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - @Override - public String blobShape(BlobShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - return """ - func () %s { - var v []interface{} - if %s == nil {return %s} - for _, e := range %s { - v = append(v, e) - } - return %s; - }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, someWrapIfRequired.formatted("dafny.SeqOf(v...)")); + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); } - - @Override - public String structureShape(final StructureShape shape) { - final var builder = new StringBuilder(); - writer.addImportFromModule("github.com/dafny-lang/DafnyStandardLibGo", "Wrappers"); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(shape.toShapeId().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(shape)); - - String someWrapIfRequired = "%s"; - - String companionStruct; - String returnType; - if (shape.hasTrait(ErrorTrait.class)) { - companionStruct = DafnyNameResolver.getDafnyErrorCompanionCreate(shape, context.symbolProvider().toSymbol(shape)); - returnType = DafnyNameResolver.getDafnyBaseErrorType(shape); - } else { - companionStruct = DafnyNameResolver.getDafnyCompanionTypeCreate(shape, context.symbolProvider().toSymbol(shape)); - returnType = DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)); - } - String nilWrapIfRequired = returnType.concat("{}"); - - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - var goCodeBlock = """ - func () %s { - %s - return %s - }()"""; - - - builder.append("%1$s(".formatted(companionStruct)); - String fieldSeparator = ","; - for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { - final var memberName = memberShapeEntry.getKey(); - final var memberShape = memberShapeEntry.getValue(); - final var targetShape = context.model().expectShape(memberShape.getTarget()); - builder.append("%1$s%2$s".formatted( - targetShape.accept( - new AwsSdkToDafnyShapeVisitor(context, dataSource + "." + StringUtils.capitalize(memberName), - writer, isConfigShape, memberShape.isOptional(), AwsSdkGoPointableIndex.of(context.model()).isPointable(memberShape) - )), fieldSeparator - )); - } - - - return goCodeBlock.formatted(returnType, nilCheck, someWrapIfRequired.formatted(builder.append(")").toString())); + var goCodeBlock = + """ + func () %s { + %s + return %s + }()"""; + + builder.append("%1$s(".formatted(companionStruct)); + String fieldSeparator = ","; + for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { + final var memberName = memberShapeEntry.getKey(); + final var memberShape = memberShapeEntry.getValue(); + final var targetShape = context + .model() + .expectShape(memberShape.getTarget()); + builder.append( + "%1$s%2$s".formatted( + targetShape.accept( + new AwsSdkToDafnyShapeVisitor( + context, + dataSource + "." + StringUtils.capitalize(memberName), + writer, + isConfigShape, + memberShape.isOptional(), + AwsSdkGoPointableIndex + .of(context.model()) + .isPointable(memberShape) + ) + ), + fieldSeparator + ) + ); } - @Override - public String mapShape(MapShape shape) { - StringBuilder builder = new StringBuilder(); - - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - MemberShape keyMemberShape = shape.getKey(); - final Shape keyTargetShape = context.model().expectShape(keyMemberShape.getTarget()); - MemberShape valueMemberShape = shape.getValue(); - final Shape valueTargetShape = context.model().expectShape(valueMemberShape.getTarget()); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Map"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - builder.append(""" - func () %s { - %s - fieldValue := dafny.NewMapBuilder() - for key, val := range %s { - fieldValue.Add(%s, %s) - } - return %s - }()""".formatted(returnType, nilCheck, dataSource, - keyTargetShape.accept( - new AwsSdkToDafnyShapeVisitor(context, "key", writer, isConfigShape, false, false)), - valueTargetShape.accept( - new AwsSdkToDafnyShapeVisitor(context, "val", writer, isConfigShape, false, false)), - someWrapIfRequired.formatted("fieldValue.ToMap()") - ) - ); - - // Close structure - return builder.toString(); - + return goCodeBlock.formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(builder.append(")").toString()) + ); + } + + @Override + public String mapShape(MapShape shape) { + StringBuilder builder = new StringBuilder(); + + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + MemberShape keyMemberShape = shape.getKey(); + final Shape keyTargetShape = context + .model() + .expectShape(keyMemberShape.getTarget()); + MemberShape valueMemberShape = shape.getValue(); + final Shape valueTargetShape = context + .model() + .expectShape(valueMemberShape.getTarget()); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Map"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - - @Override - public String listShape(ListShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - StringBuilder builder = new StringBuilder(); - - MemberShape memberShape = shape.getMember(); - final Shape targetShape = context.model().expectShape(memberShape.getTarget()); - - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - - builder.append(""" - func () %s { - if %s == nil { return %s } - var fieldValue []interface{} = make([]interface{}, 0) - for _, val := range %s { - element := %s - fieldValue = append(fieldValue, element) - } - return %s - }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, - targetShape.accept( - new AwsSdkToDafnyShapeVisitor(context, "val", writer, isConfigShape, false, false) - ), someWrapIfRequired.formatted("dafny.SeqOf(fieldValue...)"))); - - // Close structure - return builder.toString(); + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); } - - @Override - public String booleanShape(BooleanShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "false"; - String someWrapIfRequired = "%s%s"; - String returnType = "bool"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; - } - - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); + builder.append( + """ + func () %s { + %s + fieldValue := dafny.NewMapBuilder() + for key, val := range %s { + fieldValue.Add(%s, %s) + } + return %s + }()""".formatted( + returnType, + nilCheck, + dataSource, + keyTargetShape.accept( + new AwsSdkToDafnyShapeVisitor( + context, + "key", + writer, + isConfigShape, + false, + false + ) + ), + valueTargetShape.accept( + new AwsSdkToDafnyShapeVisitor( + context, + "val", + writer, + isConfigShape, + false, + false + ) + ), + someWrapIfRequired.formatted("fieldValue.ToMap()") + ) + ); + + // Close structure + return builder.toString(); + } + + @Override + public String listShape(ListShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + StringBuilder builder = new StringBuilder(); + + MemberShape memberShape = shape.getMember(); + final Shape targetShape = context + .model() + .expectShape(memberShape.getTarget()); + + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - @Override - public String stringShape(StringShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (shape.hasTrait(EnumTrait.class)) { - String someWrapIfRequired = "%s"; - String returnType = DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)); - if (this.isOptional) { - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } + builder.append( + """ + func () %s { + if %s == nil { return %s } + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range %s { + element := %s + fieldValue = append(fieldValue, element) + } + return %s + }()""".formatted( + returnType, + dataSource, + nilWrapIfRequired, + dataSource, + targetShape.accept( + new AwsSdkToDafnyShapeVisitor( + context, + "val", + writer, + isConfigShape, + false, + false + ) + ), + someWrapIfRequired.formatted("dafny.SeqOf(fieldValue...)") + ) + ); + + // Close structure + return builder.toString(); + } + + @Override + public String booleanShape(BooleanShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "false"; + String someWrapIfRequired = "%s%s"; + String returnType = "bool"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; + } - return """ - func () %s { - var index int - for _, enumVal := range %s.Values() { - index++ - if enumVal == %s{ - break; - } - } - var enum interface{} - for allEnums, i := dafny.Iterate(%s{}.AllSingletonConstructors()), 0; i < index; i++ { - var ok bool - enum, ok = allEnums() - if !ok { - break; - } - } - return %s - }()""".formatted(returnType, dataSource, dataSource, DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), someWrapIfRequired.formatted("enum.(%s)".formatted(DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))))); - } else { - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } - var nilCheck = ""; - var dereferenceIfRequired = isPointerType ? "*" : ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) + ); + } + + @Override + public String stringShape(StringShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (shape.hasTrait(EnumTrait.class)) { + String someWrapIfRequired = "%s"; + String returnType = DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ); + if (this.isOptional) { + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + return """ + func () %s { + var index int + for _, enumVal := range %s.Values() { + index++ + if enumVal == %s{ + break; + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(%s{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break; + } + } + return %s + }()""".formatted( + returnType, + dataSource, + dataSource, + DafnyNameResolver.getDafnyCompanionStructType( + shape, + context.symbolProvider().toSymbol(shape) + ), + someWrapIfRequired.formatted( + "enum.(%s)".formatted( + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ) + ) + ) + ); + } else { + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + var nilCheck = ""; + var dereferenceIfRequired = isPointerType ? "*" : ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + + if (shape.hasTrait(DafnyUtf8BytesTrait.class)) writer.addUseImports( + SmithyGoDependency.stdlib("unicode/utf8") + ); + + var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) + ? """ + dafny.SeqOf(func () []interface{} { + utf8.ValidString(%s%s) + b := []byte(%s%s) + f := make([]interface{}, len(b)) + for i, v := range b { + f[i] = v } - - if (shape.hasTrait(DafnyUtf8BytesTrait.class)) - writer.addUseImports(SmithyGoDependency.stdlib("unicode/utf8")); - - var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) ? """ - dafny.SeqOf(func () []interface{} { - utf8.ValidString(%s%s) - b := []byte(%s%s) - f := make([]interface{}, len(b)) - for i, v := range b { - f[i] = v - } - return f - }()...)""".formatted(dereferenceIfRequired, dataSource, dereferenceIfRequired, dataSource) : "dafny.SeqOfChars([]dafny.Char(%s%s)...)".formatted(dereferenceIfRequired, dataSource); - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(underlyingType)); - } + return f + }()...)""".formatted( + dereferenceIfRequired, + dataSource, + dereferenceIfRequired, + dataSource + ) + : "dafny.SeqOfChars([]dafny.Char(%s%s)...)".formatted( + dereferenceIfRequired, + dataSource + ); + + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(underlyingType) + ); } - - @Override - public String integerShape(IntegerShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "0"; - String someWrapIfRequired = "%s%s"; - String returnType = "int"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; - } - - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); - + } + + @Override + public String integerShape(IntegerShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "0"; + String someWrapIfRequired = "%s%s"; + String returnType = "int"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; } - @Override - public String longShape(LongShape shape) { - String nilWrapIfRequired = "0"; - String someWrapIfRequired = "%s%s"; - String returnType = "int64"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; - } - - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); } - @Override - public String doubleShape(DoubleShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); - writer.addUseImports(SmithyGoDependency.MATH); - - String nilWrapIfRequired = "dafny.SeqOf()"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) + ); + } + + @Override + public String longShape(LongShape shape) { + String nilWrapIfRequired = "0"; + String someWrapIfRequired = "%s%s"; + String returnType = "int64"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; + } - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } - return """ - func () %s { - %s - var bits = math.Float64bits(%s%s) - var bytes = make([]byte, 8) - binary.LittleEndian.PutUint64(bytes, bits) - var v []interface{} - for _, e := range bytes { - v = append(v, e) - } - return %s; - }()""".formatted(returnType, nilCheck, dereferenceIfRequired, dataSource, someWrapIfRequired.formatted("dafny.SeqOf(v...)")); + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) + ); + } + + @Override + public String doubleShape(DoubleShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); + writer.addUseImports(SmithyGoDependency.MATH); + + String nilWrapIfRequired = "dafny.SeqOf()"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - @Override - public String unionShape(UnionShape shape) { - return """ - func () Wrappers.Option { - _ = val - return Wrappers.Companion_Option_.Create_None_() - }()"""; + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); } - @Override - public String timestampShape(TimestampShape shape) { - if (this.isOptional) { - return "Wrappers.Companion_Option_.Create_None_()"; - } - return "dafny.SeqOf()"; + return """ + func () %s { + %s + var bits = math.Float64bits(%s%s) + var bytes = make([]byte, 8) + binary.LittleEndian.PutUint64(bytes, bits) + var v []interface{} + for _, e := range bytes { + v = append(v, e) + } + return %s; + }()""".formatted( + returnType, + nilCheck, + dereferenceIfRequired, + dataSource, + someWrapIfRequired.formatted("dafny.SeqOf(v...)") + ); + } + + @Override + public String unionShape(UnionShape shape) { + return """ + func () Wrappers.Option { + _ = val + return Wrappers.Companion_Option_.Create_None_() + }()"""; + } + + @Override + public String timestampShape(TimestampShape shape) { + if (this.isOptional) { + return "Wrappers.Companion_Option_.Create_None_()"; } -} \ No newline at end of file + return "dafny.SeqOf()"; + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/DafnyToAwsSdkShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/DafnyToAwsSdkShapeVisitor.java index db3d54c719..a427578d93 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/DafnyToAwsSdkShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/awssdk/shapevisitor/DafnyToAwsSdkShapeVisitor.java @@ -1,9 +1,11 @@ package software.amazon.polymorph.smithygo.awssdk.shapevisitor; +import java.util.Arrays; +import java.util.List; +import software.amazon.polymorph.smithygo.awssdk.AwsSdkGoPointableIndex; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoWriter; import software.amazon.polymorph.smithygo.codegen.SmithyGoDependency; -import software.amazon.polymorph.smithygo.awssdk.AwsSdkGoPointableIndex; import software.amazon.polymorph.smithygo.codegen.SymbolUtils; import software.amazon.polymorph.smithygo.codegen.Synthetic; import software.amazon.polymorph.smithygo.codegen.knowledge.GoPointableIndex; @@ -33,363 +35,537 @@ import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.utils.StringUtils; -import java.util.Arrays; -import java.util.List; - public class DafnyToAwsSdkShapeVisitor extends ShapeVisitor.Default { - private static final List shapeName = Arrays.asList("IndexSizeBytes", "ItemCount", "ProcessedSizeBytes", "TableSizeBytes"); - private final AwsSdkGoPointableIndex awsSdkGoPointableIndex; - private final GenerationContext context; - private final String dataSource; - private final GoWriter writer; - private final ServiceTrait serviceTrait; - private final boolean isOptional; - private final boolean isPointable; - public DafnyToAwsSdkShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer - ) { - this(context, dataSource, writer, false, false); - } + private static final List shapeName = Arrays.asList( + "IndexSizeBytes", + "ItemCount", + "ProcessedSizeBytes", + "TableSizeBytes" + ); + private final AwsSdkGoPointableIndex awsSdkGoPointableIndex; + private final GenerationContext context; + private final String dataSource; + private final GoWriter writer; + private final ServiceTrait serviceTrait; + private final boolean isOptional; + private final boolean isPointable; - public DafnyToAwsSdkShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isOptional, - final boolean isPointable - ) { - this.context = context; - this.dataSource = dataSource; - this.writer = writer; - this.isOptional = isOptional; - this.isPointable = isPointable; - this.awsSdkGoPointableIndex = new AwsSdkGoPointableIndex(context.model()); - this.serviceTrait = context.model().expectShape(context.settings().getService(context.model()).toShapeId()).getTrait(ServiceTrait.class).get(); - } + public DafnyToAwsSdkShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer + ) { + this(context, dataSource, writer, false, false); + } - @Override - protected String getDefault(Shape shape) { - throw new CodegenException(String.format( - "Unsupported conversion of %s to %s using the %s protocol", - shape, shape.getType(), context.protocolGenerator().getName())); - } + public DafnyToAwsSdkShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isOptional, + final boolean isPointable + ) { + this.context = context; + this.dataSource = dataSource; + this.writer = writer; + this.isOptional = isOptional; + this.isPointable = isPointable; + this.awsSdkGoPointableIndex = new AwsSdkGoPointableIndex(context.model()); + this.serviceTrait = + context + .model() + .expectShape(context.settings().getService(context.model()).toShapeId()) + .getTrait(ServiceTrait.class) + .get(); + } - @Override - public String blobShape(BlobShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - return """ - func () []byte { - var b []byte - if %s == nil { - return nil - } - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return b - } else { - b = append(b, val.(byte)) - } - } - }()""".formatted(dataSource, dataSource); - } + @Override + protected String getDefault(Shape shape) { + throw new CodegenException( + String.format( + "Unsupported conversion of %s to %s using the %s protocol", + shape, + shape.getType(), + context.protocolGenerator().getName() + ) + ); + } - @Override - public String structureShape(final StructureShape shape) { - final var builder = new StringBuilder(); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(shape.toShapeId().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(shape)); - var subtype = !(awsSdkGoPointableIndex.isOperationStruct(shape) || shape.hasTrait(Synthetic.class)) - || shape.toShapeId().getName().contains("Exception"); - var nilcheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilcheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilcheck = ""; - } - } - builder.append(""" - func() %s%s { - %s - return %s%s { - """.formatted(this.isPointable ? "*" : "", SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, subtype).concat(".").concat(shape.getId().getName()), - nilcheck, - this.isPointable ? "&" : "", - SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, subtype).concat(".").concat(shape.getId().getName())) - ); - for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { - final var memberName = memberShapeEntry.getKey(); - final var memberShape = memberShapeEntry.getValue(); - final var targetShape = context.model().expectShape(memberShape.getTarget()); - //TODO: Is it ever possible for structure to be nil? - final var derivedDataSource = "%1$s%2$s%3$s%4$s".formatted(dataSource, this.isOptional ? ".(%s)".formatted(DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))) : "", - ".Dtor_%s()".formatted(memberName), - memberShape.isOptional() ? ".UnwrapOr(nil)" : ""); - builder.append("%1$s: %2$s,".formatted( - StringUtils.capitalize(memberName), - targetShape.accept( - new DafnyToAwsSdkShapeVisitor(context, derivedDataSource, writer, memberShape.isOptional(), shapeName.contains(memberName) || awsSdkGoPointableIndex.isPointable(targetShape)) - ) - )); + @Override + public String blobShape(BlobShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + return """ + func () []byte { + var b []byte + if %s == nil { + return nil + } + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) } + } + }()""".formatted(dataSource, dataSource); + } - return builder.append("}}()").toString(); + @Override + public String structureShape(final StructureShape shape) { + final var builder = new StringBuilder(); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + shape.toShapeId().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(shape) + ); + var subtype = + !(awsSdkGoPointableIndex.isOperationStruct(shape) || + shape.hasTrait(Synthetic.class)) || + shape.toShapeId().getName().contains("Exception"); + var nilcheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilcheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilcheck = ""; + } + } + builder.append( + """ + func() %s%s { + %s + return %s%s { + """.formatted( + this.isPointable ? "*" : "", + SmithyNameResolver + .smithyTypesNamespaceAws(serviceTrait, subtype) + .concat(".") + .concat(shape.getId().getName()), + nilcheck, + this.isPointable ? "&" : "", + SmithyNameResolver + .smithyTypesNamespaceAws(serviceTrait, subtype) + .concat(".") + .concat(shape.getId().getName()) + ) + ); + for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { + final var memberName = memberShapeEntry.getKey(); + final var memberShape = memberShapeEntry.getValue(); + final var targetShape = context + .model() + .expectShape(memberShape.getTarget()); + //TODO: Is it ever possible for structure to be nil? + final var derivedDataSource = + "%1$s%2$s%3$s%4$s".formatted( + dataSource, + this.isOptional + ? ".(%s)".formatted( + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ) + ) + : "", + ".Dtor_%s()".formatted(memberName), + memberShape.isOptional() ? ".UnwrapOr(nil)" : "" + ); + builder.append( + "%1$s: %2$s,".formatted( + StringUtils.capitalize(memberName), + targetShape.accept( + new DafnyToAwsSdkShapeVisitor( + context, + derivedDataSource, + writer, + memberShape.isOptional(), + shapeName.contains(memberName) || + awsSdkGoPointableIndex.isPointable(targetShape) + ) + ) + ) + ); } - // TODO: smithy-dafny-conversion library - @Override - public String listShape(ListShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - StringBuilder builder = new StringBuilder(); + return builder.append("}}()").toString(); + } - MemberShape memberShape = shape.getMember(); - final Shape targetShape = context.model().expectShape(memberShape.getTarget()); - var typeName = GoCodegenUtils.getType(context.symbolProvider().toSymbol(targetShape), serviceTrait); - builder.append(""" - func() []%s{ - var fieldValue []%s - %s - for i := dafny.Iterate(%s.(dafny.Sequence)); ; { - val, ok := i() - if !ok { - break - } - fieldValue = append(fieldValue, %s)} - """.formatted(typeName, typeName, this.isOptional ? """ - if %s == nil { - return nil - }""".formatted(dataSource) : "", dataSource, - targetShape.accept( - new DafnyToAwsSdkShapeVisitor(context, "val%s".formatted(memberShape.isOptional() ? ".(%s)".formatted(DafnyNameResolver.getDafnyType(targetShape, context.symbolProvider().toSymbol(targetShape))) : ""), writer, false, awsSdkGoPointableIndex.isPointable(memberShape)) - ))); + // TODO: smithy-dafny-conversion library + @Override + public String listShape(ListShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + StringBuilder builder = new StringBuilder(); - // Close structure - return builder.append("return fieldValue }()").toString(); - } + MemberShape memberShape = shape.getMember(); + final Shape targetShape = context + .model() + .expectShape(memberShape.getTarget()); + var typeName = GoCodegenUtils.getType( + context.symbolProvider().toSymbol(targetShape), + serviceTrait + ); + builder.append( + """ + func() []%s{ + var fieldValue []%s + %s + for i := dafny.Iterate(%s.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, %s)} + """.formatted( + typeName, + typeName, + this.isOptional + ? """ + if %s == nil { + return nil + }""".formatted(dataSource) + : "", + dataSource, + targetShape.accept( + new DafnyToAwsSdkShapeVisitor( + context, + "val%s".formatted( + memberShape.isOptional() + ? ".(%s)".formatted( + DafnyNameResolver.getDafnyType( + targetShape, + context.symbolProvider().toSymbol(targetShape) + ) + ) + : "" + ), + writer, + false, + awsSdkGoPointableIndex.isPointable(memberShape) + ) + ) + ) + ); - @Override - public String mapShape(MapShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - StringBuilder builder = new StringBuilder(); + // Close structure + return builder.append("return fieldValue }()").toString(); + } - MemberShape keyMemberShape = shape.getKey(); - final Shape keyTargetShape = context.model().expectShape(keyMemberShape.getTarget()); - MemberShape valueMemberShape = shape.getValue(); - final Shape valueTargetShape = context.model().expectShape(valueMemberShape.getTarget()); - var typeName = GoCodegenUtils.getType(context.symbolProvider().toSymbol(valueTargetShape), serviceTrait); + @Override + public String mapShape(MapShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + StringBuilder builder = new StringBuilder(); - var nilCheck = ""; - if (this.isOptional) { - nilCheck = """ - if %s == nil { - return nil - } - """.formatted(dataSource); - } - builder.append(""" - func() map[string]%s { - var m map[string]%s = make(map[string]%s) - %s - for i := dafny.Iterate(%s%s.Items());; { - val, ok := i() - if !ok { - break; - } - m[%s] = %s - } - return m - }()""".formatted(typeName, typeName, typeName, nilCheck, dataSource, this.isOptional ? ".(dafny.Map)" : "", - keyTargetShape.accept( - new DafnyToAwsSdkShapeVisitor(context, "(*val.(dafny.Tuple).IndexInt(0))", writer, keyMemberShape.isOptional(), awsSdkGoPointableIndex.isPointable(keyMemberShape))), - valueTargetShape.accept( - new DafnyToAwsSdkShapeVisitor(context, "(*val.(dafny.Tuple).IndexInt(1))%s".formatted(valueMemberShape.isOptional() ? ".(%s)".formatted(DafnyNameResolver.getDafnyType(valueTargetShape, context.symbolProvider().toSymbol(valueTargetShape))) : ""), writer, false, awsSdkGoPointableIndex.isPointable(valueMemberShape)) - ) - )); - return builder.toString(); - } + MemberShape keyMemberShape = shape.getKey(); + final Shape keyTargetShape = context + .model() + .expectShape(keyMemberShape.getTarget()); + MemberShape valueMemberShape = shape.getValue(); + final Shape valueTargetShape = context + .model() + .expectShape(valueMemberShape.getTarget()); + var typeName = GoCodegenUtils.getType( + context.symbolProvider().toSymbol(valueTargetShape), + serviceTrait + ); - @Override - public String booleanShape(BooleanShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - var nilCheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilCheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilCheck = "if %s == nil { return b }".formatted(dataSource); - } + var nilCheck = ""; + if (this.isOptional) { + nilCheck = + """ + if %s == nil { + return nil } - return """ - func() %sbool { - var b bool - %s - b = %s%s - return %sb - }()""".formatted(this.isPointable ? "*" : "", nilCheck, dataSource, this.isOptional ? ".(%s)".formatted(context.symbolProvider().toSymbol(shape).getName()) : "", - this.isPointable ? "&" : ""); + """.formatted(dataSource); } + builder.append( + """ + func() map[string]%s { + var m map[string]%s = make(map[string]%s) + %s + for i := dafny.Iterate(%s%s.Items());; { + val, ok := i() + if !ok { + break; + } + m[%s] = %s + } + return m + }()""".formatted( + typeName, + typeName, + typeName, + nilCheck, + dataSource, + this.isOptional ? ".(dafny.Map)" : "", + keyTargetShape.accept( + new DafnyToAwsSdkShapeVisitor( + context, + "(*val.(dafny.Tuple).IndexInt(0))", + writer, + keyMemberShape.isOptional(), + awsSdkGoPointableIndex.isPointable(keyMemberShape) + ) + ), + valueTargetShape.accept( + new DafnyToAwsSdkShapeVisitor( + context, + "(*val.(dafny.Tuple).IndexInt(1))%s".formatted( + valueMemberShape.isOptional() + ? ".(%s)".formatted( + DafnyNameResolver.getDafnyType( + valueTargetShape, + context.symbolProvider().toSymbol(valueTargetShape) + ) + ) + : "" + ), + writer, + false, + awsSdkGoPointableIndex.isPointable(valueMemberShape) + ) + ) + ) + ); + return builder.toString(); + } - @Override - public String stringShape(StringShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (shape.hasTrait(EnumTrait.class)) { - if (this.isOptional) { - return """ - func () %s.%s { - var u %s.%s - //TODO: What to do if nil - if %s == nil { - return u - } - inputEnum := %s.(%s) - index := -1; - for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { - enum, ok := allEnums() - if ok { - index++ - if enum.(%s).Equals(inputEnum) { - break; - } - } - } - return u.Values()[index] - }()""".formatted(SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), context.symbolProvider().toSymbol(shape).getName(), - SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), context.symbolProvider().toSymbol(shape).getName(), - dataSource, - dataSource, DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)), - DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), - DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))); - } else { - return """ - func () %s.%s { - var u %s.%s - - inputEnum := %s - index := -1; - for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { - enum, ok := allEnums() - if ok { - index++ - if enum.(%s).Equals(inputEnum) { - break; - } - } - } - return u.Values()[index] - }()""".formatted(SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), context.symbolProvider().toSymbol(shape).getName(), - SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), context.symbolProvider().toSymbol(shape).getName(), - dataSource, - DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), - DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))); - } - } + @Override + public String booleanShape(BooleanShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + var nilCheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilCheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilCheck = "if %s == nil { return b }".formatted(dataSource); + } + } + return """ + func() %sbool { + var b bool + %s + b = %s%s + return %sb + }()""".formatted( + this.isPointable ? "*" : "", + nilCheck, + dataSource, + this.isOptional + ? ".(%s)".formatted( + context.symbolProvider().toSymbol(shape).getName() + ) + : "", + this.isPointable ? "&" : "" + ); + } - var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) ? "uint8" : "dafny.Char"; - var nilCheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilCheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilCheck = "if %s == nil { return s }".formatted(dataSource); + @Override + public String stringShape(StringShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (shape.hasTrait(EnumTrait.class)) { + if (this.isOptional) { + return """ + func () %s.%s { + var u %s.%s + //TODO: What to do if nil + if %s == nil { + return u } - } + inputEnum := %s.(%s) + index := -1; + for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(%s).Equals(inputEnum) { + break; + } + } + } + return u.Values()[index] + }()""".formatted( + SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), + context.symbolProvider().toSymbol(shape).getName(), + SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), + context.symbolProvider().toSymbol(shape).getName(), + dataSource, + dataSource, + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ), + DafnyNameResolver.getDafnyCompanionStructType( + shape, + context.symbolProvider().toSymbol(shape) + ), + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ) + ); + } else { return """ - func() (%sstring) { - var s string - %s - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return %s[]string{s}[0] - } else { - s = s + string(val.(%s)) - } - } - }()""".formatted(this.isPointable ? "*" : "", nilCheck, dataSource, this.isPointable ? "&" : "", underlyingType); - } + func () %s.%s { + var u %s.%s - @Override - public String integerShape(IntegerShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (AwsSdkGoPointableIndex.of(context.model()).isPointable(shape)) { - return """ - func() *int32 { - var i int32 - if %s == nil { - return nil - } - i = %s.(int32) - return &i - }()""".formatted(dataSource, dataSource); - } else { - return "%s.(%s)".formatted(dataSource, context.symbolProvider().toSymbol(shape).getName()); - } + inputEnum := %s + index := -1; + for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(%s).Equals(inputEnum) { + break; + } + } + } + return u.Values()[index] + }()""".formatted( + SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), + context.symbolProvider().toSymbol(shape).getName(), + SmithyNameResolver.smithyTypesNamespaceAws(serviceTrait, true), + context.symbolProvider().toSymbol(shape).getName(), + dataSource, + DafnyNameResolver.getDafnyCompanionStructType( + shape, + context.symbolProvider().toSymbol(shape) + ), + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ) + ); + } } - @Override - public String longShape(LongShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - var nilCheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilCheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilCheck = "if %s == nil { return i}".formatted(dataSource); - } - } - return """ - func() %sint64 { - var i int64 - %s - i = %s%s - return %si - }()""".formatted(this.isPointable ? "*" : "", nilCheck, dataSource, this.isOptional ? ".(int64)" : "", this.isPointable ? "&" : ""); + var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) + ? "uint8" + : "dafny.Char"; + var nilCheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilCheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilCheck = "if %s == nil { return s }".formatted(dataSource); + } } - - @Override - public String doubleShape(DoubleShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - writer.addUseImports(SmithyGoDependency.MATH); - writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); - var nilCheck = ""; - if (this.isOptional) { - if (this.isPointable) { - nilCheck = "if %s == nil { return nil }".formatted(dataSource); - } else { - nilCheck = "if %s == nil { var f float64; return f}".formatted(dataSource); - } + return """ + func() (%sstring) { + var s string + %s + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return %s[]string{s}[0] + } else { + s = s + string(val.(%s)) + } } - return """ - func () %sfloat64 { - var b []byte - %s - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return %s[]float64{math.Float64frombits(binary.LittleEndian.Uint64(b))}[0] - } else { - b = append(b, val.(byte)) - } - } - }()""".formatted(this.isPointable ? "*" : "", nilCheck, dataSource, this.isPointable ? "&" : ""); + }()""".formatted( + this.isPointable ? "*" : "", + nilCheck, + dataSource, + this.isPointable ? "&" : "", + underlyingType + ); + } + + @Override + public String integerShape(IntegerShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (AwsSdkGoPointableIndex.of(context.model()).isPointable(shape)) { + return """ + func() *int32 { + var i int32 + if %s == nil { + return nil + } + i = %s.(int32) + return &i + }()""".formatted(dataSource, dataSource); + } else { + return "%s.(%s)".formatted( + dataSource, + context.symbolProvider().toSymbol(shape).getName() + ); } + } - @Override - public String unionShape(UnionShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - return """ - func () types.%s { - _ = val - return nil - }()""".formatted(context.symbolProvider().toSymbol(shape).getName()); + @Override + public String longShape(LongShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + var nilCheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilCheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilCheck = "if %s == nil { return i}".formatted(dataSource); + } } + return """ + func() %sint64 { + var i int64 + %s + i = %s%s + return %si + }()""".formatted( + this.isPointable ? "*" : "", + nilCheck, + dataSource, + this.isOptional ? ".(int64)" : "", + this.isPointable ? "&" : "" + ); + } - @Override - public String timestampShape(TimestampShape shape) { - return "nil"; + @Override + public String doubleShape(DoubleShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + writer.addUseImports(SmithyGoDependency.MATH); + writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); + var nilCheck = ""; + if (this.isOptional) { + if (this.isPointable) { + nilCheck = "if %s == nil { return nil }".formatted(dataSource); + } else { + nilCheck = + "if %s == nil { var f float64; return f}".formatted(dataSource); + } } + return """ + func () %sfloat64 { + var b []byte + %s + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return %s[]float64{math.Float64frombits(binary.LittleEndian.Uint64(b))}[0] + } else { + b = append(b, val.(byte)) + } + } + }()""".formatted( + this.isPointable ? "*" : "", + nilCheck, + dataSource, + this.isPointable ? "&" : "" + ); + } + + @Override + public String unionShape(UnionShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + return """ + func () types.%s { + _ = val + return nil + }()""".formatted(context.symbolProvider().toSymbol(shape).getName()); + } + @Override + public String timestampShape(TimestampShape shape) { + return "nil"; + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/AddOperationShapes.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/AddOperationShapes.java index 36a3d64526..bd63a39ed6 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/AddOperationShapes.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/AddOperationShapes.java @@ -17,7 +17,6 @@ import java.util.TreeSet; import java.util.logging.Logger; - import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.shapes.AbstractShapeBuilder; @@ -31,85 +30,117 @@ * Ensures that each operation has a unique input and output shape. */ public final class AddOperationShapes { - private static final Logger LOGGER = Logger.getLogger(AddOperationShapes.class.getName()); - - private AddOperationShapes() { - } - - /** - * Processes the given model and returns a new model ensuring service operation has an unique input and output - * synthesized shape. - * - * @param model the model - * @param serviceShapeId the service shape - * @return a model with unique operation input and output shapes - */ - public static Model execute(Model model, ShapeId serviceShapeId) { - TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - ServiceShape service = model.expectShape(serviceShapeId, ServiceShape.class); - TreeSet operations = new TreeSet<>(topDownIndex.getContainedOperations( - model.expectShape(serviceShapeId))); - - Model.Builder modelBuilder = model.toBuilder(); - for (OperationShape operation : operations) { - OperationShape.Builder operationBuilder = operation.toBuilder(); - ShapeId operationId = operation.getId(); - LOGGER.info(() -> "building unique input/output shapes for " + operationId); - if (operation.getInput().isPresent()) { - StructureShape newInputShape = operation.getInput() - .map(shapeId -> cloneOperationShape( - service, operationId, (StructureShape) model.expectShape(shapeId), "Input")).get(); - modelBuilder.addShape(newInputShape); - operationBuilder.input(newInputShape.toShapeId()); - } - - if (operation.getOutput().isPresent()) { - StructureShape newOutputShape = operation.getOutput() - .map(shapeId -> cloneOperationShape( - service, operationId, (StructureShape) model.expectShape(shapeId), "Output")).get(); - modelBuilder.addShape(newOutputShape); - operationBuilder.output(newOutputShape.toShapeId()); - } - - // Update operation model with the input/output shape ids - modelBuilder.addShape(operationBuilder.build()); - } - - return modelBuilder.build(); - } -// private static StructureShape emptyOperationStructure(ServiceShape service, ShapeId opShapeId, String suffix) { -// return StructureShape.builder() -// .id(ShapeId.fromParts(service.toShapeId().getNamespace(), opShapeId.getName(service) + suffix)) -// .addTrait(Synthetic.builder().build()) -// .build(); -// } - - private static StructureShape cloneOperationShape( - ServiceShape service, - ShapeId operationShapeId, - StructureShape structureShape, - String suffix - ) { - return (StructureShape) cloneShape(structureShape, operationShapeId.getName(service) + suffix); + private static final Logger LOGGER = Logger.getLogger( + AddOperationShapes.class.getName() + ); + + private AddOperationShapes() {} + + /** + * Processes the given model and returns a new model ensuring service operation has an unique input and output + * synthesized shape. + * + * @param model the model + * @param serviceShapeId the service shape + * @return a model with unique operation input and output shapes + */ + public static Model execute(Model model, ShapeId serviceShapeId) { + TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); + ServiceShape service = model.expectShape( + serviceShapeId, + ServiceShape.class + ); + TreeSet operations = new TreeSet<>( + topDownIndex.getContainedOperations(model.expectShape(serviceShapeId)) + ); + + Model.Builder modelBuilder = model.toBuilder(); + for (OperationShape operation : operations) { + OperationShape.Builder operationBuilder = operation.toBuilder(); + ShapeId operationId = operation.getId(); + LOGGER.info(() -> "building unique input/output shapes for " + operationId + ); + if (operation.getInput().isPresent()) { + StructureShape newInputShape = operation + .getInput() + .map(shapeId -> + cloneOperationShape( + service, + operationId, + (StructureShape) model.expectShape(shapeId), + "Input" + ) + ) + .get(); + modelBuilder.addShape(newInputShape); + operationBuilder.input(newInputShape.toShapeId()); + } + + if (operation.getOutput().isPresent()) { + StructureShape newOutputShape = operation + .getOutput() + .map(shapeId -> + cloneOperationShape( + service, + operationId, + (StructureShape) model.expectShape(shapeId), + "Output" + ) + ) + .get(); + modelBuilder.addShape(newOutputShape); + operationBuilder.output(newOutputShape.toShapeId()); + } + + // Update operation model with the input/output shape ids + modelBuilder.addShape(operationBuilder.build()); } - private static Shape cloneShape(Shape shape, String cloneShapeName) { - ShapeId cloneShapeId = ShapeId.fromParts(shape.toShapeId().getNamespace(), cloneShapeName); - - AbstractShapeBuilder builder = Shape.shapeToBuilder(shape) - .id(cloneShapeId) - .addTrait(Synthetic.builder() - .archetype(shape.getId()) - .build()); - - shape.members().forEach(memberShape -> { - builder.addMember(memberShape.toBuilder() - .id(cloneShapeId.withMember(memberShape.getMemberName())) - .build()); - }); - - - return (Shape) builder.build(); - } -} \ No newline at end of file + return modelBuilder.build(); + } + + // private static StructureShape emptyOperationStructure(ServiceShape service, ShapeId opShapeId, String suffix) { + // return StructureShape.builder() + // .id(ShapeId.fromParts(service.toShapeId().getNamespace(), opShapeId.getName(service) + suffix)) + // .addTrait(Synthetic.builder().build()) + // .build(); + // } + + private static StructureShape cloneOperationShape( + ServiceShape service, + ShapeId operationShapeId, + StructureShape structureShape, + String suffix + ) { + return (StructureShape) cloneShape( + structureShape, + operationShapeId.getName(service) + suffix + ); + } + + private static Shape cloneShape(Shape shape, String cloneShapeName) { + ShapeId cloneShapeId = ShapeId.fromParts( + shape.toShapeId().getNamespace(), + cloneShapeName + ); + + AbstractShapeBuilder builder = Shape + .shapeToBuilder(shape) + .id(cloneShapeId) + .addTrait(Synthetic.builder().archetype(shape.getId()).build()); + + shape + .members() + .forEach(memberShape -> { + builder.addMember( + memberShape + .toBuilder() + .id(cloneShapeId.withMember(memberShape.getMemberName())) + .build() + ); + }); + + return (Shape) builder.build(); + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ApplicationProtocol.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ApplicationProtocol.java index a436b7d90a..d66d096247 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ApplicationProtocol.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ApplicationProtocol.java @@ -2,10 +2,14 @@ import software.amazon.smithy.codegen.core.SymbolReference; import software.amazon.smithy.utils.SmithyUnstableApi; + /** * Represents the resolves {@link Symbol}s and references for an * application protocol (e.g., "http", "mqtt", etc). */ @SmithyUnstableApi -public record ApplicationProtocol(String name, SymbolReference requestType, SymbolReference responseType) { -} +public record ApplicationProtocol( + String name, + SymbolReference requestType, + SymbolReference responseType +) {} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/CodegenUtils.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/CodegenUtils.java index 9e4d363813..aef04700fa 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/CodegenUtils.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/CodegenUtils.java @@ -15,6 +15,17 @@ package software.amazon.polymorph.smithygo.codegen; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.logging.Logger; import software.amazon.polymorph.smithygo.codegen.knowledge.GoPointableIndex; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; @@ -31,402 +42,422 @@ import software.amazon.smithy.model.traits.TitleTrait; import software.amazon.smithy.utils.StringUtils; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Optional; -import java.util.function.Predicate; -import java.util.logging.Logger; - /** * Utility methods likely to be needed across packages. */ public final class CodegenUtils { - private static final Logger LOGGER = Logger.getLogger(CodegenUtils.class.getName()); - - private static final String SYNTHETIC_NAMESPACE = "smithy.go.synthetic"; - - private CodegenUtils() { - } - - /** - * Executes a given shell command in a given directory. - * - * @param command The string command to execute, e.g. "go fmt". - * @param directory The directory to run the command in. - * @return Returns the console output of the command. - */ - public static String runCommand(String command, Path directory) { - String[] finalizedCommand; - if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { - finalizedCommand = new String[]{"cmd.exe", "/c", command}; - } else { - finalizedCommand = new String[]{"sh", "-c", command}; - } - - ProcessBuilder processBuilder = new ProcessBuilder(finalizedCommand) - .redirectErrorStream(true) - .directory(directory.toFile()); - - try { - Process process = processBuilder.start(); - List output = new ArrayList<>(); - - // Capture output for reporting. - try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( - process.getInputStream(), Charset.defaultCharset()))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - LOGGER.finest(line); - output.add(line); - } - } - - process.waitFor(); - process.destroy(); - - String joinedOutput = String.join(System.lineSeparator(), output); - if (process.exitValue() != 0) { - throw new CodegenException(String.format( - "Command `%s` failed with output:%n%n%s", command, joinedOutput)); - } - return joinedOutput; - } catch (InterruptedException | IOException e) { - throw new CodegenException(e); - } + private static final Logger LOGGER = Logger.getLogger( + CodegenUtils.class.getName() + ); + + private static final String SYNTHETIC_NAMESPACE = "smithy.go.synthetic"; + + private CodegenUtils() {} + + /** + * Executes a given shell command in a given directory. + * + * @param command The string command to execute, e.g. "go fmt". + * @param directory The directory to run the command in. + * @return Returns the console output of the command. + */ + public static String runCommand(String command, Path directory) { + String[] finalizedCommand; + if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { + finalizedCommand = new String[] { "cmd.exe", "/c", command }; + } else { + finalizedCommand = new String[] { "sh", "-c", command }; } - /** - * Gets the name under which the given package will be exported by default. - * - * @param packageName The full package name of the exported package. - * @return The name a the package will be imported under by default. - */ - public static String getDefaultPackageImportName(String packageName) { - if (StringUtils.isBlank(packageName) || !packageName.contains("/")) { - return packageName; + ProcessBuilder processBuilder = new ProcessBuilder(finalizedCommand) + .redirectErrorStream(true) + .directory(directory.toFile()); + + try { + Process process = processBuilder.start(); + List output = new ArrayList<>(); + + // Capture output for reporting. + try ( + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader( + process.getInputStream(), + Charset.defaultCharset() + ) + ) + ) { + String line; + while ((line = bufferedReader.readLine()) != null) { + LOGGER.finest(line); + output.add(line); } - return packageName.substring(packageName.lastIndexOf('/') + 1); + } + + process.waitFor(); + process.destroy(); + + String joinedOutput = String.join(System.lineSeparator(), output); + if (process.exitValue() != 0) { + throw new CodegenException( + String.format( + "Command `%s` failed with output:%n%n%s", + command, + joinedOutput + ) + ); + } + return joinedOutput; + } catch (InterruptedException | IOException e) { + throw new CodegenException(e); } - - /** - * Gets the alias to use when referencing the given symbol outside of its namespace. - * - *

The default value is the last path component of the symbol's namespace. - * - * @param symbol The symbol whose whose namespace alias should be retrieved. - * @return The alias of the symbol's namespace. - */ - public static String getSymbolNamespaceAlias(Symbol symbol) { - return symbol.getProperty(SymbolUtils.NAMESPACE_ALIAS, String.class) - .filter(StringUtils::isNotBlank) - .orElse(CodegenUtils.getDefaultPackageImportName(symbol.getNamespace())); + } + + /** + * Gets the name under which the given package will be exported by default. + * + * @param packageName The full package name of the exported package. + * @return The name a the package will be imported under by default. + */ + public static String getDefaultPackageImportName(String packageName) { + if (StringUtils.isBlank(packageName) || !packageName.contains("/")) { + return packageName; } - - /** - * Detects if an annotated mediatype indicates JSON contents. - * - * @param mediaType The media type to inspect. - * @return If the media type indicates JSON contents. - */ - public static boolean isJsonMediaType(String mediaType) { - return mediaType.equals("application/json") || mediaType.endsWith("+json"); + return packageName.substring(packageName.lastIndexOf('/') + 1); + } + + /** + * Gets the alias to use when referencing the given symbol outside of its namespace. + * + *

The default value is the last path component of the symbol's namespace. + * + * @param symbol The symbol whose whose namespace alias should be retrieved. + * @return The alias of the symbol's namespace. + */ + public static String getSymbolNamespaceAlias(Symbol symbol) { + return symbol + .getProperty(SymbolUtils.NAMESPACE_ALIAS, String.class) + .filter(StringUtils::isNotBlank) + .orElse(CodegenUtils.getDefaultPackageImportName(symbol.getNamespace())); + } + + /** + * Detects if an annotated mediatype indicates JSON contents. + * + * @param mediaType The media type to inspect. + * @return If the media type indicates JSON contents. + */ + public static boolean isJsonMediaType(String mediaType) { + return mediaType.equals("application/json") || mediaType.endsWith("+json"); + } + + /** + * Get the namespace where synthetic types are generated at runtime. + * + * @return synthetic type namespace + */ + public static String getSyntheticTypeNamespace() { + return CodegenUtils.SYNTHETIC_NAMESPACE; + } + + /** + * Get if the passed in shape is decorated as a synthetic clone, but there is no other shape the clone is + * created from. + * + * @param shape the shape to check if its a stubbed synthetic clone without an archetype. + * @return if the shape is synthetic clone, but not based on a specific shape. + */ + public static boolean isStubSynthetic(Shape shape) { + Optional optional = shape.getTrait(Synthetic.class); + if (!optional.isPresent()) { + return false; } - /** - * Get the namespace where synthetic types are generated at runtime. - * - * @return synthetic type namespace - */ - public static String getSyntheticTypeNamespace() { - return CodegenUtils.SYNTHETIC_NAMESPACE; + Synthetic synth = optional.get(); + return !synth.getArchetype().isPresent(); + } + + /** + * Returns the operand decorated with an & if the address of the shape type can be taken. + * + * @param model API model reference + * @param pointableIndex pointable index + * @param shape shape to use + * @param operand value to decorate + * @return updated operand + */ + public static String asAddressIfAddressable( + Model model, + GoPointableIndex pointableIndex, + Shape shape, + String operand + ) { + boolean isStruct = shape.getType() == ShapeType.STRUCTURE; + if (shape.isMemberShape()) { + isStruct = + model.expectShape(shape.asMemberShape().get().getTarget()).getType() == + ShapeType.STRUCTURE; } - /** - * Get if the passed in shape is decorated as a synthetic clone, but there is no other shape the clone is - * created from. - * - * @param shape the shape to check if its a stubbed synthetic clone without an archetype. - * @return if the shape is synthetic clone, but not based on a specific shape. - */ - public static boolean isStubSynthetic(Shape shape) { - Optional optional = shape.getTrait(Synthetic.class); - if (!optional.isPresent()) { - return false; - } - - Synthetic synth = optional.get(); - return !synth.getArchetype().isPresent(); + boolean shouldAddress = pointableIndex.isPointable(shape) && isStruct; + return shouldAddress ? "&" + operand : operand; + } + + /** + * Returns the operand decorated with an "*" if the shape is dereferencable. + * + * @param pointableIndex knowledge index for if shape is pointable. + * @param shape The shape whose value needs to be read. + * @param operand The value to be read from. + * @return updated operand + */ + public static String getAsValueIfDereferencable( + GoPointableIndex pointableIndex, + Shape shape, + String operand + ) { + if (!pointableIndex.isDereferencable(shape)) { + return operand; } - /** - * Returns the operand decorated with an & if the address of the shape type can be taken. - * - * @param model API model reference - * @param pointableIndex pointable index - * @param shape shape to use - * @param operand value to decorate - * @return updated operand - */ - public static String asAddressIfAddressable( - Model model, - GoPointableIndex pointableIndex, - Shape shape, - String operand - ) { - boolean isStruct = shape.getType() == ShapeType.STRUCTURE; - if (shape.isMemberShape()) { - isStruct = model.expectShape(shape.asMemberShape().get().getTarget()).getType() == ShapeType.STRUCTURE; - } - - boolean shouldAddress = pointableIndex.isPointable(shape) && isStruct; - return shouldAddress ? "&" + operand : operand; + return '*' + operand; + } + + /** + * Returns the operand decorated as a pointer type, without creating double pointer. + * + * @param pointableIndex knowledge index for if shape is pointable. + * @param shape The shape whose value of the type. + * @param operand The value to read. + * @return updated operand + */ + public static String getTypeAsTypePointer( + GoPointableIndex pointableIndex, + Shape shape, + String operand + ) { + if (pointableIndex.isPointable(shape)) { + return operand; } - /** - * Returns the operand decorated with an "*" if the shape is dereferencable. - * - * @param pointableIndex knowledge index for if shape is pointable. - * @param shape The shape whose value needs to be read. - * @param operand The value to be read from. - * @return updated operand - */ - public static String getAsValueIfDereferencable( - GoPointableIndex pointableIndex, - Shape shape, - String operand - ) { - if (!pointableIndex.isDereferencable(shape)) { - return operand; - } - - return '*' + operand; + return '*' + operand; + } + + /** + * Get the pointer reference to operand , if symbol is pointable. + * This method can be used by deserializers to get pointer to + * operand. + * + * @param model model for api. + * @param writer The writer dependencies will be added to, if needed. + * @param pointableIndex knowledge index for if shape is pointable. + * @param shape The shape whose value needs to be assigned. + * @param operand The Operand is the value to be assigned to the symbol shape. + * @return The Operand, along with pointer reference if applicable + */ + public static String getAsPointerIfPointable( + Model model, + GoWriter writer, + GoPointableIndex pointableIndex, + Shape shape, + String operand + ) { + if (!pointableIndex.isPointable(shape)) { + return operand; } - /** - * Returns the operand decorated as a pointer type, without creating double pointer. - * - * @param pointableIndex knowledge index for if shape is pointable. - * @param shape The shape whose value of the type. - * @param operand The value to read. - * @return updated operand - */ - public static String getTypeAsTypePointer( - GoPointableIndex pointableIndex, - Shape shape, - String operand - ) { - if (pointableIndex.isPointable(shape)) { - return operand; - } - - return '*' + operand; + if (shape.isMemberShape()) { + shape = model.expectShape(shape.asMemberShape().get().getTarget()); } - /** - * Get the pointer reference to operand , if symbol is pointable. - * This method can be used by deserializers to get pointer to - * operand. - * - * @param model model for api. - * @param writer The writer dependencies will be added to, if needed. - * @param pointableIndex knowledge index for if shape is pointable. - * @param shape The shape whose value needs to be assigned. - * @param operand The Operand is the value to be assigned to the symbol shape. - * @return The Operand, along with pointer reference if applicable - */ - public static String getAsPointerIfPointable( - Model model, - GoWriter writer, - GoPointableIndex pointableIndex, - Shape shape, - String operand - ) { - if (!pointableIndex.isPointable(shape)) { - return operand; - } - - if (shape.isMemberShape()) { - shape = model.expectShape(shape.asMemberShape().get().getTarget()); - } - - String prefix = ""; - String suffix = ")"; - - switch (shape.getType()) { - case STRING: - prefix = "ptr.String("; - break; - - case BOOLEAN: - prefix = "ptr.Bool("; - break; - - case BYTE: - prefix = "ptr.Int8("; - break; - case SHORT: - prefix = "ptr.Int16("; - break; - case INTEGER: - prefix = "ptr.Int32("; - break; - case LONG: - prefix = "ptr.Int64("; - break; - - case FLOAT: - prefix = "ptr.Float32("; - break; - case DOUBLE: - prefix = "ptr.Float64("; - break; - - case TIMESTAMP: - prefix = "ptr.Time("; - break; - - default: - return '&' + operand; - } - - writer.addUseImports(SmithyGoDependency.SMITHY_PTR); - return prefix + operand + suffix; + String prefix = ""; + String suffix = ")"; + + switch (shape.getType()) { + case STRING: + prefix = "ptr.String("; + break; + case BOOLEAN: + prefix = "ptr.Bool("; + break; + case BYTE: + prefix = "ptr.Int8("; + break; + case SHORT: + prefix = "ptr.Int16("; + break; + case INTEGER: + prefix = "ptr.Int32("; + break; + case LONG: + prefix = "ptr.Int64("; + break; + case FLOAT: + prefix = "ptr.Float32("; + break; + case DOUBLE: + prefix = "ptr.Float64("; + break; + case TIMESTAMP: + prefix = "ptr.Time("; + break; + default: + return '&' + operand; } - /** - * Returns the shape unpacked as a CollectionShape. Throws an exception if the passed in - * shape is not a list or set. - * - * @param shape the list or set shape. - * @return The unpacked CollectionShape. - */ - public static CollectionShape expectCollectionShape(Shape shape) { - if (shape instanceof CollectionShape) { - return (CollectionShape) (shape); - } - - throw new CodegenException("expect shape " + shape.getId() + " to be Collection, was " + shape.getType()); + writer.addUseImports(SmithyGoDependency.SMITHY_PTR); + return prefix + operand + suffix; + } + + /** + * Returns the shape unpacked as a CollectionShape. Throws an exception if the passed in + * shape is not a list or set. + * + * @param shape the list or set shape. + * @return The unpacked CollectionShape. + */ + public static CollectionShape expectCollectionShape(Shape shape) { + if (shape instanceof CollectionShape) { + return (CollectionShape) (shape); } - /** - * Returns the shape unpacked as a MapShape. Throws an exception if the passed in - * shape is not a map. - * - * @param shape the map shape. - * @return The unpacked MapShape. - */ - public static MapShape expectMapShape(Shape shape) { - if (shape instanceof MapShape) { - return (MapShape) (shape); - } - - throw new CodegenException("expect shape " + shape.getId() + " to be Map, was " + shape.getType()); + throw new CodegenException( + "expect shape " + + shape.getId() + + " to be Collection, was " + + shape.getType() + ); + } + + /** + * Returns the shape unpacked as a MapShape. Throws an exception if the passed in + * shape is not a map. + * + * @param shape the map shape. + * @return The unpacked MapShape. + */ + public static MapShape expectMapShape(Shape shape) { + if (shape instanceof MapShape) { + return (MapShape) (shape); } - /** - * Comparator to sort ShapeMember lists alphabetically, with required members first followed by optional members. - */ - public static final class SortedMembers implements Comparator { - private final SymbolProvider symbolProvider; - - /** - * Initializes the SortedMembers. - * - * @param symbolProvider symbol provider used for codegen. - */ - public SortedMembers(SymbolProvider symbolProvider) { - this.symbolProvider = symbolProvider; - } + throw new CodegenException( + "expect shape " + shape.getId() + " to be Map, was " + shape.getType() + ); + } - @Override - public int compare(MemberShape a, MemberShape b) { - // first compare if the members are required or not, which ever member is required should win. If both - // members are required or not required, continue on to alphabetic search. - - // If a is required but b isn't return -1 so a is sorted before b - // If b is required but a isn't, return 1 so a is sorted after b - // If both a and b are required or optional, use alphabetic sorting of a and b's member name. - - int requiredMember = 0; - if (a.hasTrait(RequiredTrait.class)) { - requiredMember -= 1; - } - if (b.hasTrait(RequiredTrait.class)) { - requiredMember += 1; - } - if (requiredMember != 0) { - return requiredMember; - } - - return symbolProvider.toMemberName(a) - .compareTo(symbolProvider.toMemberName(b)); - } - } + /** + * Comparator to sort ShapeMember lists alphabetically, with required members first followed by optional members. + */ + public static final class SortedMembers implements Comparator { - /** - * Attempts to find the first member by exact name in the containing structure. If the member is not found an - * exception will be thrown. - * - * @param shape structure containing member - * @param name member name - * @return MemberShape if found - */ - public static MemberShape expectMember(StructureShape shape, String name) { - return expectMember(shape, name::equals); - } + private final SymbolProvider symbolProvider; /** - * Attempts to find the first member by name using a member name predicate in the containing structure. If the - * member is not found an exception will be thrown. + * Initializes the SortedMembers. * - * @param shape structure containing member - * @param memberNamePredicate member name to search for - * @return MemberShape if found + * @param symbolProvider symbol provider used for codegen. */ - public static MemberShape expectMember(StructureShape shape, Predicate memberNamePredicate) { - return shape.getAllMembers().values().stream() - .filter((p) -> memberNamePredicate.test(p.getMemberName())) - .findFirst() - .orElseThrow(() -> new CodegenException("did not find member in structure shape, " + shape.getId())); + public SortedMembers(SymbolProvider symbolProvider) { + this.symbolProvider = symbolProvider; } - /** - * Attempts to get the title of the API's service from the model. If unalbe to get the title the fallback value - * will be returned instead. - * - * @param shape service shape - * @param fallback string to return if service does not have a title - * @return title of service - */ - public static String getServiceTitle(ServiceShape shape, String fallback) { - return shape.getTrait(TitleTrait.class).map(TitleTrait::getValue).orElse(fallback); + @Override + public int compare(MemberShape a, MemberShape b) { + // first compare if the members are required or not, which ever member is required should win. If both + // members are required or not required, continue on to alphabetic search. + + // If a is required but b isn't return -1 so a is sorted before b + // If b is required but a isn't, return 1 so a is sorted after b + // If both a and b are required or optional, use alphabetic sorting of a and b's member name. + + int requiredMember = 0; + if (a.hasTrait(RequiredTrait.class)) { + requiredMember -= 1; + } + if (b.hasTrait(RequiredTrait.class)) { + requiredMember += 1; + } + if (requiredMember != 0) { + return requiredMember; + } + + return symbolProvider + .toMemberName(a) + .compareTo(symbolProvider.toMemberName(b)); } - - /** - * isNumber returns if the shape is a number shape. - * - * @param shape shape to check - * @return true if is a number shape. - */ - public static boolean isNumber(Shape shape) { - switch (shape.getType()) { - case BYTE: - case SHORT: - case INTEGER: - case INT_ENUM: - case LONG: - case FLOAT: - case DOUBLE: - return true; - default: - return false; - } + } + + /** + * Attempts to find the first member by exact name in the containing structure. If the member is not found an + * exception will be thrown. + * + * @param shape structure containing member + * @param name member name + * @return MemberShape if found + */ + public static MemberShape expectMember(StructureShape shape, String name) { + return expectMember(shape, name::equals); + } + + /** + * Attempts to find the first member by name using a member name predicate in the containing structure. If the + * member is not found an exception will be thrown. + * + * @param shape structure containing member + * @param memberNamePredicate member name to search for + * @return MemberShape if found + */ + public static MemberShape expectMember( + StructureShape shape, + Predicate memberNamePredicate + ) { + return shape + .getAllMembers() + .values() + .stream() + .filter(p -> memberNamePredicate.test(p.getMemberName())) + .findFirst() + .orElseThrow(() -> + new CodegenException( + "did not find member in structure shape, " + shape.getId() + ) + ); + } + + /** + * Attempts to get the title of the API's service from the model. If unalbe to get the title the fallback value + * will be returned instead. + * + * @param shape service shape + * @param fallback string to return if service does not have a title + * @return title of service + */ + public static String getServiceTitle(ServiceShape shape, String fallback) { + return shape + .getTrait(TitleTrait.class) + .map(TitleTrait::getValue) + .orElse(fallback); + } + + /** + * isNumber returns if the shape is a number shape. + * + * @param shape shape to check + * @return true if is a number shape. + */ + public static boolean isNumber(Shape shape) { + switch (shape.getType()) { + case BYTE: + case SHORT: + case INTEGER: + case INT_ENUM: + case LONG: + case FLOAT: + case DOUBLE: + return true; + default: + return false; } + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/EnumGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/EnumGenerator.java index 739c4ea685..f86ec20ccf 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/EnumGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/EnumGenerator.java @@ -19,7 +19,6 @@ import java.util.Locale; import java.util.Set; import java.util.logging.Logger; - import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.shapes.EnumShape; @@ -33,66 +32,101 @@ * Renders enums and their constants. */ public final class EnumGenerator implements Runnable { - private static final Logger LOGGER = Logger.getLogger(EnumGenerator.class.getName()); - - private final SymbolProvider symbolProvider; - private final GoWriter writer; - private final Shape shape; - public EnumGenerator(SymbolProvider symbolProvider, GoWriter writer, Shape shape) { - this.symbolProvider = symbolProvider; - this.writer = writer; - this.shape = shape; - } + private static final Logger LOGGER = Logger.getLogger( + EnumGenerator.class.getName() + ); - @Override - public void run() { - Symbol symbol = symbolProvider.toSymbol(shape); - EnumTrait enumTrait = shape.expectTrait(EnumTrait.class); + private final SymbolProvider symbolProvider; + private final GoWriter writer; + private final Shape shape; - writer.write("type $L string", symbol.getName()).write(""); + public EnumGenerator( + SymbolProvider symbolProvider, + GoWriter writer, + Shape shape + ) { + this.symbolProvider = symbolProvider; + this.writer = writer; + this.shape = shape; + } - // Don't generate constants if there are no explicitly modeled names. We only need to - // look at one, since Smithy validates that if one has a name then they must all have - // a name. - if (enumTrait.getValues().get(0).getName().isPresent()) { - Set constants = new LinkedHashSet<>(); - writer.openBlock("const (", ")", () -> { - for (EnumDefinition definition : enumTrait.getValues()) { - StringBuilder labelBuilder = new StringBuilder(symbol.getName()); - String name = definition.getName().get(); + @Override + public void run() { + Symbol symbol = symbolProvider.toSymbol(shape); + EnumTrait enumTrait = shape.expectTrait(EnumTrait.class); - for (String part : name.split("(?U)[\\W_]")) { - if (part.matches(".*[a-z].*") && part.matches(".*[A-Z].*")) { - // Mixed case names should not be changed other than first letter capitalized. - labelBuilder.append(StringUtils.capitalize(part)); - } else { - // For all non-mixed case parts title case first letter, followed by all other lower cased. - labelBuilder.append(StringUtils.capitalize(part.toLowerCase(Locale.US))); - } - } - String label = labelBuilder.toString(); + writer.write("type $L string", symbol.getName()).write(""); - // If camel-casing would cause a conflict, don't camel-case this enum value. - if (constants.contains(label)) { - LOGGER.warning(String.format( - "Multiple enums resolved to the same name, `%s`, using unaltered value for: %s", - label, name)); - label = name; - } - constants.add(label); + // Don't generate constants if there are no explicitly modeled names. We only need to + // look at one, since Smithy validates that if one has a name then they must all have + // a name. + if (enumTrait.getValues().get(0).getName().isPresent()) { + Set constants = new LinkedHashSet<>(); + writer + .openBlock( + "const (", + ")", + () -> { + for (EnumDefinition definition : enumTrait.getValues()) { + StringBuilder labelBuilder = new StringBuilder(symbol.getName()); + String name = definition.getName().get(); - writer.write("$L $L = $S", label, symbol.getName(), definition.getValue()); + for (String part : name.split("(?U)[\\W_]")) { + if (part.matches(".*[a-z].*") && part.matches(".*[A-Z].*")) { + // Mixed case names should not be changed other than first letter capitalized. + labelBuilder.append(StringUtils.capitalize(part)); + } else { + // For all non-mixed case parts title case first letter, followed by all other lower cased. + labelBuilder.append( + StringUtils.capitalize(part.toLowerCase(Locale.US)) + ); } - }).write(""); - } + } + String label = labelBuilder.toString(); - writer.openBlock("func ($L) Values() []$L {", "}", symbol.getName(), symbol.getName(), () -> { - writer.openBlock("return []$L{", "}", symbol.getName(), () -> { - for (EnumDefinition definition : enumTrait.getValues()) { - writer.write("$S,", definition.getValue()); - } - }); - }); + // If camel-casing would cause a conflict, don't camel-case this enum value. + if (constants.contains(label)) { + LOGGER.warning( + String.format( + "Multiple enums resolved to the same name, `%s`, using unaltered value for: %s", + label, + name + ) + ); + label = name; + } + constants.add(label); + + writer.write( + "$L $L = $S", + label, + symbol.getName(), + definition.getValue() + ); + } + } + ) + .write(""); } -} \ No newline at end of file + + writer.openBlock( + "func ($L) Values() []$L {", + "}", + symbol.getName(), + symbol.getName(), + () -> { + writer.openBlock( + "return []$L{", + "}", + symbol.getName(), + () -> { + for (EnumDefinition definition : enumTrait.getValues()) { + writer.write("$S,", definition.getValue()); + } + } + ); + } + ); + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GenerationContext.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GenerationContext.java index 7fb586c8a6..d14117be43 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GenerationContext.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GenerationContext.java @@ -1,5 +1,7 @@ package software.amazon.polymorph.smithygo.codegen; +import java.util.ArrayList; +import java.util.List; import software.amazon.polymorph.smithygo.codegen.integration.GoIntegration; import software.amazon.polymorph.smithygo.codegen.integration.ProtocolGenerator; import software.amazon.smithy.build.FileManifest; @@ -8,152 +10,160 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.utils.SmithyBuilder; -import java.util.ArrayList; -import java.util.List; - -public class GenerationContext implements CodegenContext { - private final Model model; - private final GoSettings settings; - private final SymbolProvider symbolProvider; - private final FileManifest fileManifest; - private final GoDelegator writerDelegator; - private final List integrations; - private final ProtocolGenerator protocolGenerator; - - /** - * @return Returns the protocol generator to use in code generation. - */ - public ProtocolGenerator protocolGenerator() { - return protocolGenerator; - } - - private GenerationContext(Builder builder) { - model = SmithyBuilder.requiredState("model", builder.model); - settings = SmithyBuilder.requiredState("settings", builder.settings); - symbolProvider = SmithyBuilder.requiredState("symbolProvider", builder.symbolProvider); - fileManifest = SmithyBuilder.requiredState("fileManifest", builder.fileManifest); - writerDelegator = SmithyBuilder.requiredState("writerDelegator", builder.writerDelegator); - integrations = SmithyBuilder.requiredState("integrations", builder.integrations); - protocolGenerator = SmithyBuilder.requiredState("protocolGenerator", builder.protocolGenerator); - } +public class GenerationContext + implements CodegenContext { + + private final Model model; + private final GoSettings settings; + private final SymbolProvider symbolProvider; + private final FileManifest fileManifest; + private final GoDelegator writerDelegator; + private final List integrations; + private final ProtocolGenerator protocolGenerator; + + /** + * @return Returns the protocol generator to use in code generation. + */ + public ProtocolGenerator protocolGenerator() { + return protocolGenerator; + } + + private GenerationContext(Builder builder) { + model = SmithyBuilder.requiredState("model", builder.model); + settings = SmithyBuilder.requiredState("settings", builder.settings); + symbolProvider = + SmithyBuilder.requiredState("symbolProvider", builder.symbolProvider); + fileManifest = + SmithyBuilder.requiredState("fileManifest", builder.fileManifest); + writerDelegator = + SmithyBuilder.requiredState("writerDelegator", builder.writerDelegator); + integrations = + SmithyBuilder.requiredState("integrations", builder.integrations); + protocolGenerator = + SmithyBuilder.requiredState( + "protocolGenerator", + builder.protocolGenerator + ); + } + + @Override + public Model model() { + return model; + } + + @Override + public GoSettings settings() { + return settings; + } + + @Override + public SymbolProvider symbolProvider() { + return symbolProvider; + } + + @Override + public FileManifest fileManifest() { + return fileManifest; + } + + @Override + public GoDelegator writerDelegator() { + return writerDelegator; + } + + @Override + public List integrations() { + return integrations; + } + + /** + * @return Returns a builder. + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Builds {@link GenerationContext}s. + */ + public static final class Builder + implements SmithyBuilder { + + private Model model; + private GoSettings settings; + private SymbolProvider symbolProvider; + private FileManifest fileManifest; + private GoDelegator writerDelegator; + private List integrations = new ArrayList<>(); + private ProtocolGenerator protocolGenerator; @Override - public Model model() { - return model; + public GenerationContext build() { + return new GenerationContext(this); } - @Override - public GoSettings settings() { - return settings; + /** + * @param model The model being generated. + * @return Returns the builder. + */ + public Builder model(Model model) { + this.model = model; + return this; } - @Override - public SymbolProvider symbolProvider() { - return symbolProvider; + /** + * @param settings The resolved settings for the generator. + * @return Returns the builder. + */ + public Builder settings(GoSettings settings) { + this.settings = settings; + return this; } - @Override - public FileManifest fileManifest() { - return fileManifest; + /** + * @param symbolProvider The finalized symbol provider for the generator. + * @return Returns the builder. + */ + public Builder symbolProvider(SymbolProvider symbolProvider) { + this.symbolProvider = symbolProvider; + return this; } - @Override - public GoDelegator writerDelegator() { - return writerDelegator; + /** + * @param fileManifest The file manifest being used in the generator. + * @return Returns the builder. + */ + public Builder fileManifest(FileManifest fileManifest) { + this.fileManifest = fileManifest; + return this; } - @Override - public List integrations() { - return integrations; + /** + * @param writerDelegator The writer delegator to use in the generator. + * @return Returns the builder. + */ + public Builder writerDelegator(GoDelegator writerDelegator) { + this.writerDelegator = writerDelegator; + return this; } /** - * @return Returns a builder. + * @param integrations The integrations to use in the generator. + * @return Returns the builder. */ - public static Builder builder() { - return new Builder(); + public Builder integrations(List integrations) { + this.integrations.clear(); + this.integrations.addAll(integrations); + return this; } /** - * Builds {@link GenerationContext}s. + * @param protocolGenerator The resolved protocol generator to use. + * @return Returns the builder. */ - public static final class Builder implements SmithyBuilder { - private Model model; - private GoSettings settings; - private SymbolProvider symbolProvider; - private FileManifest fileManifest; - private GoDelegator writerDelegator; - private List integrations = new ArrayList<>(); - private ProtocolGenerator protocolGenerator; - - @Override - public GenerationContext build() { - return new GenerationContext(this); - } - - /** - * @param model The model being generated. - * @return Returns the builder. - */ - public Builder model(Model model) { - this.model = model; - return this; - } - - /** - * @param settings The resolved settings for the generator. - * @return Returns the builder. - */ - public Builder settings(GoSettings settings) { - this.settings = settings; - return this; - } - - /** - * @param symbolProvider The finalized symbol provider for the generator. - * @return Returns the builder. - */ - public Builder symbolProvider(SymbolProvider symbolProvider) { - this.symbolProvider = symbolProvider; - return this; - } - - /** - * @param fileManifest The file manifest being used in the generator. - * @return Returns the builder. - */ - public Builder fileManifest(FileManifest fileManifest) { - this.fileManifest = fileManifest; - return this; - } - - /** - * @param writerDelegator The writer delegator to use in the generator. - * @return Returns the builder. - */ - public Builder writerDelegator(GoDelegator writerDelegator) { - this.writerDelegator = writerDelegator; - return this; - } - - /** - * @param integrations The integrations to use in the generator. - * @return Returns the builder. - */ - public Builder integrations(List integrations) { - this.integrations.clear(); - this.integrations.addAll(integrations); - return this; - } - - /** - * @param protocolGenerator The resolved protocol generator to use. - * @return Returns the builder. - */ - public Builder protocolGenerator(ProtocolGenerator protocolGenerator) { - this.protocolGenerator = protocolGenerator; - return this; - } - + public Builder protocolGenerator(ProtocolGenerator protocolGenerator) { + this.protocolGenerator = protocolGenerator; + return this; } + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDelegator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDelegator.java index c2d5956024..76503ca034 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDelegator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDelegator.java @@ -24,7 +24,8 @@ * for getting shape specific GoWriters. */ public final class GoDelegator extends WriterDelegator { - public GoDelegator(FileManifest fileManifest, SymbolProvider symbolProvider) { - super(fileManifest, symbolProvider, new GoWriter.GoWriterFactory()); - } + + public GoDelegator(FileManifest fileManifest, SymbolProvider symbolProvider) { + super(fileManifest, symbolProvider, new GoWriter.GoWriterFactory()); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDependency.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDependency.java index ef207ff401..1092553d69 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDependency.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoDependency.java @@ -15,11 +15,6 @@ package software.amazon.polymorph.smithygo.codegen; -import software.amazon.smithy.codegen.core.SymbolDependency; -import software.amazon.smithy.codegen.core.SymbolDependencyContainer; -import software.amazon.smithy.utils.SetUtils; -import software.amazon.smithy.utils.SmithyBuilder; - import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -27,330 +22,377 @@ import java.util.Objects; import java.util.Set; import java.util.TreeSet; +import software.amazon.smithy.codegen.core.SymbolDependency; +import software.amazon.smithy.codegen.core.SymbolDependencyContainer; +import software.amazon.smithy.utils.SetUtils; +import software.amazon.smithy.utils.SmithyBuilder; public final class GoDependency implements SymbolDependencyContainer { - private final Type type; - private final String sourcePath; - private final String importPath; - private final String alias; - private final String version; - private final Set dependencies; - private final SymbolDependency symbolDependency; - - private GoDependency(Builder builder) { - this.type = SmithyBuilder.requiredState("type", builder.type); - this.sourcePath = !this.type.equals(Type.STANDARD_LIBRARY) - ? SmithyBuilder.requiredState("sourcePath", builder.sourcePath) : ""; - this.importPath = SmithyBuilder.requiredState("importPath", builder.importPath); - this.alias = builder.alias; - this.version = SmithyBuilder.requiredState("version", builder.version); - this.dependencies = builder.dependencies; - - this.symbolDependency = SymbolDependency.builder() - .dependencyType(this.type.toString()) - .packageName(this.sourcePath) - .version(this.version) - .build(); + + private final Type type; + private final String sourcePath; + private final String importPath; + private final String alias; + private final String version; + private final Set dependencies; + private final SymbolDependency symbolDependency; + + private GoDependency(Builder builder) { + this.type = SmithyBuilder.requiredState("type", builder.type); + this.sourcePath = + !this.type.equals(Type.STANDARD_LIBRARY) + ? SmithyBuilder.requiredState("sourcePath", builder.sourcePath) + : ""; + this.importPath = + SmithyBuilder.requiredState("importPath", builder.importPath); + this.alias = builder.alias; + this.version = SmithyBuilder.requiredState("version", builder.version); + this.dependencies = builder.dependencies; + + this.symbolDependency = + SymbolDependency + .builder() + .dependencyType(this.type.toString()) + .packageName(this.sourcePath) + .version(this.version) + .build(); + } + + /** + * Get the the set of {@link GoDependency} required by this dependency. + * + * @return the set of dependencies + */ + public Set getGoDependencies() { + return this.dependencies; + } + + /** + * Get the symbol dependency representing the dependency. + * + * @return the symbol dependency + */ + public SymbolDependency getSymbolDependency() { + return symbolDependency; + } + + /** + * Get the type of dependency. + * + * @return the dependency type + */ + public Type getType() { + return type; + } + + /** + * Get the source code path of the dependency. + * + * @return the dependency source code path + */ + public String getSourcePath() { + return sourcePath; + } + + /** + * Get the import path of the dependency. + * + * @return the import path of the dependency + */ + public String getImportPath() { + return importPath; + } + + /** + * Get the alias of the module to use. + * + * @return the alias + */ + public String getAlias() { + return alias; + } + + /** + * Get the version of the dependency. + * + * @return the version + */ + public String getVersion() { + return version; + } + + @Override + public List getDependencies() { + Set symbolDependencySet = new TreeSet<>( + SetUtils.of(getSymbolDependency()) + ); + + symbolDependencySet.addAll( + resolveDependencies(getGoDependencies(), new HashSet<>(SetUtils.of(this))) + ); + + return new ArrayList<>(symbolDependencySet); + } + + private Set resolveDependencies( + Set goDependencies, + Set processed + ) { + Set symbolDependencies = new TreeSet<>(); + if (goDependencies.size() == 0) { + return symbolDependencies; } - /** - * Get the the set of {@link GoDependency} required by this dependency. - * - * @return the set of dependencies - */ - public Set getGoDependencies() { - return this.dependencies; + Set dependenciesToResolve = new TreeSet<>(); + for (GoDependency dependency : goDependencies) { + if (processed.contains(dependency)) { + continue; + } + processed.add(dependency); + symbolDependencies.add(dependency.getSymbolDependency()); + dependenciesToResolve.addAll(dependency.getGoDependencies()); } - /** - * Get the symbol dependency representing the dependency. - * - * @return the symbol dependency - */ - public SymbolDependency getSymbolDependency() { - return symbolDependency; + symbolDependencies.addAll( + resolveDependencies(dependenciesToResolve, processed) + ); + + return symbolDependencies; + } + + public static Builder builder() { + return new Builder(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } else if (!(o instanceof GoDependency)) { + return false; } - /** - * Get the type of dependency. - * - * @return the dependency type - */ - public Type getType() { - return type; + GoDependency other = (GoDependency) o; + + return ( + this.type.equals(other.type) && + this.sourcePath.equals(other.sourcePath) && + this.importPath.equals(other.importPath) && + this.alias.equals(other.alias) && + this.version.equals(other.version) && + this.dependencies.equals(other.dependencies) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + type, + sourcePath, + importPath, + alias, + version, + dependencies + ); + } + + /** + * Represents a dependency type. + */ + public enum Type { + STANDARD_LIBRARY, + DEPENDENCY; + + @Override + public String toString() { + switch (this) { + case STANDARD_LIBRARY: + return "stdlib"; + case DEPENDENCY: + return "dependency"; + default: + return "unknown"; + } } + } + + /** + * Get {@link GoDependency} representing the provided module description. + * + * @param sourcePath the root source path for the given code + * @param importPath the import path of the package + * @param version the version of source module + * @param alias a default alias to use when importing the package, can be null + * @return the dependency + */ + public static GoDependency moduleDependency( + String sourcePath, + String importPath, + String version, + String alias + ) { + Builder builder = GoDependency + .builder() + .type(Type.DEPENDENCY) + .sourcePath(sourcePath) + .importPath(importPath) + .version(version); + if (alias != null) { + builder.alias(alias); + } + return builder.build(); + } + + /** + * Get {@link GoDependency} representing the standard library import description. + * + * @param importPath the import path of the package + * @param version the version of source module + * @return the dependency + */ + public static GoDependency standardLibraryDependency( + String importPath, + String version + ) { + return GoDependency + .builder() + .type(Type.STANDARD_LIBRARY) + .importPath(importPath) + .version(version) + .build(); + } + + /** + * Get {@link GoDependency} representing the standard library import description. + * + * @param importPath the import path of the package + * @param version the version of source module + * @param alias the alias for stdlib dependency + * @return the dependency + */ + public static GoDependency standardLibraryDependency( + String importPath, + String version, + String alias + ) { + Builder builder = GoDependency + .builder() + .type(Type.STANDARD_LIBRARY) + .importPath(importPath) + .version(version); + + if (alias != null) { + builder.alias(alias); + } + return builder.build(); + } + + /** + * Builder for {@link GoDependency}. + */ + public static final class Builder implements SmithyBuilder { + + private Type type; + private String sourcePath; + private String importPath; + private String alias; + private String version; + private final Set dependencies = new TreeSet<>(); + + private Builder() {} /** - * Get the source code path of the dependency. + * Set the dependency type. * - * @return the dependency source code path + * @param type dependency type + * @return the builder */ - public String getSourcePath() { - return sourcePath; + public Builder type(Type type) { + this.type = type; + return this; } /** - * Get the import path of the dependency. + * Set the source path. * - * @return the import path of the dependency + * @param sourcePath the source path root + * @return the builder */ - public String getImportPath() { - return importPath; + public Builder sourcePath(String sourcePath) { + this.sourcePath = sourcePath; + return this; } /** - * Get the alias of the module to use. + * Set the import path. * - * @return the alias + * @param importPath the import path + * @return the builder */ - public String getAlias() { - return alias; + public Builder importPath(String importPath) { + this.importPath = importPath; + return this; } /** - * Get the version of the dependency. + * Set the dependency alias. * - * @return the version + * @param alias the alias + * @return the builder */ - public String getVersion() { - return version; - } - - @Override - public List getDependencies() { - Set symbolDependencySet = new TreeSet<>(SetUtils.of(getSymbolDependency())); - - symbolDependencySet.addAll(resolveDependencies(getGoDependencies(), new HashSet<>(SetUtils.of(this)))); - - return new ArrayList<>(symbolDependencySet); - } - - private Set resolveDependencies(Set goDependencies, Set processed) { - Set symbolDependencies = new TreeSet<>(); - if (goDependencies.size() == 0) { - return symbolDependencies; - } - - Set dependenciesToResolve = new TreeSet<>(); - for (GoDependency dependency : goDependencies) { - if (processed.contains(dependency)) { - continue; - } - processed.add(dependency); - symbolDependencies.add(dependency.getSymbolDependency()); - dependenciesToResolve.addAll(dependency.getGoDependencies()); - } - - symbolDependencies.addAll(resolveDependencies(dependenciesToResolve, processed)); - - return symbolDependencies; - } - - public static Builder builder() { - return new Builder(); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } else if (!(o instanceof GoDependency)) { - return false; - } - - GoDependency other = (GoDependency) o; - - return this.type.equals(other.type) && this.sourcePath.equals(other.sourcePath) - && this.importPath.equals(other.importPath) && this.alias.equals(other.alias) - && this.version.equals(other.version) && this.dependencies.equals(other.dependencies); - } - - @Override - public int hashCode() { - return Objects.hash(type, sourcePath, importPath, alias, version, dependencies); + public Builder alias(String alias) { + this.alias = alias; + return this; } /** - * Represents a dependency type. + * Set the dependency version. + * + * @param version the version + * @return the builder */ - public enum Type { - STANDARD_LIBRARY, DEPENDENCY; - - @Override - public String toString() { - switch (this) { - case STANDARD_LIBRARY: - return "stdlib"; - case DEPENDENCY: - return "dependency"; - default: - return "unknown"; - } - } + public Builder version(String version) { + this.version = version; + return this; } /** - * Get {@link GoDependency} representing the provided module description. + * Set the collection of {@link GoDependency} required by this dependency. * - * @param sourcePath the root source path for the given code - * @param importPath the import path of the package - * @param version the version of source module - * @param alias a default alias to use when importing the package, can be null - * @return the dependency + * @param dependencies a collection of dependencies + * @return the builder */ - public static GoDependency moduleDependency(String sourcePath, String importPath, String version, String alias) { - Builder builder = GoDependency.builder() - .type(Type.DEPENDENCY) - .sourcePath(sourcePath) - .importPath(importPath) - .version(version); - if (alias != null) { - builder.alias(alias); - } - return builder.build(); + public Builder dependencies(Collection dependencies) { + this.dependencies.clear(); + this.dependencies.addAll(dependencies); + return this; } /** - * Get {@link GoDependency} representing the standard library import description. + * Add a dependency on another {@link GoDependency}. * - * @param importPath the import path of the package - * @param version the version of source module - * @return the dependency + * @param dependency the dependency + * @return the builder */ - public static GoDependency standardLibraryDependency(String importPath, String version) { - return GoDependency.builder() - .type(Type.STANDARD_LIBRARY) - .importPath(importPath) - .version(version) - .build(); + public Builder addDependency(GoDependency dependency) { + this.dependencies.add(dependency); + return this; } /** - * Get {@link GoDependency} representing the standard library import description. + * Remove a dependency on another {@link GoDependency}. * - * @param importPath the import path of the package - * @param version the version of source module - * @param alias the alias for stdlib dependency - * @return the dependency + * @param dependency the dependency + * @return the builder */ - public static GoDependency standardLibraryDependency(String importPath, String version, String alias) { - Builder builder = GoDependency.builder() - .type(Type.STANDARD_LIBRARY) - .importPath(importPath) - .version(version); - - if (alias != null) { - builder.alias(alias); - } - return builder.build(); + public Builder removeDependency(GoDependency dependency) { + this.dependencies.remove(dependency); + return this; } - /** - * Builder for {@link GoDependency}. - */ - public static final class Builder implements SmithyBuilder { - private Type type; - private String sourcePath; - private String importPath; - private String alias; - private String version; - private final Set dependencies = new TreeSet<>(); - - private Builder() { - } - - /** - * Set the dependency type. - * - * @param type dependency type - * @return the builder - */ - public Builder type(Type type) { - this.type = type; - return this; - } - - /** - * Set the source path. - * - * @param sourcePath the source path root - * @return the builder - */ - public Builder sourcePath(String sourcePath) { - this.sourcePath = sourcePath; - return this; - } - - /** - * Set the import path. - * - * @param importPath the import path - * @return the builder - */ - public Builder importPath(String importPath) { - this.importPath = importPath; - return this; - } - - /** - * Set the dependency alias. - * - * @param alias the alias - * @return the builder - */ - public Builder alias(String alias) { - this.alias = alias; - return this; - } - - /** - * Set the dependency version. - * - * @param version the version - * @return the builder - */ - public Builder version(String version) { - this.version = version; - return this; - } - - /** - * Set the collection of {@link GoDependency} required by this dependency. - * - * @param dependencies a collection of dependencies - * @return the builder - */ - public Builder dependencies(Collection dependencies) { - this.dependencies.clear(); - this.dependencies.addAll(dependencies); - return this; - } - - /** - * Add a dependency on another {@link GoDependency}. - * - * @param dependency the dependency - * @return the builder - */ - public Builder addDependency(GoDependency dependency) { - this.dependencies.add(dependency); - return this; - } - - /** - * Remove a dependency on another {@link GoDependency}. - * - * @param dependency the dependency - * @return the builder - */ - public Builder removeDependency(GoDependency dependency) { - this.dependencies.remove(dependency); - return this; - } - - @Override - public GoDependency build() { - return new GoDependency(this); - } + @Override + public GoDependency build() { + return new GoDependency(this); } + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoSettings.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoSettings.java index 0c079a9b3c..5d9871a06f 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoSettings.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoSettings.java @@ -1,175 +1,195 @@ package software.amazon.polymorph.smithygo.codegen; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.node.ObjectNode; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.ShapeId; -import java.util.Arrays; -import java.util.Objects; -import java.util.Optional; - public class GoSettings { - private static final String SERVICE = "service"; - private static final String MODULE_NAME = "module"; - private static final String MODULE_DESCRIPTION = "moduleDescription"; - private static final String MODULE_VERSION = "moduleVersion"; - private static final String GENERATE_GO_MOD = "generateGoMod"; - private static final String GO_DIRECTIVE = "goDirective"; - - private ShapeId service; - private String moduleName; - private String moduleDescription = ""; - private String moduleVersion; - private Boolean generateGoMod = false; - private ShapeId protocol; - - /** - * Create a settings object from a configuration object node. - * - * @param config Config object to load. - * @return Returns the extracted settings. - */ - public static GoSettings from(ObjectNode config) { - GoSettings settings = new GoSettings(); - config.warnIfAdditionalProperties( - Arrays.asList(SERVICE, MODULE_NAME, MODULE_DESCRIPTION, MODULE_VERSION, GENERATE_GO_MOD, GO_DIRECTIVE)); - - settings.setService(config.expectStringMember(SERVICE).expectShapeId()); - settings.setModuleName(config.expectStringMember("moduleName").getValue()); - settings.setModuleDescription(config.getStringMemberOrDefault( - MODULE_DESCRIPTION, settings.getModuleName() + " client")); - settings.setModuleVersion(config.getStringMemberOrDefault(MODULE_VERSION, null)); - settings.setGenerateGoMod(config.getBooleanMemberOrDefault(GENERATE_GO_MOD, false)); - return settings; - } - - /** - * Gets the id of the service that is being generated. - * - * @return Returns the service id. - * @throws NullPointerException if the service has not been set. - */ - public ShapeId getService() { - return Objects.requireNonNull(service, SERVICE + " not set"); - } - - /** - * Gets the corresponding {@link ServiceShape} from a model. - * - * @param model Model to search for the service shape by ID. - * @return Returns the found {@code Service}. - * @throws NullPointerException if the service has not been set. - * @throws CodegenException if the service is invalid or not found. - */ - public ServiceShape getService(Model model) { - return model - .getShape(getService()) - .orElseThrow(() -> new CodegenException("Service shape not found: " + getService())) - .asServiceShape() - .orElseThrow(() -> new CodegenException("Shape is not a Service: " + getService())); - } - - /** - * Sets the service to generate. - * - * @param service The service to generate. - */ - public void setService(ShapeId service) { - this.service = Objects.requireNonNull(service); - } - - /** - * Gets the required module name for the module that will be generated. - * - * @return Returns the module name. - * @throws NullPointerException if the module name has not been set. - */ - public String getModuleName() { - return Objects.requireNonNull(moduleName, MODULE_NAME + " not set"); - } - - /** - * Sets the name of the module to generate. - * - * @param moduleName The name of the module to generate. - */ - public void setModuleName(String moduleName) { - this.moduleName = Objects.requireNonNull(moduleName); - } - - /** - * Gets the optional module description for the module that will be generated. - * - * @return Returns the module description. - */ - public String getModuleDescription() { - return moduleDescription; - } - - /** - * Sets the description of the module to generate. - * - * @param moduleDescription The description of the module to generate. - */ - public void setModuleDescription(String moduleDescription) { - this.moduleDescription = Objects.requireNonNull(moduleDescription); - } - - /** - * Gets the optional module version for the module that will be generated. - * - * @return Returns the module version. - */ - public Optional getModuleVersion() { - return Optional.ofNullable(moduleVersion); - } - - /** - * Sets the version of the module to generate. - * - * @param moduleVersion The version of the module to generate. - */ - public void setModuleVersion(String moduleVersion) { - if (moduleVersion != null) { - this.moduleVersion = moduleVersion; - } - } - - /** - * Gets the flag for generating go.mod file. - * - * @return Returns if go.mod will be generated (true) or not (false) - */ - public Boolean getGenerateGoMod() { - return generateGoMod; - } - - /** - * Sets the flag for generating go.mod file. - * - * @param generateGoMod If go.mod will be generated (true) or not (false) - */ - public void setGenerateGoMod(Boolean generateGoMod) { - this.generateGoMod = Objects.requireNonNull(generateGoMod); - } - - /** - * Gets the configured protocol to generate. - * - * @return Returns the configured protocol. - */ - public ShapeId getProtocol() { - return protocol; - } - /** - * Sets the protocol to generate. - * - * @param protocol Protocols to generate. - */ - public void setProtocol(ShapeId protocol) { - this.protocol = Objects.requireNonNull(protocol); + private static final String SERVICE = "service"; + private static final String MODULE_NAME = "module"; + private static final String MODULE_DESCRIPTION = "moduleDescription"; + private static final String MODULE_VERSION = "moduleVersion"; + private static final String GENERATE_GO_MOD = "generateGoMod"; + private static final String GO_DIRECTIVE = "goDirective"; + + private ShapeId service; + private String moduleName; + private String moduleDescription = ""; + private String moduleVersion; + private Boolean generateGoMod = false; + private ShapeId protocol; + + /** + * Create a settings object from a configuration object node. + * + * @param config Config object to load. + * @return Returns the extracted settings. + */ + public static GoSettings from(ObjectNode config) { + GoSettings settings = new GoSettings(); + config.warnIfAdditionalProperties( + Arrays.asList( + SERVICE, + MODULE_NAME, + MODULE_DESCRIPTION, + MODULE_VERSION, + GENERATE_GO_MOD, + GO_DIRECTIVE + ) + ); + + settings.setService(config.expectStringMember(SERVICE).expectShapeId()); + settings.setModuleName(config.expectStringMember("moduleName").getValue()); + settings.setModuleDescription( + config.getStringMemberOrDefault( + MODULE_DESCRIPTION, + settings.getModuleName() + " client" + ) + ); + settings.setModuleVersion( + config.getStringMemberOrDefault(MODULE_VERSION, null) + ); + settings.setGenerateGoMod( + config.getBooleanMemberOrDefault(GENERATE_GO_MOD, false) + ); + return settings; + } + + /** + * Gets the id of the service that is being generated. + * + * @return Returns the service id. + * @throws NullPointerException if the service has not been set. + */ + public ShapeId getService() { + return Objects.requireNonNull(service, SERVICE + " not set"); + } + + /** + * Gets the corresponding {@link ServiceShape} from a model. + * + * @param model Model to search for the service shape by ID. + * @return Returns the found {@code Service}. + * @throws NullPointerException if the service has not been set. + * @throws CodegenException if the service is invalid or not found. + */ + public ServiceShape getService(Model model) { + return model + .getShape(getService()) + .orElseThrow(() -> + new CodegenException("Service shape not found: " + getService()) + ) + .asServiceShape() + .orElseThrow(() -> + new CodegenException("Shape is not a Service: " + getService()) + ); + } + + /** + * Sets the service to generate. + * + * @param service The service to generate. + */ + public void setService(ShapeId service) { + this.service = Objects.requireNonNull(service); + } + + /** + * Gets the required module name for the module that will be generated. + * + * @return Returns the module name. + * @throws NullPointerException if the module name has not been set. + */ + public String getModuleName() { + return Objects.requireNonNull(moduleName, MODULE_NAME + " not set"); + } + + /** + * Sets the name of the module to generate. + * + * @param moduleName The name of the module to generate. + */ + public void setModuleName(String moduleName) { + this.moduleName = Objects.requireNonNull(moduleName); + } + + /** + * Gets the optional module description for the module that will be generated. + * + * @return Returns the module description. + */ + public String getModuleDescription() { + return moduleDescription; + } + + /** + * Sets the description of the module to generate. + * + * @param moduleDescription The description of the module to generate. + */ + public void setModuleDescription(String moduleDescription) { + this.moduleDescription = Objects.requireNonNull(moduleDescription); + } + + /** + * Gets the optional module version for the module that will be generated. + * + * @return Returns the module version. + */ + public Optional getModuleVersion() { + return Optional.ofNullable(moduleVersion); + } + + /** + * Sets the version of the module to generate. + * + * @param moduleVersion The version of the module to generate. + */ + public void setModuleVersion(String moduleVersion) { + if (moduleVersion != null) { + this.moduleVersion = moduleVersion; } + } + + /** + * Gets the flag for generating go.mod file. + * + * @return Returns if go.mod will be generated (true) or not (false) + */ + public Boolean getGenerateGoMod() { + return generateGoMod; + } + + /** + * Sets the flag for generating go.mod file. + * + * @param generateGoMod If go.mod will be generated (true) or not (false) + */ + public void setGenerateGoMod(Boolean generateGoMod) { + this.generateGoMod = Objects.requireNonNull(generateGoMod); + } + + /** + * Gets the configured protocol to generate. + * + * @return Returns the configured protocol. + */ + public ShapeId getProtocol() { + return protocol; + } + + /** + * Sets the protocol to generate. + * + * @param protocol Protocols to generate. + */ + public void setProtocol(ShapeId protocol) { + this.protocol = Objects.requireNonNull(protocol); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoWriter.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoWriter.java index aae981c2be..bf3ec60ac4 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoWriter.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/GoWriter.java @@ -1,5 +1,13 @@ package software.amazon.polymorph.smithygo.codegen; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.regex.Pattern; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolContainer; @@ -12,708 +20,840 @@ import software.amazon.smithy.model.traits.DeprecatedTrait; import software.amazon.smithy.utils.StringUtils; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.regex.Pattern; - public class GoWriter extends SymbolWriter { - private static final Pattern ARGUMENT_NAME_PATTERN = Pattern.compile("\\$([a-z][a-zA-Z_0-9]+)(:\\w)?"); - private final String fullPackageName; - private final ImportDeclarations imports = new ImportDeclarations(); - private final List dependencies = new ArrayList<>(); - private final boolean innerWriter; - - /** - * Initializes the GoWriter for the package and filename to be written to. - * - * @param fullPackageName package and filename to be written to. - */ - public GoWriter(String fullPackageName) { - this(fullPackageName, false); - } - - private GoWriter(String fullPackageName, boolean innerWriter) { - super(new ImportDeclarations()); - this.fullPackageName = fullPackageName; - this.innerWriter = innerWriter; - init(); - } - - private void init() { - trimBlankLines(); - trimTrailingSpaces(); - setIndentText("\t"); - putFormatter('T', new GoSymbolFormatter()); - putFormatter('P', new PointableGoSymbolFormatter()); - putFormatter('W', new GoWritableInjector()); - } - - // TODO figure out better way to annotate where the failure occurs, check templates and args - // TODO to try to find programming bugs. - - /** - * Returns a Writable for the string and args to be composed inline to another writer's contents. - * - * @param contents string to write. - * @param args Arguments to use when evaluating the contents string. - * @return Writable to be evaluated. - */ - @SafeVarargs - public static Writable goTemplate(String contents, Map... args) { - validateTemplateArgsNotNull(args); - return (GoWriter w) -> { - w.writeGoTemplate(contents, args); - }; - } - - public static final class GoWriterFactory implements SymbolWriter.Factory { - - @Override - public GoWriter apply(String filename, String namespace) { - GoWriter writer = new GoWriter(namespace); - return writer; - } - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Consumer fn - ) { - return goBlockTemplate(beforeNewLine, afterNewLine, new Map[0], fn); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Consumer fn - ) { - return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1}, fn); - } - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param args2 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Map args2, - Consumer fn - ) { - return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2}, fn); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param args2 template arguments - * @param args3 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Map args2, - Map args3, - Consumer fn - ) { - return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2, args3}, fn); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param args2 template arguments - * @param args3 template arguments - * @param args4 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Map args2, - Map args3, - Map args4, - Consumer fn - ) { - return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2, args3, args4}, fn); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args1 template arguments - * @param args2 template arguments - * @param args3 template arguments - * @param args4 template arguments - * @param args5 template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map args1, - Map args2, - Map args3, - Map args4, - Map args5, - Consumer fn - ) { - return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2, args3, args4, args5}, fn); - } - - /** - * Returns a Writable that can later be invoked to write the contents as template - * as a code block instead of single content of text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param args template arguments - * @param fn closure to write - */ - public static Writable goBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map[] args, - Consumer fn - ) { - validateTemplateArgsNotNull(args); - return (GoWriter w) -> { - w.writeGoBlockTemplate(beforeNewLine, afterNewLine, args, fn); - }; - } - - /** - * Returns a Writable that does nothing. - * - * @return Writable that does nothing - */ - public static Writable emptyGoTemplate() { - return (GoWriter w) -> { - }; - } + private static final Pattern ARGUMENT_NAME_PATTERN = Pattern.compile( + "\\$([a-z][a-zA-Z_0-9]+)(:\\w)?" + ); + private final String fullPackageName; + private final ImportDeclarations imports = new ImportDeclarations(); + private final List dependencies = new ArrayList<>(); + private final boolean innerWriter; + + /** + * Initializes the GoWriter for the package and filename to be written to. + * + * @param fullPackageName package and filename to be written to. + */ + public GoWriter(String fullPackageName) { + this(fullPackageName, false); + } + + private GoWriter(String fullPackageName, boolean innerWriter) { + super(new ImportDeclarations()); + this.fullPackageName = fullPackageName; + this.innerWriter = innerWriter; + init(); + } + + private void init() { + trimBlankLines(); + trimTrailingSpaces(); + setIndentText("\t"); + putFormatter('T', new GoSymbolFormatter()); + putFormatter('P', new PointableGoSymbolFormatter()); + putFormatter('W', new GoWritableInjector()); + } + + // TODO figure out better way to annotate where the failure occurs, check templates and args + // TODO to try to find programming bugs. + + /** + * Returns a Writable for the string and args to be composed inline to another writer's contents. + * + * @param contents string to write. + * @param args Arguments to use when evaluating the contents string. + * @return Writable to be evaluated. + */ + @SafeVarargs + public static Writable goTemplate( + String contents, + Map... args + ) { + validateTemplateArgsNotNull(args); + return (GoWriter w) -> { + w.writeGoTemplate(contents, args); + }; + } + + public static final class GoWriterFactory + implements SymbolWriter.Factory { - /** - * Writes the contents and arguments as a template to the writer. - * - * @param contents string to write - * @param args Arguments to use when evaluating the contents string. - */ - @SafeVarargs - public final void writeGoTemplate(String contents, Map... args) { - withTemplate(contents, args, (template) -> { - try { - write(contents); - } catch (Exception e) { - throw new CodegenException("Failed to render template\n" + contents + "\nReason: " + e.getMessage(), e); - } - }); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Consumer fn - ) { - writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[0], fn); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Consumer fn - ) { - writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1}, fn); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param arg2 second map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Map arg2, - Consumer fn - ) { - writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2}, fn); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param arg2 second map argument - * @param arg3 third map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Map arg2, - Map arg3, - Consumer fn - ) { - writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2, arg3}, fn); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param arg2 second map argument - * @param arg3 third map argument - * @param arg4 forth map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Map arg2, - Map arg3, - Map arg4, - Consumer fn - ) { - writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2, arg3, arg4}, fn); - } - - /** - * Writes the contents as template as a code block instead of single content fo text. - * - * @param beforeNewLine text before new line - * @param afterNewLine text after new line - * @param arg1 first map argument - * @param arg2 second map argument - * @param arg3 third map argument - * @param arg4 forth map argument - * @param arg5 forth map argument - * @param fn closure to write - */ - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map arg1, - Map arg2, - Map arg3, - Map arg4, - Map arg5, - Consumer fn - ) { - writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2, arg3, arg4, arg5}, fn); - } - - public void writeGoBlockTemplate( - String beforeNewLine, - String afterNewLine, - Map[] args, - Consumer fn - ) { - withTemplate(beforeNewLine, args, (header) -> { - conditionalBlock(header, afterNewLine, true, new Object[0], fn); - }); - } - - private void withTemplate( - String template, - Map[] argMaps, - Consumer fn - ) { - pushState(); - for (var args : argMaps) { - putContext(args); + @Override + public GoWriter apply(String filename, String namespace) { + GoWriter writer = new GoWriter(namespace); + return writer; + } + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Consumer fn + ) { + return goBlockTemplate(beforeNewLine, afterNewLine, new Map[0], fn); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Consumer fn + ) { + return goBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { args1 }, + fn + ); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param args2 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Map args2, + Consumer fn + ) { + return goBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { args1, args2 }, + fn + ); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param args2 template arguments + * @param args3 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Map args2, + Map args3, + Consumer fn + ) { + return goBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { args1, args2, args3 }, + fn + ); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param args2 template arguments + * @param args3 template arguments + * @param args4 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Map args2, + Map args3, + Map args4, + Consumer fn + ) { + return goBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { args1, args2, args3, args4 }, + fn + ); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args1 template arguments + * @param args2 template arguments + * @param args3 template arguments + * @param args4 template arguments + * @param args5 template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map args1, + Map args2, + Map args3, + Map args4, + Map args5, + Consumer fn + ) { + return goBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { args1, args2, args3, args4, args5 }, + fn + ); + } + + /** + * Returns a Writable that can later be invoked to write the contents as template + * as a code block instead of single content of text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param args template arguments + * @param fn closure to write + */ + public static Writable goBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map[] args, + Consumer fn + ) { + validateTemplateArgsNotNull(args); + return (GoWriter w) -> { + w.writeGoBlockTemplate(beforeNewLine, afterNewLine, args, fn); + }; + } + + /** + * Returns a Writable that does nothing. + * + * @return Writable that does nothing + */ + public static Writable emptyGoTemplate() { + return (GoWriter w) -> {}; + } + + /** + * Writes the contents and arguments as a template to the writer. + * + * @param contents string to write + * @param args Arguments to use when evaluating the contents string. + */ + @SafeVarargs + public final void writeGoTemplate( + String contents, + Map... args + ) { + withTemplate( + contents, + args, + template -> { + try { + write(contents); + } catch (Exception e) { + throw new CodegenException( + "Failed to render template\n" + + contents + + "\nReason: " + + e.getMessage(), + e + ); } - validateContext(template); - fn.accept(template); - popState(); - } - - private GoWriter conditionalBlock( - String beforeNewLine, - String afterNewLine, - boolean conditional, - Object[] args, - Consumer fn - ) { - if (conditional) { - openBlock(beforeNewLine.trim(), args); + } + ); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Consumer fn + ) { + writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[0], fn); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Consumer fn + ) { + writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[] { arg1 }, fn); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param arg2 second map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Map arg2, + Consumer fn + ) { + writeGoBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { arg1, arg2 }, + fn + ); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param arg2 second map argument + * @param arg3 third map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Map arg2, + Map arg3, + Consumer fn + ) { + writeGoBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { arg1, arg2, arg3 }, + fn + ); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param arg2 second map argument + * @param arg3 third map argument + * @param arg4 forth map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Map arg2, + Map arg3, + Map arg4, + Consumer fn + ) { + writeGoBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { arg1, arg2, arg3, arg4 }, + fn + ); + } + + /** + * Writes the contents as template as a code block instead of single content fo text. + * + * @param beforeNewLine text before new line + * @param afterNewLine text after new line + * @param arg1 first map argument + * @param arg2 second map argument + * @param arg3 third map argument + * @param arg4 forth map argument + * @param arg5 forth map argument + * @param fn closure to write + */ + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map arg1, + Map arg2, + Map arg3, + Map arg4, + Map arg5, + Consumer fn + ) { + writeGoBlockTemplate( + beforeNewLine, + afterNewLine, + new Map[] { arg1, arg2, arg3, arg4, arg5 }, + fn + ); + } + + public void writeGoBlockTemplate( + String beforeNewLine, + String afterNewLine, + Map[] args, + Consumer fn + ) { + withTemplate( + beforeNewLine, + args, + header -> { + conditionalBlock(header, afterNewLine, true, new Object[0], fn); + } + ); + } + + private void withTemplate( + String template, + Map[] argMaps, + Consumer fn + ) { + pushState(); + for (var args : argMaps) { + putContext(args); + } + validateContext(template); + fn.accept(template); + popState(); + } + + private GoWriter conditionalBlock( + String beforeNewLine, + String afterNewLine, + boolean conditional, + Object[] args, + Consumer fn + ) { + if (conditional) { + openBlock(beforeNewLine.trim(), args); + } + + fn.accept(this); + + if (conditional) { + closeBlock(afterNewLine.trim()); + } + + return this; + } + + private static void validateTemplateArgsNotNull( + Map[] argMaps + ) { + for (var args : argMaps) { + args.forEach((k, v) -> { + if (v == null) { + throw new CodegenException( + "Template argument " + k + " cannot be null" + ); } - - fn.accept(this); - - if (conditional) { - closeBlock(afterNewLine.trim()); + }); + } + } + + private void validateContext(String template) { + var matcher = ARGUMENT_NAME_PATTERN.matcher(template); + + while (matcher.find()) { + var keyName = matcher.group(1); + var value = getContext(keyName); + if (value == null) { + throw new CodegenException( + "Go template expected " + + keyName + + " but was not present in context scope." + + " Template: \n" + + template + ); + } + } + } + + /** + * Imports one or more symbols if necessary, using the name of the + * symbol and only "USE" references. + * + * @param container Container of symbols to add. + * @return Returns the writer. + */ + public GoWriter addUseImports(SymbolContainer container) { + for (Symbol symbol : container.getSymbols()) { + addImport( + symbol, + CodegenUtils.getSymbolNamespaceAlias(symbol), + SymbolReference.ContextOption.USE + ); + } + return this; + } + + /** + * Imports a symbol reference if necessary, using the alias of the + * reference and only associated "USE" references. + * + * @param symbolReference Symbol reference to import. + * @return Returns the writer. + */ + public GoWriter addUseImports(SymbolReference symbolReference) { + return addImport( + symbolReference.getSymbol(), + symbolReference.getAlias(), + SymbolReference.ContextOption.USE + ); + } + + /** + * Adds and imports the given dependency. + * + * @param goDependency The GoDependency to import. + * @return Returns the writer. + */ + public GoWriter addUseImports(GoDependency goDependency) { + dependencies.addAll(goDependency.getDependencies()); + return addImport(goDependency.getImportPath(), goDependency.getAlias()); + } + + private GoWriter addImports(GoWriter other) { + this.imports.addImports(other.imports); + return this; + } + + private boolean isExternalNamespace(String namespace) { + return ( + !StringUtils.isBlank(namespace) && !namespace.equals(fullPackageName) + ); + } + + void addImportReferences( + Symbol symbol, + SymbolReference.ContextOption... options + ) { + for (SymbolReference reference : symbol.getReferences()) { + for (SymbolReference.ContextOption option : options) { + if (reference.hasOption(option)) { + addImport(reference.getSymbol(), reference.getAlias(), options); + break; } - - return this; - } - - private static void validateTemplateArgsNotNull(Map[] argMaps) { - for (var args : argMaps) { - args.forEach((k, v) -> { - if (v == null) { - throw new CodegenException("Template argument " + k + " cannot be null"); - } - }); + } + } + } + + /** + * Imports a package using an alias if necessary. + * + * @param packageName Package to import. + * @param as Alias to refer to the package as. + * @return Returns the writer. + */ + public GoWriter addImport(String packageName, String as) { + imports.addImport(packageName, as); + return this; + } + + public GoWriter addImportFromModule( + String moduleName, + String packageName, + String as + ) { + imports.addImport(moduleName.concat("/").concat(packageName), as); + return this; + } + + public GoWriter addImportFromModule(String moduleName, String packageName) { + imports.addImport(moduleName.concat("/").concat(packageName), ""); + return this; + } + + public GoWriter addImport(String packageName) { + imports.addImport(packageName, ""); + return this; + } + + private GoWriter addDependencies(GoWriter other) { + this.dependencies.addAll(other.getDependencies()); + return this; + } + + private boolean isTargetDeprecated(Model model, MemberShape member) { + return ( + model + .expectShape(member.getTarget()) + .getTrait(DeprecatedTrait.class) + .isPresent() && + // don't consider deprecated prelude shapes (like PrimitiveBoolean) + !Prelude.isPreludeShape(member.getTarget()) + ); + } + + @Override + public String toString() { + String contents = super.toString(); + + if (innerWriter) { + return contents; + } + + String[] packageParts = fullPackageName.split("/"); + String header = String.format( + "// Code generated by smithy-go-codegen DO NOT EDIT.%n%n" + ); + + String packageName = packageParts[packageParts.length - 1]; + if (packageName.startsWith("v") && packageParts.length >= 2) { + String remaining = packageName.substring(1); + try { + int value = Integer.parseInt(remaining); + packageName = packageParts[packageParts.length - 2]; + if (value == 0 || value == 1) { + throw new CodegenException( + "module paths vN version component must only be N >= 2" + ); } + } catch (NumberFormatException ne) { + // Do nothing + } } - private void validateContext(String template) { - var matcher = ARGUMENT_NAME_PATTERN.matcher(template); - - while (matcher.find()) { - var keyName = matcher.group(1); - var value = getContext(keyName); - if (value == null) { - throw new CodegenException( - "Go template expected " + keyName + " but was not present in context scope." - + " Template: \n" + template); - } - } - } - - /** - * Imports one or more symbols if necessary, using the name of the - * symbol and only "USE" references. - * - * @param container Container of symbols to add. - * @return Returns the writer. - */ - public GoWriter addUseImports(SymbolContainer container) { - for (Symbol symbol : container.getSymbols()) { - addImport(symbol, - CodegenUtils.getSymbolNamespaceAlias(symbol), - SymbolReference.ContextOption.USE); - } - return this; - } - - /** - * Imports a symbol reference if necessary, using the alias of the - * reference and only associated "USE" references. - * - * @param symbolReference Symbol reference to import. - * @return Returns the writer. - */ - public GoWriter addUseImports(SymbolReference symbolReference) { - return addImport(symbolReference.getSymbol(), symbolReference.getAlias(), SymbolReference.ContextOption.USE); - } - - /** - * Adds and imports the given dependency. - * - * @param goDependency The GoDependency to import. - * @return Returns the writer. - */ - public GoWriter addUseImports(GoDependency goDependency) { - dependencies.addAll(goDependency.getDependencies()); - return addImport(goDependency.getImportPath(), goDependency.getAlias()); - } - - private GoWriter addImports(GoWriter other) { - this.imports.addImports(other.imports); - return this; - } - - private boolean isExternalNamespace(String namespace) { - return !StringUtils.isBlank(namespace) && !namespace.equals(fullPackageName); - } + String packageStatement = String.format("package %s%n%n", packageName); - void addImportReferences(Symbol symbol, SymbolReference.ContextOption... options) { - for (SymbolReference reference : symbol.getReferences()) { - for (SymbolReference.ContextOption option : options) { - if (reference.hasOption(option)) { - addImport(reference.getSymbol(), reference.getAlias(), options); - break; - } - } - } - } + String importString = imports.toString(); + String strippedContents = StringUtils.stripStart(contents, null); + String strippedImportString = StringUtils.strip(importString, null); - /** - * Imports a package using an alias if necessary. - * - * @param packageName Package to import. - * @param as Alias to refer to the package as. - * @return Returns the writer. - */ - public GoWriter addImport(String packageName, String as) { - imports.addImport(packageName, as); - return this; - } - - public GoWriter addImportFromModule(String moduleName, String packageName, String as) { - imports.addImport(moduleName.concat("/").concat(packageName), as); - return this; - } - - public GoWriter addImportFromModule(String moduleName, String packageName) { - imports.addImport(moduleName.concat("/").concat(packageName), ""); - return this; - } - - public GoWriter addImport(String packageName) { - imports.addImport(packageName, ""); - return this; - } - - private GoWriter addDependencies(GoWriter other) { - this.dependencies.addAll(other.getDependencies()); - return this; + // Don't add an additional new line between explicit imports and managed imports. + if ( + !strippedImportString.isEmpty() && strippedContents.startsWith("import ") + ) { + return header + strippedImportString + "\n" + strippedContents; } + return header + packageStatement + importString + contents; + } - private boolean isTargetDeprecated(Model model, MemberShape member) { - return model.expectShape(member.getTarget()).getTrait(DeprecatedTrait.class).isPresent() - // don't consider deprecated prelude shapes (like PrimitiveBoolean) - && !Prelude.isPreludeShape(member.getTarget()); - } + /** + * Implements Go symbol formatting for the {@code $T} formatter. + */ + private class GoSymbolFormatter + implements BiFunction { @Override - public String toString() { - String contents = super.toString(); - - if (innerWriter) { - return contents; + public String apply(Object type, String indent) { + if (type instanceof Symbol) { + Symbol resolvedSymbol = (Symbol) type; + String literal = resolvedSymbol.getName(); + + boolean isSlice = resolvedSymbol + .getProperty(SymbolUtils.GO_SLICE, Boolean.class) + .orElse(false); + boolean isMap = resolvedSymbol + .getProperty(SymbolUtils.GO_MAP, Boolean.class) + .orElse(false); + if (isSlice || isMap) { + resolvedSymbol = + resolvedSymbol + .getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class) + .orElseThrow(() -> + new CodegenException( + "Expected go element type property to be defined" + ) + ); + literal = + new PointableGoSymbolFormatter().apply(resolvedSymbol, "nested"); + } else if ( + !SymbolUtils.isUniverseType(resolvedSymbol) && + isExternalNamespace(resolvedSymbol.getNamespace()) + ) { + literal = formatWithNamespace(resolvedSymbol); } - - - String[] packageParts = fullPackageName.split("/"); - String header = String.format("// Code generated by smithy-go-codegen DO NOT EDIT.%n%n"); - - String packageName = packageParts[packageParts.length - 1]; - if (packageName.startsWith("v") && packageParts.length >= 2) { - String remaining = packageName.substring(1); - try { - int value = Integer.parseInt(remaining); - packageName = packageParts[packageParts.length - 2]; - if (value == 0 || value == 1) { - throw new CodegenException("module paths vN version component must only be N >= 2"); - } - } catch (NumberFormatException ne) { - // Do nothing - } + addUseImports(resolvedSymbol); + + if (isSlice) { + return "[]" + literal; + } else if (isMap) { + return "map[string]" + literal; + } else { + return literal; } + } else if (type instanceof SymbolReference) { + SymbolReference typeSymbol = (SymbolReference) type; + addImport( + typeSymbol.getSymbol(), + typeSymbol.getAlias(), + SymbolReference.ContextOption.USE + ); + return typeSymbol.getAlias(); + } else { + throw new CodegenException( + "Invalid type provided to $T. Expected a Symbol, but found `" + + type + + "`" + ); + } + } + + private String formatWithNamespace(Symbol symbol) { + if (StringUtils.isEmpty(symbol.getNamespace())) { + return symbol.getName(); + } + return String.format( + "%s.%s", + CodegenUtils.getSymbolNamespaceAlias(symbol), + symbol.getName() + ); + } + } + + /** + * Implements Go symbol formatting for the {@code $P} formatter. This is identical to the $T + * formatter, except that it will add a * to symbols that can be pointers. + */ + private class PointableGoSymbolFormatter extends GoSymbolFormatter { - String packageStatement = String.format("package %s%n%n", packageName); - - String importString = imports.toString(); - String strippedContents = StringUtils.stripStart(contents, null); - String strippedImportString = StringUtils.strip(importString, null); - - // Don't add an additional new line between explicit imports and managed imports. - if (!strippedImportString.isEmpty() && strippedContents.startsWith("import ")) { - return header + strippedImportString + "\n" + strippedContents; - } + @Override + public String apply(Object type, String indent) { + String formatted = super.apply(type, indent); + if (isPointer(type)) { + formatted = "*" + formatted; + } + return formatted; + } + + private boolean isPointer(Object type) { + if (type instanceof Symbol) { + Symbol typeSymbol = (Symbol) type; + return typeSymbol + .getProperty(SymbolUtils.POINTABLE, Boolean.class) + .orElse(false); + } else if (type instanceof SymbolReference) { + SymbolReference typeSymbol = (SymbolReference) type; + return ( + typeSymbol + .getProperty(SymbolUtils.POINTABLE, Boolean.class) + .orElse(false) || + typeSymbol + .getSymbol() + .getProperty(SymbolUtils.POINTABLE, Boolean.class) + .orElse(false) + ); + } else if (type instanceof String) { + return true; + } else { + throw new CodegenException( + "Invalid type provided to $P. Expected a Symbol, but found `" + + type + + "`" + ); + } + } + } + + class GoWritableInjector extends GoSymbolFormatter { - return header + packageStatement + importString + contents; + @Override + public String apply(Object type, String indent) { + if (!(type instanceof Writable)) { + throw new CodegenException( + "expect Writable for GoWriter W injector, but got " + type + ); + } + var innerWriter = new GoWriter(fullPackageName, true); + ((Writable) type).accept(innerWriter); + addImports(innerWriter); + addDependencies(innerWriter); + return innerWriter.toString().trim(); } + } - /** - * Implements Go symbol formatting for the {@code $T} formatter. - */ - private class GoSymbolFormatter implements BiFunction { - @Override - public String apply(Object type, String indent) { - if (type instanceof Symbol) { - Symbol resolvedSymbol = (Symbol) type; - String literal = resolvedSymbol.getName(); - - boolean isSlice = resolvedSymbol.getProperty(SymbolUtils.GO_SLICE, Boolean.class).orElse(false); - boolean isMap = resolvedSymbol.getProperty(SymbolUtils.GO_MAP, Boolean.class).orElse(false); - if (isSlice || isMap) { - resolvedSymbol = resolvedSymbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class) - .orElseThrow(() -> new CodegenException("Expected go element type property to be defined")); - literal = new PointableGoSymbolFormatter().apply(resolvedSymbol, "nested"); - } else if (!SymbolUtils.isUniverseType(resolvedSymbol) - && isExternalNamespace(resolvedSymbol.getNamespace())) { - literal = formatWithNamespace(resolvedSymbol); - } - addUseImports(resolvedSymbol); - - if (isSlice) { - return "[]" + literal; - } else if (isMap) { - return "map[string]" + literal; - } else { - return literal; - } - } else if (type instanceof SymbolReference) { - SymbolReference typeSymbol = (SymbolReference) type; - addImport(typeSymbol.getSymbol(), typeSymbol.getAlias(), SymbolReference.ContextOption.USE); - return typeSymbol.getAlias(); - } else { - throw new CodegenException( - "Invalid type provided to $T. Expected a Symbol, but found `" + type + "`"); - } - } + public interface Writable extends Consumer {} - private String formatWithNamespace(Symbol symbol) { - if (StringUtils.isEmpty(symbol.getNamespace())) { - return symbol.getName(); - } - return String.format("%s.%s", CodegenUtils.getSymbolNamespaceAlias(symbol), symbol.getName()); - } - } + /** + * Chains together multiple Writables that can be composed into one Writable. + */ + public static final class ChainWritable { - /** - * Implements Go symbol formatting for the {@code $P} formatter. This is identical to the $T - * formatter, except that it will add a * to symbols that can be pointers. - */ - private class PointableGoSymbolFormatter extends GoSymbolFormatter { - @Override - public String apply(Object type, String indent) { - String formatted = super.apply(type, indent); - if (isPointer(type)) { - formatted = "*" + formatted; - } - return formatted; - } + private final List writables; - private boolean isPointer(Object type) { - if (type instanceof Symbol) { - Symbol typeSymbol = (Symbol) type; - return typeSymbol.getProperty(SymbolUtils.POINTABLE, Boolean.class).orElse(false); - } else if (type instanceof SymbolReference) { - SymbolReference typeSymbol = (SymbolReference) type; - return typeSymbol.getProperty(SymbolUtils.POINTABLE, Boolean.class).orElse(false) - || typeSymbol.getSymbol().getProperty(SymbolUtils.POINTABLE, Boolean.class).orElse(false); - } else if (type instanceof String) { - return true; - } else { - throw new CodegenException( - "Invalid type provided to $P. Expected a Symbol, but found `" + type + "`"); - } - } + public ChainWritable() { + writables = new ArrayList<>(); } - class GoWritableInjector extends GoSymbolFormatter { - @Override - public String apply(Object type, String indent) { - if (!(type instanceof Writable)) { - throw new CodegenException( - "expect Writable for GoWriter W injector, but got " + type); - } - var innerWriter = new GoWriter(fullPackageName, true); - ((Writable) type).accept(innerWriter); - addImports(innerWriter); - addDependencies(innerWriter); - return innerWriter.toString().trim(); - } + public ChainWritable add(GoWriter.Writable writable) { + writables.add(writable); + return this; } - public interface Writable extends Consumer { + public ChainWritable add(Optional value, Function fn) { + value.ifPresent(t -> writables.add(fn.apply(t))); + return this; } - /** - * Chains together multiple Writables that can be composed into one Writable. - */ - public static final class ChainWritable { - private final List writables; - - public ChainWritable() { - writables = new ArrayList<>(); - } - - public ChainWritable add(GoWriter.Writable writable) { - writables.add(writable); - return this; - } - - public ChainWritable add(Optional value, Function fn) { - value.ifPresent(t -> writables.add(fn.apply(t))); - return this; - } - - public ChainWritable add(boolean include, GoWriter.Writable writable) { - if (!include) { - writables.add(writable); - } - return this; - } + public ChainWritable add(boolean include, GoWriter.Writable writable) { + if (!include) { + writables.add(writable); + } + return this; + } - public GoWriter.Writable compose() { - return (GoWriter writer) -> { - var hasPrevious = false; - for (GoWriter.Writable writable : writables) { - if (hasPrevious) { - writer.write(""); - } - hasPrevious = true; - writer.write("$W", writable); - } - }; + public GoWriter.Writable compose() { + return (GoWriter writer) -> { + var hasPrevious = false; + for (GoWriter.Writable writable : writables) { + if (hasPrevious) { + writer.write(""); + } + hasPrevious = true; + writer.write("$W", writable); } + }; } + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ImportDeclarations.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ImportDeclarations.java index a8c3dcf30f..bd528e9d3c 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ImportDeclarations.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ImportDeclarations.java @@ -1,62 +1,65 @@ package software.amazon.polymorph.smithygo.codegen; +import java.util.Map; +import java.util.TreeMap; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.ImportContainer; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.utils.StringUtils; -import java.util.Map; -import java.util.TreeMap; - public class ImportDeclarations implements ImportContainer { - private final Map imports = new TreeMap<>(); - - ImportDeclarations addImport(String importPath, String alias) { - String importAlias = CodegenUtils.getDefaultPackageImportName(importPath); - if (!StringUtils.isBlank(alias)) { - if (alias.equals(".")) { - // Global imports are generally a bad practice. - throw new CodegenException("Globally importing packages is forbidden: " + importPath); - } - importAlias = alias; - } - imports.putIfAbsent(importAlias, importPath); - return this; - } + private final Map imports = new TreeMap<>(); - ImportDeclarations addImports(ImportDeclarations other) { - other.imports.forEach((importAlias, importPath) -> { - addImport(importPath, importAlias); - }); - return this; + ImportDeclarations addImport(String importPath, String alias) { + String importAlias = CodegenUtils.getDefaultPackageImportName(importPath); + if (!StringUtils.isBlank(alias)) { + if (alias.equals(".")) { + // Global imports are generally a bad practice. + throw new CodegenException( + "Globally importing packages is forbidden: " + importPath + ); + } + importAlias = alias; } + imports.putIfAbsent(importAlias, importPath); + return this; + } - @Override - public String toString() { - if (imports.isEmpty()) { - return ""; - } - - StringBuilder builder = new StringBuilder("import (\n"); - for (Map.Entry entry : imports.entrySet()) { - builder.append('\t'); - builder.append(createImportStatement(entry)); - builder.append('\n'); - } - builder.append(")\n\n"); - return builder.toString(); - } + ImportDeclarations addImports(ImportDeclarations other) { + other.imports.forEach((importAlias, importPath) -> { + addImport(importPath, importAlias); + }); + return this; + } - private String createImportStatement(Map.Entry entry) { - String formattedPackageName = "\"" + entry.getValue() + "\""; - return CodegenUtils.getDefaultPackageImportName(entry.getValue()).equals(entry.getKey()) - ? formattedPackageName - : entry.getKey() + " " + formattedPackageName; + @Override + public String toString() { + if (imports.isEmpty()) { + return ""; } - @Override - public void importSymbol(Symbol symbol, String alias) { - addImport(symbol.getName(), alias); + StringBuilder builder = new StringBuilder("import (\n"); + for (Map.Entry entry : imports.entrySet()) { + builder.append('\t'); + builder.append(createImportStatement(entry)); + builder.append('\n'); } + builder.append(")\n\n"); + return builder.toString(); + } + + private String createImportStatement(Map.Entry entry) { + String formattedPackageName = "\"" + entry.getValue() + "\""; + return CodegenUtils + .getDefaultPackageImportName(entry.getValue()) + .equals(entry.getKey()) + ? formattedPackageName + : entry.getKey() + " " + formattedPackageName; + } + + @Override + public void importSymbol(Symbol symbol, String alias) { + addImport(symbol.getName(), alias); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/IntEnumGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/IntEnumGenerator.java index 3d23121ce3..55387111bc 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/IntEnumGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/IntEnumGenerator.java @@ -32,60 +32,87 @@ * Renders intEnums and their constants. */ public final class IntEnumGenerator implements Runnable { - private static final Logger LOGGER = Logger.getLogger(IntEnumGenerator.class.getName()); - private final SymbolProvider symbolProvider; - private final GoWriter writer; - private final IntEnumShape shape; + private static final Logger LOGGER = Logger.getLogger( + IntEnumGenerator.class.getName() + ); - public IntEnumGenerator(SymbolProvider symbolProvider, GoWriter writer, IntEnumShape shape) { - this.symbolProvider = symbolProvider; - this.writer = writer; - this.shape = shape; - } + private final SymbolProvider symbolProvider; + private final GoWriter writer; + private final IntEnumShape shape; - @Override - public void run() { - Symbol symbol = symbolProvider.toSymbol(shape); + public IntEnumGenerator( + SymbolProvider symbolProvider, + GoWriter writer, + IntEnumShape shape + ) { + this.symbolProvider = symbolProvider; + this.writer = writer; + this.shape = shape; + } -// TODO(smithy): Use type alias instead of type definition until refactoring -// protocol generators is prioritized. - writer.write("type $L = int32", symbol.getName()).write(""); + @Override + public void run() { + Symbol symbol = symbolProvider.toSymbol(shape); - Set constants = new LinkedHashSet<>(); - writer.openBlock("const (", ")", () -> { - for (Map.Entry entry : shape.getAllMembers().entrySet()) { - StringBuilder labelBuilder = new StringBuilder(symbol.getName()); - String name = entry.getKey(); + // TODO(smithy): Use type alias instead of type definition until refactoring + // protocol generators is prioritized. + writer.write("type $L = int32", symbol.getName()).write(""); - for (String part : name.split("(?U)[\\W_]")) { - if (part.matches(".*[a-z].*") && part.matches(".*[A-Z].*")) { -// Mixed case names should not be changed other than first letter capitalized. - labelBuilder.append(StringUtils.capitalize(part)); - } else { -// For all non-mixed case parts title case first letter, followed by all other lower cased. - labelBuilder.append(StringUtils.capitalize(part.toLowerCase(Locale.US))); - } - } - String label = labelBuilder.toString(); + Set constants = new LinkedHashSet<>(); + writer + .openBlock( + "const (", + ")", + () -> { + for (Map.Entry entry : shape + .getAllMembers() + .entrySet()) { + StringBuilder labelBuilder = new StringBuilder(symbol.getName()); + String name = entry.getKey(); -// If camel-casing would cause a conflict, don't camel-case this enum value. - if (constants.contains(label)) { - LOGGER.warning(String.format( - "Multiple enums resolved to the same name, `%s`, using unaltered value for: %s", - label, name)); - label = name; - } - constants.add(label); + for (String part : name.split("(?U)[\\W_]")) { + if (part.matches(".*[a-z].*") && part.matches(".*[A-Z].*")) { + // Mixed case names should not be changed other than first letter capitalized. + labelBuilder.append(StringUtils.capitalize(part)); + } else { + // For all non-mixed case parts title case first letter, followed by all other lower cased. + labelBuilder.append( + StringUtils.capitalize(part.toLowerCase(Locale.US)) + ); + } + } + String label = labelBuilder.toString(); - writer.write("$L $L = $L", label, symbol.getName(), - entry.getValue().expectTrait(EnumValueTrait.class).expectIntValue()); + // If camel-casing would cause a conflict, don't camel-case this enum value. + if (constants.contains(label)) { + LOGGER.warning( + String.format( + "Multiple enums resolved to the same name, `%s`, using unaltered value for: %s", + label, + name + ) + ); + label = name; } - }).write(""); + constants.add(label); -// TODO(smithy): type aliases don't allow defining methods on base types (e.g. int32). -// Uncomment generating the Value() method when the type alias is migrated to type definition. -/* + writer.write( + "$L $L = $L", + label, + symbol.getName(), + entry + .getValue() + .expectTrait(EnumValueTrait.class) + .expectIntValue() + ); + } + } + ) + .write(""); + // TODO(smithy): type aliases don't allow defining methods on base types (e.g. int32). + // Uncomment generating the Value() method when the type alias is migrated to type definition. + /* writer.writeDocs(String.format("Values returns all known values for %s. Note that this can be expanded in the " + "future, and so it is only as up to date as the client.%n%nThe ordering of this slice is not " + "guaranteed to be stable across updates.", symbol.getName())); @@ -97,5 +124,5 @@ public void run() { }); }); */ - } -} \ No newline at end of file + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SmithyGoDependency.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SmithyGoDependency.java index 20955d8ea8..c5c95d399c 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SmithyGoDependency.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SmithyGoDependency.java @@ -19,116 +19,171 @@ * A class of constants for dependencies used by this package. */ public final class SmithyGoDependency { - // The version in the stdlib dependencies should reflect the minimum Go version. - // The values aren't currently used, but they could potentially used to dynamically - // set the minimum go version. - public static final GoDependency BIG = stdlib("math/big"); - public static final GoDependency TIME = stdlib("time"); - public static final GoDependency FMT = stdlib("fmt"); - public static final GoDependency CONTEXT = stdlib("context"); - public static final GoDependency STRCONV = stdlib("strconv"); - public static final GoDependency BASE64 = stdlib("encoding/base64"); - public static final GoDependency NET = stdlib("net"); - public static final GoDependency NET_URL = stdlib("net/url"); - public static final GoDependency NET_HTTP = stdlib("net/http"); - public static final GoDependency NET_HTTP_TEST = stdlib("net/http/httptest"); - public static final GoDependency BYTES = stdlib("bytes"); - public static final GoDependency STRINGS = stdlib("strings"); - public static final GoDependency JSON = stdlib("encoding/json"); - public static final GoDependency IO = stdlib("io"); - public static final GoDependency IOUTIL = stdlib("io/ioutil"); - public static final GoDependency CRYPTORAND = stdlib("crypto/rand", "cryptorand"); - public static final GoDependency TESTING = stdlib("testing"); - public static final GoDependency ERRORS = stdlib("errors"); - public static final GoDependency XML = stdlib("encoding/xml"); - public static final GoDependency SYNC = stdlib("sync"); - public static final GoDependency PATH = stdlib("path"); - - public static final GoDependency SMITHY = smithy(null, "smithy"); - public static final GoDependency SMITHY_HTTP_TRANSPORT = smithy("transport/http", "smithyhttp"); - public static final GoDependency SMITHY_MIDDLEWARE = smithy("middleware"); - public static final GoDependency SMITHY_TIME = smithy("time", "smithytime"); - public static final GoDependency SMITHY_HTTP_BINDING = smithy("encoding/httpbinding"); - public static final GoDependency SMITHY_JSON = smithy("encoding/json", "smithyjson"); - public static final GoDependency SMITHY_XML = smithy("encoding/xml", "smithyxml"); - public static final GoDependency SMITHY_IO = smithy("io", "smithyio"); - public static final GoDependency SMITHY_LOGGING = smithy("logging"); - public static final GoDependency SMITHY_PTR = smithy("ptr"); - public static final GoDependency SMITHY_RAND = smithy("rand", "smithyrand"); - public static final GoDependency SMITHY_TESTING = smithy("testing", "smithytesting"); - public static final GoDependency SMITHY_WAITERS = smithy("waiter", "smithywaiter"); - public static final GoDependency SMITHY_DOCUMENT = smithy("document", "smithydocument"); - public static final GoDependency SMITHY_DOCUMENT_JSON = smithy("document/json", "smithydocumentjson"); - public static final GoDependency SMITHY_SYNC = smithy("sync", "smithysync"); - public static final GoDependency SMITHY_AUTH_BEARER = smithy("auth/bearer"); - - public static final GoDependency GO_CMP = goCmp("cmp"); - public static final GoDependency GO_CMP_OPTIONS = goCmp("cmp/cmpopts"); - - public static final GoDependency GO_JMESPATH = goJmespath(null); - public static final GoDependency MATH = stdlib("math"); - - private static final String SMITHY_SOURCE_PATH = "github.com/aws/smithy-go"; - private static final String GO_CMP_SOURCE_PATH = "github.com/google/go-cmp"; - private static final String GO_JMESPATH_SOURCE_PATH = "github.com/jmespath/go-jmespath"; - - private SmithyGoDependency() { - } - /** - * Get a {@link GoDependency} representing the standard library package import path. - * - * @param importPath standard library import path - * @return the {@link GoDependency} for the package import path - */ - public static GoDependency stdlib(String importPath) { - return GoDependency.standardLibraryDependency(importPath, Versions.GO_STDLIB); - } + // The version in the stdlib dependencies should reflect the minimum Go version. + // The values aren't currently used, but they could potentially used to dynamically + // set the minimum go version. + public static final GoDependency BIG = stdlib("math/big"); + public static final GoDependency TIME = stdlib("time"); + public static final GoDependency FMT = stdlib("fmt"); + public static final GoDependency CONTEXT = stdlib("context"); + public static final GoDependency STRCONV = stdlib("strconv"); + public static final GoDependency BASE64 = stdlib("encoding/base64"); + public static final GoDependency NET = stdlib("net"); + public static final GoDependency NET_URL = stdlib("net/url"); + public static final GoDependency NET_HTTP = stdlib("net/http"); + public static final GoDependency NET_HTTP_TEST = stdlib("net/http/httptest"); + public static final GoDependency BYTES = stdlib("bytes"); + public static final GoDependency STRINGS = stdlib("strings"); + public static final GoDependency JSON = stdlib("encoding/json"); + public static final GoDependency IO = stdlib("io"); + public static final GoDependency IOUTIL = stdlib("io/ioutil"); + public static final GoDependency CRYPTORAND = stdlib( + "crypto/rand", + "cryptorand" + ); + public static final GoDependency TESTING = stdlib("testing"); + public static final GoDependency ERRORS = stdlib("errors"); + public static final GoDependency XML = stdlib("encoding/xml"); + public static final GoDependency SYNC = stdlib("sync"); + public static final GoDependency PATH = stdlib("path"); - /** - * Get a {@link GoDependency} representing the standard library package import path with the given alias. - * - * @param importPath standard library package import path - * @param alias the package alias - * @return the {@link GoDependency} for the package import path - */ - public static GoDependency stdlib(String importPath, String alias) { - return GoDependency.standardLibraryDependency(importPath, Versions.GO_STDLIB, alias); - } + public static final GoDependency SMITHY = smithy(null, "smithy"); + public static final GoDependency SMITHY_HTTP_TRANSPORT = smithy( + "transport/http", + "smithyhttp" + ); + public static final GoDependency SMITHY_MIDDLEWARE = smithy("middleware"); + public static final GoDependency SMITHY_TIME = smithy("time", "smithytime"); + public static final GoDependency SMITHY_HTTP_BINDING = smithy( + "encoding/httpbinding" + ); + public static final GoDependency SMITHY_JSON = smithy( + "encoding/json", + "smithyjson" + ); + public static final GoDependency SMITHY_XML = smithy( + "encoding/xml", + "smithyxml" + ); + public static final GoDependency SMITHY_IO = smithy("io", "smithyio"); + public static final GoDependency SMITHY_LOGGING = smithy("logging"); + public static final GoDependency SMITHY_PTR = smithy("ptr"); + public static final GoDependency SMITHY_RAND = smithy("rand", "smithyrand"); + public static final GoDependency SMITHY_TESTING = smithy( + "testing", + "smithytesting" + ); + public static final GoDependency SMITHY_WAITERS = smithy( + "waiter", + "smithywaiter" + ); + public static final GoDependency SMITHY_DOCUMENT = smithy( + "document", + "smithydocument" + ); + public static final GoDependency SMITHY_DOCUMENT_JSON = smithy( + "document/json", + "smithydocumentjson" + ); + public static final GoDependency SMITHY_SYNC = smithy("sync", "smithysync"); + public static final GoDependency SMITHY_AUTH_BEARER = smithy("auth/bearer"); - private static GoDependency smithy(String relativePath) { - return smithy(relativePath, null); - } + public static final GoDependency GO_CMP = goCmp("cmp"); + public static final GoDependency GO_CMP_OPTIONS = goCmp("cmp/cmpopts"); - private static GoDependency smithy(String relativePath, String alias) { - return relativePackage(SMITHY_SOURCE_PATH, relativePath, Versions.SMITHY_GO, alias); - } + public static final GoDependency GO_JMESPATH = goJmespath(null); + public static final GoDependency MATH = stdlib("math"); - private static GoDependency goCmp(String relativePath) { - return relativePackage(GO_CMP_SOURCE_PATH, relativePath, Versions.GO_CMP, null); - } + private static final String SMITHY_SOURCE_PATH = "github.com/aws/smithy-go"; + private static final String GO_CMP_SOURCE_PATH = "github.com/google/go-cmp"; + private static final String GO_JMESPATH_SOURCE_PATH = + "github.com/jmespath/go-jmespath"; - private static GoDependency goJmespath(String relativePath) { - return relativePackage(GO_JMESPATH_SOURCE_PATH, relativePath, Versions.GO_JMESPATH, null); - } + private SmithyGoDependency() {} - private static GoDependency relativePackage( - String moduleImportPath, - String relativePath, - String version, - String alias - ) { - String importPath = moduleImportPath; - if (relativePath != null) { - importPath = importPath + "/" + relativePath; - } - return GoDependency.moduleDependency(moduleImportPath, importPath, version, alias); - } + /** + * Get a {@link GoDependency} representing the standard library package import path. + * + * @param importPath standard library import path + * @return the {@link GoDependency} for the package import path + */ + public static GoDependency stdlib(String importPath) { + return GoDependency.standardLibraryDependency( + importPath, + Versions.GO_STDLIB + ); + } - private static final class Versions { - private static final String GO_STDLIB = "1.15"; - private static final String GO_CMP = "v0.5.4"; - private static final String SMITHY_GO = "v1.4.0"; - private static final String GO_JMESPATH = "v0.4.0"; + /** + * Get a {@link GoDependency} representing the standard library package import path with the given alias. + * + * @param importPath standard library package import path + * @param alias the package alias + * @return the {@link GoDependency} for the package import path + */ + public static GoDependency stdlib(String importPath, String alias) { + return GoDependency.standardLibraryDependency( + importPath, + Versions.GO_STDLIB, + alias + ); + } + + private static GoDependency smithy(String relativePath) { + return smithy(relativePath, null); + } + + private static GoDependency smithy(String relativePath, String alias) { + return relativePackage( + SMITHY_SOURCE_PATH, + relativePath, + Versions.SMITHY_GO, + alias + ); + } + + private static GoDependency goCmp(String relativePath) { + return relativePackage( + GO_CMP_SOURCE_PATH, + relativePath, + Versions.GO_CMP, + null + ); + } + + private static GoDependency goJmespath(String relativePath) { + return relativePackage( + GO_JMESPATH_SOURCE_PATH, + relativePath, + Versions.GO_JMESPATH, + null + ); + } + + private static GoDependency relativePackage( + String moduleImportPath, + String relativePath, + String version, + String alias + ) { + String importPath = moduleImportPath; + if (relativePath != null) { + importPath = importPath + "/" + relativePath; } + return GoDependency.moduleDependency( + moduleImportPath, + importPath, + version, + alias + ); + } + + private static final class Versions { + + private static final String GO_STDLIB = "1.15"; + private static final String GO_CMP = "v0.5.4"; + private static final String SMITHY_GO = "v1.4.0"; + private static final String GO_JMESPATH = "v0.4.0"; + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java index cca398c08c..ecf9687753 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java @@ -15,14 +15,21 @@ package software.amazon.polymorph.smithygo.codegen; +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + +import java.math.BigDecimal; +import java.util.HashSet; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; import software.amazon.polymorph.smithygo.localservice.nameresolver.SmithyNameResolver; import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; import software.amazon.polymorph.traits.ReferenceTrait; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.MemberShape; +import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.LengthTrait; @@ -31,48 +38,134 @@ import software.amazon.smithy.model.traits.StreamingTrait; import software.amazon.smithy.utils.SetUtils; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - -import java.math.BigDecimal; -import java.util.HashSet; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; - /** * Renders structures. */ public final class StructureGenerator implements Runnable { - private static final Set ERROR_MEMBER_NAMES = SetUtils.of("ErrorMessage", "Message", "ErrorCodeOverride"); - - private final Model model; - private final SymbolProvider symbolProvider; - private final GoWriter writer; - private final StructureShape shape; - private final GenerationContext context; - private final ValidationGenerator validationGenerator; - - public StructureGenerator( - final GenerationContext context, - GoWriter writer, - StructureShape shape) { - this.context = context; - this.model = context.model(); - this.symbolProvider = context.symbolProvider(); - this.writer = writer; - this.shape = shape; - this.validationGenerator = new ValidationGenerator(model, symbolProvider, writer); + + private static final Set ERROR_MEMBER_NAMES = SetUtils.of( + "ErrorMessage", + "Message", + "ErrorCodeOverride" + ); + + private final Model model; + private final SymbolProvider symbolProvider; + private final GoWriter writer; + private final StructureShape shape; + private final GenerationContext context; + private final ValidationGenerator validationGenerator; + + public StructureGenerator( + final GenerationContext context, + GoWriter writer, + StructureShape shape + ) { + this.context = context; + this.model = context.model(); + this.symbolProvider = context.symbolProvider(); + this.writer = writer; + this.shape = shape; + this.validationGenerator = + new ValidationGenerator(model, symbolProvider, writer); + } + + @Override + public void run() { + if (!shape.hasTrait(ErrorTrait.class)) { + renderStructure(() -> {}); + } else { + renderErrorStructure(); } + } - @Override - public void run() { - if (!shape.hasTrait(ErrorTrait.class)) { - renderStructure(() -> { - }); + /** + * Renders a non-error structure. + * + * @param runnable A runnable that runs before the structure definition is closed. This can be used to write + * additional members. + */ + public void renderStructure(Runnable runnable) { + renderStructure(runnable, false); + } + + /** + * Renders a non-error structure. + * + * @param runnable A runnable that runs before the structure definition is closed. This can be used to write + * additional members. + * @param isInputStructure A boolean indicating if input variants for member symbols should be used. + */ + public void renderStructure(Runnable runnable, boolean isInputStructure) { + writer.addImport("fmt"); + Symbol symbol = symbolProvider.toSymbol(shape); + writer.openBlock("type $L struct {", symbol.getName()); + CodegenUtils.SortedMembers sortedMembers = new CodegenUtils.SortedMembers( + symbolProvider + ); + shape + .getAllMembers() + .values() + .stream() + .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) + .sorted(sortedMembers) + .forEach(member -> { + writer.write(""); + + String memberName = symbolProvider.toMemberName(member); + + Symbol memberSymbol = symbolProvider.toSymbol(member); + + var targetShape = model.expectShape(member.getTarget()); + + if (isInputStructure) { + memberSymbol = + memberSymbol + .getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) + .orElse(memberSymbol); + } + var namespace = SmithyNameResolver.smithyTypesNamespace(targetShape); + + if (targetShape.hasTrait(ReferenceTrait.class)) { + memberSymbol = + memberSymbol.getProperty("Referred", Symbol.class).get(); + var refShape = targetShape.expectTrait(ReferenceTrait.class); + if (refShape.isService()) { + namespace = + SmithyNameResolver.shapeNamespace( + model.expectShape(refShape.getReferentId()) + ); + } + if ( + !member + .toShapeId() + .getNamespace() + .equals(refShape.getReferentId().getNamespace()) + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + refShape.getReferentId().getNamespace() + ), + namespace + ); + } } else { - renderErrorStructure(); + if ( + !member + .toShapeId() + .getNamespace() + .equals(targetShape.toShapeId().getNamespace()) && + !targetShape.toShapeId().getNamespace().startsWith("smithy") && + targetShape.asStructureShape().isPresent() + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + targetShape.toShapeId().getNamespace() + ), + namespace + ); + } } - } /** * Renders a non-error structure. diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolUtils.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolUtils.java index 390a6919d8..ec7d1aba80 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolUtils.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolUtils.java @@ -23,173 +23,217 @@ */ public final class SymbolUtils { - public static final String POINTABLE = "pointable"; - public static final String NAMESPACE_ALIAS = "namespaceAlias"; - public static final String GO_UNIVERSE_TYPE = "universeType"; - public static final String GO_SLICE = "goSlice"; - public static final String GO_MAP = "goMap"; - public static final String GO_ELEMENT_TYPE = "goElementType"; - - // Used when a given shape must be represented differently on input. - public static final String INPUT_VARIANT = "inputVariant"; - - private SymbolUtils() { - } - - /** - * Create a value symbol builder. - * - * @param typeName the name of the type. - * @return the symbol builder type. - */ - public static Symbol.Builder createValueSymbolBuilder(String typeName) { - return Symbol.builder() - .putProperty(POINTABLE, false) - .name(typeName); - } - - /** - * Create a pointable symbol builder. - * - * @param typeName the name of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder(String typeName) { - return Symbol.builder() - .putProperty(POINTABLE, true) - .name(typeName); - } - - /** - * Create a value symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder(Shape shape, String typeName) { - return createValueSymbolBuilder(typeName).putProperty("shape", shape); - } - - /** - * Create a pointable symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder(Shape shape, String typeName) { - return createPointableSymbolBuilder(typeName).putProperty("shape", shape); - } - - /** - * Create a pointable symbol builder. - * - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder(String typeName, String namespace) { - return createPointableSymbolBuilder(typeName).namespace(namespace, "."); - } - - /** - * Create a value symbol builder. - * - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder(String typeName, String namespace) { - return createValueSymbolBuilder(typeName).namespace(namespace, "."); - } - - /** - * Create a pointable symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder(Shape shape, String typeName, String namespace) { - return createPointableSymbolBuilder(shape, typeName).namespace(namespace, "."); - } - - /** - * Create a value symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder(Shape shape, String typeName, String namespace) { - return createValueSymbolBuilder(shape, typeName).namespace(namespace, "."); - } - - /** - * Create a pointable symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder(Shape shape, String typeName, GoDependency namespace) { - return setImportedNamespace(createPointableSymbolBuilder(shape, typeName), namespace); - } - - /** - * Create a value symbol builder. - * - * @param shape the shape that the type is for. - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder(Shape shape, String typeName, GoDependency namespace) { - return setImportedNamespace(createValueSymbolBuilder(shape, typeName), namespace); - } - - /** - * Create a pointable symbol builder. - * - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createPointableSymbolBuilder(String typeName, GoDependency namespace) { - return setImportedNamespace(createPointableSymbolBuilder(typeName), namespace); - } - - /** - * Create a value symbol builder. - * - * @param typeName the name of the type. - * @param namespace the namespace of the type. - * @return the symbol builder. - */ - public static Symbol.Builder createValueSymbolBuilder(String typeName, GoDependency namespace) { - return setImportedNamespace(createValueSymbolBuilder(typeName), namespace); - } - - private static Symbol.Builder setImportedNamespace(Symbol.Builder builder, GoDependency dependency) { - return builder.namespace(dependency.getImportPath(), ".") - .addDependency(dependency) - .putProperty(NAMESPACE_ALIAS, dependency.getAlias()); - } - - /** - * Go declares several built-in language types in what is known as the Universe block. This function determines - * whether the provided symbol represents a Go universe type. - * - * @param symbol the symbol to check - * @return whether the symbol type is in the Go universe block - * @see The Go Programming Language Specification - */ - public static boolean isUniverseType(Symbol symbol) { - return symbol.getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class) - .orElse(false); - } + public static final String POINTABLE = "pointable"; + public static final String NAMESPACE_ALIAS = "namespaceAlias"; + public static final String GO_UNIVERSE_TYPE = "universeType"; + public static final String GO_SLICE = "goSlice"; + public static final String GO_MAP = "goMap"; + public static final String GO_ELEMENT_TYPE = "goElementType"; + + // Used when a given shape must be represented differently on input. + public static final String INPUT_VARIANT = "inputVariant"; + + private SymbolUtils() {} + + /** + * Create a value symbol builder. + * + * @param typeName the name of the type. + * @return the symbol builder type. + */ + public static Symbol.Builder createValueSymbolBuilder(String typeName) { + return Symbol.builder().putProperty(POINTABLE, false).name(typeName); + } + + /** + * Create a pointable symbol builder. + * + * @param typeName the name of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder(String typeName) { + return Symbol.builder().putProperty(POINTABLE, true).name(typeName); + } + + /** + * Create a value symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder( + Shape shape, + String typeName + ) { + return createValueSymbolBuilder(typeName).putProperty("shape", shape); + } + + /** + * Create a pointable symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder( + Shape shape, + String typeName + ) { + return createPointableSymbolBuilder(typeName).putProperty("shape", shape); + } + + /** + * Create a pointable symbol builder. + * + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder( + String typeName, + String namespace + ) { + return createPointableSymbolBuilder(typeName).namespace(namespace, "."); + } + + /** + * Create a value symbol builder. + * + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder( + String typeName, + String namespace + ) { + return createValueSymbolBuilder(typeName).namespace(namespace, "."); + } + + /** + * Create a pointable symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder( + Shape shape, + String typeName, + String namespace + ) { + return createPointableSymbolBuilder(shape, typeName) + .namespace(namespace, "."); + } + + /** + * Create a value symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder( + Shape shape, + String typeName, + String namespace + ) { + return createValueSymbolBuilder(shape, typeName).namespace(namespace, "."); + } + + /** + * Create a pointable symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder( + Shape shape, + String typeName, + GoDependency namespace + ) { + return setImportedNamespace( + createPointableSymbolBuilder(shape, typeName), + namespace + ); + } + + /** + * Create a value symbol builder. + * + * @param shape the shape that the type is for. + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder( + Shape shape, + String typeName, + GoDependency namespace + ) { + return setImportedNamespace( + createValueSymbolBuilder(shape, typeName), + namespace + ); + } + + /** + * Create a pointable symbol builder. + * + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createPointableSymbolBuilder( + String typeName, + GoDependency namespace + ) { + return setImportedNamespace( + createPointableSymbolBuilder(typeName), + namespace + ); + } + + /** + * Create a value symbol builder. + * + * @param typeName the name of the type. + * @param namespace the namespace of the type. + * @return the symbol builder. + */ + public static Symbol.Builder createValueSymbolBuilder( + String typeName, + GoDependency namespace + ) { + return setImportedNamespace(createValueSymbolBuilder(typeName), namespace); + } + + private static Symbol.Builder setImportedNamespace( + Symbol.Builder builder, + GoDependency dependency + ) { + return builder + .namespace(dependency.getImportPath(), ".") + .addDependency(dependency) + .putProperty(NAMESPACE_ALIAS, dependency.getAlias()); + } + + /** + * Go declares several built-in language types in what is known as the Universe block. This function determines + * whether the provided symbol represents a Go universe type. + * + * @param symbol the symbol to check + * @return whether the symbol type is in the Go universe block + * @see The Go Programming Language Specification + */ + public static boolean isUniverseType(Symbol symbol) { + return symbol + .getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class) + .orElse(false); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolVisitor.java index 7bd6ee95ff..d23cbda14f 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/SymbolVisitor.java @@ -15,6 +15,10 @@ package software.amazon.polymorph.smithygo.codegen; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.logging.Logger; import software.amazon.polymorph.smithygo.codegen.knowledge.GoPointableIndex; import software.amazon.polymorph.smithygo.localservice.nameresolver.SmithyNameResolver; import software.amazon.polymorph.traits.ReferenceTrait; @@ -61,11 +65,6 @@ import software.amazon.smithy.model.traits.StreamingTrait; import software.amazon.smithy.utils.StringUtils; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.logging.Logger; - /** * Responsible for type mapping and file/identifier formatting. * @@ -73,449 +72,593 @@ * suffixed with "_". See "reserved-words.txt" for the list of words. */ public class SymbolVisitor implements SymbolProvider, ShapeVisitor { - private static final Logger LOGGER = Logger.getLogger(SymbolVisitor.class.getName()); - - private final Model model; - private final String rootModuleName; - private final ReservedWordSymbolProvider.Escaper escaper; - private final ReservedWordSymbolProvider.Escaper errorMemberEscaper; - private final Map structureSpecificMemberEscapers = new HashMap<>(); - private final GoPointableIndex pointableIndex; - private final GoSettings settings; - - public SymbolVisitor(Model model, GoSettings settings) { - this.model = model; - this.settings = settings; - this.rootModuleName = SmithyNameResolver.shapeNamespace(settings.getService(model)); - this.pointableIndex = GoPointableIndex.of(model); - - // Reserve the generated names for union members, including the unknown case. - ReservedWordsBuilder reservedNames = new ReservedWordsBuilder(); - reserveUnionMemberNames(model, reservedNames); - - ReservedWords reservedMembers = new ReservedWordsBuilder() - // Since Go only exports names if the first character is upper case and all - // the go reserved words are lower case, it's functionally impossible to conflict, - // so we only need to protect against common names. As of now there's only one. - .put("String", "String_") - .put("GetStream", "GetStream_") - .build(); - - model.shapes(StructureShape.class) - .filter(this::supportsInheritance) - .forEach(this::reserveInterfaceMemberAccessors); - - escaper = ReservedWordSymbolProvider.builder() - .nameReservedWords(reservedNames.build()) - .memberReservedWords(reservedMembers) - // Only escape words when the symbol has a definition file to - // prevent escaping intentional references to built-in types. - .escapePredicate((shape, symbol) -> !StringUtils.isEmpty(symbol.getDefinitionFile())) - .buildEscaper(); - - // Reserved words that only apply to error members. - ReservedWords reservedErrorMembers = new ReservedWordsBuilder() - .put("ErrorCode", "ErrorCode_") - .put("ErrorMessage", "ErrorMessage_") - .put("ErrorFault", "ErrorFault_") - .put("Unwrap", "Unwrap_") - .put("Error", "Error_") - .put("ErrorCodeOverride", "ErrorCodeOverride_") - .build(); - - errorMemberEscaper = ReservedWordSymbolProvider.builder() - .memberReservedWords(ReservedWords.compose(reservedMembers, reservedErrorMembers)) - .escapePredicate((shape, symbol) -> !StringUtils.isEmpty(symbol.getDefinitionFile())) - .buildEscaper(); - } - - /** - * Reserves generated member names for unions. - * - *

These have the format {UnionName}Member{MemberName}. - * - * @param model The model whose unions should be reserved. - * @param builder A reserved words builder to add on to. - */ - private void reserveUnionMemberNames(Model model, ReservedWordsBuilder builder) { - model.shapes(UnionShape.class).forEach(union -> { - for (MemberShape member : union.getAllMembers().values()) { - String memberName = formatUnionMemberName(union, member); - builder.put(memberName, escapeWithTrailingUnderscore(memberName)); - } - }); - } - - private boolean supportsInheritance(Shape shape) { - return shape.isStructureShape() && shape.hasTrait(ErrorTrait.class); - } - - /** - * Reserves Get* and Has* member names for the given structure for use as accessor methods. - * - *

These reservations will only apply to the given structure, not to other structures. - * - * @param shape The structure shape whose members should be reserved. - */ - private void reserveInterfaceMemberAccessors(StructureShape shape) { - ReservedWordsBuilder builder = new ReservedWordsBuilder(); - for (MemberShape member : shape.getAllMembers().values()) { - String name = getDefaultMemberName(member); - String getterName = "Get" + name; - String haserName = "Has" + name; - builder.put(getterName, escapeWithTrailingUnderscore(getterName)); - builder.put(haserName, escapeWithTrailingUnderscore(haserName)); - } - ReservedWordSymbolProvider.Escaper structureSpecificMemberEscaper = ReservedWordSymbolProvider.builder() - .memberReservedWords(builder.build()) - .buildEscaper(); - structureSpecificMemberEscapers.put(shape.getId(), structureSpecificMemberEscaper); - } - - private String escapeWithTrailingUnderscore(String symbolName) { - return symbolName + "_"; - } - - @Override - public Symbol toSymbol(Shape shape) { - Symbol symbol = shape.accept(this); - LOGGER.fine(() -> String.format("Creating symbol from %s: %s", shape, symbol)); - return linkArchetypeShape(shape, escaper.escapeSymbol(shape, symbol)); - } - - /** - * Links the archetype shape id for the symbol. - * - * @param shape the model shape - * @param symbol the symbol to set the archetype property on - * @return the symbol with archetype set if shape is a synthetic clone otherwise the original symbol - */ - private Symbol linkArchetypeShape(Shape shape, Symbol symbol) { - return shape.getTrait(Synthetic.class) - .map(synthetic -> symbol.toBuilder() - .putProperty("archetype", synthetic.getArchetype()) - .build()) - .orElse(symbol); - } - - @Override - public String toMemberName(MemberShape shape) { - Shape container = model.expectShape(shape.getContainer()); - if (container.isUnionShape()) { - // Union member names are not escaped as they are used to build the escape set. - return formatUnionMemberName(container.asUnionShape().get(), shape); - } - - String memberName = getDefaultMemberName(shape); - memberName = escaper.escapeMemberName(memberName); - - // Escape words reserved for the specific container. - if (structureSpecificMemberEscapers.containsKey(shape.getContainer())) { - memberName = structureSpecificMemberEscapers.get(shape.getContainer()).escapeMemberName(memberName); - } - - // Escape words that are only reserved for error members. - if (isErrorMember(shape)) { - memberName = errorMemberEscaper.escapeMemberName(memberName); - } - return memberName; - } - - private String formatUnionMemberName(UnionShape union, MemberShape member) { - return String.format("%sMember%s", getDefaultShapeName(union), getDefaultMemberName(member)); - } - - private String getDefaultShapeName(Shape shape) { - ServiceShape serviceShape = model.expectShape(settings.getService(), ServiceShape.class); - return StringUtils.capitalize(removeLeadingInvalidIdentCharacters(shape.getId().getName(serviceShape))); - } - - private String getDefaultMemberName(MemberShape shape) { - String memberName = StringUtils.capitalize(removeLeadingInvalidIdentCharacters(shape.getMemberName())); - - return memberName; - } - - private String removeLeadingInvalidIdentCharacters(String value) { - if (Character.isAlphabetic(value.charAt(0))) { - return value; - } - - int i; - for (i = 0; i < value.length(); i++) { - if (Character.isAlphabetic(value.charAt(i))) { - break; - } - } - - String remaining = value.substring(i); - if (remaining.length() == 0) { - throw new CodegenException("tried to clean name " + value + ", but resulted in empty string"); - } - - return remaining; - } - - - private boolean isErrorMember(MemberShape shape) { - return model.getShape(shape.getContainer()) - .map(container -> container.hasTrait(ErrorTrait.ID)) - .orElse(false); - } - - @Override - public Symbol blobShape(BlobShape shape) { - if (shape.hasTrait(StreamingTrait.ID)) { - Symbol inputVariant = symbolBuilderFor(shape, "Reader", SmithyGoDependency.IO).build(); - return symbolBuilderFor(shape, "ReadCloser", SmithyGoDependency.IO) - .putProperty(SymbolUtils.INPUT_VARIANT, inputVariant) - .build(); - } - return symbolBuilderFor(shape, "[]byte") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol booleanShape(BooleanShape shape) { - return symbolBuilderFor(shape, "bool") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol listShape(ListShape shape) { - return createCollectionSymbol(shape); - } - - @Override - public Symbol setShape(SetShape shape) { - // Go doesn't have a set type. Rather than hack together a set using a map, - // we instead just create a list and let the service be responsible for - // asserting that there are no duplicates. - return createCollectionSymbol(shape); - } - - private Symbol createCollectionSymbol(CollectionShape shape) { - Symbol reference = toSymbol(shape.getMember()); - // Shape name will be unused for symbols that represent a slice, but in the event it does we set the collection - // shape's name to make debugging simpler. - return symbolBuilderFor(shape, getDefaultShapeName(shape)) - .putProperty(SymbolUtils.GO_SLICE, true) - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, - reference.getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class).orElse(false)) - .putProperty(SymbolUtils.GO_ELEMENT_TYPE, reference) - .build(); - } - - @Override - public Symbol mapShape(MapShape shape) { - Symbol reference = toSymbol(shape.getValue()); - // Shape name will be unused for symbols that represent a map, but in the event it does we set the map shape's - // name to make debugging simpler. - return symbolBuilderFor(shape, getDefaultShapeName(shape)) - .putProperty(SymbolUtils.GO_MAP, true) - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, - reference.getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class).orElse(false)) - .putProperty(SymbolUtils.GO_ELEMENT_TYPE, reference) - .build(); - } - - private Symbol.Builder symbolBuilderFor(Shape shape, String typeName) { - if (pointableIndex.isPointable(shape)) { - return SymbolUtils.createPointableSymbolBuilder(shape, typeName, SmithyNameResolver.smithyTypesNamespace(shape)); - } - - return SymbolUtils.createValueSymbolBuilder(shape, typeName, SmithyNameResolver.smithyTypesNamespace(shape)); - } - - private Symbol.Builder symbolBuilderFor(Shape shape, String typeName, GoDependency namespace) { - if (pointableIndex.isPointable(shape)) { - return SymbolUtils.createPointableSymbolBuilder(shape, typeName, namespace); - } - - return SymbolUtils.createValueSymbolBuilder(shape, typeName, namespace); - } - private Symbol.Builder symbolBuilderFor(Shape shape, String typeName, String namespace) { - if (pointableIndex.isPointable(shape)) { - return SymbolUtils.createPointableSymbolBuilder(shape, typeName, namespace); + private static final Logger LOGGER = Logger.getLogger( + SymbolVisitor.class.getName() + ); + + private final Model model; + private final String rootModuleName; + private final ReservedWordSymbolProvider.Escaper escaper; + private final ReservedWordSymbolProvider.Escaper errorMemberEscaper; + private final Map< + ShapeId, + ReservedWordSymbolProvider.Escaper + > structureSpecificMemberEscapers = new HashMap<>(); + private final GoPointableIndex pointableIndex; + private final GoSettings settings; + + public SymbolVisitor(Model model, GoSettings settings) { + this.model = model; + this.settings = settings; + this.rootModuleName = + SmithyNameResolver.shapeNamespace(settings.getService(model)); + this.pointableIndex = GoPointableIndex.of(model); + + // Reserve the generated names for union members, including the unknown case. + ReservedWordsBuilder reservedNames = new ReservedWordsBuilder(); + reserveUnionMemberNames(model, reservedNames); + + ReservedWords reservedMembers = new ReservedWordsBuilder() + // Since Go only exports names if the first character is upper case and all + // the go reserved words are lower case, it's functionally impossible to conflict, + // so we only need to protect against common names. As of now there's only one. + .put("String", "String_") + .put("GetStream", "GetStream_") + .build(); + + model + .shapes(StructureShape.class) + .filter(this::supportsInheritance) + .forEach(this::reserveInterfaceMemberAccessors); + + escaper = + ReservedWordSymbolProvider + .builder() + .nameReservedWords(reservedNames.build()) + .memberReservedWords(reservedMembers) + // Only escape words when the symbol has a definition file to + // prevent escaping intentional references to built-in types. + .escapePredicate((shape, symbol) -> + !StringUtils.isEmpty(symbol.getDefinitionFile()) + ) + .buildEscaper(); + + // Reserved words that only apply to error members. + ReservedWords reservedErrorMembers = new ReservedWordsBuilder() + .put("ErrorCode", "ErrorCode_") + .put("ErrorMessage", "ErrorMessage_") + .put("ErrorFault", "ErrorFault_") + .put("Unwrap", "Unwrap_") + .put("Error", "Error_") + .put("ErrorCodeOverride", "ErrorCodeOverride_") + .build(); + + errorMemberEscaper = + ReservedWordSymbolProvider + .builder() + .memberReservedWords( + ReservedWords.compose(reservedMembers, reservedErrorMembers) + ) + .escapePredicate((shape, symbol) -> + !StringUtils.isEmpty(symbol.getDefinitionFile()) + ) + .buildEscaper(); + } + + /** + * Reserves generated member names for unions. + * + *

These have the format {UnionName}Member{MemberName}. + * + * @param model The model whose unions should be reserved. + * @param builder A reserved words builder to add on to. + */ + private void reserveUnionMemberNames( + Model model, + ReservedWordsBuilder builder + ) { + model + .shapes(UnionShape.class) + .forEach(union -> { + for (MemberShape member : union.getAllMembers().values()) { + String memberName = formatUnionMemberName(union, member); + builder.put(memberName, escapeWithTrailingUnderscore(memberName)); } - - return SymbolUtils.createValueSymbolBuilder(shape, typeName, namespace); - } - - @Override - public Symbol byteShape(ByteShape shape) { - return symbolBuilderFor(shape, "int8") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol shortShape(ShortShape shape) { - return symbolBuilderFor(shape, "int16") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol integerShape(IntegerShape shape) { - return symbolBuilderFor(shape, "int32") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol longShape(LongShape shape) { - return symbolBuilderFor(shape, "int64") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol floatShape(FloatShape shape) { - return symbolBuilderFor(shape, "float32") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol documentShape(DocumentShape shape) { - return null; - } - - @Override - public Symbol doubleShape(DoubleShape shape) { - return symbolBuilderFor(shape, "float64") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol bigIntegerShape(BigIntegerShape shape) { - return createBigSymbol(shape, "Int"); - } - - @Override - public Symbol bigDecimalShape(BigDecimalShape shape) { - - return createBigSymbol(shape, "Float"); - } - - private Symbol createBigSymbol(Shape shape, String symbolName) { - return symbolBuilderFor(shape, symbolName, SmithyGoDependency.BIG) - .build(); - } - - @Override - public Symbol operationShape(OperationShape shape) { - String name = getDefaultShapeName(shape); - return SymbolUtils.createPointableSymbolBuilder(shape, name, rootModuleName) - .definitionFile(String.format("./api_op_%s.go", name)) - .addDependency("./types", "./types") - .build(); - } - - @Override - public Symbol resourceShape(ResourceShape shape) { - // TODO: implement resources - return SymbolUtils.createPointableSymbolBuilder(shape, "nil").build(); - } - - @Override - public Symbol serviceShape(ServiceShape shape) { - return symbolBuilderFor(shape, "Client", rootModuleName) - .definitionFile("./%s/api_client.go".formatted(SmithyNameResolver.shapeNamespace(shape))) - .build(); - } - - @Override - public Symbol stringShape(StringShape shape) { - if (shape.hasTrait(EnumTrait.class)) { - String name = getDefaultShapeName(shape); - return symbolBuilderFor(shape, name, SmithyNameResolver.smithyTypesNamespace(settings.getService(model))) - .definitionFile("./%s/enums.go".formatted(SmithyNameResolver.smithyTypesNamespace(shape))) - .build(); - } - - return symbolBuilderFor(shape, "string") - .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) - .build(); - } - - @Override - public Symbol structureShape(StructureShape shape) { - String name = getDefaultShapeName(shape); - if (shape.getId().getNamespace().equals(CodegenUtils.getSyntheticTypeNamespace())) { - Optional boundOperationName = getNameOfBoundOperation(shape); - if (boundOperationName.isPresent()) { - return symbolBuilderFor(shape, name, rootModuleName) - .definitionFile("./api_op_" + boundOperationName.get() + ".go") - .build(); - } - } - Symbol.Builder builder = symbolBuilderFor(shape, name); - if (shape.hasTrait(ErrorTrait.ID)) { - builder.definitionFile("./%s/errors.go".formatted(SmithyNameResolver.smithyTypesNamespace(shape))); - } else { - builder.definitionFile("./%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(shape))); - } - - if (shape.hasTrait(ReferenceTrait.class)) { - var referredShape = model.expectShape(shape.expectTrait(ReferenceTrait.class).getReferentId()); - var isService = shape.expectTrait(ReferenceTrait.class).isService(); - if (isService) { - builder.putProperty("Referred", symbolBuilderFor(referredShape, "Client", SmithyNameResolver.shapeNamespace(referredShape)) - .putProperty(SymbolUtils.POINTABLE, true).build()); - } else { - builder.putProperty("Referred", symbolBuilderFor(referredShape, "I".concat(getDefaultShapeName(referredShape))) - .putProperty(SymbolUtils.POINTABLE, false).build()); - } - - } - - return builder.build(); - } - - private Optional getNameOfBoundOperation(StructureShape shape) { - NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); - for (Relationship relationship : provider.getNeighbors(shape)) { - RelationshipType relationshipType = relationship.getRelationshipType(); - if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { - return Optional.of(getDefaultShapeName(relationship.getNeighborShape().get())); - } - } - return Optional.empty(); - } - - @Override - public Symbol unionShape(UnionShape shape) { - String name = getDefaultShapeName(shape); - return symbolBuilderFor(shape, name, SmithyNameResolver.smithyTypesNamespace(settings.getService(model))) - .definitionFile("./types/types.go") - .build(); - } - - @Override - public Symbol memberShape(MemberShape member) { - Shape targetShape = model.expectShape(member.getTarget()); - return toSymbol(targetShape) - .toBuilder() - .putProperty(SymbolUtils.POINTABLE, pointableIndex.isPointable(member)) - .build(); - } - - @Override - public Symbol timestampShape(TimestampShape shape) { - return symbolBuilderFor(shape, "Time", SmithyGoDependency.TIME).build(); - } - - @Override - public Symbol intEnumShape(IntEnumShape shape) { - String name = getDefaultShapeName(shape); - return symbolBuilderFor(shape, name, SmithyNameResolver.smithyTypesNamespace(settings.getService(model))) - .definitionFile("./%s/enums.go".formatted(SmithyNameResolver.smithyTypesNamespace(shape))) - .build(); - } + }); + } + + private boolean supportsInheritance(Shape shape) { + return shape.isStructureShape() && shape.hasTrait(ErrorTrait.class); + } + + /** + * Reserves Get* and Has* member names for the given structure for use as accessor methods. + * + *

These reservations will only apply to the given structure, not to other structures. + * + * @param shape The structure shape whose members should be reserved. + */ + private void reserveInterfaceMemberAccessors(StructureShape shape) { + ReservedWordsBuilder builder = new ReservedWordsBuilder(); + for (MemberShape member : shape.getAllMembers().values()) { + String name = getDefaultMemberName(member); + String getterName = "Get" + name; + String haserName = "Has" + name; + builder.put(getterName, escapeWithTrailingUnderscore(getterName)); + builder.put(haserName, escapeWithTrailingUnderscore(haserName)); + } + ReservedWordSymbolProvider.Escaper structureSpecificMemberEscaper = + ReservedWordSymbolProvider + .builder() + .memberReservedWords(builder.build()) + .buildEscaper(); + structureSpecificMemberEscapers.put( + shape.getId(), + structureSpecificMemberEscaper + ); + } + + private String escapeWithTrailingUnderscore(String symbolName) { + return symbolName + "_"; + } + + @Override + public Symbol toSymbol(Shape shape) { + Symbol symbol = shape.accept(this); + LOGGER.fine(() -> + String.format("Creating symbol from %s: %s", shape, symbol) + ); + return linkArchetypeShape(shape, escaper.escapeSymbol(shape, symbol)); + } + + /** + * Links the archetype shape id for the symbol. + * + * @param shape the model shape + * @param symbol the symbol to set the archetype property on + * @return the symbol with archetype set if shape is a synthetic clone otherwise the original symbol + */ + private Symbol linkArchetypeShape(Shape shape, Symbol symbol) { + return shape + .getTrait(Synthetic.class) + .map(synthetic -> + symbol + .toBuilder() + .putProperty("archetype", synthetic.getArchetype()) + .build() + ) + .orElse(symbol); + } + + @Override + public String toMemberName(MemberShape shape) { + Shape container = model.expectShape(shape.getContainer()); + if (container.isUnionShape()) { + // Union member names are not escaped as they are used to build the escape set. + return formatUnionMemberName(container.asUnionShape().get(), shape); + } + + String memberName = getDefaultMemberName(shape); + memberName = escaper.escapeMemberName(memberName); + + // Escape words reserved for the specific container. + if (structureSpecificMemberEscapers.containsKey(shape.getContainer())) { + memberName = + structureSpecificMemberEscapers + .get(shape.getContainer()) + .escapeMemberName(memberName); + } + + // Escape words that are only reserved for error members. + if (isErrorMember(shape)) { + memberName = errorMemberEscaper.escapeMemberName(memberName); + } + return memberName; + } + + private String formatUnionMemberName(UnionShape union, MemberShape member) { + return String.format( + "%sMember%s", + getDefaultShapeName(union), + getDefaultMemberName(member) + ); + } + + private String getDefaultShapeName(Shape shape) { + ServiceShape serviceShape = model.expectShape( + settings.getService(), + ServiceShape.class + ); + return StringUtils.capitalize( + removeLeadingInvalidIdentCharacters(shape.getId().getName(serviceShape)) + ); + } + + private String getDefaultMemberName(MemberShape shape) { + String memberName = StringUtils.capitalize( + removeLeadingInvalidIdentCharacters(shape.getMemberName()) + ); + + return memberName; + } + + private String removeLeadingInvalidIdentCharacters(String value) { + if (Character.isAlphabetic(value.charAt(0))) { + return value; + } + + int i; + for (i = 0; i < value.length(); i++) { + if (Character.isAlphabetic(value.charAt(i))) { + break; + } + } + + String remaining = value.substring(i); + if (remaining.length() == 0) { + throw new CodegenException( + "tried to clean name " + value + ", but resulted in empty string" + ); + } + + return remaining; + } + + private boolean isErrorMember(MemberShape shape) { + return model + .getShape(shape.getContainer()) + .map(container -> container.hasTrait(ErrorTrait.ID)) + .orElse(false); + } + + @Override + public Symbol blobShape(BlobShape shape) { + if (shape.hasTrait(StreamingTrait.ID)) { + Symbol inputVariant = symbolBuilderFor( + shape, + "Reader", + SmithyGoDependency.IO + ) + .build(); + return symbolBuilderFor(shape, "ReadCloser", SmithyGoDependency.IO) + .putProperty(SymbolUtils.INPUT_VARIANT, inputVariant) + .build(); + } + return symbolBuilderFor(shape, "[]byte") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol booleanShape(BooleanShape shape) { + return symbolBuilderFor(shape, "bool") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol listShape(ListShape shape) { + return createCollectionSymbol(shape); + } + + @Override + public Symbol setShape(SetShape shape) { + // Go doesn't have a set type. Rather than hack together a set using a map, + // we instead just create a list and let the service be responsible for + // asserting that there are no duplicates. + return createCollectionSymbol(shape); + } + + private Symbol createCollectionSymbol(CollectionShape shape) { + Symbol reference = toSymbol(shape.getMember()); + // Shape name will be unused for symbols that represent a slice, but in the event it does we set the collection + // shape's name to make debugging simpler. + return symbolBuilderFor(shape, getDefaultShapeName(shape)) + .putProperty(SymbolUtils.GO_SLICE, true) + .putProperty( + SymbolUtils.GO_UNIVERSE_TYPE, + reference + .getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class) + .orElse(false) + ) + .putProperty(SymbolUtils.GO_ELEMENT_TYPE, reference) + .build(); + } + + @Override + public Symbol mapShape(MapShape shape) { + Symbol reference = toSymbol(shape.getValue()); + // Shape name will be unused for symbols that represent a map, but in the event it does we set the map shape's + // name to make debugging simpler. + return symbolBuilderFor(shape, getDefaultShapeName(shape)) + .putProperty(SymbolUtils.GO_MAP, true) + .putProperty( + SymbolUtils.GO_UNIVERSE_TYPE, + reference + .getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class) + .orElse(false) + ) + .putProperty(SymbolUtils.GO_ELEMENT_TYPE, reference) + .build(); + } + + private Symbol.Builder symbolBuilderFor(Shape shape, String typeName) { + if (pointableIndex.isPointable(shape)) { + return SymbolUtils.createPointableSymbolBuilder( + shape, + typeName, + SmithyNameResolver.smithyTypesNamespace(shape) + ); + } + + return SymbolUtils.createValueSymbolBuilder( + shape, + typeName, + SmithyNameResolver.smithyTypesNamespace(shape) + ); + } + + private Symbol.Builder symbolBuilderFor( + Shape shape, + String typeName, + GoDependency namespace + ) { + if (pointableIndex.isPointable(shape)) { + return SymbolUtils.createPointableSymbolBuilder( + shape, + typeName, + namespace + ); + } + + return SymbolUtils.createValueSymbolBuilder(shape, typeName, namespace); + } + + private Symbol.Builder symbolBuilderFor( + Shape shape, + String typeName, + String namespace + ) { + if (pointableIndex.isPointable(shape)) { + return SymbolUtils.createPointableSymbolBuilder( + shape, + typeName, + namespace + ); + } + + return SymbolUtils.createValueSymbolBuilder(shape, typeName, namespace); + } + + @Override + public Symbol byteShape(ByteShape shape) { + return symbolBuilderFor(shape, "int8") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol shortShape(ShortShape shape) { + return symbolBuilderFor(shape, "int16") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol integerShape(IntegerShape shape) { + return symbolBuilderFor(shape, "int32") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol longShape(LongShape shape) { + return symbolBuilderFor(shape, "int64") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol floatShape(FloatShape shape) { + return symbolBuilderFor(shape, "float32") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol documentShape(DocumentShape shape) { + return null; + } + + @Override + public Symbol doubleShape(DoubleShape shape) { + return symbolBuilderFor(shape, "float64") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol bigIntegerShape(BigIntegerShape shape) { + return createBigSymbol(shape, "Int"); + } + + @Override + public Symbol bigDecimalShape(BigDecimalShape shape) { + return createBigSymbol(shape, "Float"); + } + + private Symbol createBigSymbol(Shape shape, String symbolName) { + return symbolBuilderFor(shape, symbolName, SmithyGoDependency.BIG).build(); + } + + @Override + public Symbol operationShape(OperationShape shape) { + String name = getDefaultShapeName(shape); + return SymbolUtils + .createPointableSymbolBuilder(shape, name, rootModuleName) + .definitionFile(String.format("./api_op_%s.go", name)) + .addDependency("./types", "./types") + .build(); + } + + @Override + public Symbol resourceShape(ResourceShape shape) { + // TODO: implement resources + return SymbolUtils.createPointableSymbolBuilder(shape, "nil").build(); + } + + @Override + public Symbol serviceShape(ServiceShape shape) { + return symbolBuilderFor(shape, "Client", rootModuleName) + .definitionFile( + "./%s/api_client.go".formatted(SmithyNameResolver.shapeNamespace(shape)) + ) + .build(); + } + + @Override + public Symbol stringShape(StringShape shape) { + if (shape.hasTrait(EnumTrait.class)) { + String name = getDefaultShapeName(shape); + return symbolBuilderFor( + shape, + name, + SmithyNameResolver.smithyTypesNamespace(settings.getService(model)) + ) + .definitionFile( + "./%s/enums.go".formatted( + SmithyNameResolver.smithyTypesNamespace(shape) + ) + ) + .build(); + } + + return symbolBuilderFor(shape, "string") + .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) + .build(); + } + + @Override + public Symbol structureShape(StructureShape shape) { + String name = getDefaultShapeName(shape); + if ( + shape + .getId() + .getNamespace() + .equals(CodegenUtils.getSyntheticTypeNamespace()) + ) { + Optional boundOperationName = getNameOfBoundOperation(shape); + if (boundOperationName.isPresent()) { + return symbolBuilderFor(shape, name, rootModuleName) + .definitionFile("./api_op_" + boundOperationName.get() + ".go") + .build(); + } + } + Symbol.Builder builder = symbolBuilderFor(shape, name); + if (shape.hasTrait(ErrorTrait.ID)) { + builder.definitionFile( + "./%s/errors.go".formatted( + SmithyNameResolver.smithyTypesNamespace(shape) + ) + ); + } else { + builder.definitionFile( + "./%s/types.go".formatted( + SmithyNameResolver.smithyTypesNamespace(shape) + ) + ); + } + + if (shape.hasTrait(ReferenceTrait.class)) { + var referredShape = model.expectShape( + shape.expectTrait(ReferenceTrait.class).getReferentId() + ); + var isService = shape.expectTrait(ReferenceTrait.class).isService(); + if (isService) { + builder.putProperty( + "Referred", + symbolBuilderFor( + referredShape, + "Client", + SmithyNameResolver.shapeNamespace(referredShape) + ) + .putProperty(SymbolUtils.POINTABLE, true) + .build() + ); + } else { + builder.putProperty( + "Referred", + symbolBuilderFor( + referredShape, + "I".concat(getDefaultShapeName(referredShape)) + ) + .putProperty(SymbolUtils.POINTABLE, false) + .build() + ); + } + } + + return builder.build(); + } + + private Optional getNameOfBoundOperation(StructureShape shape) { + NeighborProvider provider = NeighborProviderIndex + .of(model) + .getReverseProvider(); + for (Relationship relationship : provider.getNeighbors(shape)) { + RelationshipType relationshipType = relationship.getRelationshipType(); + if ( + relationshipType == RelationshipType.INPUT || + relationshipType == RelationshipType.OUTPUT + ) { + return Optional.of( + getDefaultShapeName(relationship.getNeighborShape().get()) + ); + } + } + return Optional.empty(); + } + + @Override + public Symbol unionShape(UnionShape shape) { + String name = getDefaultShapeName(shape); + return symbolBuilderFor( + shape, + name, + SmithyNameResolver.smithyTypesNamespace(settings.getService(model)) + ) + .definitionFile("./types/types.go") + .build(); + } + + @Override + public Symbol memberShape(MemberShape member) { + Shape targetShape = model.expectShape(member.getTarget()); + return toSymbol(targetShape) + .toBuilder() + .putProperty(SymbolUtils.POINTABLE, pointableIndex.isPointable(member)) + .build(); + } + + @Override + public Symbol timestampShape(TimestampShape shape) { + return symbolBuilderFor(shape, "Time", SmithyGoDependency.TIME).build(); + } + + @Override + public Symbol intEnumShape(IntEnumShape shape) { + String name = getDefaultShapeName(shape); + return symbolBuilderFor( + shape, + name, + SmithyNameResolver.smithyTypesNamespace(settings.getService(model)) + ) + .definitionFile( + "./%s/enums.go".formatted( + SmithyNameResolver.smithyTypesNamespace(shape) + ) + ) + .build(); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/Synthetic.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/Synthetic.java index 5a762dd69b..e71f52778b 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/Synthetic.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/Synthetic.java @@ -15,6 +15,7 @@ package software.amazon.polymorph.smithygo.codegen; +import java.util.Optional; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.shapes.ShapeId; @@ -23,95 +24,106 @@ import software.amazon.smithy.utils.SmithyBuilder; import software.amazon.smithy.utils.ToSmithyBuilder; -import java.util.Optional; - /** * Defines a shape as being a clone of another modeled shape. *

* Must only be used as a runtime trait-only applied to shapes based on model processing */ -public final class Synthetic extends AbstractTrait implements ToSmithyBuilder { - public static final ShapeId ID = ShapeId.from("smithy.go.traits#Synthetic"); - - private static final String ARCHETYPE = "archetype"; - - private final Optional archetype; - - private Synthetic(Builder builder) { - super(ID, builder.getSourceLocation()); - this.archetype = builder.archetype; - } - - /** - * Get the archetype shape that this clone is based on. - * - * @return the original archetype shape - */ - public Optional getArchetype() { - return archetype; - } - - @Override - protected Node createNode() { - throw new CodegenException("attempted to serialize runtime only trait"); - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } else if (!(other instanceof Synthetic)) { - return false; - } else { - Synthetic b = (Synthetic) other; - return toShapeId().equals(b.toShapeId()) && archetype.equals(b.getArchetype()); - } +public final class Synthetic + extends AbstractTrait + implements ToSmithyBuilder { + + public static final ShapeId ID = ShapeId.from("smithy.go.traits#Synthetic"); + + private static final String ARCHETYPE = "archetype"; + + private final Optional archetype; + + private Synthetic(Builder builder) { + super(ID, builder.getSourceLocation()); + this.archetype = builder.archetype; + } + + /** + * Get the archetype shape that this clone is based on. + * + * @return the original archetype shape + */ + public Optional getArchetype() { + return archetype; + } + + @Override + protected Node createNode() { + throw new CodegenException("attempted to serialize runtime only trait"); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } else if (!(other instanceof Synthetic)) { + return false; + } else { + Synthetic b = (Synthetic) other; + return ( + toShapeId().equals(b.toShapeId()) && archetype.equals(b.getArchetype()) + ); } + } + + @Override + public int hashCode() { + return ( + toShapeId().hashCode() * 17 + + Node + .objectNode() + .withOptionalMember( + ARCHETYPE, + archetype.map(ShapeId::toString).map(Node::from) + ) + .hashCode() + ); + } + + @Override + public SmithyBuilder toBuilder() { + Builder builder = builder(); + getArchetype().ifPresent(builder::archetype); + + return builder; + } + + /** + * @return Returns a builder used to create {@link Synthetic}. + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Builder for {@link Synthetic}. + */ + public static final class Builder + extends AbstractTraitBuilder { + + private Optional archetype = Optional.empty(); + + private Builder() {} @Override - public int hashCode() { - return toShapeId().hashCode() * 17 + Node.objectNode() - .withOptionalMember(ARCHETYPE, archetype.map(ShapeId::toString).map(Node::from)) - .hashCode(); - } - - @Override - public SmithyBuilder toBuilder() { - Builder builder = builder(); - getArchetype().ifPresent(builder::archetype); - - return builder; + public Synthetic build() { + return new Synthetic(this); } - /** - * @return Returns a builder used to create {@link Synthetic}. - */ - public static Builder builder() { - return new Builder(); + public Builder archetype(ShapeId archetype) { + this.archetype = Optional.ofNullable(archetype); + return this; } - /** - * Builder for {@link Synthetic}. - */ - public static final class Builder extends AbstractTraitBuilder { - private Optional archetype = Optional.empty(); - - private Builder() { - } - - @Override - public Synthetic build() { - return new Synthetic(this); - } - - public Builder archetype(ShapeId archetype) { - this.archetype = Optional.ofNullable(archetype); - return this; - } - - public Builder removeArchetype() { - this.archetype = Optional.empty(); - return this; - } + public Builder removeArchetype() { + this.archetype = Optional.empty(); + return this; } + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/UnionGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/UnionGenerator.java index 68cfbbfb26..7d800dac15 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/UnionGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/UnionGenerator.java @@ -5,100 +5,137 @@ import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; - import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.MemberShape; +import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.SimpleShape; import software.amazon.smithy.model.shapes.UnionShape; -import software.amazon.smithy.model.traits.StreamingTrait; -import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.traits.ErrorTrait; +import software.amazon.smithy.model.traits.StreamingTrait; public class UnionGenerator { - public static final String UNKNOWN_MEMBER_NAME = "UnknownUnionMember"; - private final Model model; - private final SymbolProvider symbolProvider; - private final UnionShape shape; - private final boolean isEventStream; + public static final String UNKNOWN_MEMBER_NAME = "UnknownUnionMember"; - public UnionGenerator(Model model, SymbolProvider symbolProvider, UnionShape shape) { - this.model = model; - this.symbolProvider = symbolProvider; - this.shape = shape; - this.isEventStream = StreamingTrait.isEventStream(shape); - } + private final Model model; + private final SymbolProvider symbolProvider; + private final UnionShape shape; + private final boolean isEventStream; - /** - * Generates the Go type definitions for the UnionShape. - * - * @param writer the writer - */ - public void generateUnion(GoWriter writer) { - Symbol symbol = symbolProvider.toSymbol(shape); - Collection memberShapes = shape.getAllMembers().values() - .stream() - .filter(memberShape -> !isEventStreamErrorMember(memberShape)) - .collect(Collectors.toCollection(TreeSet::new)); + public UnionGenerator( + Model model, + SymbolProvider symbolProvider, + UnionShape shape + ) { + this.model = model; + this.symbolProvider = symbolProvider; + this.shape = shape; + this.isEventStream = StreamingTrait.isEventStream(shape); + } - memberShapes.stream().map(symbolProvider::toMemberName).forEach(name -> { - writer.write("// " + name); - }); - writer.openBlock("type $L interface {", "}", symbol.getName(), () -> { - writer.write("is$L()", symbol.getName()); - }).write(""); + /** + * Generates the Go type definitions for the UnionShape. + * + * @param writer the writer + */ + public void generateUnion(GoWriter writer) { + Symbol symbol = symbolProvider.toSymbol(shape); + Collection memberShapes = shape + .getAllMembers() + .values() + .stream() + .filter(memberShape -> !isEventStreamErrorMember(memberShape)) + .collect(Collectors.toCollection(TreeSet::new)); - // Create structs for each member that satisfy the interface. - for (MemberShape member : memberShapes) { - Symbol memberSymbol = symbolProvider.toSymbol(member); - String exportedMemberName = symbolProvider.toMemberName(member); - Shape target = model.expectShape(member.getTarget()); + memberShapes + .stream() + .map(symbolProvider::toMemberName) + .forEach(name -> { + writer.write("// " + name); + }); + writer + .openBlock( + "type $L interface {", + "}", + symbol.getName(), + () -> { + writer.write("is$L()", symbol.getName()); + } + ) + .write(""); - writer.openBlock("type $L struct {", "}", exportedMemberName, () -> { - // Union members can't have null values, so for simple shapes we don't - // use pointers. We have to use pointers for complex shapes since, - // for example, we could still have a map that's empty or which has - // null values. - if (target instanceof SimpleShape) { - writer.write("Value $T", memberSymbol); - } else { - writer.write("Value $P", memberSymbol); - } - writer.write(""); - }); + // Create structs for each member that satisfy the interface. + for (MemberShape member : memberShapes) { + Symbol memberSymbol = symbolProvider.toSymbol(member); + String exportedMemberName = symbolProvider.toMemberName(member); + Shape target = model.expectShape(member.getTarget()); - writer.write("func (*$L) is$L() {}", exportedMemberName, symbol.getName()); + writer.openBlock( + "type $L struct {", + "}", + exportedMemberName, + () -> { + // Union members can't have null values, so for simple shapes we don't + // use pointers. We have to use pointers for complex shapes since, + // for example, we could still have a map that's empty or which has + // null values. + if (target instanceof SimpleShape) { + writer.write("Value $T", memberSymbol); + } else { + writer.write("Value $P", memberSymbol); + } + writer.write(""); } - } + ); - private boolean isEventStreamErrorMember(MemberShape memberShape) { - return isEventStream && memberShape.getMemberTrait(model, ErrorTrait.class).isPresent(); + writer.write( + "func (*$L) is$L() {}", + exportedMemberName, + symbol.getName() + ); } + } - /** - * Generates a struct for unknown union values that applies to every union in the given set. - * - * @param writer The writer to write the union to. - * @param unions A set of unions whose interfaces the union should apply to. - * @param symbolProvider A symbol provider used to get the symbols for the unions. - */ - public static void generateUnknownUnion( - final GoWriter writer, - final Collection unions, - final SymbolProvider symbolProvider - ) { - writer.openBlock("type $L struct {", "}", UNKNOWN_MEMBER_NAME, () -> { - // The tag (member) name received over the wire. - writer.write("Tag string"); - // The value received. - writer.write("Value []byte"); - writer.write(""); - }); + private boolean isEventStreamErrorMember(MemberShape memberShape) { + return ( + isEventStream && + memberShape.getMemberTrait(model, ErrorTrait.class).isPresent() + ); + } - for (UnionShape union : unions) { - writer.write("func (*$L) is$L() {}", UNKNOWN_MEMBER_NAME, symbolProvider.toSymbol(union).getName()); - } + /** + * Generates a struct for unknown union values that applies to every union in the given set. + * + * @param writer The writer to write the union to. + * @param unions A set of unions whose interfaces the union should apply to. + * @param symbolProvider A symbol provider used to get the symbols for the unions. + */ + public static void generateUnknownUnion( + final GoWriter writer, + final Collection unions, + final SymbolProvider symbolProvider + ) { + writer.openBlock( + "type $L struct {", + "}", + UNKNOWN_MEMBER_NAME, + () -> { + // The tag (member) name received over the wire. + writer.write("Tag string"); + // The value received. + writer.write("Value []byte"); + writer.write(""); + } + ); + + for (UnionShape union : unions) { + writer.write( + "func (*$L) is$L() {}", + UNKNOWN_MEMBER_NAME, + symbolProvider.toSymbol(union).getName() + ); } + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ValidationGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ValidationGenerator.java index 9d8ddc14a4..13107c50a3 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ValidationGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/ValidationGenerator.java @@ -1,306 +1,395 @@ package software.amazon.polymorph.smithygo.codegen; +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + import java.math.BigDecimal; import java.util.Optional; - import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; import software.amazon.polymorph.traits.ReferenceTrait; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.Model; +import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.SimpleShape; -import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.traits.LengthTrait; import software.amazon.smithy.model.traits.RangeTrait; import software.amazon.smithy.model.traits.RequiredTrait; import software.amazon.smithy.model.traits.StreamingTrait; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - // Renders constraint validation public class ValidationGenerator { - private final Model model; - private final SymbolProvider symbolProvider; - private final GoWriter writer; - private final CodegenUtils.SortedMembers sortedMembers; - private static final String LIST_ITEM = "item"; - private static final String MAP_KEY = "key"; - private static final String MAP_VALUE = "value"; - private static final String UNION_DATASOURCE = "unionType.Value"; + private final Model model; + private final SymbolProvider symbolProvider; + private final GoWriter writer; + private final CodegenUtils.SortedMembers sortedMembers; + + private static final String LIST_ITEM = "item"; + private static final String MAP_KEY = "key"; + private static final String MAP_VALUE = "value"; + private static final String UNION_DATASOURCE = "unionType.Value"; + + public ValidationGenerator( + final Model model, + final SymbolProvider symbolProvider, + final GoWriter writer + ) { + this.model = model; + this.symbolProvider = symbolProvider; + this.writer = writer; + this.sortedMembers = new CodegenUtils.SortedMembers(symbolProvider); + } + + public void renderValidator( + final Shape shape, + final boolean isInputStructure + ) { + Symbol symbol = symbolProvider.toSymbol(shape); + writer.openBlock("func (input $L) Validate() (error) {", symbol.getName()); + renderValidatorHelper(shape, isInputStructure, "input"); + writer.write("return nil"); + writer.closeBlock("}").write(""); + } - public ValidationGenerator( - final Model model, - final SymbolProvider symbolProvider, - final GoWriter writer + private void renderValidatorHelper( + final Shape containerShape, + final boolean isInputStructure, + final String dataSource + ) { + containerShape + .getAllMembers() + .values() + .stream() + .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) + .sorted(sortedMembers) + .forEach(member -> { + String memberName; + if ( + containerShape.isListShape() || containerShape.isMapShape() + ) memberName = dataSource; else memberName = + dataSource + "." + symbolProvider.toMemberName(member); + renderValidatorForEachShape( + model.expectShape(member.getTarget()), + member, + isInputStructure, + memberName + ); + }); + } + + private void renderValidatorForEachShape( + final Shape currentShape, + final MemberShape memberShape, + final boolean isInputStructure, + final String dataSource + ) { + Symbol symbol = symbolProvider.toSymbol(currentShape); + if (isInputStructure) { + symbol = + symbol + .getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) + .orElse(symbol); + } + if (currentShape.hasTrait(ReferenceTrait.class)) { + symbol = symbol.getProperty("Referred", Symbol.class).get(); + } + String pointableString = ""; + if ( + !(dataSource.equals(LIST_ITEM) || + dataSource.equals(MAP_KEY) || + dataSource.equals(MAP_VALUE) || + (dataSource.equals(UNION_DATASOURCE) && + currentShape instanceof SimpleShape)) ) { - this.model = model; - this.symbolProvider = symbolProvider; - this.writer = writer; - this.sortedMembers = new CodegenUtils.SortedMembers(symbolProvider); + if ( + (boolean) symbol.getProperty(POINTABLE, Boolean.class).orElse(false) && + memberShape.isOptional() + ) { + pointableString = "*"; + } } - - public void renderValidator (final Shape shape, final boolean isInputStructure) { - Symbol symbol = symbolProvider.toSymbol(shape); - writer.openBlock("func (input $L) Validate() (error) {", symbol.getName()); - renderValidatorHelper( shape, isInputStructure, "input"); - writer.write("return nil"); - writer.closeBlock("}").write(""); + if (currentShape.hasTrait(RangeTrait.class)) { + addRangeCheck(currentShape, dataSource, pointableString); } - - private void renderValidatorHelper (final Shape containerShape, final boolean isInputStructure, final String dataSource) { - containerShape.getAllMembers().values().stream() - .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) - .sorted(sortedMembers) - .forEach((member) -> { - String memberName; - if (containerShape.isListShape() || containerShape.isMapShape()) - memberName = dataSource; - else - memberName = dataSource + "." + symbolProvider.toMemberName(member); - renderValidatorForEachShape(model.expectShape(member.getTarget()), member, isInputStructure, memberName); - }); + if (currentShape.hasTrait(LengthTrait.class)) { + addLengthCheck(currentShape, dataSource, pointableString); } - - private void renderValidatorForEachShape (final Shape currentShape, final MemberShape memberShape, final boolean isInputStructure, final String dataSource) { - Symbol symbol = symbolProvider.toSymbol(currentShape); - if (isInputStructure) { - symbol = symbol.getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) - .orElse(symbol); - } - if (currentShape.hasTrait(ReferenceTrait.class)) { - symbol = symbol.getProperty("Referred", Symbol.class).get(); - } - String pointableString = ""; - if (!(dataSource.equals(LIST_ITEM) || dataSource.equals(MAP_KEY) || dataSource.equals(MAP_VALUE) || dataSource.equals(UNION_DATASOURCE) && currentShape instanceof SimpleShape)) { - if ((boolean) symbol.getProperty(POINTABLE, Boolean.class).orElse(false) && memberShape.isOptional()){ - pointableString = "*"; - } - } - if (currentShape.hasTrait(RangeTrait.class)) { - addRangeCheck(currentShape, dataSource, pointableString); - } - if (currentShape.hasTrait(LengthTrait.class)) { - addLengthCheck(currentShape, dataSource, pointableString); - } - if (currentShape.hasTrait(RequiredTrait.class)) { - addRequiredCheck(symbol, currentShape, dataSource); - } - if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { - addUTFCheck(currentShape, dataSource, pointableString); - } - // Broke list and map into two different if else because for _, item := range %s looked good for list - // And for key, value := range %s looked good for map - if (currentShape.isListShape()) { - writer.write(""" - for _, %s := range %s { - // To avoid declared and not used error for shapes which does not need validation check - _ = item - """.formatted(LIST_ITEM, dataSource)); - renderValidatorHelper(currentShape, false, LIST_ITEM); - writer.write(""" - } - """); - } - else if (currentShape.isMapShape()) { - writer.write(""" - for %s, %s := range %s { - // To avoid declared and not used error for shapes which does not need validation check - _ = key - _ = value - """.formatted(MAP_KEY, MAP_VALUE, dataSource)); - renderValidatorHelper(currentShape, false, MAP_KEY); - renderValidatorHelper(currentShape, false, MAP_VALUE); - writer.write(""" - } - """); - } - else if (currentShape.isUnionShape()) { - writer.write(""" - switch unionType := %s.(type) { - """.formatted(dataSource)); - for (var memberInUnion : currentShape.getAllMembers().values()) { - writer.write(""" - case *%s: - """.formatted( - symbolProvider.toMemberName(memberInUnion) - )); - - renderValidatorForEachShape(model.expectShape(memberInUnion.getTarget()), memberInUnion, false, "unionType.Value"); - } - writer.write(""" - // Default case should not be reached. - default: - // To avoid used and not used error when nothing to validate - _ = unionType - panic("Unhandled union type") - } - """); - } - else { - renderValidatorHelper(currentShape, isInputStructure, dataSource); - } + if (currentShape.hasTrait(RequiredTrait.class)) { + addRequiredCheck(symbol, currentShape, dataSource); } - - private void addRangeCheck(final Shape currentShape, final String dataSource, final String pointableString) { - StringBuilder rangeCheck = new StringBuilder(); - RangeTrait rangeTraitShape = currentShape.expectTrait(RangeTrait.class); - Optional min = rangeTraitShape.getMin(); - Optional max = rangeTraitShape.getMax(); - if (pointableString.equals("*")){ - rangeCheck.append(""" - if (%s != nil) { - """.formatted(dataSource)); - } - if (min.isPresent()) { - rangeCheck.append(""" - if (%s%s < %s) { - return fmt.Errorf(\"%s has a minimum of %s but has the value of %%d.\", %s%s) - } - """.formatted( - pointableString, - dataSource, - min.get().toString(), - currentShape.getId().getName(), - min.get().toString(), - pointableString, - dataSource)); - } - if (max.isPresent()) { - rangeCheck.append(""" - if (%s%s > %s) { - return fmt.Errorf(\"%s has a maximum of %s but has the value of %%d.\", %s%s) - } - """.formatted( - pointableString, - dataSource, - max.get().toString(), - currentShape.getId().getName(), - max.get().toString(), - pointableString, - dataSource)); + if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { + addUTFCheck(currentShape, dataSource, pointableString); + } + // Broke list and map into two different if else because for _, item := range %s looked good for list + // And for key, value := range %s looked good for map + if (currentShape.isListShape()) { + writer.write( + """ + for _, %s := range %s { + // To avoid declared and not used error for shapes which does not need validation check + _ = item + """.formatted(LIST_ITEM, dataSource) + ); + renderValidatorHelper(currentShape, false, LIST_ITEM); + writer.write( + """ } - if (pointableString.equals("*")){ - rangeCheck.append(""" + """ + ); + } else if (currentShape.isMapShape()) { + writer.write( + """ + for %s, %s := range %s { + // To avoid declared and not used error for shapes which does not need validation check + _ = key + _ = value + """.formatted(MAP_KEY, MAP_VALUE, dataSource) + ); + renderValidatorHelper(currentShape, false, MAP_KEY); + renderValidatorHelper(currentShape, false, MAP_VALUE); + writer.write( + """ + } + """ + ); + } else if (currentShape.isUnionShape()) { + writer.write( + """ + switch unionType := %s.(type) { + """.formatted(dataSource) + ); + for (var memberInUnion : currentShape.getAllMembers().values()) { + writer.write( + """ + case *%s: + """.formatted(symbolProvider.toMemberName(memberInUnion)) + ); + + renderValidatorForEachShape( + model.expectShape(memberInUnion.getTarget()), + memberInUnion, + false, + "unionType.Value" + ); + } + writer.write( + """ + // Default case should not be reached. + default: + // To avoid used and not used error when nothing to validate + _ = unionType + panic("Unhandled union type") } - """); - } - writer.write(rangeCheck); + """ + ); + } else { + renderValidatorHelper(currentShape, isInputStructure, dataSource); } + } - private void addLengthCheck(final Shape currentShape, final String dataSource, final String pointableString) { - StringBuilder lengthCheck = new StringBuilder(); - LengthTrait lengthTraitShape = currentShape.expectTrait(LengthTrait.class); - Optional min = lengthTraitShape.getMin(); - Optional max = lengthTraitShape.getMax(); - if (pointableString.equals("*")){ - lengthCheck.append(""" - if (%s != nil) { - """.formatted(dataSource)); - } - if (min.isPresent()) { - if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { - lengthCheck.append(""" - if (utf8.RuneCountInString(%s%s) < %s) { - return fmt.Errorf(\"%s has a minimum length of %s but has the length of %%d.\", utf8.RuneCountInString(%s%s)) - } - """.formatted( - pointableString, - dataSource, - min.get().toString(), - currentShape.getId().getName(), - min.get().toString(), - pointableString, - dataSource)); - } - else { - lengthCheck.append(""" - if (len(%s%s) < %s) { - return fmt.Errorf(\"%s has a minimum length of %s but has the length of %%d.\", len(%s%s)) - } - """.formatted( - pointableString, - dataSource, - min.get().toString(), - currentShape.getId().getName(), - min.get().toString(), - pointableString, - dataSource)); - } + private void addRangeCheck( + final Shape currentShape, + final String dataSource, + final String pointableString + ) { + StringBuilder rangeCheck = new StringBuilder(); + RangeTrait rangeTraitShape = currentShape.expectTrait(RangeTrait.class); + Optional min = rangeTraitShape.getMin(); + Optional max = rangeTraitShape.getMax(); + if (pointableString.equals("*")) { + rangeCheck.append( + """ + if (%s != nil) { + """.formatted(dataSource) + ); + } + if (min.isPresent()) { + rangeCheck.append( + """ + if (%s%s < %s) { + return fmt.Errorf(\"%s has a minimum of %s but has the value of %%d.\", %s%s) } - if (max.isPresent()) { - if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { - lengthCheck.append(""" - if (utf8.RuneCountInString(%s%s) > %s) { - return fmt.Errorf(\"%s has a maximum length of %s but has the length of %%d.\", utf8.RuneCountInString(%s%s)) - } - """.formatted( - pointableString, - dataSource, - max.get().toString(), - currentShape.getId().getName(), - max.get().toString(), - pointableString, - dataSource)); - } - else { - lengthCheck.append(""" - if (len(%s%s) > %s) { - return fmt.Errorf(\"%s has a maximum length of %s but has the length of %%d.\", len(%s%s)) - } - """.formatted( - pointableString, - dataSource, - max.get().toString(), - currentShape.getId().getName(), - max.get().toString(), - pointableString, - dataSource)); - } + """.formatted( + pointableString, + dataSource, + min.get().toString(), + currentShape.getId().getName(), + min.get().toString(), + pointableString, + dataSource + ) + ); + } + if (max.isPresent()) { + rangeCheck.append( + """ + if (%s%s > %s) { + return fmt.Errorf(\"%s has a maximum of %s but has the value of %%d.\", %s%s) } - if (pointableString.equals("*")){ - lengthCheck.append(""" - } - """); + """.formatted( + pointableString, + dataSource, + max.get().toString(), + currentShape.getId().getName(), + max.get().toString(), + pointableString, + dataSource + ) + ); + } + if (pointableString.equals("*")) { + rangeCheck.append( + """ } - writer.write(lengthCheck); + """ + ); } + writer.write(rangeCheck); + } - private void addRequiredCheck(final Symbol memberSymbol, final Shape currentShape, final String dataSource) { - StringBuilder RequiredCheck = new StringBuilder(); - if( memberSymbol.getProperty(POINTABLE).isPresent() && (boolean) memberSymbol.getProperty(POINTABLE).get()) - RequiredCheck.append(""" - if ( %s == nil ) { - return fmt.Errorf(\"%s is required but has a nil value.\") - } - """.formatted( - dataSource, - dataSource)); - writer.write(RequiredCheck); + private void addLengthCheck( + final Shape currentShape, + final String dataSource, + final String pointableString + ) { + StringBuilder lengthCheck = new StringBuilder(); + LengthTrait lengthTraitShape = currentShape.expectTrait(LengthTrait.class); + Optional min = lengthTraitShape.getMin(); + Optional max = lengthTraitShape.getMax(); + if (pointableString.equals("*")) { + lengthCheck.append( + """ + if (%s != nil) { + """.formatted(dataSource) + ); } - - private void addUTFCheck(final Shape currentShape, final String dataSource, final String pointableString) { - StringBuilder UTFCheck = new StringBuilder(); - if (pointableString.equals("*")){ - UTFCheck.append(""" - if ( %s != nil ) { - """.formatted(dataSource)); + if (min.isPresent()) { + if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { + lengthCheck.append( + """ + if (utf8.RuneCountInString(%s%s) < %s) { + return fmt.Errorf(\"%s has a minimum length of %s but has the length of %%d.\", utf8.RuneCountInString(%s%s)) + } + """.formatted( + pointableString, + dataSource, + min.get().toString(), + currentShape.getId().getName(), + min.get().toString(), + pointableString, + dataSource + ) + ); + } else { + lengthCheck.append( + """ + if (len(%s%s) < %s) { + return fmt.Errorf(\"%s has a minimum length of %s but has the length of %%d.\", len(%s%s)) + } + """.formatted( + pointableString, + dataSource, + min.get().toString(), + currentShape.getId().getName(), + min.get().toString(), + pointableString, + dataSource + ) + ); + } + } + if (max.isPresent()) { + if (currentShape.hasTrait(DafnyUtf8BytesTrait.class)) { + lengthCheck.append( + """ + if (utf8.RuneCountInString(%s%s) > %s) { + return fmt.Errorf(\"%s has a maximum length of %s but has the length of %%d.\", utf8.RuneCountInString(%s%s)) + } + """.formatted( + pointableString, + dataSource, + max.get().toString(), + currentShape.getId().getName(), + max.get().toString(), + pointableString, + dataSource + ) + ); + } else { + lengthCheck.append( + """ + if (len(%s%s) > %s) { + return fmt.Errorf(\"%s has a maximum length of %s but has the length of %%d.\", len(%s%s)) + } + """.formatted( + pointableString, + dataSource, + max.get().toString(), + currentShape.getId().getName(), + max.get().toString(), + pointableString, + dataSource + ) + ); + } + } + if (pointableString.equals("*")) { + lengthCheck.append( + """ } - UTFCheck.append(""" - if (!utf8.ValidString(%s%s)) { - return fmt.Errorf(\"Invalid UTF bytes %%s \", %s%s) - } - """.formatted( - pointableString, - dataSource, - pointableString, - dataSource)); - if (pointableString.equals("*")){ - UTFCheck.append(""" - } - """); + """ + ); + } + writer.write(lengthCheck); + } + + private void addRequiredCheck( + final Symbol memberSymbol, + final Shape currentShape, + final String dataSource + ) { + StringBuilder RequiredCheck = new StringBuilder(); + if ( + memberSymbol.getProperty(POINTABLE).isPresent() && + (boolean) memberSymbol.getProperty(POINTABLE).get() + ) RequiredCheck.append( + """ + if ( %s == nil ) { + return fmt.Errorf(\"%s is required but has a nil value.\") + } + """.formatted(dataSource, dataSource) + ); + writer.write(RequiredCheck); + } + + private void addUTFCheck( + final Shape currentShape, + final String dataSource, + final String pointableString + ) { + StringBuilder UTFCheck = new StringBuilder(); + if (pointableString.equals("*")) { + UTFCheck.append( + """ + if ( %s != nil ) { + """.formatted(dataSource) + ); + } + UTFCheck.append( + """ + if (!utf8.ValidString(%s%s)) { + return fmt.Errorf(\"Invalid UTF bytes %%s \", %s%s) + } + """.formatted(pointableString, dataSource, pointableString, dataSource) + ); + if (pointableString.equals("*")) { + UTFCheck.append( + """ } - writer.write(UTFCheck); + """ + ); } + writer.write(UTFCheck); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/GoIntegration.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/GoIntegration.java index acf1f770c4..5eb8b38504 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/GoIntegration.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/GoIntegration.java @@ -8,5 +8,5 @@ import software.amazon.polymorph.smithygo.codegen.GoWriter; import software.amazon.smithy.codegen.core.SmithyIntegration; -public interface GoIntegration extends SmithyIntegration { -} +public interface GoIntegration + extends SmithyIntegration {} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/ProtocolGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/ProtocolGenerator.java index abda4b6764..c63f0803a0 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/ProtocolGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/integration/ProtocolGenerator.java @@ -14,57 +14,57 @@ */ package software.amazon.polymorph.smithygo.codegen.integration; +import static java.lang.String.format; + import software.amazon.polymorph.smithygo.codegen.ApplicationProtocol; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.utils.SmithyUnstableApi; -import static java.lang.String.format; - /** * Generates code to implement a protocol for both servers and clients. */ @SmithyUnstableApi public interface ProtocolGenerator { - /** - * Gets the supported protocol {@link ShapeId}. - * - * @return Returns the protocol supported - */ - ShapeId getProtocol(); + /** + * Gets the supported protocol {@link ShapeId}. + * + * @return Returns the protocol supported + */ + ShapeId getProtocol(); - /** - * Gets the name of the protocol. - * - *

The default implementation is the ShapeId name of the protocol trait in - * Smithy models (e.g., "aws.protocols#restJson1" would return "restJson1"). - * - * @return Returns the protocol name. - */ - default String getName() { - return getProtocol().getName(); - } + /** + * Gets the name of the protocol. + * + *

The default implementation is the ShapeId name of the protocol trait in + * Smithy models (e.g., "aws.protocols#restJson1" would return "restJson1"). + * + * @return Returns the protocol name. + */ + default String getName() { + return getProtocol().getName(); + } - /** - * Creates an application protocol for the generator. - * - * @return Returns the created application protocol. - */ - ApplicationProtocol getApplicationProtocol(); + /** + * Creates an application protocol for the generator. + * + * @return Returns the created application protocol. + */ + ApplicationProtocol getApplicationProtocol(); - /** - * Generates the code used to serialize the shapes of a service - * for requests. - * - * @param context Serialization context. - */ - void generateSerializers(GenerationContext context); + /** + * Generates the code used to serialize the shapes of a service + * for requests. + * + * @param context Serialization context. + */ + void generateSerializers(GenerationContext context); - /** - * Generates the code used to deserialize the shapes of a service - * for responses. - * - * @param context Deserialization context. - */ - void generateDeserializers(GenerationContext context); + /** + * Generates the code used to deserialize the shapes of a service + * for responses. + * + * @param context Deserialization context. + */ + void generateDeserializers(GenerationContext context); } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java index 0a7e5834f4..9f490144f0 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoPointableIndex.java @@ -17,6 +17,9 @@ package software.amazon.polymorph.smithygo.codegen.knowledge; +import java.util.HashSet; +import java.util.Set; +import java.util.logging.Logger; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.KnowledgeIndex; import software.amazon.smithy.model.knowledge.NeighborProviderIndex; @@ -34,253 +37,276 @@ import software.amazon.smithy.model.traits.StreamingTrait; import software.amazon.smithy.utils.SetUtils; -import java.util.HashSet; -import java.util.Set; -import java.util.logging.Logger; - /** * An index that checks if a member or shape type should be a pointer type in Go. *

* Extends the rules of smithy's NullableIndex for Go's translation of the smithy shapes to Go types. */ public class GoPointableIndex implements KnowledgeIndex { - private static final Logger LOGGER = Logger.getLogger(GoPointableIndex.class.getName()); - - // All types that are Go value types - private static final Set INHERENTLY_VALUE = SetUtils.of( - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - ShapeType.UNION, - ShapeType.DOCUMENT - ); - - // All types that are Go pointer types - private static final Set INHERENTLY_POINTABLE = SetUtils.of( - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER - ); - // All types that cannot be dereferenced - private static final Set INHERENTLY_NONDEREFERENCABLE = SetUtils.of( - // built in slice/map - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - - // Interfaces - ShapeType.UNION, - ShapeType.DOCUMENT, - - // known pointer types. - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER + private static final Logger LOGGER = Logger.getLogger( + GoPointableIndex.class.getName() + ); + + // All types that are Go value types + private static final Set INHERENTLY_VALUE = SetUtils.of( + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + ShapeType.UNION, + ShapeType.DOCUMENT + ); + + // All types that are Go pointer types + private static final Set INHERENTLY_POINTABLE = SetUtils.of( + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + // All types that cannot be dereferenced + private static final Set INHERENTLY_NONDEREFERENCABLE = + SetUtils.of( + // built in slice/map + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + // Interfaces + ShapeType.UNION, + ShapeType.DOCUMENT, + // known pointer types. + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER ); - // All types types that are comparable to nil - private static final Set INHERENTLY_NILLABLE = SetUtils.of( - // built in slice/map - ShapeType.BLOB, - ShapeType.LIST, - ShapeType.SET, - ShapeType.MAP, - - // Interfaces - ShapeType.UNION, - ShapeType.DOCUMENT, - - // known pointer types. - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER + // All types types that are comparable to nil + private static final Set INHERENTLY_NILLABLE = SetUtils.of( + // built in slice/map + ShapeType.BLOB, + ShapeType.LIST, + ShapeType.SET, + ShapeType.MAP, + // Interfaces + ShapeType.UNION, + ShapeType.DOCUMENT, + // known pointer types. + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + // All the known pointer type if not required + private static final Set KNOWN_POINTER_TYPE = SetUtils.of( + ShapeType.BYTE, + ShapeType.SHORT, + ShapeType.INTEGER, + ShapeType.LONG, + ShapeType.FLOAT, + ShapeType.DOUBLE, + ShapeType.BIG_DECIMAL, + ShapeType.BIG_INTEGER + ); + + private final Model model; + private final NullableIndex nullableIndex; + private final Set pointableShapes = new HashSet<>(); + private final Set nillableShapes = new HashSet<>(); + private final Set dereferencableShapes = new HashSet<>(); + + public GoPointableIndex(Model model) { + this.model = model; + this.nullableIndex = NullableIndex.of(model); + + for (Shape shape : model.toSet()) { + if (shape.asMemberShape().isPresent()) { + MemberShape member = shape.asMemberShape().get(); + Shape targetShape = model.expectShape(member.getTarget()); + + if (isMemberPointable(member, targetShape)) { + pointableShapes.add(shape.getId()); + } + if (isMemberNillable(member, targetShape)) { + nillableShapes.add(shape.getId()); + } + if (isMemberDereferencable(member, targetShape)) { + dereferencableShapes.add(shape.getId()); + } + } else { + if (isShapePointable(shape)) { + pointableShapes.add(shape.getId()); + nillableShapes.add(shape.getId()); + } + if (isShapeNillable(shape)) { + nillableShapes.add(shape.getId()); + } + if (isShapeDereferencable(shape)) { + dereferencableShapes.add(shape.getId()); + } + } + } + } + + public static GoPointableIndex of(Model model) { + return model.getKnowledge(GoPointableIndex.class, GoPointableIndex::new); + } + + private boolean isMemberDereferencable( + MemberShape member, + Shape targetShape + ) { + return ( + !INHERENTLY_NONDEREFERENCABLE.contains(targetShape.getType()) && + isMemberPointable(member, targetShape) ); + } - // All the known pointer type if not required - private static final Set KNOWN_POINTER_TYPE = SetUtils.of( - ShapeType.BYTE, - ShapeType.SHORT, - ShapeType.INTEGER, - ShapeType.LONG, - ShapeType.FLOAT, - ShapeType.DOUBLE, - ShapeType.BIG_DECIMAL, - ShapeType.BIG_INTEGER + private boolean isMemberNillable(MemberShape member, Shape targetShape) { + return ( + INHERENTLY_NILLABLE.contains(targetShape.getType()) || + isMemberPointable(member, targetShape) ); + } - private final Model model; - private final NullableIndex nullableIndex; - private final Set pointableShapes = new HashSet<>(); - private final Set nillableShapes = new HashSet<>(); - private final Set dereferencableShapes = new HashSet<>(); - - public GoPointableIndex(Model model) { - this.model = model; - this.nullableIndex = NullableIndex.of(model); - - for (Shape shape : model.toSet()) { - if (shape.asMemberShape().isPresent()) { - MemberShape member = shape.asMemberShape().get(); - Shape targetShape = model.expectShape(member.getTarget()); - - if (isMemberPointable(member, targetShape)) { - pointableShapes.add(shape.getId()); - } - if (isMemberNillable(member, targetShape)) { - nillableShapes.add(shape.getId()); - } - if (isMemberDereferencable(member, targetShape)) { - dereferencableShapes.add(shape.getId()); - } - } else { - if (isShapePointable(shape)) { - pointableShapes.add(shape.getId()); - nillableShapes.add(shape.getId()); - } - if (isShapeNillable(shape)) { - nillableShapes.add(shape.getId()); - } - if (isShapeDereferencable(shape)) { - dereferencableShapes.add(shape.getId()); - } - } - } + private boolean isMemberPointable(MemberShape member, Shape targetShape) { + // Streamed blob shapes are never pointers because they are interfaces + if (isBlobStream(targetShape)) { + return false; } - public static GoPointableIndex of(Model model) { - return model.getKnowledge(GoPointableIndex.class, GoPointableIndex::new); + if (INHERENTLY_VALUE.contains(targetShape.getType())) { + return false; } - private boolean isMemberDereferencable(MemberShape member, Shape targetShape) { - return !INHERENTLY_NONDEREFERENCABLE.contains(targetShape.getType()) && isMemberPointable(member, targetShape); + //if membershape is required return it is not pointable + if (member.hasTrait(RequiredTrait.class)) { + return false; } - private boolean isMemberNillable(MemberShape member, Shape targetShape) { - return INHERENTLY_NILLABLE.contains(targetShape.getType()) || isMemberPointable(member, targetShape); + if (model.expectShape(member.getContainer()).isMapShape()) { + return false; } - private boolean isMemberPointable(MemberShape member, Shape targetShape) { - // Streamed blob shapes are never pointers because they are interfaces - if (isBlobStream(targetShape)) { - return false; - } - - if (INHERENTLY_VALUE.contains(targetShape.getType())) { - return false; - } + if (KNOWN_POINTER_TYPE.contains(targetShape.getType())) { + return true; + } - //if membershape is required return it is not pointable - if (member.hasTrait(RequiredTrait.class)) { - return false; - } + return nullableIndex.isMemberNullable( + member, + NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1_NO_INPUT + ); + } - if (model.expectShape(member.getContainer()).isMapShape()) { - return false; - } + private boolean isShapeDereferencable(Shape shape) { + return ( + !INHERENTLY_NONDEREFERENCABLE.contains(shape.getType()) && + isShapePointable(shape) + ); + } - if (KNOWN_POINTER_TYPE.contains(targetShape.getType())) { - return true; - } + private boolean isShapeNillable(Shape shape) { + return ( + INHERENTLY_NILLABLE.contains(shape.getType()) || isShapePointable(shape) + ); + } - return nullableIndex.isMemberNullable(member, NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1_NO_INPUT); + private boolean isShapePointable(Shape shape) { + // All operation input and output shapes are pointable. + if (isOperationStruct(shape)) { + return true; } - private boolean isShapeDereferencable(Shape shape) { - return !INHERENTLY_NONDEREFERENCABLE.contains(shape.getType()) && isShapePointable(shape); + // Streamed blob shapes are never pointers because they are interfaces + if (isBlobStream(shape)) { + return false; } - private boolean isShapeNillable(Shape shape) { - return INHERENTLY_NILLABLE.contains(shape.getType()) || isShapePointable(shape); + if (shape.isServiceShape()) { + return true; } - private boolean isShapePointable(Shape shape) { - // All operation input and output shapes are pointable. - if (isOperationStruct(shape)) { - return true; - } - - // Streamed blob shapes are never pointers because they are interfaces - if (isBlobStream(shape)) { - return false; - } - - if (shape.isServiceShape()) { - return true; - } - - // This is odd because its not a go type but a function with receiver - if (shape.isOperationShape()) { - return false; - } - - if (INHERENTLY_POINTABLE.contains(shape.getType())) { - return true; - } - - if (INHERENTLY_VALUE.contains(shape.getType())) { - return false; - } - - if (shape.hasTrait(RequiredTrait.class)) { - return false; - } - - if (KNOWN_POINTER_TYPE.contains(shape.getType())) { - return true; - } - - return nullableIndex.isNullable(shape); + // This is odd because its not a go type but a function with receiver + if (shape.isOperationShape()) { + return false; } - private boolean isShapeEnum(Shape shape) { - return shape.getType() == ShapeType.STRING && shape.hasTrait(EnumTrait.class) - || shape.getType() == ShapeType.ENUM - || shape.getType() == ShapeType.INT_ENUM; + if (INHERENTLY_POINTABLE.contains(shape.getType())) { + return true; } - private boolean isBlobStream(Shape shape) { - return shape.getType() == ShapeType.BLOB && shape.hasTrait(StreamingTrait.ID); + if (INHERENTLY_VALUE.contains(shape.getType())) { + return false; } - private boolean isOperationStruct(Shape shape) { - NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); - for (Relationship relationship : provider.getNeighbors(shape)) { - RelationshipType relationshipType = relationship.getRelationshipType(); - if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { - return true; - } - } - - return false; + if (shape.hasTrait(RequiredTrait.class)) { + return false; } - /** - * Returns if the shape should be generated as a Go pointer type or not. - * - * @param shape the shape to check if should be pointable type. - * @return if the shape is should be a Go pointer type. - */ - public final boolean isPointable(ToShapeId shape) { - return pointableShapes.contains(shape.toShapeId()); + if (KNOWN_POINTER_TYPE.contains(shape.getType())) { + return true; } - /** - * Returns if the Go type generated for the shape is comparable to nil. - * - * @param shape the shape to check - * @return if the shape's go type is comparable to nil - */ - public final boolean isNillable(ToShapeId shape) { - return nillableShapes.contains(shape.toShapeId()); - } + return nullableIndex.isNullable(shape); + } + + private boolean isShapeEnum(Shape shape) { + return ( + (shape.getType() == ShapeType.STRING && + shape.hasTrait(EnumTrait.class)) || + shape.getType() == ShapeType.ENUM || + shape.getType() == ShapeType.INT_ENUM + ); + } - /** - * Returns if the Go type generated for the shape can be dereferenced. - * - * @param shape the shape to check - * @return if the shape's go type is dereferencable - */ - public final boolean isDereferencable(ToShapeId shape) { - return dereferencableShapes.contains(shape.toShapeId()); + private boolean isBlobStream(Shape shape) { + return ( + shape.getType() == ShapeType.BLOB && shape.hasTrait(StreamingTrait.ID) + ); + } + + private boolean isOperationStruct(Shape shape) { + NeighborProvider provider = NeighborProviderIndex + .of(model) + .getReverseProvider(); + for (Relationship relationship : provider.getNeighbors(shape)) { + RelationshipType relationshipType = relationship.getRelationshipType(); + if ( + relationshipType == RelationshipType.INPUT || + relationshipType == RelationshipType.OUTPUT + ) { + return true; + } } + + return false; + } + + /** + * Returns if the shape should be generated as a Go pointer type or not. + * + * @param shape the shape to check if should be pointable type. + * @return if the shape is should be a Go pointer type. + */ + public final boolean isPointable(ToShapeId shape) { + return pointableShapes.contains(shape.toShapeId()); + } + + /** + * Returns if the Go type generated for the shape is comparable to nil. + * + * @param shape the shape to check + * @return if the shape's go type is comparable to nil + */ + public final boolean isNillable(ToShapeId shape) { + return nillableShapes.contains(shape.toShapeId()); + } + + /** + * Returns if the Go type generated for the shape can be dereferenced. + * + * @param shape the shape to check + * @return if the shape's go type is dereferencable + */ + public final boolean isDereferencable(ToShapeId shape) { + return dereferencableShapes.contains(shape.toShapeId()); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoUsageIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoUsageIndex.java index e8e00b0fa0..8bd7b5226f 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoUsageIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoUsageIndex.java @@ -15,6 +15,9 @@ package software.amazon.polymorph.smithygo.codegen.knowledge; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.KnowledgeIndex; import software.amazon.smithy.model.knowledge.OperationIndex; @@ -27,65 +30,87 @@ import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.ToShapeId; -import java.util.HashSet; -import java.util.Set; -import java.util.stream.Collectors; - /** * Provides {@link KnowledgeIndex} of how shapes are used in the model. */ public class GoUsageIndex implements KnowledgeIndex { - private final Model model; - private final Walker walker; - private final Set inputShapes = new HashSet<>(); - private final Set outputShapes = new HashSet<>(); + private final Model model; + private final Walker walker; - public GoUsageIndex(Model model) { - this.model = model; - this.walker = new Walker(model); + private final Set inputShapes = new HashSet<>(); + private final Set outputShapes = new HashSet<>(); - TopDownIndex topDownIndex = TopDownIndex.of(model); - OperationIndex operationIndex = OperationIndex.of(model); + public GoUsageIndex(Model model) { + this.model = model; + this.walker = new Walker(model); - model.shapes(ServiceShape.class).forEach(serviceShape -> { - topDownIndex.getContainedOperations(serviceShape).forEach(operationShape -> { - StructureShape inputShape = operationIndex.getInput(operationShape).get(); - StructureShape outputShape = operationIndex.getOutput(operationShape).get(); + TopDownIndex topDownIndex = TopDownIndex.of(model); + OperationIndex operationIndex = OperationIndex.of(model); - inputShapes.addAll(walker.walkShapes(inputShape, relationship -> - relationship.getDirection() == RelationshipDirection.DIRECTED).stream() - .map(Shape::toShapeId).collect(Collectors.toList())); + model + .shapes(ServiceShape.class) + .forEach(serviceShape -> { + topDownIndex + .getContainedOperations(serviceShape) + .forEach(operationShape -> { + StructureShape inputShape = operationIndex + .getInput(operationShape) + .get(); + StructureShape outputShape = operationIndex + .getOutput(operationShape) + .get(); - outputShapes.addAll(walker.walkShapes(outputShape, relationship -> - relationship.getDirection() == RelationshipDirection.DIRECTED).stream() - .map(Shape::toShapeId).collect(Collectors.toList())); + inputShapes.addAll( + walker + .walkShapes( + inputShape, + relationship -> + relationship.getDirection() == + RelationshipDirection.DIRECTED + ) + .stream() + .map(Shape::toShapeId) + .collect(Collectors.toList()) + ); - }); - }); - } + outputShapes.addAll( + walker + .walkShapes( + outputShape, + relationship -> + relationship.getDirection() == + RelationshipDirection.DIRECTED + ) + .stream() + .map(Shape::toShapeId) + .collect(Collectors.toList()) + ); + }); + }); + } - /** - * Returns whether shape is used as part of an input to an operation. - * - * @param shape the shape - * @return whether the shape is used as input. - */ - public boolean isUsedForInput(ToShapeId shape) { - return inputShapes.contains(shape.toShapeId()); - } + /** + * Returns whether shape is used as part of an input to an operation. + * + * @param shape the shape + * @return whether the shape is used as input. + */ + public boolean isUsedForInput(ToShapeId shape) { + return inputShapes.contains(shape.toShapeId()); + } - /** - * Returns whether shape is used as output of an operation. - * - * @param shape the shape - * @return whether the shape is used as input. - */ - public boolean isUsedForOutput(ToShapeId shape) { - return outputShapes.contains(shape.toShapeId()); - } + /** + * Returns whether shape is used as output of an operation. + * + * @param shape the shape + * @return whether the shape is used as input. + */ + public boolean isUsedForOutput(ToShapeId shape) { + return outputShapes.contains(shape.toShapeId()); + } - public static GoUsageIndex of(Model model) { - return model.getKnowledge(GoUsageIndex.class, GoUsageIndex::new); - } + public static GoUsageIndex of(Model model) { + return model.getKnowledge(GoUsageIndex.class, GoUsageIndex::new); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoValidationIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoValidationIndex.java index 60ef46d1b5..c4410f6eca 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoValidationIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/knowledge/GoValidationIndex.java @@ -30,6 +30,13 @@ package software.amazon.polymorph.smithygo.codegen.knowledge; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.Consumer; +import java.util.stream.Collectors; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.KnowledgeIndex; import software.amazon.smithy.model.knowledge.TopDownIndex; @@ -44,148 +51,209 @@ import software.amazon.smithy.model.traits.RequiredTrait; import software.amazon.smithy.utils.SetUtils; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.TreeSet; -import java.util.function.Consumer; -import java.util.stream.Collectors; - /** * Provides a knowledge index of which service operations and shapes require validation helpers. */ public class GoValidationIndex implements KnowledgeIndex { - private final Map> serviceToOperationMap = new HashMap<>(); - private final Map> serviceValidationHelpers = new HashMap<>(); - - public GoValidationIndex(Model model) { - TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - Walker walker = new Walker(model); - - model.shapes(ServiceShape.class).forEach(serviceShape -> { - // Go uses unique input shapes per operation so we can index using the input shape as our key - Map inputShapeToOperation = new HashMap<>(); - Set requireValidationHelpers = new TreeSet<>(); - - // First pass is to collect member containers that contain members requiring validation - Set operations = topDownIndex.getContainedOperations(serviceShape); - operations.forEach(operationShape -> { - Shape inputShape = model.expectShape(operationShape.getInput().get()); - GoValidationIndex.walkValidationTree(walker, inputShape, shape -> { - if (shape.isMemberShape()) { - Shape container = model.expectShape(((MemberShape) shape).getContainer()); - if (isRequiredParameter(model, (MemberShape) shape, inputShape.equals(container))) { - inputShapeToOperation.put(inputShape, operationShape); - requireValidationHelpers.add(container.toShapeId()); - } - } - }); - }); - - // 2nd step is final all containers that reference the initial containers which require validation until - // we've discovered all intermediate containing types - inputShapeToOperation.keySet().forEach(input -> { - Set helpers = new TreeSet<>(); - do { - GoValidationIndex.walkValidationTree(walker, input, shape -> { - if (shape.isMemberShape()) { - MemberShape memberShape = shape.asMemberShape().get(); - Shape container = model.expectShape(memberShape.getContainer()); - Shape target = model.expectShape(memberShape.getTarget()); - if (requireValidationHelpers.contains(target.toShapeId()) - && !requireValidationHelpers.contains(container.toShapeId())) { - helpers.add(container.toShapeId()); - } - } - }); - if (helpers.isEmpty()) { - break; - } - requireValidationHelpers.addAll(helpers); - helpers.clear(); - } while (true); - }); - - serviceToOperationMap.put(serviceShape.toShapeId(), new TreeSet<>(inputShapeToOperation.values().stream() - .map(OperationShape::toShapeId).collect(Collectors.toSet()))); - serviceValidationHelpers.put(serviceShape.toShapeId(), requireValidationHelpers); - }); - } - - public static GoValidationIndex of(Model model) { - return model.getKnowledge(GoValidationIndex.class, GoValidationIndex::new); - } - - /** - * Get the set of operations that require validation. - * - * @param service service to find operations for - * @return operations requiring validation - */ - public Set getOperationsRequiringValidation(ToShapeId service) { - return serviceToOperationMap.getOrDefault(service.toShapeId(), SetUtils.of()); - } - - /** - * Get a set of shapes that require validation helpers. - * - * @param service service to find operations for - * @return operations requiring validation - */ - public Set getShapesRequiringValidationHelpers(ToShapeId service) { - return serviceValidationHelpers.getOrDefault(service.toShapeId(), SetUtils.of()); - } - - /** - * Returns whether the given shape requires a validation helper. - * - * @param shape the shape to check - * @return whether the shape requires a validation helper - */ - public boolean isValidationHelperRequired(ToShapeId shape) { - return serviceValidationHelpers.containsKey(shape.toShapeId()); - } - - /** - * Checks whether a {@link MemberShape} has any validation constraints. - * - * @param model the model - * @param shape the {@link MemberShape} to check - * @param validateHttpBindings whether http bindings should be checked for additional implicit constraints - * @return whether the {@link MemberShape} has validation costraints - */ - public static boolean hasValidation(Model model, MemberShape shape, boolean validateHttpBindings) { - return isRequiredParameter(model, shape, validateHttpBindings); - } - - /** - * Checks whether a {@link MemberShape} is marked as being required explicitly or implicitly. - * - * @param model the model - * @param shape the {@link MemberShape} to check - * @param validateHttpBindings whether http bindings should be checked for additional implicit constraints - * @return whether the {@link MemberShape} is a required parameter - */ - public static boolean isRequiredParameter(Model model, MemberShape shape, boolean validateHttpBindings) { - Optional requiredTrait = shape.getMemberTrait(model, RequiredTrait.class); - return requiredTrait.isPresent() || (validateHttpBindings && shape.getMemberTrait(model, - HttpLabelTrait.class).isPresent()); - } - - private static void walkValidationTree(Walker walker, Shape shape, Consumer visitor) { - walker.walkShapes(shape, relationship -> { - switch (relationship.getRelationshipType()) { - case STRUCTURE_MEMBER: - case UNION_MEMBER: - case MAP_VALUE: - case LIST_MEMBER: - case SET_MEMBER: - case MEMBER_TARGET: - return true; - default: - return false; + + private final Map> serviceToOperationMap = + new HashMap<>(); + private final Map> serviceValidationHelpers = + new HashMap<>(); + + public GoValidationIndex(Model model) { + TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); + Walker walker = new Walker(model); + + model + .shapes(ServiceShape.class) + .forEach(serviceShape -> { + // Go uses unique input shapes per operation so we can index using the input shape as our key + Map inputShapeToOperation = new HashMap<>(); + Set requireValidationHelpers = new TreeSet<>(); + + // First pass is to collect member containers that contain members requiring validation + Set operations = topDownIndex.getContainedOperations( + serviceShape + ); + operations.forEach(operationShape -> { + Shape inputShape = model.expectShape(operationShape.getInput().get()); + GoValidationIndex.walkValidationTree( + walker, + inputShape, + shape -> { + if (shape.isMemberShape()) { + Shape container = model.expectShape( + ((MemberShape) shape).getContainer() + ); + if ( + isRequiredParameter( + model, + (MemberShape) shape, + inputShape.equals(container) + ) + ) { + inputShapeToOperation.put(inputShape, operationShape); + requireValidationHelpers.add(container.toShapeId()); + } + } } - }).forEach(visitor::accept); - } + ); + }); + + // 2nd step is final all containers that reference the initial containers which require validation until + // we've discovered all intermediate containing types + inputShapeToOperation + .keySet() + .forEach(input -> { + Set helpers = new TreeSet<>(); + do { + GoValidationIndex.walkValidationTree( + walker, + input, + shape -> { + if (shape.isMemberShape()) { + MemberShape memberShape = shape.asMemberShape().get(); + Shape container = model.expectShape( + memberShape.getContainer() + ); + Shape target = model.expectShape(memberShape.getTarget()); + if ( + requireValidationHelpers.contains(target.toShapeId()) && + !requireValidationHelpers.contains(container.toShapeId()) + ) { + helpers.add(container.toShapeId()); + } + } + } + ); + if (helpers.isEmpty()) { + break; + } + requireValidationHelpers.addAll(helpers); + helpers.clear(); + } while (true); + }); + + serviceToOperationMap.put( + serviceShape.toShapeId(), + new TreeSet<>( + inputShapeToOperation + .values() + .stream() + .map(OperationShape::toShapeId) + .collect(Collectors.toSet()) + ) + ); + serviceValidationHelpers.put( + serviceShape.toShapeId(), + requireValidationHelpers + ); + }); + } + + public static GoValidationIndex of(Model model) { + return model.getKnowledge(GoValidationIndex.class, GoValidationIndex::new); + } + + /** + * Get the set of operations that require validation. + * + * @param service service to find operations for + * @return operations requiring validation + */ + public Set getOperationsRequiringValidation(ToShapeId service) { + return serviceToOperationMap.getOrDefault( + service.toShapeId(), + SetUtils.of() + ); + } + + /** + * Get a set of shapes that require validation helpers. + * + * @param service service to find operations for + * @return operations requiring validation + */ + public Set getShapesRequiringValidationHelpers(ToShapeId service) { + return serviceValidationHelpers.getOrDefault( + service.toShapeId(), + SetUtils.of() + ); + } + + /** + * Returns whether the given shape requires a validation helper. + * + * @param shape the shape to check + * @return whether the shape requires a validation helper + */ + public boolean isValidationHelperRequired(ToShapeId shape) { + return serviceValidationHelpers.containsKey(shape.toShapeId()); + } + + /** + * Checks whether a {@link MemberShape} has any validation constraints. + * + * @param model the model + * @param shape the {@link MemberShape} to check + * @param validateHttpBindings whether http bindings should be checked for additional implicit constraints + * @return whether the {@link MemberShape} has validation costraints + */ + public static boolean hasValidation( + Model model, + MemberShape shape, + boolean validateHttpBindings + ) { + return isRequiredParameter(model, shape, validateHttpBindings); + } + + /** + * Checks whether a {@link MemberShape} is marked as being required explicitly or implicitly. + * + * @param model the model + * @param shape the {@link MemberShape} to check + * @param validateHttpBindings whether http bindings should be checked for additional implicit constraints + * @return whether the {@link MemberShape} is a required parameter + */ + public static boolean isRequiredParameter( + Model model, + MemberShape shape, + boolean validateHttpBindings + ) { + Optional requiredTrait = shape.getMemberTrait( + model, + RequiredTrait.class + ); + return ( + requiredTrait.isPresent() || + (validateHttpBindings && + shape.getMemberTrait(model, HttpLabelTrait.class).isPresent()) + ); + } + + private static void walkValidationTree( + Walker walker, + Shape shape, + Consumer visitor + ) { + walker + .walkShapes( + shape, + relationship -> { + switch (relationship.getRelationshipType()) { + case STRUCTURE_MEMBER: + case UNION_MEMBER: + case MAP_VALUE: + case LIST_MEMBER: + case SET_MEMBER: + case MEMBER_TARGET: + return true; + default: + return false; + } + } + ) + .forEach(visitor::accept); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyGoPointableIndex.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyGoPointableIndex.java index 7d23954f7d..e9d301b029 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyGoPointableIndex.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyGoPointableIndex.java @@ -7,7 +7,10 @@ public class DafnyGoPointableIndex { - public static boolean isNillable(final Model model, final Shape shape) { - return !shape.hasTrait(RequiredTrait.class) && !GoCodegenUtils.isOperationStruct(model, shape); - } + public static boolean isNillable(final Model model, final Shape shape) { + return ( + !shape.hasTrait(RequiredTrait.class) && + !GoCodegenUtils.isOperationStruct(model, shape) + ); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceCodegenPlugin.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceCodegenPlugin.java index eea7ae096f..40c1b2e659 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceCodegenPlugin.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceCodegenPlugin.java @@ -1,5 +1,6 @@ package software.amazon.polymorph.smithygo.localservice; +import java.util.Map; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoSettings; import software.amazon.polymorph.smithygo.codegen.GoWriter; @@ -9,51 +10,58 @@ import software.amazon.smithy.build.SmithyBuildPlugin; import software.amazon.smithy.codegen.core.directed.CodegenDirector; -import java.util.Map; - public class DafnyLocalServiceCodegenPlugin implements SmithyBuildPlugin { - public DafnyLocalServiceCodegenPlugin(final Map smithyNamespaceToPythonModuleNameMap) { - super(); - SmithyNameResolver.setSmithyNamespaceToGoModuleNameMap(smithyNamespaceToPythonModuleNameMap); - } - public void run(PluginContext context) { - CodegenDirector runner - = new CodegenDirector<>(); + public DafnyLocalServiceCodegenPlugin( + final Map smithyNamespaceToPythonModuleNameMap + ) { + super(); + SmithyNameResolver.setSmithyNamespaceToGoModuleNameMap( + smithyNamespaceToPythonModuleNameMap + ); + } + + public void run(PluginContext context) { + CodegenDirector< + GoWriter, + GoIntegration, + GenerationContext, + GoSettings + > runner = new CodegenDirector<>(); - runner.directedCodegen(new DafnyLocalServiceDirectedCodegen()); + runner.directedCodegen(new DafnyLocalServiceDirectedCodegen()); - // Set the SmithyIntegration class to look for and apply using SPI. - runner.integrationClass(GoIntegration.class); + // Set the SmithyIntegration class to look for and apply using SPI. + runner.integrationClass(GoIntegration.class); - // Set the FileManifest and Model from the plugin. - runner.fileManifest(context.getFileManifest()); - runner.model(context.getModel()); + // Set the FileManifest and Model from the plugin. + runner.fileManifest(context.getFileManifest()); + runner.model(context.getModel()); - // Create the GoSettings object from the plugin settings. - GoSettings settings = GoSettings.from(context.getSettings()); - runner.settings(settings); + // Create the GoSettings object from the plugin settings. + GoSettings settings = GoSettings.from(context.getSettings()); + runner.settings(settings); - runner.service(settings.getService()); + runner.service(settings.getService()); - // Configure the director to perform some common model transforms. - runner.performDefaultCodegenTransforms(); + // Configure the director to perform some common model transforms. + runner.performDefaultCodegenTransforms(); - // TODO: Not using below because it would break existing AWS SDKs. Maybe it should be configurable - // so generic SDKs call this by default, but AWS SDKs can opt-out of it via a setting. - // runner.createDedicatedInputsAndOutputs(); + // TODO: Not using below because it would break existing AWS SDKs. Maybe it should be configurable + // so generic SDKs call this by default, but AWS SDKs can opt-out of it via a setting. + // runner.createDedicatedInputsAndOutputs(); - // Run it! - runner.run(); - } + // Run it! + runner.run(); + } - @Override - public String getName() { - return "go-client-codegen"; - } + @Override + public String getName() { + return "go-client-codegen"; + } - @Override - public void execute(PluginContext context) { - this.run(context); - } + @Override + public void execute(PluginContext context) { + this.run(context); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceDirectedCodegen.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceDirectedCodegen.java index cd22bd32c5..7c3b043bee 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceDirectedCodegen.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceDirectedCodegen.java @@ -1,5 +1,6 @@ package software.amazon.polymorph.smithygo.localservice; +import java.util.logging.Logger; import software.amazon.polymorph.smithygo.codegen.EnumGenerator; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoDelegator; @@ -20,112 +21,191 @@ import software.amazon.smithy.codegen.core.directed.GenerateStructureDirective; import software.amazon.smithy.codegen.core.directed.GenerateUnionDirective; -import java.util.logging.Logger; - -public class DafnyLocalServiceDirectedCodegen implements DirectedCodegen { - private static final Logger LOGGER = Logger.getLogger(DafnyLocalServiceDirectedCodegen.class.getName()); - @Override - public SymbolProvider createSymbolProvider(CreateSymbolProviderDirective directive) { - return new SymbolVisitor(directive.model(), directive.settings()); +public class DafnyLocalServiceDirectedCodegen + implements DirectedCodegen { + + private static final Logger LOGGER = Logger.getLogger( + DafnyLocalServiceDirectedCodegen.class.getName() + ); + + @Override + public SymbolProvider createSymbolProvider( + CreateSymbolProviderDirective directive + ) { + return new SymbolVisitor(directive.model(), directive.settings()); + } + + @Override + public GenerationContext createContext( + CreateContextDirective directive + ) { + return GenerationContext + .builder() + .model(directive.model()) + .settings(directive.settings()) + .symbolProvider(directive.symbolProvider()) + .fileManifest(directive.fileManifest()) + .integrations(directive.integrations()) + .writerDelegator( + new GoDelegator(directive.fileManifest(), directive.symbolProvider()) + ) + .protocolGenerator(new DafnyLocalServiceTypeConversionProtocol()) + .build(); + } + + @Override + public void generateService( + GenerateServiceDirective directive + ) { + if ( + !directive + .shape() + .getId() + .getNamespace() + .equals(directive.context().settings().getService().getNamespace()) + ) { + return; } + new DafnyLocalServiceGenerator(directive.context(), directive.service()) + .run(); - @Override - public GenerationContext createContext(CreateContextDirective directive) { - return GenerationContext.builder() - .model(directive.model()) - .settings(directive.settings()) - .symbolProvider(directive.symbolProvider()) - .fileManifest(directive.fileManifest()) - .integrations(directive.integrations()) - .writerDelegator(new GoDelegator(directive.fileManifest(), directive.symbolProvider())) - .protocolGenerator(new DafnyLocalServiceTypeConversionProtocol()) - .build(); + var protocolGenerator = directive.context().protocolGenerator(); + if (protocolGenerator == null) { + return; } - @Override - public void generateService(GenerateServiceDirective directive) { - if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) - { - return; - } - new DafnyLocalServiceGenerator(directive.context(), directive.service()).run(); - - var protocolGenerator = directive.context().protocolGenerator(); - if (protocolGenerator == null) { - return; - } - - protocolGenerator.generateSerializers(directive.context()); - - protocolGenerator.generateDeserializers(directive.context()); - + protocolGenerator.generateSerializers(directive.context()); + + protocolGenerator.generateDeserializers(directive.context()); + } + + @Override + public void generateStructure( + GenerateStructureDirective directive + ) { + if ( + !directive + .shape() + .getId() + .getNamespace() + .equals(directive.context().settings().getService().getNamespace()) + ) { + return; } - - @Override - public void generateStructure(GenerateStructureDirective directive) { - if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) - { - return; + directive + .context() + .writerDelegator() + .useShapeWriter( + directive.shape(), + writer -> { + StructureGenerator generator = new StructureGenerator( + directive.context(), + writer, + directive.shape() + ); + generator.run(); } - directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { - StructureGenerator generator = new StructureGenerator( - directive.context(), - writer, - directive.shape() - ); - generator.run(); - }); + ); + } + + @Override + public void generateError( + GenerateErrorDirective directive + ) { + if ( + !directive + .shape() + .getId() + .getNamespace() + .equals(directive.context().settings().getService().getNamespace()) + ) { + return; } - - @Override - public void generateError(GenerateErrorDirective directive) { - if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) - { - return; + directive + .context() + .writerDelegator() + .useShapeWriter( + directive.shape(), + writer -> { + StructureGenerator generator = new StructureGenerator( + directive.context(), + writer, + directive.shape() + ); + generator.run(); } - directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { - StructureGenerator generator = new StructureGenerator( - directive.context(), - writer, - directive.shape() - ); - generator.run(); - }); + ); + } + + @Override + public void generateUnion( + GenerateUnionDirective directive + ) {} + + @Override + public void generateEnumShape( + GenerateEnumDirective directive + ) { + if ( + !directive + .shape() + .getId() + .getNamespace() + .equals(directive.context().settings().getService().getNamespace()) + ) { + return; } - - @Override - public void generateUnion(GenerateUnionDirective directive) { - - } - - @Override - public void generateEnumShape(GenerateEnumDirective directive) { - if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) - { - return; + directive + .context() + .writerDelegator() + .useShapeWriter( + directive.shape(), + writer -> { + EnumGenerator enumGenerator = new EnumGenerator( + directive.symbolProvider(), + writer, + directive.shape() + ); + enumGenerator.run(); } - directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { - EnumGenerator enumGenerator = new EnumGenerator(directive.symbolProvider(), writer, directive.shape()); - enumGenerator.run(); - }); + ); + } + + @Override + public void generateIntEnumShape( + GenerateIntEnumDirective directive + ) { + if ( + !directive + .shape() + .getId() + .getNamespace() + .equals(directive.context().settings().getService().getNamespace()) + ) { + return; } - - @Override - public void generateIntEnumShape(GenerateIntEnumDirective directive) { - if(!directive.shape().getId().getNamespace().equals(directive.context().settings().getService().getNamespace())) - { - return; + directive + .context() + .writerDelegator() + .useShapeWriter( + directive.shape(), + writer -> { + IntEnumGenerator intEnumGenerator = new IntEnumGenerator( + directive.symbolProvider(), + writer, + directive.shape().asIntEnumShape().get() + ); + intEnumGenerator.run(); } - directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { - IntEnumGenerator intEnumGenerator = new IntEnumGenerator(directive.symbolProvider(), writer, directive.shape().asIntEnumShape().get()); - intEnumGenerator.run(); - }); - } - - @Override - public void generateResource(GenerateResourceDirective directive) { -// System.out.println("##############" + directive.shape()); -// directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { -// }); - } + ); + } + + @Override + public void generateResource( + GenerateResourceDirective directive + ) { + // System.out.println("##############" + directive.shape()); + // directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { + // }); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java index 3147ea8eed..38c1f0474b 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceGenerator.java @@ -4,6 +4,8 @@ package software.amazon.polymorph.smithygo.localservice; import software.amazon.awssdk.core.traits.RequiredTrait; +import java.util.Collection; +import java.util.stream.Collectors; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoDelegator; import software.amazon.polymorph.smithygo.codegen.GoWriter; @@ -28,97 +30,326 @@ import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.UnitTypeTrait; -import java.util.Collection; -import java.util.stream.Collectors; - - public class DafnyLocalServiceGenerator implements Runnable { - private final GenerationContext context; - private final ServiceShape service; - private final TopDownIndex topDownIndex; - private final GoDelegator writerDelegator; - private final Model model; - private final SymbolProvider symbolProvider; - - public DafnyLocalServiceGenerator(GenerationContext context, ServiceShape service) { - this.context = context; - this.service = service; - model = context.model(); - topDownIndex = TopDownIndex.of(model); - writerDelegator = context.writerDelegator(); - symbolProvider = context.symbolProvider(); - } - @Override - public void run() { - writerDelegator.useShapeWriter(service, this::generateService); + private final GenerationContext context; + private final ServiceShape service; + private final TopDownIndex topDownIndex; + private final GoDelegator writerDelegator; + private final Model model; + private final SymbolProvider symbolProvider; + + public DafnyLocalServiceGenerator( + GenerationContext context, + ServiceShape service + ) { + this.context = context; + this.service = service; + model = context.model(); + topDownIndex = TopDownIndex.of(model); + writerDelegator = context.writerDelegator(); + symbolProvider = context.symbolProvider(); + } + + @Override + public void run() { + writerDelegator.useShapeWriter(service, this::generateService); + } + + private void generateService(GoWriter writer) { + if (service.hasTrait(LocalServiceTrait.class)) { + generateClient(writer); + generateUnmodelledErrors(context); + generateReferencedResources(context); + generateUnboundedStructures(context); } - - private void generateService(GoWriter writer) { - if (service.hasTrait(LocalServiceTrait.class)) { - generateClient(writer); - generateUnmodelledErrors(context); - generateReferencedResources(context); - generateUnboundedStructures(context); + generateShim(); + } + + void generateClient(GoWriter writer) { + // Generate each operation for the service. We do this here instead of via the operation visitor method to + // limit it to the operations bound to the service. + final var serviceSymbol = symbolProvider.toSymbol(service); + final var serviceTrait = service.expectTrait(LocalServiceTrait.class); + final var configSymbol = symbolProvider.toSymbol( + model.expectShape(serviceTrait.getConfigId()) + ); + + writerDelegator.useFileWriter( + "%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), + SmithyNameResolver.smithyTypesNamespace(service), + writer1 -> { + new StructureGenerator( + context, + writer1, + model.expectShape(serviceTrait.getConfigId()).asStructureShape().get() + ) + .run(); + model + .getUnionShapes() + .stream() + .filter(unionShape -> + unionShape + .getId() + .getNamespace() + .equals(service.getId().getNamespace()) + ) + .forEach(unionShape -> { + new UnionGenerator(model, symbolProvider, unionShape) + .generateUnion(writer1); + }); + } + ); + + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(service) + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + DafnyNameResolver.dafnyNamespace(service) + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(service) + ); + writer.addUseImports(SmithyGoDependency.CONTEXT); + + final var dafnyClient = DafnyNameResolver.getDafnyClient( + service, + serviceTrait.getSdkId() + ); + writer.write( + """ + type $T struct { + DafnyClient *$L + } + + func NewClient(clientConfig $L) (*$T, error) { + var dafnyConfig = $L(clientConfig) + var dafny_response = $L(dafnyConfig) + if (dafny_response.Is_Failure()) { + panic("Client construction failed. This should never happen") + } + var dafnyClient = dafny_response.Extract().(*$L) + client := &$T { dafnyClient } + return client, nil + } + """, + serviceSymbol, + dafnyClient, + SmithyNameResolver.getSmithyType(service, configSymbol), + serviceSymbol, + SmithyNameResolver.getToDafnyMethodName( + service, + context.model().expectShape(serviceTrait.getConfigId()), + "" + ), + DafnyNameResolver.createDafnyClient(service, serviceTrait.getSdkId()), + dafnyClient, + serviceSymbol + ); + + service + .getOperations() + .forEach(operation -> { + final var operationShape = model.expectShape( + operation, + OperationShape.class + ); + final var inputShape = model.expectShape( + operationShape.getInputShape() + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + inputShape.toShapeId().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(inputShape) + ); + if ( + !inputShape + .toShapeId() + .getNamespace() + .equals(service.toShapeId().getNamespace()) + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + inputShape.toShapeId().getNamespace() + ), + SmithyNameResolver.shapeNamespace(inputShape) + ); + } + final var outputShape = model.expectShape( + operationShape.getOutputShape() + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + outputShape.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(outputShape) + ); + if ( + !outputShape + .toShapeId() + .getNamespace() + .equals(service.toShapeId().getNamespace()) + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + outputShape.toShapeId().getNamespace() + ), + SmithyNameResolver.shapeNamespace(outputShape) + ); + } + final var inputType = inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : ", params %s.%s".formatted( + SmithyNameResolver.smithyTypesNamespace(inputShape), + inputShape.toShapeId().getName() + ); + final var outputType = outputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "*%s.%s,".formatted( + SmithyNameResolver.smithyTypesNamespace(outputShape), + outputShape.toShapeId().getName() + ); + String validationCheck = ""; + if (!inputType.equals("")) { + validationCheck = + """ + err := params.Validate() + if err != nil { + opaqueErr := %s.OpaqueError{ + ErrObject: err, + } + """.formatted(SmithyNameResolver.smithyTypesNamespace(inputShape)); + if (outputType.equals("")) { + validationCheck += "return opaqueErr }"; + } else { + validationCheck += "return nil, opaqueErr }"; + } + } + String baseClientCall; + if (inputShape.hasTrait(UnitTypeTrait.class)) { + baseClientCall = + "var dafny_response = client.DafnyClient.%s()".formatted( + operationShape.getId().getName() + ); + } else { + baseClientCall = + """ + var dafny_request %s = %s(params) + var dafny_response = client.DafnyClient.%s(dafny_request) + """.formatted( + DafnyNameResolver.getDafnyType( + inputShape, + symbolProvider.toSymbol(inputShape) + ), + SmithyNameResolver.getToDafnyMethodName( + service, + inputShape, + "" + ), + operationShape.getId().getName() + ); } - generateShim(); - } - void generateClient(GoWriter writer) { - // Generate each operation for the service. We do this here instead of via the operation visitor method to - // limit it to the operations bound to the service. - final var serviceSymbol = symbolProvider.toSymbol(service); - final var serviceTrait = service.expectTrait(LocalServiceTrait.class); - final var configSymbol = symbolProvider.toSymbol(model.expectShape(serviceTrait.getConfigId())); - - writerDelegator.useFileWriter("%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), SmithyNameResolver.smithyTypesNamespace(service), writer1 -> { - new StructureGenerator(context, writer1, - model.expectShape(serviceTrait.getConfigId()).asStructureShape().get()).run(); - model.getUnionShapes().stream() - .filter(unionShape -> unionShape.getId().getNamespace().equals(service.getId().getNamespace())) - .forEach(unionShape -> { - new UnionGenerator(model, symbolProvider, unionShape).generateUnion(writer1); - }); - }); + String returnResponse, returnError; + if (outputShape.hasTrait(UnitTypeTrait.class)) { + returnResponse = "return nil"; + returnError = "return"; + } else { + returnResponse = + """ + var native_response = %s(dafny_response.Extract().(%s)) + return &native_response, nil + """.formatted( + SmithyNameResolver.getFromDafnyMethodName( + service, + outputShape, + "" + ), + DafnyNameResolver.getDafnyType( + outputShape, + symbolProvider.toSymbol(outputShape) + ) + ); + returnError = "return nil,"; + } - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(service)); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), DafnyNameResolver.dafnyNamespace(service)); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.smithyTypesNamespace(service)); + writer.write( + """ + func (client *$T) $L(ctx context.Context $L) ($L error) { + $L + $L + if (dafny_response.Is_Failure()) { + err := dafny_response.Dtor_error().($L.Error); + $L Error_FromDafny(err) + } + $L + } + """, + serviceSymbol, + operationShape.getId().getName(), + inputType, + outputType, + validationCheck, + baseClientCall, + DafnyNameResolver.dafnyTypesNamespace(service), + returnError, + returnResponse + ); + }); + } + + void generateShim() { + final var namespace = + "%swrapped".formatted(DafnyNameResolver.dafnyNamespace(service)); + + writerDelegator.useFileWriter( + "%s/shim.go".formatted(namespace), + namespace, + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(service) + ); + writer.addImportFromModule( + "github.com/dafny-lang/DafnyStandardLibGo", + "Wrappers" + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(service) + ); writer.addUseImports(SmithyGoDependency.CONTEXT); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + SmithyNameResolver.shapeNamespace(service) + ); - final var dafnyClient = DafnyNameResolver.getDafnyClient(service, serviceTrait.getSdkId()); - writer.write(""" - type $T struct { - DafnyClient *$L - } - - func NewClient(clientConfig $L) (*$T, error) { - var dafnyConfig = $L(clientConfig) - var dafny_response = $L(dafnyConfig) - if (dafny_response.Is_Failure()) { - panic("Client construction failed. This should never happen") - } - var dafnyClient = dafny_response.Extract().(*$L) - client := &$T { dafnyClient } - return client, nil - } - """, - serviceSymbol, dafnyClient, SmithyNameResolver.getSmithyType(service, configSymbol), serviceSymbol, - SmithyNameResolver.getToDafnyMethodName(service, context.model().expectShape(serviceTrait.getConfigId()), ""), - DafnyNameResolver.createDafnyClient(service, serviceTrait.getSdkId()), - dafnyClient, serviceSymbol); - - service.getOperations().forEach(operation -> { - final var operationShape = model.expectShape(operation, OperationShape.class); - final var inputShape = model.expectShape(operationShape.getInputShape()); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(inputShape.toShapeId().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(inputShape)); - if (!inputShape.toShapeId().getNamespace().equals(service.toShapeId().getNamespace())) { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(inputShape.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(inputShape)); - } - final var outputShape = model.expectShape(operationShape.getOutputShape()); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(outputShape.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(outputShape)); - if (!outputShape.toShapeId().getNamespace().equals(service.toShapeId().getNamespace())) { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(outputShape.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(outputShape)); + if (service.hasTrait(LocalServiceTrait.class)) { + final var serviceTrait = service.expectTrait(LocalServiceTrait.class); + final var configShape = model.expectShape(serviceTrait.getConfigId()); + final var configSymbol = symbolProvider.toSymbol(configShape); + + writer.write( + """ + type Shim struct { + $L + client *$L.Client } final var inputType = inputShape.hasTrait(UnitTypeTrait.class) ? "" : ", params %s.%s".formatted(SmithyNameResolver.smithyTypesNamespace(inputShape), inputShape.toShapeId().getName()); @@ -199,51 +430,34 @@ func NewClient(clientConfig $L) (*$T, error) { validationCheck, baseClientCall, DafnyNameResolver.dafnyTypesNamespace(service), returnError, returnResponse ); - }); - } - - void generateShim() { - final var namespace = "%swrapped".formatted(DafnyNameResolver.dafnyNamespace(service)); - - writerDelegator.useFileWriter("%s/shim.go".formatted(namespace), namespace, writer -> { - - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(service)); - writer.addImportFromModule("github.com/dafny-lang/DafnyStandardLibGo", "Wrappers"); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.smithyTypesNamespace(service)); - writer.addUseImports(SmithyGoDependency.CONTEXT); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.shapeNamespace(service)); - - if (service.hasTrait(LocalServiceTrait.class)) { - final var serviceTrait = service.expectTrait(LocalServiceTrait.class); - final var configShape = model.expectShape(serviceTrait.getConfigId()); - final var configSymbol = symbolProvider.toSymbol(configShape); - - writer.write(""" - type Shim struct { - $L - client *$L.Client - } - """, - DafnyNameResolver.getDafnyInterfaceClient(service), - SmithyNameResolver.shapeNamespace(service) + final var inputShape = model.expectShape( + operationShape.getInputShape() + ); + final var outputShape = model.expectShape( + operationShape.getOutputShape() + ); + final var inputType = inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "input %s".formatted( + DafnyNameResolver.getDafnyType( + inputShape, + symbolProvider.toSymbol(inputShape) + ) ); - writer.write(""" - func Wrapped$L(inputConfig $L) Wrappers.Result { - var nativeConfig = $L.$L(inputConfig) - var nativeClient, nativeError = $L.NewClient(nativeConfig) - if nativeError != nil { - return Wrappers.Companion_Result_.Create_Failure_($L.Companion_Error_.Create_Opaque_(nativeError)) - } - return Wrappers.Companion_Result_.Create_Success_(&Shim{client: nativeClient}) - } - """, - serviceTrait.getSdkId(), DafnyNameResolver.getDafnyType(configShape, configSymbol), - SmithyNameResolver.shapeNamespace(model.expectShape(serviceTrait.getConfigId())), SmithyNameResolver.getFromDafnyMethodName(service, model.expectShape(serviceTrait.getConfigId()), ""), - SmithyNameResolver.shapeNamespace(service), DafnyNameResolver.dafnyTypesNamespace(service) + final var typeConversion = inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "var native_request = %s(input)".formatted( + SmithyNameResolver.getFromDafnyMethodName(inputShape, "") ); - } + final var clientCall = + "shim.client.%s(context.Background() %s)".formatted( + operationShape.getId().getName(), + inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : ", native_request" + ); service.getOperations().forEach(operation -> { final var operationShape = model.expectShape(operation, OperationShape.class); @@ -298,260 +512,480 @@ void generateShim() { }); }); } + } - void shimErrors(GoWriter writer) { - for (final var error : model.getShapesWithTrait(ErrorTrait.class)) { - writer.write(""" - case $L.$L: - return Wrappers.Companion_Result_.Create_Failure_($L(native_error.($L.$L))) - - - """, - SmithyNameResolver.smithyTypesNamespace(error), - symbolProvider.toSymbol(error).getName(), - SmithyNameResolver.getToDafnyMethodName(service, error, ""), SmithyNameResolver.smithyTypesNamespace(error), - symbolProvider.toSymbol(error).getName()); - } - } + void resourceErrors(GoWriter writer) { + for (final var error : model.getShapesWithTrait(ErrorTrait.class)) { + writer.write( + """ + case $L: + return Wrappers.Companion_Result_.Create_Failure_($L(native_error.($L))) - void resourceErrors(GoWriter writer) { - for (final var error : model.getShapesWithTrait(ErrorTrait.class)) { - writer.write(""" - case $L: - return Wrappers.Companion_Result_.Create_Failure_($L(native_error.($L))) - - - """, - SmithyNameResolver.getSmithyType(error, symbolProvider.toSymbol(error)), SmithyNameResolver.getToDafnyMethodName(service, error, ""), - SmithyNameResolver.getSmithyType(error, symbolProvider.toSymbol(error))); - } - } - void generateUnmodelledErrors(GenerationContext context) { - writerDelegator.useFileWriter("%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), SmithyNameResolver.smithyTypesNamespace(service), writer -> { - writer.write(""" - type $LBaseException interface { - // This is a dummy method to allow type assertion since Go empty interfaces - // aren't useful for type assertion checks. No concrete class is expected to implement - // this method. This is also not exported. - interfaceBindingMethod() - } - """, service.toShapeId().getName()); - }); - writerDelegator.useFileWriter("%s/unmodelled_errors.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), SmithyNameResolver.smithyTypesNamespace(service), writer -> { - writer.addUseImports(SmithyGoDependency.FMT); - writer.write(""" - type CollectionOfErrors struct { - $LBaseException - ListOfErrors []error - Message string - } - - func (e CollectionOfErrors) Error() string { - return fmt.Sprintf("message: %s\\n err %v", e.Message, e.ListOfErrors) - } - - type OpaqueError struct { - $LBaseException - ErrObject interface{} - } - - func (e OpaqueError) Error() string { - return fmt.Sprintf("message: %v", e.ErrObject ) - } - """, service.toShapeId().getName(), service.toShapeId().getName()); - }); + """, + SmithyNameResolver.getSmithyType(error, symbolProvider.toSymbol(error)), + SmithyNameResolver.getToDafnyMethodName(service, error, ""), + SmithyNameResolver.getSmithyType(error, symbolProvider.toSymbol(error)) + ); } - - void generateUnboundedStructures(GenerationContext context) { - final var serviceOperationShapes = model.getServiceShapes().stream() - .map(topDownIndex::getContainedOperations) - .flatMap(Collection::stream) - .map(OperationShape::toShapeId) - .collect(Collectors.toSet()); - final var nonServiceOperationShapes = model.getOperationShapes() - .stream() - .map(Shape::getId) - .filter(operationShapeId -> operationShapeId.getNamespace() - .equals(service.getId().getNamespace())) - .collect(Collectors.toSet()); - nonServiceOperationShapes.removeAll(serviceOperationShapes); - for (final var operationShapeId : nonServiceOperationShapes) { - OperationShape operationShape = model.expectShape(operationShapeId, OperationShape.class); - StructureShape inputShape = model.expectShape(operationShape.getInputShape(), StructureShape.class); - writerDelegator.useShapeWriter(inputShape, w -> new StructureGenerator(context, w, inputShape).run()); - StructureShape outputShape = model.expectShape(operationShape.getOutputShape(), StructureShape.class); - writerDelegator.useShapeWriter(outputShape, w -> new StructureGenerator(context, w, outputShape).run()); - } + } + + void generateUnmodelledErrors(GenerationContext context) { + writerDelegator.useFileWriter( + "%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), + SmithyNameResolver.smithyTypesNamespace(service), + writer -> { + writer.write( + """ + type $LBaseException interface { + // This is a dummy method to allow type assertion since Go empty interfaces + // aren't useful for type assertion checks. No concrete class is expected to implement + // this method. This is also not exported. + interfaceBindingMethod() + } + """, + service.toShapeId().getName() + ); + } + ); + writerDelegator.useFileWriter( + "%s/unmodelled_errors.go".formatted( + SmithyNameResolver.smithyTypesNamespace(service) + ), + SmithyNameResolver.smithyTypesNamespace(service), + writer -> { + writer.addUseImports(SmithyGoDependency.FMT); + writer.write( + """ + type CollectionOfErrors struct { + $LBaseException + ListOfErrors []error + Message string + } + + func (e CollectionOfErrors) Error() string { + return fmt.Sprintf("message: %s\\n err %v", e.Message, e.ListOfErrors) + } + + type OpaqueError struct { + $LBaseException + ErrObject interface{} + } + + func (e OpaqueError) Error() string { + return fmt.Sprintf("message: %v", e.ErrObject ) + } + """, + service.toShapeId().getName(), + service.toShapeId().getName() + ); + } + ); + } + + void generateUnboundedStructures(GenerationContext context) { + final var serviceOperationShapes = model + .getServiceShapes() + .stream() + .map(topDownIndex::getContainedOperations) + .flatMap(Collection::stream) + .map(OperationShape::toShapeId) + .collect(Collectors.toSet()); + final var nonServiceOperationShapes = model + .getOperationShapes() + .stream() + .map(Shape::getId) + .filter(operationShapeId -> + operationShapeId.getNamespace().equals(service.getId().getNamespace()) + ) + .collect(Collectors.toSet()); + nonServiceOperationShapes.removeAll(serviceOperationShapes); + for (final var operationShapeId : nonServiceOperationShapes) { + OperationShape operationShape = model.expectShape( + operationShapeId, + OperationShape.class + ); + StructureShape inputShape = model.expectShape( + operationShape.getInputShape(), + StructureShape.class + ); + writerDelegator.useShapeWriter( + inputShape, + w -> new StructureGenerator(context, w, inputShape).run() + ); + StructureShape outputShape = model.expectShape( + operationShape.getOutputShape(), + StructureShape.class + ); + writerDelegator.useShapeWriter( + outputShape, + w -> new StructureGenerator(context, w, outputShape).run() + ); } - - void generateReferencedResources(GenerationContext context) { - var refResources = model.getShapesWithTrait(ReferenceTrait.class); - for (final var refResource : refResources) { - if (!refResource.expectTrait(ReferenceTrait.class).isService()) { - final var resource = refResource.expectTrait(ReferenceTrait.class).getReferentId(); - final var resourceShape = model.expectShape(resource); - - if (!service.toShapeId().getNamespace().equals(resource.getNamespace())) { - - continue; - } - writerDelegator.useFileWriter("%s/types.go".formatted(SmithyNameResolver.smithyTypesNamespace(service)), SmithyNameResolver.smithyTypesNamespace(service), writer -> { - writer.write(""" - type I$L interface { - ${C|} - } - """, resource.getName(), writer.consumer((w) -> { - model.expectShape(resource, ResourceShape.class).getOperations().forEach(operation -> { - var operationShape = model.expectShape(operation, OperationShape.class); - w.write(""" - $L($L) (*$L, error) - """, operationShape.getId().getName(), operationShape.getInputShape().getName(), operationShape.getOutputShape().getName()); - }); - })); - }); - - if (model.expectShape(resource, ResourceShape.class).hasTrait(ExtendableTrait.class)) { - generateNativeResourceWrapper(context, model.expectShape(resource, ResourceShape.class)); - } - - writerDelegator.useFileWriter("%s/%s.go".formatted(SmithyNameResolver.shapeNamespace(service), resource.getName()), SmithyNameResolver.shapeNamespace(service), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(context.settings().getService().getNamespace()), SmithyNameResolver.smithyTypesNamespace(service)); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resource.getNamespace()), DafnyNameResolver.dafnyTypesNamespace(resourceShape)); - writer.write(""" - type %s struct { - Impl %s.I%s - } - """.formatted(resource.getName(), DafnyNameResolver.dafnyTypesNamespace(resourceShape), resource.getName())); - - model.expectShape(resource, ResourceShape.class).getOperations().forEach(operation -> { - final var operationShape = model.expectShape(operation, OperationShape.class); - final var inputShape = model.expectShape(operationShape.getInputShape()); - - - final var outputShape = model.expectShape(operationShape.getOutputShape()); - final var inputType = inputShape.hasTrait(UnitTypeTrait.class) ? "" : "params %s".formatted(SmithyNameResolver.getSmithyType(inputShape, symbolProvider.toSymbol(inputShape))); - final var outputType = outputShape.hasTrait(UnitTypeTrait.class) ? "" : "*%s".formatted(SmithyNameResolver.getSmithyType(outputShape, symbolProvider.toSymbol(outputShape))); - - String baseClientCall; - if (inputShape.hasTrait(UnitTypeTrait.class)) { - baseClientCall = "var dafny_response = this.Impl.%s()".formatted(operationShape.getId().getName()); - } else { - baseClientCall = """ - var dafny_request %s = %s(params) - var dafny_response = this.Impl.%s(dafny_request) - """.formatted(DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(inputShape)), - SmithyNameResolver.getToDafnyMethodName(service, inputShape, ""), operationShape.getId().getName()); - } - - String returnResponse, returnError; - if (outputShape.hasTrait(UnitTypeTrait.class)) { - returnResponse = "return nil"; - returnError = "return"; - } else { - returnResponse = """ - var native_response = %s(dafny_response.Extract().(%s)) - return &native_response, nil - """.formatted(SmithyNameResolver.getFromDafnyMethodName(service, outputShape, ""), - DafnyNameResolver.getDafnyType(inputShape, symbolProvider.toSymbol(outputShape))); - returnError = "return nil,"; - } - - - writer.write(""" - func (this *$L) $L($L) ($L, error) { - $L - if (dafny_response.Is_Failure()) { - err := dafny_response.Dtor_error().($L.Error); - ${C|} - if err.Is_CollectionOfErrors() { - $L CollectionOfErrors_Output_FromDafny(err) - } - if err.Is_Opaque() { - $L OpaqueError_Output_FromDafny(err) - } - } - $L - } - """, - resource.getName(), - operationShape.getId().getName(), - inputType, outputType, - baseClientCall, - DafnyNameResolver.dafnyTypesNamespace(service), - writer.consumer(w -> { - for (var errorShape : - model.getShapesWithTrait(ErrorTrait.class)) { - w.write(""" - if err.Is_$L() { - $L $L(err) - } - """, errorShape.toShapeId().getName(), returnError, SmithyNameResolver.getFromDafnyMethodName(service, errorShape, "")); - } - }), returnError, returnError, returnResponse - ); - }); - }); - } else { - //Generate Service - } + } + + void generateReferencedResources(GenerationContext context) { + var refResources = model.getShapesWithTrait(ReferenceTrait.class); + for (final var refResource : refResources) { + if (!refResource.expectTrait(ReferenceTrait.class).isService()) { + final var resource = refResource + .expectTrait(ReferenceTrait.class) + .getReferentId(); + final var resourceShape = model.expectShape(resource); + + if ( + !service.toShapeId().getNamespace().equals(resource.getNamespace()) + ) { + continue; + } + writerDelegator.useFileWriter( + "%s/types.go".formatted( + SmithyNameResolver.smithyTypesNamespace(service) + ), + SmithyNameResolver.smithyTypesNamespace(service), + writer -> { + writer.write( + """ + type I$L interface { + ${C|} + } + """, + resource.getName(), + writer.consumer(w -> { + model + .expectShape(resource, ResourceShape.class) + .getOperations() + .forEach(operation -> { + var operationShape = model.expectShape( + operation, + OperationShape.class + ); + w.write( + """ + $L($L) (*$L, error) + """, + operationShape.getId().getName(), + operationShape.getInputShape().getName(), + operationShape.getOutputShape().getName() + ); + }); + }) + ); + } + ); + + if ( + model + .expectShape(resource, ResourceShape.class) + .hasTrait(ExtendableTrait.class) + ) { + generateNativeResourceWrapper( + context, + model.expectShape(resource, ResourceShape.class) + ); } - } - void generateNativeResourceWrapper(GenerationContext context, ResourceShape resourceShape) { - writerDelegator.useFileWriter("%s/NativeWrapper.go".formatted(SmithyNameResolver.shapeNamespace(service)), SmithyNameResolver.shapeNamespace(service), writer -> { - writer.addImportFromModule(context.settings().getModuleName(), SmithyNameResolver.smithyTypesNamespace(service)); - writer.addImportFromModule("github.com/dafny-lang/DafnyStandardLibGo", "Wrappers"); - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resourceShape.toShapeId().getNamespace()), DafnyNameResolver.dafnyTypesNamespace(resourceShape)); + writerDelegator.useFileWriter( + "%s/%s.go".formatted( + SmithyNameResolver.shapeNamespace(service), + resource.getName() + ), + SmithyNameResolver.shapeNamespace(service), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + context.settings().getService().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(service) + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + resource.getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(resourceShape) + ); + writer.write( + """ + type %s struct { + Impl %s.I%s + } + """.formatted( + resource.getName(), + DafnyNameResolver.dafnyTypesNamespace(resourceShape), + resource.getName() + ) + ); - writer.write(""" - type NativeWrapper struct { - %s.I%s - Impl %s.I%s - } - """.formatted(DafnyNameResolver.dafnyTypesNamespace(resourceShape), resourceShape.getId().getName(), SmithyNameResolver.smithyTypesNamespace(resourceShape), resourceShape.getId().getName())); + model + .expectShape(resource, ResourceShape.class) + .getOperations() + .forEach(operation -> { + final var operationShape = model.expectShape( + operation, + OperationShape.class + ); + final var inputShape = model.expectShape( + operationShape.getInputShape() + ); - resourceShape.getOperations().forEach(operation -> { - final var operationShape = model.expectShape(operation, OperationShape.class); - final var inputShape = model.expectShape(operationShape.getInputShape()); - final var outputShape = model.expectShape(operationShape.getOutputShape()); - final var inputType = inputShape.hasTrait(UnitTypeTrait.class) ? "" : "input %s".formatted(DafnyNameResolver.getDafnyType(resourceShape, symbolProvider.toSymbol(inputShape))); - final var outputType = outputShape.hasTrait(UnitTypeTrait.class) ? "" : "*%s,".formatted(SmithyNameResolver.getSmithyType(outputShape, symbolProvider.toSymbol(outputShape))); + final var outputShape = model.expectShape( + operationShape.getOutputShape() + ); + final var inputType = inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "params %s".formatted( + SmithyNameResolver.getSmithyType( + inputShape, + symbolProvider.toSymbol(inputShape) + ) + ); + final var outputType = outputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "*%s".formatted( + SmithyNameResolver.getSmithyType( + outputShape, + symbolProvider.toSymbol(outputShape) + ) + ); + + String baseClientCall; + if (inputShape.hasTrait(UnitTypeTrait.class)) { + baseClientCall = + "var dafny_response = this.Impl.%s()".formatted( + operationShape.getId().getName() + ); + } else { + baseClientCall = + """ + var dafny_request %s = %s(params) + var dafny_response = this.Impl.%s(dafny_request) + """.formatted( + DafnyNameResolver.getDafnyType( + inputShape, + symbolProvider.toSymbol(inputShape) + ), + SmithyNameResolver.getToDafnyMethodName( + service, + inputShape, + "" + ), + operationShape.getId().getName() + ); + } - final var typeConversion = inputShape.hasTrait(UnitTypeTrait.class) ? "" : "var native_request = %s(input)".formatted(SmithyNameResolver.getFromDafnyMethodName(service, inputShape, "")); - final var clientCall = "this.Impl.%s(%s)".formatted(operationShape.getId().getName(), inputShape.hasTrait(UnitTypeTrait.class) ? "" : "native_request"); - String clientResponse, returnResponse; + String returnResponse, returnError; if (outputShape.hasTrait(UnitTypeTrait.class)) { - clientResponse = "var native_error"; - returnResponse = "dafny.TupleOf()"; - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + returnResponse = "return nil"; + returnError = "return"; } else { - clientResponse = "var native_response, native_error"; - returnResponse = "%s(*native_response)".formatted( - SmithyNameResolver.getToDafnyMethodName(service, outputShape, "")); + returnResponse = + """ + var native_response = %s(dafny_response.Extract().(%s)) + return &native_response, nil + """.formatted( + SmithyNameResolver.getFromDafnyMethodName( + service, + outputShape, + "" + ), + DafnyNameResolver.getDafnyType( + inputShape, + symbolProvider.toSymbol(outputShape) + ) + ); + returnError = "return nil,"; } - writer.write(""" - func (this *NativeWrapper) $L($L) Wrappers.Result { - $L - $L = $L - if native_error != nil { - switch native_error.(type) { - ${C|} - case $L.CollectionOfErrors: - return Wrappers.Companion_Result_.Create_Failure_(CollectionOfErrors_Input_ToDafny(native_error.($L.CollectionOfErrors))) - default: - return Wrappers.Companion_Result_.Create_Failure_(OpaqueError_Input_ToDafny(native_error.($L.OpaqueError))) - } + + writer.write( + """ + func (this *$L) $L($L) ($L, error) { + $L + if (dafny_response.Is_Failure()) { + err := dafny_response.Dtor_error().($L.Error); + ${C|} + if err.Is_CollectionOfErrors() { + $L CollectionOfErrors_Output_FromDafny(err) + } + if err.Is_Opaque() { + $L OpaqueError_Output_FromDafny(err) + } + } + $L + } + """, + resource.getName(), + operationShape.getId().getName(), + inputType, + outputType, + baseClientCall, + DafnyNameResolver.dafnyTypesNamespace(service), + writer.consumer(w -> { + for (var errorShape : model.getShapesWithTrait( + ErrorTrait.class + )) { + w.write( + """ + if err.Is_$L() { + $L $L(err) } - return Wrappers.Companion_Result_.Create_Success_($L) - } - """, - operationShape.getId().getName(), - inputType, typeConversion, clientResponse, clientCall, - writer.consumer(w -> resourceErrors(w)), SmithyNameResolver.smithyTypesNamespace(service), SmithyNameResolver.smithyTypesNamespace(service), SmithyNameResolver.smithyTypesNamespace(service), - returnResponse + """, + errorShape.toShapeId().getName(), + returnError, + SmithyNameResolver.getFromDafnyMethodName( + service, + errorShape, + "" + ) + ); + } + }), + returnError, + returnError, + returnResponse ); - }); - }); + }); + } + ); + } else { + //Generate Service + } } + } + + void generateNativeResourceWrapper( + GenerationContext context, + ResourceShape resourceShape + ) { + writerDelegator.useFileWriter( + "%s/NativeWrapper.go".formatted( + SmithyNameResolver.shapeNamespace(service) + ), + SmithyNameResolver.shapeNamespace(service), + writer -> { + writer.addImportFromModule( + context.settings().getModuleName(), + SmithyNameResolver.smithyTypesNamespace(service) + ); + writer.addImportFromModule( + "github.com/dafny-lang/DafnyStandardLibGo", + "Wrappers" + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + resourceShape.toShapeId().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(resourceShape) + ); + + writer.write( + """ + type NativeWrapper struct { + %s.I%s + Impl %s.I%s + } + """.formatted( + DafnyNameResolver.dafnyTypesNamespace(resourceShape), + resourceShape.getId().getName(), + SmithyNameResolver.smithyTypesNamespace(resourceShape), + resourceShape.getId().getName() + ) + ); + + resourceShape + .getOperations() + .forEach(operation -> { + final var operationShape = model.expectShape( + operation, + OperationShape.class + ); + final var inputShape = model.expectShape( + operationShape.getInputShape() + ); + final var outputShape = model.expectShape( + operationShape.getOutputShape() + ); + final var inputType = inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "input %s".formatted( + DafnyNameResolver.getDafnyType( + resourceShape, + symbolProvider.toSymbol(inputShape) + ) + ); + final var outputType = outputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "*%s,".formatted( + SmithyNameResolver.getSmithyType( + outputShape, + symbolProvider.toSymbol(outputShape) + ) + ); + + final var typeConversion = inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "var native_request = %s(input)".formatted( + SmithyNameResolver.getFromDafnyMethodName( + service, + inputShape, + "" + ) + ); + final var clientCall = + "this.Impl.%s(%s)".formatted( + operationShape.getId().getName(), + inputShape.hasTrait(UnitTypeTrait.class) + ? "" + : "native_request" + ); + String clientResponse, returnResponse; + if (outputShape.hasTrait(UnitTypeTrait.class)) { + clientResponse = "var native_error"; + returnResponse = "dafny.TupleOf()"; + writer.addImportFromModule( + "github.com/dafny-lang/DafnyRuntimeGo", + "dafny" + ); + } else { + clientResponse = "var native_response, native_error"; + returnResponse = + "%s(*native_response)".formatted( + SmithyNameResolver.getToDafnyMethodName( + service, + outputShape, + "" + ) + ); + } + writer.write( + """ + func (this *NativeWrapper) $L($L) Wrappers.Result { + $L + $L = $L + if native_error != nil { + switch native_error.(type) { + ${C|} + case $L.CollectionOfErrors: + return Wrappers.Companion_Result_.Create_Failure_(CollectionOfErrors_Input_ToDafny(native_error.($L.CollectionOfErrors))) + default: + return Wrappers.Companion_Result_.Create_Failure_(OpaqueError_Input_ToDafny(native_error.($L.OpaqueError))) + } + } + return Wrappers.Companion_Result_.Create_Success_($L) + } + """, + operationShape.getId().getName(), + inputType, + typeConversion, + clientResponse, + clientCall, + writer.consumer(w -> resourceErrors(w)), + SmithyNameResolver.smithyTypesNamespace(service), + SmithyNameResolver.smithyTypesNamespace(service), + SmithyNameResolver.smithyTypesNamespace(service), + returnResponse + ); + }); + } + ); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java index fb8ac01d2e..a2382f988f 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/DafnyLocalServiceTypeConversionProtocol.java @@ -1,5 +1,8 @@ package software.amazon.polymorph.smithygo.localservice; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Set; import software.amazon.polymorph.smithygo.codegen.ApplicationProtocol; import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoDelegator; @@ -22,23 +25,133 @@ import software.amazon.smithy.model.traits.UnitTypeTrait; import software.amazon.smithy.codegen.core.Symbol; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Set; +public class DafnyLocalServiceTypeConversionProtocol + implements ProtocolGenerator { -public class DafnyLocalServiceTypeConversionProtocol implements ProtocolGenerator { - public static String TO_DAFNY = "to_dafny.go"; - public static String TO_NATIVE = "to_native.go"; + public static String TO_DAFNY = "to_dafny.go"; + public static String TO_NATIVE = "to_native.go"; - @Override - public ShapeId getProtocol() { - return ShapeId.from("aws.polymorph#localService"); - } + @Override + public ShapeId getProtocol() { + return ShapeId.from("aws.polymorph#localService"); + } - @Override - public ApplicationProtocol getApplicationProtocol() { - return null; - } + @Override + public ApplicationProtocol getApplicationProtocol() { + return null; + } + + @Override + public void generateSerializers(GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var model = context.model(); + final var serviceShape = model.expectShape( + context.settings().getService(), + ServiceShape.class + ); + final var symbolProvider = context.symbolProvider(); + final var writerDelegator = context.writerDelegator(); + serviceShape + .getOperations() + .forEach(eachOperation -> { + final var operation = model.expectShape( + eachOperation, + OperationShape.class + ); + final var input = model.expectShape(operation.getInputShape()); + if (!alreadyVisited.contains(input.toShapeId())) { + alreadyVisited.add(input.toShapeId()); + if ( + !input.hasTrait(UnitTypeTrait.class) && + input + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var inputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName(serviceShape, input, ""); + final var inputSymbol = symbolProvider.toSymbol(input); + writerDelegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + input.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(input) + ); + writer.write( + """ + func $L(nativeInput $L)($L) { + ${C|} + }""", + inputToDafnyMethodName, + SmithyNameResolver.getSmithyType(input, inputSymbol), + DafnyNameResolver.getDafnyType(input, inputSymbol), + writer.consumer(w -> + generateRequestSerializer( + context, + operation, + context.writerDelegator() + ) + ) + ); + } + ); + } + } + + final var output = model.expectShape(operation.getOutputShape()); + if (!alreadyVisited.contains(output.toShapeId())) { + alreadyVisited.add(output.toShapeId()); + if ( + !output.hasTrait(UnitTypeTrait.class) && + output + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var outputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName(serviceShape, output, ""); + final var outputSymbol = symbolProvider.toSymbol(output); + writerDelegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + output.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(output) + ); + writer.write( + """ + func $L(nativeOutput $L)($L) { + ${C|} + }""", + outputToDafnyMethodName, + SmithyNameResolver.getSmithyType(output, outputSymbol), + DafnyNameResolver.getDafnyType(output, outputSymbol), + writer.consumer(w -> + generateResponseSerializer( + context, + operation, + context.writerDelegator() + ) + ) + ); + } + ); + } + } + }); @Override public void generateSerializers(GenerationContext context) { @@ -94,91 +207,205 @@ public void generateSerializers(GenerationContext context) { }); } } - }); - - final var refResources = context.model().getShapesWithTrait(ReferenceTrait.class); - for (var refResource : refResources) { - final var resource = refResource.expectTrait(ReferenceTrait.class).getReferentId(); - if (!refResource.expectTrait(ReferenceTrait.class).isService()) { - var resourceShape = model.expectShape(resource, ResourceShape.class); - resourceShape.getOperations().forEach(eachOperation -> { - final var operation = model.expectShape(eachOperation, OperationShape.class); - final var input = model.expectShape(operation.getInputShape()); - if (!alreadyVisited.contains(input.toShapeId())) { - alreadyVisited.add(input.toShapeId()); - if (!input.hasTrait(UnitTypeTrait.class) && input.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var inputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, input, ""); - final var inputSymbol = symbolProvider.toSymbol(input); - writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(input.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(input)); - writer.write(""" - func $L(nativeInput $L)($L) { - ${C|} - }""", inputToDafnyMethodName, SmithyNameResolver.getSmithyType(input, inputSymbol), - DafnyNameResolver.getDafnyType(input, inputSymbol), - writer.consumer(w -> generateRequestSerializer(context, operation, context.writerDelegator()))); - }); - } + if ( + !alreadyVisited.contains(resourceShape.toShapeId()) && + resourceShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + alreadyVisited.add(resourceShape.toShapeId()); + writerDelegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + var goBody = + """ + return nativeResource.(*%s).Impl + """.formatted(resourceShape.getId().getName()); + if (resourceShape.hasTrait(ExtendableTrait.class)) { + goBody = + """ + val, ok := nativeResource.(*%s) + if ok { + return val.Impl + } + return %s{&NativeWrapper{Impl: nativeResource}}.Impl + """.formatted( + resourceShape.getId().getName(), + resourceShape.getId().getName() + ); + } + writer.write( + """ + func $L_ToDafny(nativeResource $L.I$L) $L.I$L { + $L } - - final var output = model.expectShape(operation.getOutputShape()); - if (!alreadyVisited.contains(output.toShapeId())) { - alreadyVisited.add(output.toShapeId()); - if (!output.hasTrait(UnitTypeTrait.class) && output.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var outputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, output, ""); - final var outputSymbol = symbolProvider.toSymbol(output); - writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(output.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(output)); - writer.write(""" - func $L(nativeOutput $L)($L) { - ${C|} - }""", outputToDafnyMethodName, SmithyNameResolver.getSmithyType(output, outputSymbol), - DafnyNameResolver.getDafnyType(output, outputSymbol), - writer.consumer(w -> generateResponseSerializer(context, operation, context.writerDelegator()))); - }); - } - } - if (!alreadyVisited.contains(resourceShape.toShapeId()) && resourceShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - alreadyVisited.add(resourceShape.toShapeId()); - writerDelegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - var goBody = """ - return nativeResource.(*%s).Impl - """.formatted(resourceShape.getId().getName()); - if (resourceShape.hasTrait(ExtendableTrait.class)) { - goBody = """ - val, ok := nativeResource.(*%s) - if ok { - return val.Impl - } - return %s{&NativeWrapper{Impl: nativeResource}}.Impl - """.formatted(resourceShape.getId().getName(), resourceShape.getId().getName()); - } - writer.write(""" - func $L_ToDafny(nativeResource $L.I$L) $L.I$L { - $L - } - """, resourceShape.getId().getName(), SmithyNameResolver.smithyTypesNamespace(resourceShape), resourceShape.getId().getName(), DafnyNameResolver.dafnyTypesNamespace(resourceShape), resourceShape.getId().getName(), goBody); - }); - } - }); + """, + resourceShape.getId().getName(), + SmithyNameResolver.smithyTypesNamespace(resourceShape), + resourceShape.getId().getName(), + DafnyNameResolver.dafnyTypesNamespace(resourceShape), + resourceShape.getId().getName(), + goBody + ); + } + ); } - } - generateErrorSerializer(context); - if (serviceShape.hasTrait(LocalServiceTrait.class)) { - generateConfigSerializer(context); - } + }); + } } + generateErrorSerializer(context); + if (serviceShape.hasTrait(LocalServiceTrait.class)) { + generateConfigSerializer(context); + } + } - @Override - public void generateDeserializers(GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var serviceShape = context.settings().getService(context.model()); - final var delegator = context.writerDelegator(); + @Override + public void generateDeserializers(GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var serviceShape = context.settings().getService(context.model()); + final var delegator = context.writerDelegator(); - serviceShape.getOperations().forEach(eachOperation -> { - var operation = context.model().expectShape(eachOperation, OperationShape.class); + serviceShape + .getOperations() + .forEach(eachOperation -> { + var operation = context + .model() + .expectShape(eachOperation, OperationShape.class); + + final var input = context + .model() + .expectShape(operation.getInputShape()); + if (!alreadyVisited.contains(input.toShapeId())) { + alreadyVisited.add(input.toShapeId()); + if ( + !input.hasTrait(UnitTypeTrait.class) && + input + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var inputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + input, + "" + ); + final var inputSymbol = context.symbolProvider().toSymbol(input); + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + input.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(input) + ); + + writer.write( + """ + func $L(dafnyInput $L)($L) { + ${C|} + }""", + inputFromDafnyMethodName, + DafnyNameResolver.getDafnyType(input, inputSymbol), + SmithyNameResolver.getSmithyType(input, inputSymbol), + writer.consumer(w -> + generateRequestDeserializer( + context, + operation, + context.writerDelegator() + ) + ) + ); + } + ); + } + } + + final var output = context + .model() + .expectShape(operation.getOutputShape()); + if (!alreadyVisited.contains(output.toShapeId())) { + alreadyVisited.add(output.toShapeId()); + if ( + !output.hasTrait(UnitTypeTrait.class) && + output + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + final var outputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + output, + "" + ); + final var outputSymbol = context.symbolProvider().toSymbol(output); + + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + output.toShapeId().getNamespace() + ), + SmithyNameResolver.smithyTypesNamespace(output) + ); + + writer.write( + """ + func $L(dafnyOutput $L)($L) { + ${C|} + }""", + outputFromDafnyMethodName, + DafnyNameResolver.getDafnyType(output, outputSymbol), + SmithyNameResolver.getSmithyType(output, outputSymbol), + writer.consumer(w -> + generateResponseDeserializer( + context, + operation, + context.writerDelegator() + ) + ) + ); + } + ); + } + } + }); + + var refResources = context.model().getShapesWithTrait(ReferenceTrait.class); + for (var refResource : refResources) { + final var resource = refResource + .expectTrait(ReferenceTrait.class) + .getReferentId(); - final var input = context.model().expectShape(operation.getInputShape()); + if (!refResource.expectTrait(ReferenceTrait.class).isService()) { + var resourceShape = context + .model() + .expectShape(resource, ResourceShape.class); + resourceShape + .getOperations() + .forEach(eachOperation -> { + final var operation = context + .model() + .expectShape(eachOperation, OperationShape.class); + final var input = context + .model() + .expectShape(operation.getInputShape()); if (!alreadyVisited.contains(input.toShapeId())) { alreadyVisited.add(input.toShapeId()); if (!input.hasTrait(UnitTypeTrait.class) && input.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { @@ -226,444 +453,674 @@ public void generateDeserializers(GenerationContext context) { }); } } - }); - - var refResources = context.model().getShapesWithTrait(ReferenceTrait.class); - for (var refResource : refResources) { - final var resource = refResource.expectTrait(ReferenceTrait.class).getReferentId(); - - if (!refResource.expectTrait(ReferenceTrait.class).isService()) { - var resourceShape = context.model().expectShape(resource, ResourceShape.class); - resourceShape.getOperations().forEach(eachOperation -> { - final var operation = context.model().expectShape(eachOperation, OperationShape.class); - final var input = context.model().expectShape(operation.getInputShape()); - if (!alreadyVisited.contains(input.toShapeId())) { - alreadyVisited.add(input.toShapeId()); - if (!input.hasTrait(UnitTypeTrait.class) && input.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var inputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, input, ""); - final var inputSymbol = context.symbolProvider().toSymbol(input); - - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(input.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(input)); - - writer.write(""" - func $L(dafnyInput $L)($L) { - ${C|} - }""", inputFromDafnyMethodName, DafnyNameResolver.getDafnyType(input, inputSymbol), - SmithyNameResolver.getSmithyType(input, inputSymbol), - writer.consumer(w -> generateRequestDeserializer(context, operation, context.writerDelegator()))); - }); - } + if ( + !alreadyVisited.contains(resourceShape.toShapeId()) && + resourceShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + alreadyVisited.add(resourceShape.toShapeId()); + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + var extendableResourceWrapperCheck = ""; + if (resourceShape.hasTrait(ExtendableTrait.class)) { + extendableResourceWrapperCheck = + """ + val, ok := dafnyResource.(*NativeWrapper) + if ok { + return val.Impl + } + """; + } + writer.write( + """ + func $L_FromDafny(dafnyResource $L.I$L)($L.I$L) { + $L + return &$L{dafnyResource} } + """, + resourceShape.getId().getName(), + DafnyNameResolver.dafnyTypesNamespace(resourceShape), + resourceShape.getId().getName(), + SmithyNameResolver.smithyTypesNamespace(resourceShape), + resourceShape.getId().getName(), + extendableResourceWrapperCheck, + resourceShape.getId().getName() + ); + } + ); + } + }); + } + } + generateErrorDeserializer(context); + if (serviceShape.hasTrait(LocalServiceTrait.class)) { + generateConfigDeserializer(context); + } + } - final var output = context.model().expectShape(operation.getOutputShape()); - if (!alreadyVisited.contains(output.toShapeId())) { - alreadyVisited.add(output.toShapeId()); - if (!output.hasTrait(UnitTypeTrait.class) && output.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - final var outputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, output, ""); - final var outputSymbol = context.symbolProvider().toSymbol(output); - - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(output.toShapeId().getNamespace()), SmithyNameResolver.smithyTypesNamespace(output)); - - writer.write(""" - func $L(dafnyOutput $L)($L) { - ${C|} - }""", outputFromDafnyMethodName, DafnyNameResolver.getDafnyType(output, outputSymbol), - SmithyNameResolver.getSmithyType(output, outputSymbol), - writer.consumer(w -> generateResponseDeserializer(context, operation, context.writerDelegator()))); - }); - } - } - if (!alreadyVisited.contains(resourceShape.toShapeId()) && resourceShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - alreadyVisited.add(resourceShape.toShapeId()); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - var extendableResourceWrapperCheck = ""; - if (resourceShape.hasTrait(ExtendableTrait.class)) { - extendableResourceWrapperCheck = """ - val, ok := dafnyResource.(*NativeWrapper) - if ok { - return val.Impl - } - """; - } - writer.write(""" - func $L_FromDafny(dafnyResource $L.I$L)($L.I$L) { - $L - return &$L{dafnyResource} - } - """, resourceShape.getId().getName(), DafnyNameResolver.dafnyTypesNamespace(resourceShape), resourceShape.getId().getName(), SmithyNameResolver.smithyTypesNamespace(resourceShape), resourceShape.getId().getName(), extendableResourceWrapperCheck, resourceShape.getId().getName()); - }); - } + private void generateRequestSerializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + final var targetShape = context + .model() + .expectShape(operation.getInputShape()); + delegator.useFileWriter( + "%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var input = targetShape.accept( + new SmithyToDafnyShapeVisitor( + context, + "nativeInput", + writer, + false, + false, + false + ) + ); + writer.write( + """ + return $L + """, + input + ); + } + ); + } - }); - } - } - generateErrorDeserializer(context); - if (serviceShape.hasTrait(LocalServiceTrait.class)) { - generateConfigDeserializer(context); - } + private void generateResponseSerializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + final var targetShape = context + .model() + .expectShape(operation.getOutputShape()); + delegator.useFileWriter( + "%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var input = targetShape.accept( + new SmithyToDafnyShapeVisitor( + context, + "nativeOutput", + writer, + false, + false, + false + ) + ); + writer.write( + """ + return $L + """, + input + ); + } + ); + } - } + private void generateRequestDeserializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(operation), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var inputShape = operation.getInputShape(); - private void generateRequestSerializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - final var targetShape = context.model().expectShape(operation.getInputShape()); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), SmithyNameResolver.shapeNamespace(operation), writer -> { - final var input = targetShape.accept(new SmithyToDafnyShapeVisitor( - context, - "nativeInput", - writer, - false, false, false - )); - writer.write(""" - return $L - """, - input); - } + final var targetShape = context.model().expectShape(inputShape); + final var input = targetShape.accept( + new DafnyToSmithyShapeVisitor(context, "dafnyInput", writer, false) ); - } - private void generateResponseSerializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - final var targetShape = context.model().expectShape(operation.getOutputShape()); - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_DAFNY), SmithyNameResolver.shapeNamespace(operation), writer -> { - final var input = targetShape.accept(new SmithyToDafnyShapeVisitor( - context, - "nativeOutput", - writer, - false, false, false - )); - writer.write(""" - return $L - """, - input); - } + writer.write( + """ + return $L + """, + input ); - } + } + ); + } - private void generateRequestDeserializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_NATIVE), SmithyNameResolver.shapeNamespace(operation), writer -> { - - final var inputShape = operation.getInputShape(); - - final var targetShape = context.model().expectShape(inputShape); - final var input = targetShape.accept(new DafnyToSmithyShapeVisitor( - context, - "dafnyInput", - writer, - false - )); - - writer.write(""" - return $L - """, input); - }); - } + private void generateResponseDeserializer( + final GenerationContext context, + final OperationShape operation, + final GoDelegator delegator + ) { + delegator.useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(operation), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(operation), + writer -> { + final var outputShape = operation.getOutputShape(); - private void generateResponseDeserializer( - final GenerationContext context, - final OperationShape operation, - final GoDelegator delegator - ) { - delegator.useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(operation), TO_NATIVE), SmithyNameResolver.shapeNamespace(operation), writer -> { - - final var outputShape = operation.getOutputShape(); - - final var targetShape = context.model().expectShape(outputShape); - final var output = targetShape.accept(new DafnyToSmithyShapeVisitor( - context, - "dafnyOutput", - writer, - false - )); - - writer.write(""" - return $L - """, output); - }); - } + final var targetShape = context.model().expectShape(outputShape); + final var output = targetShape.accept( + new DafnyToSmithyShapeVisitor(context, "dafnyOutput", writer, false) + ); - private void generateConfigSerializer(final GenerationContext context) { - final var service = context.settings().getService(context.model()); - final var localServiceTrait = service.expectTrait(LocalServiceTrait.class); - final var configShape = context.model().expectShape(localServiceTrait.getConfigId(), StructureShape.class); - final var getInputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(service, configShape, ""); - - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(service), TO_DAFNY), SmithyNameResolver.shapeNamespace(service), writer -> { - writer.write(""" - func $L(nativeInput $L)($L) { - ${C|} - }""", - getInputToDafnyMethodName, SmithyNameResolver.getSmithyType(configShape, context.symbolProvider().toSymbol(configShape)), DafnyNameResolver.getDafnyType(configShape, context.symbolProvider().toSymbol(configShape)), - writer.consumer(w -> { - String output = configShape.accept(new SmithyToDafnyShapeVisitor( - context, - "nativeInput", - writer, - true, false, false - )); - writer.write(""" - return $L - """, output); - })); - }); - } + writer.write( + """ + return $L + """, + output + ); + } + ); + } - private void generateErrorSerializer(final GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var serviceShape = context.settings().getService(context.model()); - final var errorShapes = context.model().getShapesWithTrait(ErrorTrait.class); + private void generateConfigSerializer(final GenerationContext context) { + final var service = context.settings().getService(context.model()); + final var localServiceTrait = service.expectTrait(LocalServiceTrait.class); + final var configShape = context + .model() + .expectShape(localServiceTrait.getConfigId(), StructureShape.class); + final var getInputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName(service, configShape, ""); - for (final var errorShape : - errorShapes) { - if (!errorShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - continue; - } - if (!alreadyVisited.contains(errorShape.toShapeId())) { - alreadyVisited.add(errorShape.toShapeId()); - final var getInputToDafnyMethodName = SmithyNameResolver.getToDafnyMethodName(serviceShape, errorShape, ""); - - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(errorShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(errorShape), writer -> { - writer.write(""" - func $L(nativeInput $L)($L) { - ${C|} - }""", - getInputToDafnyMethodName, SmithyNameResolver.getSmithyType(errorShape, context.symbolProvider().toSymbol(errorShape)), DafnyNameResolver.getDafnyBaseErrorType(errorShape), - writer.consumer(w -> { - String output = errorShape.accept(new SmithyToDafnyShapeVisitor( - context, - "nativeInput", - writer, - false, false, false - )); - writer.write(""" - return $L - """, output); - })); - }); - } + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted(SmithyNameResolver.shapeNamespace(service), TO_DAFNY), + SmithyNameResolver.shapeNamespace(service), + writer -> { + writer.write( + """ + func $L(nativeInput $L)($L) { + ${C|} + }""", + getInputToDafnyMethodName, + SmithyNameResolver.getSmithyType( + configShape, + context.symbolProvider().toSymbol(configShape) + ), + DafnyNameResolver.getDafnyType( + configShape, + context.symbolProvider().toSymbol(configShape) + ), + writer.consumer(w -> { + String output = configShape.accept( + new SmithyToDafnyShapeVisitor( + context, + "nativeInput", + writer, + true, + false, + false + ) + ); + writer.write( + """ + return $L + """, + output + ); + }) + ); } + ); + } - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_DAFNY), SmithyNameResolver.shapeNamespace(serviceShape), writer -> { - writer.write(""" - func CollectionOfErrors_Input_ToDafny(nativeInput $L.CollectionOfErrors)($L.Error) { - var e []interface{} - for _, i2 := range nativeInput.ListOfErrors { - e = append(e, Error_ToDafny(i2)) - } - return $L.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) - } - func OpaqueError_Input_ToDafny(nativeInput $L.OpaqueError)($L.Error) { - return $L.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) - }""", SmithyNameResolver.smithyTypesNamespace(serviceShape), - DafnyNameResolver.dafnyTypesNamespace(serviceShape), - DafnyNameResolver.dafnyTypesNamespace(serviceShape), SmithyNameResolver.smithyTypesNamespace(serviceShape), DafnyNameResolver.dafnyTypesNamespace(serviceShape), DafnyNameResolver.dafnyTypesNamespace(serviceShape)); - }); - - - context.writerDelegator() - .useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), TO_DAFNY), - SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), writer -> { - writer.write(""" - func Error_ToDafny(err error)($L.Error) { - switch err.(type) { - // Service Errors - ${C|} - //DependentErrors - ${C|} - - //Unmodelled Errors - case $L.CollectionOfErrors: - return CollectionOfErrors_Input_ToDafny(err.($L.CollectionOfErrors)) - - default: - error, ok := err.($L.OpaqueError) - if !ok { - panic("Error is not an OpaqueError") - } - return OpaqueError_Input_ToDafny(error) - } - } - """, DafnyNameResolver.dafnyTypesNamespace(serviceShape), - writer.consumer(w -> { - for (var error : serviceShape.getErrors()) { - w.write(""" - case $L: - return $L(err.($L)) - """, SmithyNameResolver.getSmithyType(context.model().expectShape(error), context.symbolProvider().toSymbol(context.model().expectShape(error))), - SmithyNameResolver.getToDafnyMethodName(serviceShape, context.model().expectShape(error), ""), - SmithyNameResolver.getSmithyType(context.model().expectShape(error), context.symbolProvider().toSymbol(context.model().expectShape(error)))); - } - }), - writer.consumer(w -> { - var dependencies = serviceShape.hasTrait(LocalServiceTrait.class) ? serviceShape.expectTrait(LocalServiceTrait.class).getDependencies() : new LinkedList(); - if (dependencies != null) { - for (var dep : dependencies) { - var depShape = context.model().expectShape(dep); - w.write(""" - case $L.$LBaseException: - return $L.Create_$L_($L.Error_ToDafny(err)) - """, SmithyNameResolver.smithyTypesNamespace(depShape), dep.getName(), DafnyNameResolver.getDafnyErrorCompanion(serviceShape), dep.getName(), SmithyNameResolver.shapeNamespace(depShape)); - } - } - }), - SmithyNameResolver.smithyTypesNamespace(serviceShape), SmithyNameResolver.smithyTypesNamespace(serviceShape), SmithyNameResolver.smithyTypesNamespace(serviceShape) - ); - }); - } + private void generateErrorSerializer(final GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var serviceShape = context.settings().getService(context.model()); + final var errorShapes = context + .model() + .getShapesWithTrait(ErrorTrait.class); + + for (final var errorShape : errorShapes) { + if ( + !errorShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + continue; + } + if (!alreadyVisited.contains(errorShape.toShapeId())) { + alreadyVisited.add(errorShape.toShapeId()); + final var getInputToDafnyMethodName = + SmithyNameResolver.getToDafnyMethodName(serviceShape, errorShape, ""); - private void generateConfigDeserializer(final GenerationContext context) { - final var serviceShape = context.settings().getService(context.model()); - final var localServiceTrait = serviceShape.expectTrait(LocalServiceTrait.class); - final var configShape = context.model().expectShape(localServiceTrait.getConfigId(), StructureShape.class); - final var getOutputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, configShape, ""); - - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(serviceShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(configShape), writer -> { - writer.write(""" - func $L(dafnyOutput $L)($L) { - ${C|} - }""", - getOutputFromDafnyMethodName, DafnyNameResolver.getDafnyType(configShape, context.symbolProvider().toSymbol(configShape)), SmithyNameResolver.getSmithyType(configShape, context.symbolProvider().toSymbol(configShape)), - writer.consumer(w -> { - String output = configShape.accept(new DafnyToSmithyShapeVisitor( - context, - "dafnyOutput", - writer, - true - )); - writer.write(""" - return $L - """, output); - })); - }); + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(errorShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(errorShape), + writer -> { + writer.write( + """ + func $L(nativeInput $L)($L) { + ${C|} + }""", + getInputToDafnyMethodName, + SmithyNameResolver.getSmithyType( + errorShape, + context.symbolProvider().toSymbol(errorShape) + ), + DafnyNameResolver.getDafnyBaseErrorType(errorShape), + writer.consumer(w -> { + String output = errorShape.accept( + new SmithyToDafnyShapeVisitor( + context, + "nativeInput", + writer, + false, + false, + false + ) + ); + writer.write( + """ + return $L + """, + output + ); + }) + ); + } + ); + } } - private void generateErrorDeserializer(final GenerationContext context) { - final Set alreadyVisited = new HashSet<>(); - final var serviceShape = context.settings().getService(context.model()); - final var errorShapes = context.model().getShapesWithTrait(ErrorTrait.class); - for (final var errorShape : - errorShapes) { - if (!errorShape.toShapeId().getNamespace().equals(serviceShape.toShapeId().getNamespace())) { - continue; + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace(serviceShape), + writer -> { + writer.write( + """ + func CollectionOfErrors_Input_ToDafny(nativeInput $L.CollectionOfErrors)($L.Error) { + var e []interface{} + for _, i2 := range nativeInput.ListOfErrors { + e = append(e, Error_ToDafny(i2)) + } + return $L.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) } - if (!alreadyVisited.contains(errorShape.toShapeId())) { - alreadyVisited.add(errorShape.toShapeId()); - final var getOutputFromDafnyMethodName = SmithyNameResolver.getFromDafnyMethodName(serviceShape, errorShape, ""); - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(errorShape), TO_NATIVE), SmithyNameResolver.shapeNamespace(errorShape), writer -> { - writer.write(""" - func $L(dafnyOutput $L)($L) { - ${C|} - }""", - getOutputFromDafnyMethodName, DafnyNameResolver.getDafnyBaseErrorType(errorShape), SmithyNameResolver.getSmithyType(errorShape, context.symbolProvider().toSymbol(errorShape)), - writer.consumer(w -> { - String output = errorShape.accept(new DafnyToSmithyShapeVisitor( - context, - "dafnyOutput", - writer, - false - )); - writer.write(""" - return $L - """, output); - })); - }); + func OpaqueError_Input_ToDafny(nativeInput $L.OpaqueError)($L.Error) { + return $L.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) + }""", + SmithyNameResolver.smithyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape) + ); + } + ); + + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace( + context.settings().getService(context.model()) + ), + TO_DAFNY + ), + SmithyNameResolver.shapeNamespace( + context.settings().getService(context.model()) + ), + writer -> { + writer.write( + """ + func Error_ToDafny(err error)($L.Error) { + switch err.(type) { + // Service Errors + ${C|} + //DependentErrors + ${C|} + + //Unmodelled Errors + case $L.CollectionOfErrors: + return CollectionOfErrors_Input_ToDafny(err.($L.CollectionOfErrors)) + + default: + error, ok := err.($L.OpaqueError) + if !ok { + panic("Error is not an OpaqueError") + } + return OpaqueError_Input_ToDafny(error) + } } + """, + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + writer.consumer(w -> { + for (var error : serviceShape.getErrors()) { + w.write( + """ + case $L: + return $L(err.($L)) + """, + SmithyNameResolver.getSmithyType( + context.model().expectShape(error), + context + .symbolProvider() + .toSymbol(context.model().expectShape(error)) + ), + SmithyNameResolver.getToDafnyMethodName( + serviceShape, + context.model().expectShape(error), + "" + ), + SmithyNameResolver.getSmithyType( + context.model().expectShape(error), + context + .symbolProvider() + .toSymbol(context.model().expectShape(error)) + ) + ); + } + }), + writer.consumer(w -> { + var dependencies = serviceShape.hasTrait(LocalServiceTrait.class) + ? serviceShape + .expectTrait(LocalServiceTrait.class) + .getDependencies() + : new LinkedList(); + if (dependencies != null) { + for (var dep : dependencies) { + var depShape = context.model().expectShape(dep); + w.write( + """ + case $L.$LBaseException: + return $L.Create_$L_($L.Error_ToDafny(err)) + """, + SmithyNameResolver.smithyTypesNamespace(depShape), + dep.getName(), + DafnyNameResolver.getDafnyErrorCompanion(serviceShape), + dep.getName(), + SmithyNameResolver.shapeNamespace(depShape) + ); + } + } + }), + SmithyNameResolver.smithyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape) + ); + } + ); + } + + private void generateConfigDeserializer(final GenerationContext context) { + final var serviceShape = context.settings().getService(context.model()); + final var localServiceTrait = serviceShape.expectTrait( + LocalServiceTrait.class + ); + final var configShape = context + .model() + .expectShape(localServiceTrait.getConfigId(), StructureShape.class); + final var getOutputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName(serviceShape, configShape, ""); + + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(serviceShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(configShape), + writer -> { + writer.write( + """ + func $L(dafnyOutput $L)($L) { + ${C|} + }""", + getOutputFromDafnyMethodName, + DafnyNameResolver.getDafnyType( + configShape, + context.symbolProvider().toSymbol(configShape) + ), + SmithyNameResolver.getSmithyType( + configShape, + context.symbolProvider().toSymbol(configShape) + ), + writer.consumer(w -> { + String output = configShape.accept( + new DafnyToSmithyShapeVisitor( + context, + "dafnyOutput", + writer, + true + ) + ); + writer.write( + """ + return $L + """, + output + ); + }) + ); } + ); + } - context.writerDelegator().useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), TO_NATIVE), SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), writer -> { - writer.write(""" - func CollectionOfErrors_Output_FromDafny(dafnyOutput $L.Error)($L.CollectionOfErrors) { - listOfErrors := dafnyOutput.Dtor_list() - message := dafnyOutput.Dtor_message() - t := $L.CollectionOfErrors {} - for i := dafny.Iterate(listOfErrors) ; ; { - val, ok := i() - if !ok { - break; - } - err := val.($L.Error) - t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) - - } - t.Message = func() (string) { - var s string - for i := dafny.Iterate(message) ; ; { - val, ok := i() - if !ok { - return s - } else { - s = s + string(val.(dafny.Char)) - } - } - }() - return t - } - func OpaqueError_Output_FromDafny(dafnyOutput $L.Error)($L.OpaqueError) { - return $L.OpaqueError { - ErrObject: dafnyOutput.Dtor_obj(), - } - }""", DafnyNameResolver.dafnyTypesNamespace(serviceShape), SmithyNameResolver.smithyTypesNamespace(serviceShape), - SmithyNameResolver.smithyTypesNamespace(serviceShape), - DafnyNameResolver.dafnyTypesNamespace(serviceShape), DafnyNameResolver.dafnyTypesNamespace(serviceShape), - SmithyNameResolver.smithyTypesNamespace(serviceShape), - SmithyNameResolver.smithyTypesNamespace(serviceShape)); - }); - - context.writerDelegator() - .useFileWriter("%s/%s".formatted(SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), TO_NATIVE), - SmithyNameResolver.shapeNamespace(context.settings().getService(context.model())), writer -> { - writer.write(""" - func Error_FromDafny(err $L.Error)(error) { - // Service Errors - ${C|} - - //DependentErrors - ${C|} - - //Unmodelled Errors - if err.Is_CollectionOfErrors() { - return CollectionOfErrors_Output_FromDafny(err) - } - - return OpaqueError_Output_FromDafny(err) - } - """, DafnyNameResolver.dafnyTypesNamespace(serviceShape), - writer.consumer(w -> { - for (var error : serviceShape.getErrors()) { - w.write(""" - if err.Is_$L() { - return $L(err) - } - """, error.getName(), SmithyNameResolver.getFromDafnyMethodName(serviceShape, context.model().expectShape(error), "")); - } - }), - writer.consumer(w -> { - var dependencies = serviceShape.hasTrait(LocalServiceTrait.class) ? serviceShape.expectTrait(LocalServiceTrait.class).getDependencies() : null; - if (dependencies == null) { - return; - } - for (var dep : dependencies) { - var depService = context.model().expectShape(dep, ServiceShape.class); - w.write(""" - if err.Is_$L() { - return $L.Error_FromDafny(err.Dtor_$L()) - } - """, depService.expectTrait(LocalServiceTrait.class).getSdkId(), SmithyNameResolver.shapeNamespace(depService), depService.expectTrait(LocalServiceTrait.class).getSdkId()); - } - }) - ); - }); + private void generateErrorDeserializer(final GenerationContext context) { + final Set alreadyVisited = new HashSet<>(); + final var serviceShape = context.settings().getService(context.model()); + final var errorShapes = context + .model() + .getShapesWithTrait(ErrorTrait.class); + for (final var errorShape : errorShapes) { + if ( + !errorShape + .toShapeId() + .getNamespace() + .equals(serviceShape.toShapeId().getNamespace()) + ) { + continue; + } + if (!alreadyVisited.contains(errorShape.toShapeId())) { + alreadyVisited.add(errorShape.toShapeId()); + final var getOutputFromDafnyMethodName = + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + errorShape, + "" + ); + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace(errorShape), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace(errorShape), + writer -> { + writer.write( + """ + func $L(dafnyOutput $L)($L) { + ${C|} + }""", + getOutputFromDafnyMethodName, + DafnyNameResolver.getDafnyBaseErrorType(errorShape), + SmithyNameResolver.getSmithyType( + errorShape, + context.symbolProvider().toSymbol(errorShape) + ), + writer.consumer(w -> { + String output = errorShape.accept( + new DafnyToSmithyShapeVisitor( + context, + "dafnyOutput", + writer, + false + ) + ); + writer.write( + """ + return $L + """, + output + ); + }) + ); + } + ); + } } + + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace( + context.settings().getService(context.model()) + ), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace( + context.settings().getService(context.model()) + ), + writer -> { + writer.write( + """ + func CollectionOfErrors_Output_FromDafny(dafnyOutput $L.Error)($L.CollectionOfErrors) { + listOfErrors := dafnyOutput.Dtor_list() + message := dafnyOutput.Dtor_message() + t := $L.CollectionOfErrors {} + for i := dafny.Iterate(listOfErrors) ; ; { + val, ok := i() + if !ok { + break; + } + err := val.($L.Error) + t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) + + } + t.Message = func() (string) { + var s string + for i := dafny.Iterate(message) ; ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() + return t + } + func OpaqueError_Output_FromDafny(dafnyOutput $L.Error)($L.OpaqueError) { + return $L.OpaqueError { + ErrObject: dafnyOutput.Dtor_obj(), + } + }""", + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape), + SmithyNameResolver.smithyTypesNamespace(serviceShape) + ); + } + ); + + context + .writerDelegator() + .useFileWriter( + "%s/%s".formatted( + SmithyNameResolver.shapeNamespace( + context.settings().getService(context.model()) + ), + TO_NATIVE + ), + SmithyNameResolver.shapeNamespace( + context.settings().getService(context.model()) + ), + writer -> { + writer.write( + """ + func Error_FromDafny(err $L.Error)(error) { + // Service Errors + ${C|} + + //DependentErrors + ${C|} + + //Unmodelled Errors + if err.Is_CollectionOfErrors() { + return CollectionOfErrors_Output_FromDafny(err) + } + + return OpaqueError_Output_FromDafny(err) + } + """, + DafnyNameResolver.dafnyTypesNamespace(serviceShape), + writer.consumer(w -> { + for (var error : serviceShape.getErrors()) { + w.write( + """ + if err.Is_$L() { + return $L(err) + } + """, + error.getName(), + SmithyNameResolver.getFromDafnyMethodName( + serviceShape, + context.model().expectShape(error), + "" + ) + ); + } + }), + writer.consumer(w -> { + var dependencies = serviceShape.hasTrait(LocalServiceTrait.class) + ? serviceShape + .expectTrait(LocalServiceTrait.class) + .getDependencies() + : null; + if (dependencies == null) { + return; + } + for (var dep : dependencies) { + var depService = context + .model() + .expectShape(dep, ServiceShape.class); + w.write( + """ + if err.Is_$L() { + return $L.Error_FromDafny(err.Dtor_$L()) + } + """, + depService.expectTrait(LocalServiceTrait.class).getSdkId(), + SmithyNameResolver.shapeNamespace(depService), + depService.expectTrait(LocalServiceTrait.class).getSdkId() + ); + } + }) + ); + } + ); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/Constants.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/Constants.java index e443603dff..2d1e961fc6 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/Constants.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/Constants.java @@ -1,8 +1,9 @@ package software.amazon.polymorph.smithygo.localservice.nameresolver; public class Constants { - public static final String DOT = "."; - public static final String BLANK = ""; - public static final String INTERNAL_DAFNY_TYPES = "internaldafnytypes"; - public static final String INTERNAL_DAFNY = "internaldafny"; + + public static final String DOT = "."; + public static final String BLANK = ""; + public static final String INTERNAL_DAFNY_TYPES = "internaldafnytypes"; + public static final String INTERNAL_DAFNY = "internaldafny"; } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java index a5fb3118dd..29041ac6d2 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/DafnyNameResolver.java @@ -1,153 +1,198 @@ package software.amazon.polymorph.smithygo.localservice.nameresolver; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.DOT; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.INTERNAL_DAFNY; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.INTERNAL_DAFNY_TYPES; + import software.amazon.smithy.aws.traits.ServiceTrait; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.traits.SensitiveTrait; - import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.shapes.UnionShape; import software.amazon.smithy.model.traits.EnumTrait; - -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.DOT; -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.INTERNAL_DAFNY; -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.INTERNAL_DAFNY_TYPES; +import software.amazon.smithy.model.traits.SensitiveTrait; public class DafnyNameResolver { - - public static String dafnyTypesNamespace(final Shape shape) { - return shape.toShapeId().getNamespace() - .replace(DOT, BLANK).toLowerCase() - .concat(INTERNAL_DAFNY_TYPES); - } - - public static String dafnyNamespace(final Shape shape) { - return shape.toShapeId().getNamespace() - .replace(DOT, BLANK).toLowerCase() - .concat(INTERNAL_DAFNY); - } - - /** - * Returns the Dafny type for a given Shape. - * - * @param shape The Shape for which the Dafny type needs to be determined. - * @param symbol The Symbol representing the Shape. - * @return The Dafny type as a String. - */ - public static String getDafnyType(final Shape shape, final Symbol symbol) { - ShapeType type = shape.getType(); - if (shape.hasTrait(EnumTrait.class)) { - type = ShapeType.ENUM; - } - switch (type) { - case INTEGER, LONG, BOOLEAN: - return symbol.getName(); - case MAP: - return "dafny.Map"; - case DOUBLE, STRING, BLOB, LIST: - return "dafny.Sequence"; - // default catches a case where users may author their own classes that implement and extend resource (ExtendableTrait) - // ENUM, STRUCTURE, UNION can be removed but for posterity it looks great to see all the shapes being covered. - case ENUM, STRUCTURE, UNION: - default: - return DafnyNameResolver.dafnyTypesNamespace(shape) - .concat(DOT) - .concat(symbol.getName()); - } - } - - public static String getDafnySubErrorType(final Shape shape, final Symbol symbol) { - return DafnyNameResolver.getDafnyBaseErrorType(shape) - .concat("_") - .concat(symbol.getName()); - } - - public static String getDafnyBaseErrorType(final Shape shape) { - return DafnyNameResolver.dafnyTypesNamespace(shape) - .concat(DOT) - .concat("Error"); - } - - public static String getDafnyCompanionType(final Shape shape, final Symbol symbol) { - return DafnyNameResolver.dafnyTypesNamespace(shape) - .concat(DOT) - .concat("Companion_%s_".formatted(symbol.getName())); - } - - public static String getDafnyErrorCompanion(final Shape shape) { - return DafnyNameResolver.dafnyTypesNamespace(shape) - .concat(DOT) - .concat("Companion_Error_"); - } - - public static String getDafnyErrorCompanionCreate(final Shape shape, final Symbol symbol) { - return DafnyNameResolver.getDafnyErrorCompanion(shape) - .concat(DOT) - .concat("Create_%s_".formatted(symbol.getName())); - } - - public static String getDafnyCompanionStructType(final Shape shape, final Symbol symbol) { - return DafnyNameResolver.dafnyTypesNamespace(shape) - .concat(DOT) - .concat("CompanionStruct_%s_".formatted(symbol.getName())); - } - - public static String getDafnyCompanionTypeCreate(final Shape shape, final Symbol symbol) { - return DafnyNameResolver.getDafnyCompanionType(shape, symbol) - .concat(DOT) - .concat("Create_%s_".formatted(symbol.getName())); - } - - /** - * Returns the path to Create_ function for creating member shape within a union shape. - * - * @param unionShape The union shape containing the member shape. - * @param memberName The name of the member shape within the union shape. - */ - public static String getDafnyCreateFuncForUnionMemberShape(final UnionShape unionShape, final String memberName) { - return "companion" - .concat(DOT) - .concat(memberName.replace(unionShape.getId().getName() + "Member", "Create_")) - .concat("_"); - } - - public static String getDafnyClient(final Shape shape, final String sdkId) { - return DafnyNameResolver.dafnyNamespace(shape) - .concat(DOT) - .concat(sdkId) - .concat("Client"); - } - public static String getDafnyInterfaceClient(final Shape shape) { - return DafnyNameResolver.dafnyTypesNamespace(shape) - .concat(DOT).concat("I") - .concat(shape.toShapeId().getName()) - .concat("Client"); - } - - public static String getDafnyInterfaceClient(final ServiceShape serviceShape, - final ServiceTrait awsSdkServiceTrait) { - return DafnyNameResolver.dafnyTypesNamespace(serviceShape) - .concat(DOT).concat("I") - .concat(awsSdkServiceTrait.getSdkId()) - .concat("Client"); - } - - - public static String createDafnyClient(final Shape shape, final String sdkId) { - return DafnyNameResolver.dafnyNamespace(shape) - .concat(".Companion_Default___") - .concat(DOT) - .concat(sdkId); - } - - public static String getDafnyDependentErrorType(final Shape shape, final String sdkId) { - return DafnyNameResolver.dafnyNamespace(shape) - .concat(".Companion_Default___") - .concat(DOT) - .concat(sdkId); - } - -} \ No newline at end of file + public static String dafnyTypesNamespace(final Shape shape) { + return shape + .toShapeId() + .getNamespace() + .replace(DOT, BLANK) + .toLowerCase() + .concat(INTERNAL_DAFNY_TYPES); + } + + public static String dafnyNamespace(final Shape shape) { + return shape + .toShapeId() + .getNamespace() + .replace(DOT, BLANK) + .toLowerCase() + .concat(INTERNAL_DAFNY); + } + + /** + * Returns the Dafny type for a given Shape. + * + * @param shape The Shape for which the Dafny type needs to be determined. + * @param symbol The Symbol representing the Shape. + * @return The Dafny type as a String. + */ + public static String getDafnyType(final Shape shape, final Symbol symbol) { + ShapeType type = shape.getType(); + if (shape.hasTrait(EnumTrait.class)) { + type = ShapeType.ENUM; + } + switch (type) { + case INTEGER, LONG, BOOLEAN: + return symbol.getName(); + case MAP: + return "dafny.Map"; + case DOUBLE, STRING, BLOB, LIST: + return "dafny.Sequence"; + // default catches a case where users may author their own classes that implement and extend resource (ExtendableTrait) + // ENUM, STRUCTURE, UNION can be removed but for posterity it looks great to see all the shapes being covered. + case ENUM, STRUCTURE, UNION: + default: + return DafnyNameResolver + .dafnyTypesNamespace(shape) + .concat(DOT) + .concat(symbol.getName()); + } + } + + public static String getDafnySubErrorType( + final Shape shape, + final Symbol symbol + ) { + return DafnyNameResolver + .getDafnyBaseErrorType(shape) + .concat("_") + .concat(symbol.getName()); + } + + public static String getDafnyBaseErrorType(final Shape shape) { + return DafnyNameResolver + .dafnyTypesNamespace(shape) + .concat(DOT) + .concat("Error"); + } + + public static String getDafnyCompanionType( + final Shape shape, + final Symbol symbol + ) { + return DafnyNameResolver + .dafnyTypesNamespace(shape) + .concat(DOT) + .concat("Companion_%s_".formatted(symbol.getName())); + } + + public static String getDafnyErrorCompanion(final Shape shape) { + return DafnyNameResolver + .dafnyTypesNamespace(shape) + .concat(DOT) + .concat("Companion_Error_"); + } + + public static String getDafnyErrorCompanionCreate( + final Shape shape, + final Symbol symbol + ) { + return DafnyNameResolver + .getDafnyErrorCompanion(shape) + .concat(DOT) + .concat("Create_%s_".formatted(symbol.getName())); + } + + public static String getDafnyCompanionStructType( + final Shape shape, + final Symbol symbol + ) { + return DafnyNameResolver + .dafnyTypesNamespace(shape) + .concat(DOT) + .concat("CompanionStruct_%s_".formatted(symbol.getName())); + } + + public static String getDafnyCompanionTypeCreate( + final Shape shape, + final Symbol symbol + ) { + return DafnyNameResolver + .getDafnyCompanionType(shape, symbol) + .concat(DOT) + .concat("Create_%s_".formatted(symbol.getName())); + } + + /** + * Returns the path to Create_ function for creating member shape within a union shape. + * + * @param unionShape The union shape containing the member shape. + * @param memberName The name of the member shape within the union shape. + */ + public static String getDafnyCreateFuncForUnionMemberShape( + final UnionShape unionShape, + final String memberName + ) { + return "companion".concat(DOT) + .concat( + memberName.replace(unionShape.getId().getName() + "Member", "Create_") + ) + .concat("_"); + } + + public static String getDafnyClient(final Shape shape, final String sdkId) { + return DafnyNameResolver + .dafnyNamespace(shape) + .concat(DOT) + .concat(sdkId) + .concat("Client"); + } + + public static String getDafnyInterfaceClient(final Shape shape) { + return DafnyNameResolver + .dafnyTypesNamespace(shape) + .concat(DOT) + .concat("I") + .concat(shape.toShapeId().getName()) + .concat("Client"); + } + + public static String getDafnyInterfaceClient( + final ServiceShape serviceShape, + final ServiceTrait awsSdkServiceTrait + ) { + return DafnyNameResolver + .dafnyTypesNamespace(serviceShape) + .concat(DOT) + .concat("I") + .concat(awsSdkServiceTrait.getSdkId()) + .concat("Client"); + } + + public static String createDafnyClient( + final Shape shape, + final String sdkId + ) { + return DafnyNameResolver + .dafnyNamespace(shape) + .concat(".Companion_Default___") + .concat(DOT) + .concat(sdkId); + } + + public static String getDafnyDependentErrorType( + final Shape shape, + final String sdkId + ) { + return DafnyNameResolver + .dafnyNamespace(shape) + .concat(".Companion_Default___") + .concat(DOT) + .concat(sdkId); + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java index 7b58ad8ef7..179d22b375 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/nameresolver/SmithyNameResolver.java @@ -1,5 +1,9 @@ package software.amazon.polymorph.smithygo.localservice.nameresolver; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; +import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.DOT; + +import java.util.Map; import software.amazon.smithy.aws.traits.ServiceTrait; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.model.Model; @@ -7,47 +11,117 @@ import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.SimpleShape; -import java.util.Map; - -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.BLANK; -import static software.amazon.polymorph.smithygo.localservice.nameresolver.Constants.DOT; - public class SmithyNameResolver { - private static Map smithyNamespaceToGoModuleNameMap; - - public static void setSmithyNamespaceToGoModuleNameMap( - Map smithyNamespaceToGoModuleNameMap) { - SmithyNameResolver.smithyNamespaceToGoModuleNameMap = smithyNamespaceToGoModuleNameMap; + private static Map smithyNamespaceToGoModuleNameMap; + + public static void setSmithyNamespaceToGoModuleNameMap( + Map smithyNamespaceToGoModuleNameMap + ) { + SmithyNameResolver.smithyNamespaceToGoModuleNameMap = + smithyNamespaceToGoModuleNameMap; + } + + public static String getGoModuleNameForSmithyNamespace( + final String smithyNamespace + ) { + if (smithyNamespace.contains("smithy.")) return ""; + if (!smithyNamespaceToGoModuleNameMap.containsKey(smithyNamespace)) { + throw new IllegalArgumentException( + "Go module name not found for Smithy namespace: " + smithyNamespace + ); } - - public static String getGoModuleNameForSmithyNamespace(final String smithyNamespace) { - if (smithyNamespace.contains("smithy.")) return ""; - if (!smithyNamespaceToGoModuleNameMap.containsKey(smithyNamespace)) { - throw new IllegalArgumentException("Go module name not found for Smithy namespace: " + smithyNamespace); - } - return smithyNamespaceToGoModuleNameMap.get(smithyNamespace); + return smithyNamespaceToGoModuleNameMap.get(smithyNamespace); + } + + public static String shapeNamespace(final Shape shape) { + return shape.toShapeId().getNamespace().replace(DOT, BLANK).toLowerCase(); + } + + public static String smithyTypesNamespace(final Shape shape) { + return shape + .toShapeId() + .getNamespace() + .replace(DOT, BLANK) + .toLowerCase() + .concat("types"); + } + + public static String getGoModuleNameForSdkNamespace( + final String smithyNamespace + ) { + return getGoModuleNameForSmithyNamespace("sdk.".concat(smithyNamespace)); + } + + public static String smithyTypesNamespaceAws( + final ServiceTrait serviceTrait, + boolean isAwsSubType + ) { + if (isAwsSubType) { + return "types"; } - - public static String shapeNamespace(final Shape shape) { - return shape.toShapeId().getNamespace().replace(DOT, BLANK).toLowerCase(); + return serviceTrait.getSdkId().toLowerCase(); + } + + public static String getSmithyType(final Shape shape, final Symbol symbol) { + if ( + symbol.getNamespace().contains("smithy.") || + symbol.getName().contains("string") + ) { + return symbol.getName(); } - - public static String smithyTypesNamespace(final Shape shape) { - return shape.toShapeId().getNamespace().replace(DOT, BLANK).toLowerCase().concat("types"); + return SmithyNameResolver + .smithyTypesNamespace(shape) + .concat(DOT) + .concat(symbol.getName()); + } + + public static String getSmithyTypeAws( + final ServiceTrait serviceTrait, + final Symbol symbol, + boolean subtype + ) { + if ( + symbol.getNamespace().contains("smithy.") || + symbol.getName().equals("string") || + symbol.getName().equals("float64") + ) { + return symbol.getName(); } - - public static String getGoModuleNameForSdkNamespace(final String smithyNamespace) { - return getGoModuleNameForSmithyNamespace("sdk.".concat(smithyNamespace)); + return SmithyNameResolver + .smithyTypesNamespaceAws(serviceTrait, subtype) + .concat(DOT) + .concat(symbol.getName()); + } + + public static String getSmithyType(final Shape shape) { + return SmithyNameResolver + .smithyTypesNamespace(shape) + .concat(DOT) + .concat(shape.toShapeId().getName()); + } + + public static String getToDafnyMethodName( + final ServiceShape serviceShape, + final Shape shape, + final String disambiguator + ) { + final var methodName = serviceShape + .getContextualName(shape) + .concat("_ToDafny"); + if ( + serviceShape + .toShapeId() + .getNamespace() + .equals(shape.toShapeId().getNamespace()) + ) { + return methodName; + } else { + return SmithyNameResolver + .shapeNamespace(shape) + .concat(DOT) + .concat(methodName); } - - public static String smithyTypesNamespaceAws(final ServiceTrait serviceTrait, boolean isAwsSubType) { - if (isAwsSubType) { - return "types"; - } - return serviceTrait.getSdkId().toLowerCase(); - } - public static String getSmithyType(final Shape shape, final Symbol symbol) { if(symbol.getNamespace().contains("smithy.") || symbol.getName().contains("string")) { return symbol.getName(); @@ -103,4 +177,23 @@ public static String getAwsServiceClient(final ServiceTrait serviceTrait) { .concat(DOT) .concat("Client"); } + } + + public static String getFromDafnyMethodName( + final Shape shape, + final String disambiguator + ) { + final var methodName = shape.getId().getName().concat("_FromDafny"); + return SmithyNameResolver + .shapeNamespace(shape) + .concat(DOT) + .concat(methodName); + } + + public static String getAwsServiceClient(final ServiceTrait serviceTrait) { + return SmithyNameResolver + .smithyTypesNamespaceAws(serviceTrait, false) + .concat(DOT) + .concat("Client"); + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java index 6d4c88d90c..b83a2e15a5 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/DafnyToSmithyShapeVisitor.java @@ -1,5 +1,7 @@ package software.amazon.polymorph.smithygo.localservice.shapevisitor; +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoWriter; import software.amazon.polymorph.smithygo.codegen.SmithyGoDependency; @@ -28,105 +30,226 @@ import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.utils.StringUtils; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - public class DafnyToSmithyShapeVisitor extends ShapeVisitor.Default { - private final GenerationContext context; - private final String dataSource; - private final GoWriter writer; - private final boolean isConfigShape; - private final boolean isOptional; - public DafnyToSmithyShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isConfigShape - ) { - this(context, dataSource, writer, isConfigShape, false); - } + private final GenerationContext context; + private final String dataSource; + private final GoWriter writer; + private final boolean isConfigShape; + private final boolean isOptional; - public DafnyToSmithyShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isConfigShape, - final boolean isOptional - ) { - this.context = context; - this.dataSource = dataSource; - this.writer = writer; - this.isConfigShape = isConfigShape; - this.isOptional = isOptional; + public DafnyToSmithyShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isConfigShape + ) { + this(context, dataSource, writer, isConfigShape, false); + } + + public DafnyToSmithyShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isConfigShape, + final boolean isOptional + ) { + this.context = context; + this.dataSource = dataSource; + this.writer = writer; + this.isConfigShape = isConfigShape; + this.isOptional = isOptional; + } + + protected String referenceStructureShape(StructureShape shape) { + ReferenceTrait referenceTrait = shape.expectTrait(ReferenceTrait.class); + Shape resourceOrService = context + .model() + .expectShape(referenceTrait.getReferentId()); + var namespace = ""; + if (resourceOrService.asResourceShape().isPresent()) { + var resourceShape = resourceOrService.asResourceShape().get(); + if ( + !resourceOrService + .toShapeId() + .getNamespace() + .equals(context.settings().getService().getNamespace()) + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + resourceOrService.toShapeId().getNamespace() + ), + SmithyNameResolver.shapeNamespace(resourceShape) + ); + namespace = + SmithyNameResolver.shapeNamespace(resourceOrService).concat("."); + } + if (!this.isOptional) { + return "%s_FromDafny(%s)".formatted( + namespace.concat(resourceShape.toShapeId().getName()), + dataSource + ); + } + return """ + func () %s.I%s { + if %s == nil { + return nil; + } + return %s + }()""".formatted( + SmithyNameResolver.smithyTypesNamespace(resourceShape), + resourceShape.getId().getName(), + dataSource, + "%s_FromDafny(%s.(%s.I%s))".formatted( + namespace.concat(resourceShape.toShapeId().getName()), + dataSource, + DafnyNameResolver.dafnyTypesNamespace(resourceShape), + resourceShape.getId().getName() + ) + ); + } else { + var serviceShape = resourceOrService.asServiceShape().get(); + if ( + !resourceOrService + .toShapeId() + .getNamespace() + .equals(context.settings().getService().getNamespace()) + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + resourceOrService.toShapeId().getNamespace() + ), + SmithyNameResolver.shapeNamespace(serviceShape) + ); + namespace = + SmithyNameResolver.shapeNamespace(resourceOrService).concat("."); + } + if (!this.isOptional) { + return "%1$s{%2$s}".formatted( + namespace.concat( + context.symbolProvider().toSymbol(serviceShape).getName() + ), + dataSource + ); + } + return """ + func () *%s { + if %s == nil { + return nil; + } + return &%s{%s.(*%s)} + }()""".formatted( + namespace.concat( + context.symbolProvider().toSymbol(serviceShape).getName() + ), + dataSource, + namespace.concat( + context.symbolProvider().toSymbol(serviceShape).getName() + ), + dataSource, + DafnyNameResolver.getDafnyClient( + serviceShape, + serviceShape.toShapeId().getName() + ) + ); } + } - protected String referenceStructureShape(StructureShape shape) { - ReferenceTrait referenceTrait = shape.expectTrait(ReferenceTrait.class); - Shape resourceOrService = context.model().expectShape(referenceTrait.getReferentId()); - var namespace = ""; - if (resourceOrService.asResourceShape().isPresent()) { - var resourceShape = resourceOrService.asResourceShape().get(); - if (!resourceOrService.toShapeId().getNamespace().equals(context.settings().getService().getNamespace())) { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resourceOrService.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(resourceShape)); - namespace = SmithyNameResolver.shapeNamespace(resourceOrService).concat("."); - } - if (!this.isOptional) { - return "%s_FromDafny(%s)".formatted(namespace.concat(resourceShape.toShapeId().getName()), dataSource); - } - return """ - func () %s.I%s { - if %s == nil { - return nil; - } - return %s - }()""".formatted(SmithyNameResolver.smithyTypesNamespace(resourceShape), resourceShape.getId().getName(), dataSource, - "%s_FromDafny(%s.(%s.I%s))".formatted(namespace.concat(resourceShape.toShapeId().getName()), dataSource, - DafnyNameResolver.dafnyTypesNamespace(resourceShape), resourceShape.getId().getName())); + @Override + protected String getDefault(Shape shape) { + throw new CodegenException( + String.format( + "Unsupported conversion of %s to %s using the %s protocol", + shape, + shape.getType(), + context.protocolGenerator().getName() + ) + ); + } + + @Override + public String blobShape(BlobShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + return """ + func () []byte { + var b []byte + if %s == nil { + return nil + } + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return b } else { - var serviceShape = resourceOrService.asServiceShape().get(); - if (!resourceOrService.toShapeId().getNamespace().equals(context.settings().getService().getNamespace())) { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resourceOrService.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(serviceShape)); - namespace = SmithyNameResolver.shapeNamespace(resourceOrService).concat("."); - } - if (!this.isOptional) { - return "%1$s{%2$s}".formatted(namespace.concat(context.symbolProvider().toSymbol(serviceShape).getName()), dataSource); - } - return """ - func () *%s { - if %s == nil { - return nil; - } - return &%s{%s.(*%s)} - }()""".formatted(namespace.concat(context.symbolProvider().toSymbol(serviceShape).getName()), dataSource, namespace.concat(context.symbolProvider().toSymbol(serviceShape).getName()), - dataSource, DafnyNameResolver.getDafnyClient(serviceShape, serviceShape.toShapeId().getName())); + b = append(b, val.(byte)) } } + }()""".formatted(dataSource, dataSource); + } - @Override - protected String getDefault(Shape shape) { - throw new CodegenException(String.format( - "Unsupported conversion of %s to %s using the %s protocol", - shape, shape.getType(), context.protocolGenerator().getName())); + @Override + public String structureShape(final StructureShape shape) { + if (shape.hasTrait(ReferenceTrait.class)) { + return referenceStructureShape(shape); } + final var builder = new StringBuilder(); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + shape.toShapeId().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(shape) + ); - @Override - public String blobShape(BlobShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - return """ - func () []byte { - var b []byte - if %s == nil { - return nil - } - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return b - } else { - b = append(b, val.(byte)) - } - } - }()""".formatted(dataSource, dataSource); + builder.append( + "%1$s{".formatted( + SmithyNameResolver + .smithyTypesNamespace(shape) + .concat(".") + .concat(shape.getId().getName()) + ) + ); + String fieldSeparator = ","; + for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { + final var memberName = memberShapeEntry.getKey(); + final var memberShape = memberShapeEntry.getValue(); + final var targetShape = context + .model() + .expectShape(memberShape.getTarget()); + //TODO: Is it ever possible for structure to be nil? + final var derivedDataSource = + "%1$s%2$s%3$s%4$s".formatted( + dataSource, + ".Dtor_%s()".formatted(memberName), + memberShape.isOptional() ? ".UnwrapOr(nil)" : "", + memberShape.isOptional() && + targetShape.isStructureShape() && + !targetShape.hasTrait(ReferenceTrait.class) + ? ".(%s)".formatted( + DafnyNameResolver.getDafnyType( + targetShape, + context.symbolProvider().toSymbol(memberShape) + ) + ) + : "" + ); + builder.append( + "%1$s: %2$s%3$s,".formatted( + StringUtils.capitalize(memberName), + (targetShape.isStructureShape() && memberShape.isOptional()) && + !targetShape.hasTrait(ReferenceTrait.class) + ? "&" + : "", + targetShape.accept( + new DafnyToSmithyShapeVisitor( + context, + derivedDataSource, + writer, + isConfigShape, + memberShape.isOptional() + ) + ) + ) + ); } @Override @@ -164,297 +287,401 @@ public String structureShape(final StructureShape shape) { )); } - return builder.append("}").toString(); - } + // TODO: smithy-dafny-conversion library + @Override + public String listShape(ListShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + StringBuilder builder = new StringBuilder(); - // TODO: smithy-dafny-conversion library - @Override - public String listShape(ListShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - StringBuilder builder = new StringBuilder(); + MemberShape memberShape = shape.getMember(); + final Shape targetShape = context + .model() + .expectShape(memberShape.getTarget()); + var typeName = targetShape.isStructureShape() + ? context.symbolProvider().toSymbol(memberShape) + : context.symbolProvider().toSymbol(memberShape); + builder.append( + """ + func() []%s{ + var fieldValue []%s + if %s == nil { + return nil + } + for i := dafny.Iterate(%s.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, %s)} + """.formatted( + SmithyNameResolver.getSmithyType(shape, typeName), + SmithyNameResolver.getSmithyType(shape, typeName), + dataSource, + dataSource, + targetShape.accept( + new DafnyToSmithyShapeVisitor( + context, + "val%s".formatted( + targetShape.isStructureShape() + ? ".(%s)".formatted( + DafnyNameResolver.getDafnyType( + targetShape, + context.symbolProvider().toSymbol(targetShape) + ) + ) + : "" + ), + writer, + isConfigShape + ) + ) + ) + ); - MemberShape memberShape = shape.getMember(); - final Shape targetShape = context.model().expectShape(memberShape.getTarget()); - var typeName = targetShape.isStructureShape() ? context.symbolProvider().toSymbol(memberShape) : context.symbolProvider().toSymbol(memberShape); - builder.append(""" - func() []%s{ - var fieldValue []%s - if %s == nil { - return nil - } - for i := dafny.Iterate(%s.(dafny.Sequence)); ; { - val, ok := i() - if !ok { - break - } - fieldValue = append(fieldValue, %s)} - """.formatted(SmithyNameResolver.getSmithyType(shape, typeName), SmithyNameResolver.getSmithyType(shape, typeName), dataSource, dataSource, - targetShape.accept( - new DafnyToSmithyShapeVisitor(context, "val%s".formatted(targetShape.isStructureShape() ? ".(%s)".formatted(DafnyNameResolver.getDafnyType(targetShape, context.symbolProvider().toSymbol(targetShape))) : ""), writer, isConfigShape) - ))); + // Close structure + return builder + .append("return fieldValue }()".formatted(dataSource)) + .toString(); + } - // Close structure - return builder.append("return fieldValue }()".formatted(dataSource)).toString(); - } + @Override + public String mapShape(MapShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + StringBuilder builder = new StringBuilder(); - @Override - public String mapShape(MapShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - StringBuilder builder = new StringBuilder(); + MemberShape keyMemberShape = shape.getKey(); + final Shape keyTargetShape = context + .model() + .expectShape(keyMemberShape.getTarget()); + MemberShape valueMemberShape = shape.getValue(); + final Shape valueTargetShape = context + .model() + .expectShape(valueMemberShape.getTarget()); + final var type = context + .symbolProvider() + .toSymbol(valueTargetShape) + .getName(); - MemberShape keyMemberShape = shape.getKey(); - final Shape keyTargetShape = context.model().expectShape(keyMemberShape.getTarget()); - MemberShape valueMemberShape = shape.getValue(); - final Shape valueTargetShape = context.model().expectShape(valueMemberShape.getTarget()); - final var type = context.symbolProvider().toSymbol(valueTargetShape).getName(); + builder.append( + """ + func() map[string]%s { + var m map[string]%s = make(map[string]%s) + if %s == nil { + return nil + } + for i := dafny.Iterate(%s.(dafny.Map).Items());; { + val, ok := i() + if !ok { + break; + } + m[%s] = %s + } + return m + }()""".formatted( + type, + type, + type, + dataSource, + dataSource, + keyTargetShape.accept( + new DafnyToSmithyShapeVisitor( + context, + "(*val.(dafny.Tuple).IndexInt(0))", + writer, + isConfigShape + ) + ), + valueTargetShape.accept( + new DafnyToSmithyShapeVisitor( + context, + "(*val.(dafny.Tuple).IndexInt(1))", + writer, + isConfigShape + ) + ) + ) + ); + return builder.toString(); + } - builder.append(""" - func() map[string]%s { - var m map[string]%s = make(map[string]%s) - if %s == nil { - return nil - } - for i := dafny.Iterate(%s.(dafny.Map).Items());; { - val, ok := i() - if !ok { - break; - } - m[%s] = %s - } - return m - }()""".formatted(type, type, type, dataSource, dataSource, keyTargetShape.accept( - new DafnyToSmithyShapeVisitor(context, "(*val.(dafny.Tuple).IndexInt(0))", writer, isConfigShape) - ), - valueTargetShape.accept( - new DafnyToSmithyShapeVisitor(context, "(*val.(dafny.Tuple).IndexInt(1))", writer, isConfigShape) - ) - )); - return builder.toString(); + @Override + public String booleanShape(BooleanShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (this.isOptional) { + return """ + func() *bool { + var b bool + if %s == nil { + return nil + } + b = %s.(%s) + return &b + }()""".formatted( + dataSource, + dataSource, + context.symbolProvider().toSymbol(shape).getName() + ); + } else { + return "%s.(%s)".formatted( + dataSource, + context.symbolProvider().toSymbol(shape).getName() + ); } + } - @Override - public String booleanShape(BooleanShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (this.isOptional) { - return """ - func() *bool { - var b bool - if %s == nil { - return nil - } - b = %s.(%s) - return &b - }()""".formatted(dataSource, dataSource, context.symbolProvider().toSymbol(shape).getName()); - } else { - return "%s.(%s)".formatted(dataSource, context.symbolProvider().toSymbol(shape).getName()); - } + @Override + public String stringShape(StringShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (shape.hasTrait(EnumTrait.class)) { + return """ + func () *%s.%s { + var u %s.%s + if %s == nil { + return nil + } + inputEnum := %s.(%s) + index := -1; + for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(%s).Equals(inputEnum) { + break; + } + } + } + + return &u.Values()[index] + }()""".formatted( + SmithyNameResolver.smithyTypesNamespace(shape), + context.symbolProvider().toSymbol(shape).getName(), + SmithyNameResolver.smithyTypesNamespace(shape), + context.symbolProvider().toSymbol(shape).getName(), + dataSource, + dataSource, + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ), + DafnyNameResolver.getDafnyCompanionStructType( + shape, + context.symbolProvider().toSymbol(shape) + ), + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ) + ); } - @Override - public String stringShape(StringShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (shape.hasTrait(EnumTrait.class)) { - return """ - func () *%s.%s { - var u %s.%s - if %s == nil { - return nil - } - inputEnum := %s.(%s) - index := -1; - for allEnums := dafny.Iterate(%s{}.AllSingletonConstructors()); ; { - enum, ok := allEnums() - if ok { - index++ - if enum.(%s).Equals(inputEnum) { - break; - } - } - } - - return &u.Values()[index] - }()""".formatted(SmithyNameResolver.smithyTypesNamespace(shape), context.symbolProvider().toSymbol(shape).getName(), SmithyNameResolver.smithyTypesNamespace(shape), context.symbolProvider().toSymbol(shape).getName(), dataSource, dataSource, DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)), DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), - DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))); - } + var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) + ? "uint8" + : "dafny.Char"; + var strConv = "s = s + string(val.(%s))".formatted(underlyingType); + if (underlyingType == "uint8") { + strConv = + """ + // UTF bytes should be always converted from bytes to string in go + // Otherwise go treats the string as a unicode codepoint - var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) ? "uint8" : "dafny.Char"; - var strConv = "s = s + string(val.(%s))".formatted(underlyingType); - if( underlyingType == "uint8" ) { - strConv = """ - // UTF bytes should be always converted from bytes to string in go - // Otherwise go treats the string as a unicode codepoint - - var valUint, _ = val.(%s) - var byteSlice = []byte{valUint} - s = s + string(byteSlice) - """.formatted(underlyingType); - } - if ((boolean)isOptional) { - return """ - func() (*string) { - var s string - if %s == nil { - return nil - } - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return &[]string{s}[0] - } else { - %s - } - } - }()""".formatted(dataSource, dataSource, strConv); - } - else { - return """ - func() (string) { - var s string - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return s - } else { - %s - } - } - }()""".formatted(dataSource, strConv); - } + var valUint, _ = val.(%s) + var byteSlice = []byte{valUint} + s = s + string(byteSlice) + """.formatted(underlyingType); + } + if ((boolean) isOptional) { + return """ + func() (*string) { + var s string + if %s == nil { + return nil + } + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + %s + } + } + }()""".formatted(dataSource, dataSource, strConv); + } else { + return """ + func() (string) { + var s string + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return s + } else { + %s + } + } + }()""".formatted(dataSource, strConv); } + } - @Override - public String integerShape(IntegerShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + @Override + public String integerShape(IntegerShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if ((boolean)isOptional) { - return (""" - func() *int32 { - var b int32 - if %s == nil { - return nil - } - b = %s.(int32) - return &b - }()""".formatted(dataSource, dataSource)); - }else { - return """ - func() int32 { - var b = %s.(int32) - return b - }() - """.formatted(dataSource); - } + if ((boolean) isOptional) { + return ( + """ + func() *int32 { + var b int32 + if %s == nil { + return nil + } + b = %s.(int32) + return &b + }()""".formatted(dataSource, dataSource) + ); + } else { + return """ + func() int32 { + var b = %s.(int32) + return b + }() + """.formatted(dataSource); } + } - @Override - public String longShape(LongShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - return (""" - func() *int64 { - var b int64 - if %s == nil { - return nil - } - b = %s.(int64) - return &b - }()""").formatted(dataSource, dataSource); - } + @Override + public String longShape(LongShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + return ( + """ + func() *int64 { + var b int64 + if %s == nil { + return nil + } + b = %s.(int64) + return &b + }()""" + ).formatted(dataSource, dataSource); + } - @Override - public String doubleShape(DoubleShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - writer.addUseImports(SmithyGoDependency.MATH); - return """ - func () *float64 { - var b []byte - if %s == nil { - return nil - } - for i := dafny.Iterate(%s) ; ; { - val, ok := i() - if !ok { - return &[]float64{math.Float64frombits(binary.LittleEndian.Uint64(b))}[0] - } else { - b = append(b, val.(byte)) - } - } - }()""".formatted(dataSource, dataSource); + @Override + public String doubleShape(DoubleShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + writer.addUseImports(SmithyGoDependency.MATH); + return """ + func () *float64 { + var b []byte + if %s == nil { + return nil } - - @Override - public String unionShape(UnionShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilCheck; - if (GoPointableIndex.of(context.model()).isPointable(shape) == false) { - nilCheck = ""; - } else { - nilCheck = """ - if %s == nil { - return nil - }""".formatted( - dataSource - ); + for i := dafny.Iterate(%s) ; ; { + val, ok := i() + if !ok { + return &[]float64{math.Float64frombits(binary.LittleEndian.Uint64(b))}[0] + } else { + b = append(b, val.(byte)) + } } - final String functionInit = """ - func() %s { - var union %s - %s - """.formatted( - context.symbolProvider().toSymbol(shape), - context.symbolProvider().toSymbol(shape), - nilCheck + }()""".formatted(dataSource, dataSource); + } + + @Override + public String unionShape(UnionShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilCheck; + if (GoPointableIndex.of(context.model()).isPointable(shape) == false) { + nilCheck = ""; + } else { + nilCheck = + """ + if %s == nil { + return nil + }""".formatted(dataSource); + } + final String functionInit = + """ + func() %s { + var union %s + %s + """.formatted( + context.symbolProvider().toSymbol(shape), + context.symbolProvider().toSymbol(shape), + nilCheck + ); + StringBuilder eachMemberInUnion = new StringBuilder(); + for (var member : shape.getAllMembers().values()) { + final Shape targetShape = context.model().expectShape(member.getTarget()); + final String memberName = context.symbolProvider().toMemberName(member); + final String rawUnionDataSource = + "(" + + dataSource + + ".(" + + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ) + + "))"; + // unwrap union type, assert it then convert it to its member type with Dtor_ (example: Dtor_BlobValue()). unionDataSource is not a wrapper object until now. + String unionDataSource = + rawUnionDataSource + + ".Dtor_" + + memberName.replace(shape.getId().getName() + "Member", "") + + "()"; + final Boolean isMemberShapePointable = + (GoPointableIndex.of(context.model()).isPointable(targetShape) && + GoPointableIndex.of(context.model()).isDereferencable(targetShape)) && + !targetShape.isStructureShape(); + final String pointerForPointableShape = isMemberShapePointable ? "*" : ""; + final String isMemberCheck = + """ + if ((%s).%s()) {""".formatted( + rawUnionDataSource, + memberName.replace(shape.getId().getName() + "Member", "Is_") + ); + String wrappedDataSource = ""; + if (!(targetShape.isStructureShape())) { + // All other shape except structure needs a Wrapper object but unionDataSource is not a Wrapper object. + wrappedDataSource = + """ + var dataSource = Wrappers.Companion_Option_.Create_Some_(%s)""".formatted( + unionDataSource ); - StringBuilder eachMemberInUnion = new StringBuilder(); - for (var member : shape.getAllMembers().values()) { - final Shape targetShape = context.model().expectShape(member.getTarget()); - final String memberName = context.symbolProvider().toMemberName(member); - final String rawUnionDataSource = "(" + dataSource + ".(" + DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)) + "))"; - // unwrap union type, assert it then convert it to its member type with Dtor_ (example: Dtor_BlobValue()). unionDataSource is not a wrapper object until now. - String unionDataSource = rawUnionDataSource + ".Dtor_" + memberName.replace(shape.getId().getName() + "Member", "") + "()"; - final Boolean isMemberShapePointable = (GoPointableIndex.of(context.model()).isPointable(targetShape) && GoPointableIndex.of(context.model()).isDereferencable(targetShape)) && !targetShape.isStructureShape(); - final String pointerForPointableShape = isMemberShapePointable ? "*" : ""; - final String isMemberCheck = """ - if ((%s).%s()) {""".formatted( - rawUnionDataSource, - memberName.replace(shape.getId().getName() + "Member", "Is_") - ); - String wrappedDataSource = ""; - if (!(targetShape.isStructureShape())) { - // All other shape except structure needs a Wrapper object but unionDataSource is not a Wrapper object. - wrappedDataSource = """ - var dataSource = Wrappers.Companion_Option_.Create_Some_(%s)""".formatted(unionDataSource); - unionDataSource = "dataSource.UnwrapOr(nil)"; + unionDataSource = "dataSource.UnwrapOr(nil)"; + } + eachMemberInUnion.append( + """ + %s + %s + union = &%s.%s{ + Value: %s(%s), } - eachMemberInUnion.append(""" - %s - %s - union = &%s.%s{ - Value: %s(%s), - } - } - """.formatted( - isMemberCheck, - wrappedDataSource, - SmithyNameResolver.smithyTypesNamespace(shape), - memberName, - pointerForPointableShape, - targetShape.accept( - new DafnyToSmithyShapeVisitor(context, unionDataSource, writer, isConfigShape, isMemberShapePointable) - ))); } - return - """ - %s - %s - return union - }()""".formatted( - functionInit, - eachMemberInUnion - ); + """.formatted( + isMemberCheck, + wrappedDataSource, + SmithyNameResolver.smithyTypesNamespace(shape), + memberName, + pointerForPointableShape, + targetShape.accept( + new DafnyToSmithyShapeVisitor( + context, + unionDataSource, + writer, + isConfigShape, + isMemberShapePointable + ) + ) + ) + ); } + return """ + %s + %s + return union + }()""".formatted(functionInit, eachMemberInUnion); + } - @Override - public String timestampShape(TimestampShape shape) { - return "nil"; - } -} \ No newline at end of file + @Override + public String timestampShape(TimestampShape shape) { + return "nil"; + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java index 425b3436b6..a912031367 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/localservice/shapevisitor/SmithyToDafnyShapeVisitor.java @@ -1,5 +1,7 @@ package software.amazon.polymorph.smithygo.localservice.shapevisitor; +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + import software.amazon.polymorph.smithygo.codegen.GenerationContext; import software.amazon.polymorph.smithygo.codegen.GoWriter; import software.amazon.polymorph.smithygo.codegen.SmithyGoDependency; @@ -29,108 +31,192 @@ import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.utils.StringUtils; -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - public class SmithyToDafnyShapeVisitor extends ShapeVisitor.Default { - private final GenerationContext context; - private final String dataSource; - private final GoWriter writer; - private final boolean isConfigShape; - - private final boolean isOptional; - protected boolean isPointerType; - public void setPointerType() { - this.isPointerType = false; + private final GenerationContext context; + private final String dataSource; + private final GoWriter writer; + private final boolean isConfigShape; + + private final boolean isOptional; + protected boolean isPointerType; + + public void setPointerType() { + this.isPointerType = false; + } + + public SmithyToDafnyShapeVisitor( + final GenerationContext context, + final String dataSource, + final GoWriter writer, + final boolean isConfigShape, + final boolean isOptional, + final boolean isPointerType + ) { + this.context = context; + this.dataSource = dataSource; + this.writer = writer; + this.isConfigShape = isConfigShape; + this.isOptional = isOptional; + this.isPointerType = isPointerType; + } + + protected String referenceStructureShape(StructureShape shape) { + ReferenceTrait referenceTrait = shape.expectTrait(ReferenceTrait.class); + Shape resourceOrService = context + .model() + .expectShape(referenceTrait.getReferentId()); + + if (resourceOrService.asResourceShape().isPresent()) { + ResourceShape resourceShape = resourceOrService.asResourceShape().get(); + var namespace = ""; + if ( + !resourceShape + .toShapeId() + .getNamespace() + .equals(context.settings().getService().getNamespace()) + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + resourceShape.toShapeId().getNamespace() + ), + SmithyNameResolver.shapeNamespace(resourceShape) + ); + namespace = + SmithyNameResolver.shapeNamespace(resourceShape).concat("."); + } + if (!this.isOptional) { + return "%s_ToDafny(%s)".formatted( + namespace.concat(resourceShape.toShapeId().getName()), + dataSource + ); + } else { + var goCodeBlock = + """ + func () Wrappers.Option { + if %s == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(%s) + }()"""; + return goCodeBlock.formatted( + dataSource, + "%s_ToDafny(%s)".formatted( + namespace.concat(resourceShape.toShapeId().getName()), + dataSource + ) + ); + } } - public SmithyToDafnyShapeVisitor( - final GenerationContext context, - final String dataSource, - final GoWriter writer, - final boolean isConfigShape, - final boolean isOptional, - final boolean isPointerType - ) { - this.context = context; - this.dataSource = dataSource; - this.writer = writer; - this.isConfigShape = isConfigShape; - this.isOptional = isOptional; - this.isPointerType = isPointerType; + if (resourceOrService.asServiceShape().isPresent()) { + ServiceShape resourceShape = resourceOrService.asServiceShape().get(); + if (!this.isOptional) { + return dataSource; + } else { + var goCodeBlock = + """ + func () Wrappers.Option { + if %s == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(%s) + }()"""; + return goCodeBlock.formatted(dataSource, dataSource); + } } - protected String referenceStructureShape(StructureShape shape) { - ReferenceTrait referenceTrait = shape.expectTrait(ReferenceTrait.class); - Shape resourceOrService = context.model().expectShape(referenceTrait.getReferentId()); - - if (resourceOrService.asResourceShape().isPresent()) { - ResourceShape resourceShape = resourceOrService.asResourceShape().get(); - var namespace = ""; - if (!resourceShape.toShapeId().getNamespace().equals(context.settings().getService().getNamespace())) { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(resourceShape.toShapeId().getNamespace()), SmithyNameResolver.shapeNamespace(resourceShape)); - namespace = SmithyNameResolver.shapeNamespace(resourceShape).concat("."); - } - if(!this.isOptional) { - return "%s_ToDafny(%s)".formatted(namespace.concat(resourceShape.toShapeId().getName()), dataSource); - } else { - var goCodeBlock = """ - func () Wrappers.Option { - if %s == nil { - return Wrappers.Companion_Option_.Create_None_() - } - return Wrappers.Companion_Option_.Create_Some_(%s) - }()"""; - return goCodeBlock.formatted(dataSource, "%s_ToDafny(%s)".formatted(namespace.concat(resourceShape.toShapeId().getName()), dataSource)); - } - } - - if (resourceOrService.asServiceShape().isPresent()) { - ServiceShape resourceShape = resourceOrService.asServiceShape().get(); - if(!this.isOptional) { - return dataSource; - } else { - var goCodeBlock = """ - func () Wrappers.Option { - if %s == nil { - return Wrappers.Companion_Option_.Create_None_() - } - return Wrappers.Companion_Option_.Create_Some_(%s) - }()"""; - return goCodeBlock.formatted(dataSource, dataSource); - } + throw new UnsupportedOperationException( + "Unknown referenceStructureShape type: " + shape + ); + } + + @Override + protected String getDefault(Shape shape) { + throw new CodegenException( + String.format( + "Unsupported conversion of %s to %s using the %s protocol", + shape, + shape.getType(), + context.protocolGenerator().getName() + ) + ); + } + + @Override + public String blobShape(BlobShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + return """ + func () %s { + var v []interface{} + if %s == nil {return %s} + for _, e := range %s { + v = append(v, e) } - - throw new UnsupportedOperationException("Unknown referenceStructureShape type: " + shape); + return %s; + }()""".formatted( + returnType, + dataSource, + nilWrapIfRequired, + dataSource, + someWrapIfRequired.formatted("dafny.SeqOf(v...)") + ); + } + + @Override + public String structureShape(final StructureShape shape) { + if (shape.hasTrait(ReferenceTrait.class)) { + return referenceStructureShape(shape); } - - @Override - protected String getDefault(Shape shape) { - throw new CodegenException(String.format( - "Unsupported conversion of %s to %s using the %s protocol", - shape, shape.getType(), context.protocolGenerator().getName())); + final var builder = new StringBuilder(); + writer.addImportFromModule( + "github.com/dafny-lang/DafnyStandardLibGo", + "Wrappers" + ); + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + shape.toShapeId().getNamespace() + ), + DafnyNameResolver.dafnyTypesNamespace(shape) + ); + + String someWrapIfRequired = "%s"; + + String companionStruct; + String returnType; + if (shape.hasTrait(ErrorTrait.class)) { + companionStruct = + DafnyNameResolver.getDafnyErrorCompanionCreate( + shape, + context.symbolProvider().toSymbol(shape) + ); + returnType = DafnyNameResolver.getDafnyBaseErrorType(shape); + } else { + companionStruct = + DafnyNameResolver.getDafnyCompanionTypeCreate( + shape, + context.symbolProvider().toSymbol(shape) + ); + returnType = + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ); } + String nilWrapIfRequired = returnType.concat("{}"); - @Override - public String blobShape(BlobShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - return """ - func () %s { - var v []interface{} - if %s == nil {return %s} - for _, e := range %s { - v = append(v, e) - } - return %s; - }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, someWrapIfRequired.formatted("dafny.SeqOf(v...)")); + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } @Override @@ -199,321 +285,488 @@ public String structureShape(final StructureShape shape) { } return goCodeBlock.formatted(returnType, nilCheck, someWrapIfRequired.formatted(builder.append(")").toString())); } - - @Override - public String mapShape(MapShape shape) { - StringBuilder builder = new StringBuilder(); - - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - MemberShape keyMemberShape = shape.getKey(); - final Shape keyTargetShape = context.model().expectShape(keyMemberShape.getTarget()); - MemberShape valueMemberShape = shape.getValue(); - final Shape valueTargetShape = context.model().expectShape(valueMemberShape.getTarget()); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Map"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - builder.append(""" - func () %s { - if %s == nil { return %s } - fieldValue := dafny.NewMapBuilder() - for key, val := range %s { - fieldValue.Add(%s, %s) - } - return %s - }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, - keyTargetShape.accept( - new SmithyToDafnyShapeVisitor(context, "key", writer, isConfigShape, false, false)), - valueTargetShape.accept( - new SmithyToDafnyShapeVisitor(context, "val", writer, isConfigShape, false, false)), - someWrapIfRequired.formatted("fieldValue.ToMap()") - ) - ); - - // Close structure - return builder.toString(); - + var goCodeBlock = + """ + func () %s { + %s + return %s + }()"""; + + builder.append("%1$s(".formatted(companionStruct)); + String fieldSeparator = ","; + for (final var memberShapeEntry : shape.getAllMembers().entrySet()) { + final var memberName = memberShapeEntry.getKey(); + final var memberShape = memberShapeEntry.getValue(); + final var targetShape = context + .model() + .expectShape(memberShape.getTarget()); + builder.append( + "%1$s%2$s".formatted( + targetShape.accept( + new SmithyToDafnyShapeVisitor( + context, + dataSource + "." + StringUtils.capitalize(memberName), + writer, + isConfigShape, + memberShape.isOptional(), + context + .symbolProvider() + .toSymbol(memberShape) + .getProperty(POINTABLE, Boolean.class) + .orElse(false) + ) + ), + fieldSeparator + ) + ); } - @Override - public String listShape(ListShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - StringBuilder builder = new StringBuilder(); - - MemberShape memberShape = shape.getMember(); - final Shape targetShape = context.model().expectShape(memberShape.getTarget()); - - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } - - builder.append(""" - func () %s { - if %s == nil { return %s } - var fieldValue []interface{} = make([]interface{}, 0) - for _, val := range %s { - element := %s - fieldValue = append(fieldValue, element) - } - return %s - }()""".formatted(returnType, dataSource, nilWrapIfRequired, dataSource, - targetShape.accept( - new SmithyToDafnyShapeVisitor(context, "val", writer, isConfigShape, false, false) - ), someWrapIfRequired.formatted("dafny.SeqOf(fieldValue...)"))); - - // Close structure - return builder.toString(); + return goCodeBlock.formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(builder.append(")").toString()) + ); + } + + @Override + public String mapShape(MapShape shape) { + StringBuilder builder = new StringBuilder(); + + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + MemberShape keyMemberShape = shape.getKey(); + final Shape keyTargetShape = context + .model() + .expectShape(keyMemberShape.getTarget()); + MemberShape valueMemberShape = shape.getValue(); + final Shape valueTargetShape = context + .model() + .expectShape(valueMemberShape.getTarget()); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Map"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - - @Override - public String booleanShape(BooleanShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s%s"; - String returnType = "interface {}"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; - } - - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); + builder.append( + """ + func () %s { + if %s == nil { return %s } + fieldValue := dafny.NewMapBuilder() + for key, val := range %s { + fieldValue.Add(%s, %s) + } + return %s + }()""".formatted( + returnType, + dataSource, + nilWrapIfRequired, + dataSource, + keyTargetShape.accept( + new SmithyToDafnyShapeVisitor( + context, + "key", + writer, + isConfigShape, + false, + false + ) + ), + valueTargetShape.accept( + new SmithyToDafnyShapeVisitor( + context, + "val", + writer, + isConfigShape, + false, + false + ) + ), + someWrapIfRequired.formatted("fieldValue.ToMap()") + ) + ); + + // Close structure + return builder.toString(); + } + + @Override + public String listShape(ListShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + StringBuilder builder = new StringBuilder(); + + MemberShape memberShape = shape.getMember(); + final Shape targetShape = context + .model() + .expectShape(memberShape.getTarget()); + + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - @Override - public String stringShape(StringShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - if (shape.hasTrait(EnumTrait.class)) { - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)); - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } + builder.append( + """ + func () %s { + if %s == nil { return %s } + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range %s { + element := %s + fieldValue = append(fieldValue, element) + } + return %s + }()""".formatted( + returnType, + dataSource, + nilWrapIfRequired, + dataSource, + targetShape.accept( + new SmithyToDafnyShapeVisitor( + context, + "val", + writer, + isConfigShape, + false, + false + ) + ), + someWrapIfRequired.formatted("dafny.SeqOf(fieldValue...)") + ) + ); + + // Close structure + return builder.toString(); + } + + @Override + public String booleanShape(BooleanShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s%s"; + String returnType = "interface {}"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; + } - var nilCheck = ""; - var dereferenceIfRequired = isPointerType ? "*" : ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - return """ - func () %s { - %s - var index int - for _, enumVal := range %s.Values() { - index++ - if enumVal == %s%s{ - break; - } - } - var enum interface{} - for allEnums, i := dafny.Iterate(%s{}.AllSingletonConstructors()), 0; i < index; i++ { - var ok bool - enum, ok = allEnums() - if !ok { - break; - } - } - return %s - }()""".formatted(returnType, nilCheck, dataSource, dereferenceIfRequired, dataSource, DafnyNameResolver.getDafnyCompanionStructType(shape, context.symbolProvider().toSymbol(shape)), someWrapIfRequired.formatted("enum.(%s)".formatted(DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape))))); - } else { - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "dafny.Sequence"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } - var nilCheck = ""; - var dereferenceIfRequired = isPointerType ? "*" : ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) + ); + } + + @Override + public String stringShape(StringShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + if (shape.hasTrait(EnumTrait.class)) { + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ); + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + var nilCheck = ""; + var dereferenceIfRequired = isPointerType ? "*" : ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + return """ + func () %s { + %s + var index int + for _, enumVal := range %s.Values() { + index++ + if enumVal == %s%s{ + break; + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(%s{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break; + } + } + return %s + }()""".formatted( + returnType, + nilCheck, + dataSource, + dereferenceIfRequired, + dataSource, + DafnyNameResolver.getDafnyCompanionStructType( + shape, + context.symbolProvider().toSymbol(shape) + ), + someWrapIfRequired.formatted( + "enum.(%s)".formatted( + DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ) + ) + ) + ); + } else { + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "dafny.Sequence"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; + } + + var nilCheck = ""; + var dereferenceIfRequired = isPointerType ? "*" : ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } + + if (shape.hasTrait(DafnyUtf8BytesTrait.class)) writer.addUseImports( + SmithyGoDependency.stdlib("unicode/utf8") + ); + + var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) + ? """ + dafny.SeqOf(func () []interface{} { + utf8.ValidString(%s%s) + b := []byte(%s%s) + f := make([]interface{}, len(b)) + for i, v := range b { + f[i] = v } - - if (shape.hasTrait(DafnyUtf8BytesTrait.class)) - writer.addUseImports(SmithyGoDependency.stdlib("unicode/utf8")); - - var underlyingType = shape.hasTrait(DafnyUtf8BytesTrait.class) ? """ - dafny.SeqOf(func () []interface{} { - utf8.ValidString(%s%s) - b := []byte(%s%s) - f := make([]interface{}, len(b)) - for i, v := range b { - f[i] = v - } - return f - }()...)""".formatted(dereferenceIfRequired, dataSource, dereferenceIfRequired, dataSource) : "dafny.SeqOfChars([]dafny.Char(%s%s)...)".formatted(dereferenceIfRequired, dataSource); - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(underlyingType)); - } + return f + }()...)""".formatted( + dereferenceIfRequired, + dataSource, + dereferenceIfRequired, + dataSource + ) + : "dafny.SeqOfChars([]dafny.Char(%s%s)...)".formatted( + dereferenceIfRequired, + dataSource + ); + + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(underlyingType) + ); } - - @Override - public String integerShape(IntegerShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s%s"; - String returnType = "interface {}"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; - } - - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); - + } + + @Override + public String integerShape(IntegerShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s%s"; + String returnType = "interface {}"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; } - @Override - public String longShape(LongShape shape) { - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s%s"; - String returnType = "interface {}"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; - returnType = "Wrappers.Option"; - } - - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } - - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - - return """ - func () %s { - %s - return %s - }()""".formatted(returnType, nilCheck, someWrapIfRequired.formatted(dereferenceIfRequired, dataSource)); + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); } - @Override - public String doubleShape(DoubleShape shape) { - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); - writer.addUseImports(SmithyGoDependency.MATH); - - String nilWrapIfRequired = "nil"; - String someWrapIfRequired = "%s"; - String returnType = "interface {}"; - if (this.isOptional) { - nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; - someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; - returnType = "Wrappers.Option"; - } + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) + ); + } + + @Override + public String longShape(LongShape shape) { + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s%s"; + String returnType = "interface {}"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s%s)"; + returnType = "Wrappers.Option"; + } - var dereferenceIfRequired = isPointerType ? "*" : ""; - var nilCheck = ""; - if (isPointerType) { - nilCheck = "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); - } + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); + } - return """ - func () %s { - %s - var bits = math.Float64bits(%s%s) - var bytes = make([]byte, 8) - binary.LittleEndian.PutUint64(bytes, bits) - var v []interface{} - for _, e := range bytes { - v = append(v, e) - } - return %s; - }()""".formatted(returnType, nilCheck, dereferenceIfRequired, dataSource, someWrapIfRequired.formatted("dafny.SeqOf(v...)")); + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + + return """ + func () %s { + %s + return %s + }()""".formatted( + returnType, + nilCheck, + someWrapIfRequired.formatted(dereferenceIfRequired, dataSource) + ); + } + + @Override + public String doubleShape(DoubleShape shape) { + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + writer.addUseImports(SmithyGoDependency.stdlib("encoding/binary")); + writer.addUseImports(SmithyGoDependency.MATH); + + String nilWrapIfRequired = "nil"; + String someWrapIfRequired = "%s"; + String returnType = "interface {}"; + if (this.isOptional) { + nilWrapIfRequired = "Wrappers.Companion_Option_.Create_None_()"; + someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s)"; + returnType = "Wrappers.Option"; } - @Override - public String unionShape(UnionShape shape) { - final String internalDafnyType = DafnyNameResolver.getDafnyType(shape, context.symbolProvider().toSymbol(shape)); - writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); - final String functionInit = """ - func() Wrappers.Option { - switch %s.(type) {""".formatted(dataSource); - StringBuilder eachMemberInUnion = new StringBuilder(); - for (var member : shape.getAllMembers().values()) { - final String memberName = context.symbolProvider().toMemberName(member); - final Shape targetShape = context.model().expectShape(member.getTarget()); - final String someWrapIfRequired = "Wrappers.Companion_Option_.Create_Some_(%s(%s))"; - final String baseType = DafnyNameResolver.getDafnyType(targetShape, context.symbolProvider().toSymbol(targetShape)); - eachMemberInUnion.append(""" - case *%s.%s: - var companion = %s - var inputToConversion = %s - return %s - """.formatted( - SmithyNameResolver.smithyTypesNamespace(shape), - context.symbolProvider().toMemberName(member), - internalDafnyType.replace(shape.getId().getName(), "CompanionStruct_" + shape.getId().getName() + "_{}"), - targetShape.accept( - new SmithyToDafnyShapeVisitor( - context, dataSource + ".(*" + SmithyNameResolver.smithyTypesNamespace(shape) + "." + context.symbolProvider().toMemberName(member) + ").Value", writer, isConfigShape, true, false - ) - ), - someWrapIfRequired.formatted( - DafnyNameResolver.getDafnyCreateFuncForUnionMemberShape(shape, memberName), - "inputToConversion.UnwrapOr(nil)%s".formatted(baseType != "" ? ".(" + baseType + ")" : "") - ) - )); - } - final String defaultCase = """ - default: - panic("Unhandled union type") - } - }()"""; - return """ - %s - %s - %s""".formatted( - functionInit, - eachMemberInUnion, - defaultCase - ); + var dereferenceIfRequired = isPointerType ? "*" : ""; + var nilCheck = ""; + if (isPointerType) { + nilCheck = + "if %s == nil {return %s}".formatted(dataSource, nilWrapIfRequired); } - @Override - public String timestampShape(TimestampShape shape) { - return "Wrappers.Companion_Option_.Create_None_()"; + return """ + func () %s { + %s + var bits = math.Float64bits(%s%s) + var bytes = make([]byte, 8) + binary.LittleEndian.PutUint64(bytes, bits) + var v []interface{} + for _, e := range bytes { + v = append(v, e) + } + return %s; + }()""".formatted( + returnType, + nilCheck, + dereferenceIfRequired, + dataSource, + someWrapIfRequired.formatted("dafny.SeqOf(v...)") + ); + } + + @Override + public String unionShape(UnionShape shape) { + final String internalDafnyType = DafnyNameResolver.getDafnyType( + shape, + context.symbolProvider().toSymbol(shape) + ); + writer.addImportFromModule("github.com/dafny-lang/DafnyRuntimeGo", "dafny"); + final String functionInit = + """ + func() Wrappers.Option { + switch %s.(type) {""".formatted(dataSource); + StringBuilder eachMemberInUnion = new StringBuilder(); + for (var member : shape.getAllMembers().values()) { + final String memberName = context.symbolProvider().toMemberName(member); + final Shape targetShape = context.model().expectShape(member.getTarget()); + final String someWrapIfRequired = + "Wrappers.Companion_Option_.Create_Some_(%s(%s))"; + final String baseType = DafnyNameResolver.getDafnyType( + targetShape, + context.symbolProvider().toSymbol(targetShape) + ); + eachMemberInUnion.append( + """ + case *%s.%s: + var companion = %s + var inputToConversion = %s + return %s + """.formatted( + SmithyNameResolver.smithyTypesNamespace(shape), + context.symbolProvider().toMemberName(member), + internalDafnyType.replace( + shape.getId().getName(), + "CompanionStruct_" + shape.getId().getName() + "_{}" + ), + targetShape.accept( + new SmithyToDafnyShapeVisitor( + context, + dataSource + + ".(*" + + SmithyNameResolver.smithyTypesNamespace(shape) + + "." + + context.symbolProvider().toMemberName(member) + + ").Value", + writer, + isConfigShape, + true, + false + ) + ), + someWrapIfRequired.formatted( + DafnyNameResolver.getDafnyCreateFuncForUnionMemberShape( + shape, + memberName + ), + "inputToConversion.UnwrapOr(nil)%s".formatted( + baseType != "" ? ".(" + baseType + ")" : "" + ) + ) + ) + ); } -} \ No newline at end of file + final String defaultCase = + """ + default: + panic("Unhandled union type") + } + }()"""; + return """ + %s + %s + %s""".formatted(functionInit, eachMemberInUnion, defaultCase); + } + + @Override + public String timestampShape(TimestampShape shape) { + return "Wrappers.Companion_Option_.Create_None_()"; + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/utils/GoCodegenUtils.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/utils/GoCodegenUtils.java index 086859e8ee..00f7ade743 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/utils/GoCodegenUtils.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/utils/GoCodegenUtils.java @@ -13,36 +13,50 @@ public class GoCodegenUtils { - public static String getType(Symbol symbol, ServiceTrait serviceTrait) { - if (symbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class).isEmpty()) { - return SmithyNameResolver.getSmithyTypeAws(serviceTrait, symbol, true); - } - var type = getType(symbol.expectProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class), serviceTrait); - if(symbol.getProperty(SymbolUtils.GO_MAP).isPresent()) { - return "map[string]" + type; - } - if (symbol.getProperty(SymbolUtils.GO_SLICE).isPresent()) { - return "[]" + type; - } - throw new RuntimeException("Failed to determine shape type"); + public static String getType(Symbol symbol, ServiceTrait serviceTrait) { + if ( + symbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class).isEmpty() + ) { + return SmithyNameResolver.getSmithyTypeAws(serviceTrait, symbol, true); } - - public static Symbol getRootSymbol(Symbol symbol) { - if (symbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class).isEmpty()) { - return symbol; - } - return getRootSymbol(symbol.expectProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class)); + var type = getType( + symbol.expectProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class), + serviceTrait + ); + if (symbol.getProperty(SymbolUtils.GO_MAP).isPresent()) { + return "map[string]" + type; + } + if (symbol.getProperty(SymbolUtils.GO_SLICE).isPresent()) { + return "[]" + type; } + throw new RuntimeException("Failed to determine shape type"); + } - public static boolean isOperationStruct(Model model, Shape shape) { - NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); - for (Relationship relationship : provider.getNeighbors(shape)) { - RelationshipType relationshipType = relationship.getRelationshipType(); - if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { - return true; - } - } + public static Symbol getRootSymbol(Symbol symbol) { + if ( + symbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class).isEmpty() + ) { + return symbol; + } + return getRootSymbol( + symbol.expectProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class) + ); + } - return false; + public static boolean isOperationStruct(Model model, Shape shape) { + NeighborProvider provider = NeighborProviderIndex + .of(model) + .getReverseProvider(); + for (Relationship relationship : provider.getNeighbors(shape)) { + RelationshipType relationshipType = relationship.getRelationshipType(); + if ( + relationshipType == RelationshipType.INPUT || + relationshipType == RelationshipType.OUTPUT + ) { + return true; + } } + + return false; + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/AbstractRustShimGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/AbstractRustShimGenerator.java index 7a67e71036..5319e4a0db 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/AbstractRustShimGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/AbstractRustShimGenerator.java @@ -8,15 +8,19 @@ import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; +import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; import software.amazon.polymorph.utils.IOUtils; +import software.amazon.polymorph.utils.MapUtils; +import software.amazon.polymorph.utils.ModelUtils; import software.amazon.polymorph.utils.TokenTree; -import software.amazon.smithy.aws.traits.ServiceTrait; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.OperationIndex; +import software.amazon.smithy.model.shapes.EnumShape; import software.amazon.smithy.model.shapes.ListShape; import software.amazon.smithy.model.shapes.MapShape; import software.amazon.smithy.model.shapes.MemberShape; @@ -26,7 +30,6 @@ import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.UnionShape; -import software.amazon.smithy.model.traits.EnumDefinition; import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.RequiredTrait; @@ -103,7 +106,7 @@ protected RustFile conversionsErrorModule() { evalTemplate( getClass(), "runtimes/rust/conversions/error.rs", - dafnyModuleVariables() + serviceVariables() ) ); return new RustFile( @@ -122,17 +125,6 @@ protected TokenTree declarePubModules(Stream moduleNames) { .lineSeparated(); } - protected Map dafnyModuleVariables() { - final Map stringStringMap = new HashMap<>(); - stringStringMap.put("dafnyModuleName", getDafnyModuleName()); - stringStringMap.put( - "dafnyInternalModuleName", - getDafnyInternalModuleName() - ); - stringStringMap.put("dafnyTypesModuleName", getDafnyTypesModuleName()); - return stringStringMap; - } - protected RustFile conversionsModule() { Stream operationModules = model .getOperationShapes() @@ -153,9 +145,8 @@ protected RustFile conversionsModule() { .filter(this::shouldGenerateEnumForUnion) .map(structureShape -> toSnakeCase(structureShape.getId().getName())); - Stream enumModules = model - .getStringShapesWithTrait(EnumTrait.class) - .stream() + Stream enumModules = ModelUtils + .streamEnumShapes(model, service.getId().getNamespace()) .map(structureShape -> toSnakeCase(structureShape.getId().getName())); TokenTree content = declarePubModules( @@ -301,8 +292,8 @@ private TokenTree fromDafny( boolean isDafnyOption ) { return switch (shape.getType()) { - case STRING -> { - if (shape.hasTrait(EnumTrait.class)) { + case STRING, ENUM -> { + if (shape.hasTrait(EnumTrait.class) || shape.isEnumShape()) { var enumShapeName = toSnakeCase(shape.toShapeId().getName()); if (isDafnyOption) { yield TokenTree.of( @@ -328,6 +319,30 @@ private TokenTree fromDafny( } yield result; } + } else if (shape.hasTrait(DafnyUtf8BytesTrait.class)) { + final String dafnyToRust = + "::std::string::String::from_utf8(dafny_runtime::dafny_runtime_conversions::dafny_sequence_to_vec(&%s, |b| *b)).unwrap()"; + String valueToRust; + if (isDafnyOption) { + valueToRust = + """ + match %s.as_ref() { + crate::_Wrappers_Compile::Option::Some { .. } => ::std::option::Option::Some(%s), + _ => ::std::option::Option::None, + }""".formatted( + dafnyValue, + dafnyToRust.formatted(dafnyValue + ".Extract()") + ); + if (!isRustOption) { + valueToRust = "(%s).unwrap()".formatted(valueToRust); + } + } else { + valueToRust = dafnyToRust.formatted(dafnyValue + ".as_ref()"); + if (isRustOption) { + valueToRust = "Some(%s)".formatted(valueToRust); + } + } + yield TokenTree.of(valueToRust); } else { if (isDafnyOption) { yield TokenTree.of( @@ -571,21 +586,30 @@ private TokenTree toDafnyVariantMemberForOperationRequest( ) { Shape targetShape = model.expectShape(member.getTarget()); String snakeCaseMemberName = toSnakeCase(member.getMemberName()); - boolean isRequired = member.hasTrait(RequiredTrait.class); - // These rules were mostly reverse-engineered from inspection of Rust SDKs, - // and may not be complete! - boolean isRustRequired = - (isRequired && - !operationIndex.isOutputStructure(parent) && - !operationIndex.isInputStructure(parent) && - !targetShape.isStructureShape()) || - (operationIndex.isOutputStructure(parent) && - targetShape.isIntegerShape()); return toDafny( targetShape, "value." + snakeCaseMemberName, - !isRustRequired, - !isRequired + !isRustFieldRequired(parent, member), + !hasRequiredTrait(member) + ); + } + + protected final boolean hasRequiredTrait(final MemberShape member) { + return member.hasTrait(RequiredTrait.class); + } + + protected boolean isRustFieldRequired( + final Shape parent, + final MemberShape member + ) { + // These rules were mostly reverse-engineered from inspection of Rust SDKs, + // and may not be complete! + final Shape targetShape = model.expectShape(member.getTarget()); + return ( + hasRequiredTrait(member) && + !operationIndex.isOutputStructure(parent) && + !operationIndex.isInputStructure(parent) && + !targetShape.isStructureShape() ); } @@ -604,8 +628,8 @@ private TokenTree toDafny( boolean isDafnyOption ) { return switch (shape.getType()) { - case STRING -> { - if (shape.hasTrait(EnumTrait.class)) { + case STRING, ENUM -> { + if (shape.hasTrait(EnumTrait.class) || shape.isEnumShape()) { var enumShapeName = toSnakeCase(shape.toShapeId().getName()); if (isDafnyOption) { yield TokenTree.of( @@ -631,6 +655,24 @@ private TokenTree toDafny( ) ); } + } else if (shape.hasTrait(DafnyUtf8BytesTrait.class)) { + final String rustToDafny = + "dafny_runtime::dafny_runtime_conversions::vec_to_dafny_sequence(&%s.as_bytes().to_vec(), |b| *b)"; + String valueToDafny; + if (isRustOption) { + valueToDafny = + """ + match %s { + Some(s) => crate::_Wrappers_Compile::Option::Some { value: %s }, + None => crate::_Wrappers_Compile::Option::None {}, + }""".formatted(rustValue, rustToDafny.formatted("s")); + if (!isDafnyOption) { + valueToDafny = "(%s).Extract()".formatted(valueToDafny); + } + } else { + valueToDafny = rustToDafny.formatted(rustValue); + } + yield TokenTree.of("::std::rc::Rc::new(%s)".formatted(valueToDafny)); } else { if (isRustOption) { var result = TokenTree.of( @@ -867,154 +909,82 @@ private TokenTree toDafny( }; } - protected TokenTree enumToDafnyFunction(final Shape enumShape) { - String enumName = enumShape.getId().getName(); - String rustEnumName = toPascalCase(enumName); - String sdkId = service - .expectTrait(ServiceTrait.class) - .getSdkId() - .toLowerCase(); - String dafnyTypesModuleName = getDafnyTypesModuleName(); - Map variables = Map.of( - "sdkCrate", - "aws_sdk_" + sdkId, - "enumName", - enumName, - "rustEnumName", - rustEnumName, - "dafnyTypesModuleName", - dafnyTypesModuleName - ); - - String sdkTypeName = evalTemplate( - "$sdkCrate:L::types::$rustEnumName:L", - variables + protected TokenTree enumToDafnyFunction(final EnumShape enumShape) { + final Map variables = MapUtils.merge( + serviceVariables(), + enumVariables(enumShape) ); + var branches = enumShape + .getEnumValues() + .keySet() + .stream() + .map(memberName -> + evalTemplate( + "$rustTypesModuleName:L::$rustEnumName:L::$rustEnumMemberName:L => crate::r#$dafnyTypesModuleName:L::$enumName:L::$dafnyEnumMemberName:L {},", + MapUtils.merge(variables, enumMemberVariables(memberName)) + ) + ) + .collect(Collectors.joining("\n")); + variables.put("branches", branches); - var prelude = TokenTree.of( + // TODO: This should not be a panic, but the Dafny image of the enum shape doesn't have an Unknown variant of any kind, + // so there's no way to succeed. + // See https://github.com/smithy-lang/smithy-dafny/issues/476. + // This could be handled more cleanly if conversion functions returned Results, + // but that would be a large and disruptive change to the overall code flow. + return TokenTree.of( evalTemplate( """ #[allow(dead_code)] pub fn to_dafny( - value: $sdkCrate:L::types::$rustEnumName:L, + value: $rustTypesModuleName:L::$rustEnumName:L, ) -> ::std::rc::Rc{ ::std::rc::Rc::new(match value { - + $branches:L + _ => panic!("Unknown enum variant: {}", value), + }) + } """, variables ) ); - - var branches = TokenTree - .of( - enumShape - .expectTrait(EnumTrait.class) - .getValues() - .stream() - .map(e -> - TokenTree.of( - sdkTypeName + - "::" + - rustEnumName(e) + - " => crate::r#" + - dafnyTypesModuleName + - "::" + - enumName + - "::" + - dafnyEnumName(e) + - " {}," - ) - ) - ) - .lineSeparated(); - // TODO: This should not be a panic, but the Dafny image of the enum shape doesn't have an Unknown variant of any kind, - // so there's no way to succeed. - // See https://github.com/smithy-lang/smithy-dafny/issues/476. - // This could be handled more cleanly if conversion functions returned Results, - // but that would be a large and disruptive change to the overall code flow. - final var postlude = TokenTree.of( - """ - - _ => panic!("Unknown enum variant: {}", value), - }) - } - """ - ); - - return TokenTree.of(prelude, branches, postlude); } - protected TokenTree enumFromDafnyFunction(final Shape enumShape) { - String enumName = enumShape.getId().getName(); - String rustEnumName = toPascalCase(enumName); - String sdkId = service - .expectTrait(ServiceTrait.class) - .getSdkId() - .toLowerCase(); - String dafnyTypesModuleName = getDafnyTypesModuleName(); - Map variables = Map.of( - "sdkCrate", - "aws_sdk_" + sdkId, - "enumName", - enumName, - "rustEnumName", - rustEnumName, - "dafnyTypesModuleName", - dafnyTypesModuleName + protected TokenTree enumFromDafnyFunction(final EnumShape enumShape) { + final Map variables = MapUtils.merge( + serviceVariables(), + enumVariables(enumShape) ); - String sdkTypeName = evalTemplate( - "$sdkCrate:L::types::$rustEnumName:L", - variables - ); + var branches = enumShape + .getEnumValues() + .keySet() + .stream() + .map(memberName -> + evalTemplate( + "crate::r#$dafnyTypesModuleName:L::$enumName:L::$dafnyEnumMemberName:L {} => $rustTypesModuleName:L::$rustEnumName:L::$rustEnumMemberName:L,", + MapUtils.merge(variables, enumMemberVariables(memberName)) + ) + ) + .collect(Collectors.joining("\n")); + variables.put("branches", branches); - var prelude = TokenTree.of( + return TokenTree.of( evalTemplate( """ #[allow(dead_code)] pub fn from_dafny( dafny_value: &crate::r#$dafnyTypesModuleName:L::$enumName:L, - ) -> $sdkCrate:L::types::$rustEnumName:L { + ) -> $rustTypesModuleName:L::$rustEnumName:L { match dafny_value { - + $branches:L + } + } """, variables ) ); - - var branches = TokenTree - .of( - enumShape - .expectTrait(EnumTrait.class) - .getValues() - .stream() - .map(e -> - TokenTree.of( - "crate::r#" + - dafnyTypesModuleName + - "::" + - enumName + - "::" + - dafnyEnumName(e) + - " {} => " + - sdkTypeName + - "::" + - rustEnumName(e) + - "," - ) - ) - ) - .lineSeparated(); - final var postlude = TokenTree.of( - """ - - } - } - """ - ); - - return TokenTree.of(prelude, branches, postlude); } protected Set allOperationConversionModules() { @@ -1028,16 +998,40 @@ protected abstract Set operationConversionModules( final OperationShape operationShape ); - private String rustEnumName(EnumDefinition ed) { - return toPascalCase(ed.getValue()); + protected RustFile enumConversionModule(final EnumShape enumShape) { + Path path = Path.of( + "src", + "conversions", + toSnakeCase(enumName(enumShape)) + ".rs" + ); + + return new RustFile( + path, + TokenTree + .of(enumToDafnyFunction(enumShape), enumFromDafnyFunction(enumShape)) + .lineSeparated() + ); } - private String dafnyEnumName(EnumDefinition ed) { - return ed.getValue(); + /** + * Generates values for variables commonly used in service-specific templates. + */ + protected HashMap serviceVariables() { + final HashMap variables = new HashMap<>(); + variables.put("serviceName", service.getId().getName(service)); + variables.put("dafnyModuleName", getDafnyModuleName()); + variables.put("dafnyInternalModuleName", getDafnyInternalModuleName()); + variables.put("dafnyTypesModuleName", getDafnyTypesModuleName()); + variables.put("rustTypesModuleName", getRustTypesModuleName()); + return variables; } protected String getDafnyModuleName() { - return service.getId().getNamespace().replace(".", "::"); + return service + .getId() + .getNamespace() + .replace(".", "::") + .toLowerCase(Locale.ROOT); } protected String getDafnyInternalModuleName() { @@ -1048,14 +1042,7 @@ protected String getDafnyTypesModuleName() { return "%s::types".formatted(getDafnyInternalModuleName()); } - /** - * Generates values for variables commonly used in service-specific templates. - */ - protected HashMap serviceVariables() { - final HashMap variables = new HashMap<>(); - variables.put("serviceName", service.getId().getName(service)); - return variables; - } + protected abstract String getRustTypesModuleName(); /** * Generates values for variables commonly used in operation-specific templates. @@ -1066,6 +1053,8 @@ protected HashMap operationVariables( final String opName = operationName(operationShape); final String opInputName = operationInputName(operationShape); final String opOutputName = operationOutputName(operationShape); + final String synOpInputName = syntheticOperationInputName(operationShape); + final String synOpOutputName = syntheticOperationOutputName(operationShape); final String snakeCaseOpName = toSnakeCase(opName); final HashMap variables = new HashMap<>(); @@ -1073,16 +1062,18 @@ protected HashMap operationVariables( variables.put("operationInputName", opInputName); variables.put("operationOutputName", opOutputName); variables.put("operationErrorName", operationErrorTypeName(operationShape)); + variables.put("syntheticOperationInputName", synOpInputName); + variables.put("syntheticOperationOutputName", synOpOutputName); variables.put("snakeCaseOperationName", snakeCaseOpName); variables.put("snakeCaseOperationInputName", toSnakeCase(opInputName)); variables.put("snakeCaseOperationOutputName", toSnakeCase(opOutputName)); variables.put( - "syntheticOperationInputName", - syntheticOperationInputName(operationShape) + "snakeCaseSyntheticOperationInputName", + toSnakeCase(synOpInputName) ); variables.put( - "syntheticOperationOutputName", - syntheticOperationOutputName(operationShape) + "snakeCaseSyntheticOperationOutputName", + toSnakeCase(synOpOutputName) ); return variables; } @@ -1111,43 +1102,46 @@ protected String operationErrorTypeName(final OperationShape operationShape) { return "%sError".formatted(operationName(operationShape)); } - /** - * Generates values for variables commonly used in structure-member-specific templates. - */ - protected HashMap memberVariables( - final MemberShape memberShape - ) { + protected String enumName(final EnumShape enumShape) { + return enumShape.getId().getName(service); + } + + protected String rustEnumName(final EnumShape enumShape) { + return toPascalCase(enumName(enumShape)); + } + + protected String qualifiedRustEnumType(final EnumShape enumShape) { + return "%s::%s".formatted( + getRustTypesModuleName(), + rustEnumName(enumShape) + ); + } + + protected HashMap enumVariables(final EnumShape enumShape) { final HashMap variables = new HashMap<>(); - variables.put("fieldName", toSnakeCase(memberShape.getMemberName())); - variables.put( - "fieldType", - rustTypeForShape(model.expectShape(memberShape.getTarget())) - ); + final String enumName = enumName(enumShape); + variables.put("enumName", enumName); + variables.put("snakeCaseEnumName", toSnakeCase(enumName)); + variables.put("rustEnumName", rustEnumName(enumShape)); + variables.put("qualifiedRustEnumType", qualifiedRustEnumType(enumShape)); return variables; } - // Currently only handles simple types, and doesn't account for any traits - protected String rustTypeForShape(final Shape shape) { - return switch (shape.getType()) { - case BOOLEAN -> "::std::primitive::bool"; - // integral - case BYTE -> "::std::primitive::i8"; - case SHORT -> "::std::primitive::i16"; - case INTEGER -> "::std::primitive::i32"; - case LONG -> "::std::primitive::i64"; - // floats - case FLOAT -> "::std::primitive::f32"; - case DOUBLE -> "::std::primitive::f64"; - // special numerics - case BIG_INTEGER -> "::num::bigint::BigInt"; - case BIG_DECIMAL -> "::num::rational::BigRational"; - // special collections - case BLOB -> "::std::vec::Vec<::std::primitive::u8>"; - case STRING -> "::std::string::String"; - // TODO: enum, list, map, structure, union - default -> throw new UnsupportedOperationException( - "Unsupported shape type: " + shape.getType() - ); - }; + protected String rustEnumMemberName(final String memberName) { + return toPascalCase(memberName); + } + + protected String dafnyEnumMemberName(final String memberName) { + return memberName; + } + + protected HashMap enumMemberVariables( + final String memberName + ) { + final HashMap variables = new HashMap<>(); + variables.put("enumMemberName", memberName); + variables.put("dafnyEnumMemberName", dafnyEnumMemberName(memberName)); + variables.put("rustEnumMemberName", rustEnumMemberName(memberName)); + return variables; } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustAwsSdkShimGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustAwsSdkShimGenerator.java index 3c08de804c..ca2ecf80e9 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustAwsSdkShimGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustAwsSdkShimGenerator.java @@ -13,15 +13,16 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.polymorph.utils.MapUtils; +import software.amazon.polymorph.utils.ModelUtils; import software.amazon.polymorph.utils.TokenTree; import software.amazon.smithy.aws.traits.ServiceTrait; import software.amazon.smithy.model.Model; +import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.StructureShape; -import software.amazon.smithy.model.traits.EnumTrait; /** * Generates all Rust modules needed to wrap @@ -47,11 +48,10 @@ protected Set rustFiles() { ); result.addAll( - model - .getStringShapesWithTrait(EnumTrait.class) - .stream() + ModelUtils + .streamEnumShapes(model, service.getId().getNamespace()) .map(this::enumConversionModule) - .collect(Collectors.toSet()) + .toList() ); result.add(conversionsModule()); @@ -64,12 +64,7 @@ protected Set rustFiles() { } private RustFile clientModule() { - final Map variables = MapUtils.merge( - serviceVariables(), - dafnyModuleVariables() - ); - variables.put("clientName", "%sClient".formatted(getSdkId())); - + final Map variables = serviceVariables(); var preamble = TokenTree.of( evalTemplate( """ @@ -152,10 +147,8 @@ private TokenTree operationClientFunction( ) { final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); - variables.put("clientName", "%sClient".formatted(getSdkId())); final ShapeId outputShapeId = operationShape.getOutputShape(); final String outputType = outputShapeId.equals( @@ -221,7 +214,7 @@ private TokenTree structureToDafnyFunction( """ #[allow(dead_code)] pub fn to_dafny( - value: &$sdkCrate:L::types::$rustStructureName:L, + value: &$rustTypesModuleName:L::$rustStructureName:L, ) -> ::std::rc::Rc{ ::std::rc::Rc::new( crate::r#$dafnyTypesModuleName:L::$structureName:L::$structureName:L { @@ -230,10 +223,7 @@ pub fn to_dafny( ) } """; - final Map variables = MapUtils.merge( - serviceVariables(), - dafnyModuleVariables() - ); + final Map variables = serviceVariables(); variables.put("structureName", structureName); variables.put("rustStructureName", toPascalCase(structureName)); variables.put( @@ -259,10 +249,7 @@ private TokenTree structureFromDafnyFunction( ) ? ".unwrap()" : ""; - final Map variables = MapUtils.merge( - serviceVariables(), - dafnyModuleVariables() - ); + final Map variables = serviceVariables(); variables.put("structureName", structureName); variables.put("rustStructureName", toPascalCase(structureName)); variables.put("snakeCaseStructureName", toSnakeCase(structureName)); @@ -280,8 +267,8 @@ pub fn from_dafny( dafny_value: ::std::rc::Rc< crate::r#$dafnyTypesModuleName:L::$structureName:L, >, - ) -> $sdkCrate:L::types::$rustStructureName:L { - $sdkCrate:L::types::$rustStructureName:L::builder() + ) -> $rustTypesModuleName:L::$rustStructureName:L { + $rustTypesModuleName:L::$rustStructureName:L::builder() $fluentMemberSetters:L .build() $unwrapIfNeeded:L @@ -298,7 +285,6 @@ protected TokenTree operationRequestToDafnyFunction( ) { final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); StructureShape inputShape = model.expectShape( @@ -329,13 +315,23 @@ pub fn to_dafny( ); } + @Override + protected boolean isRustFieldRequired(Shape parent, MemberShape member) { + // These rules were mostly reverse-engineered from inspection of Rust SDKs, + // and may not be complete! + final Shape targetShape = model.expectShape(member.getTarget()); + return ( + super.isRustFieldRequired(parent, member) || + (operationIndex.isOutputStructure(parent) && targetShape.isIntegerShape()) + ); + } + @Override protected TokenTree operationRequestFromDafnyFunction( final OperationShape operationShape ) { final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); StructureShape inputShape = model.expectShape( @@ -372,7 +368,6 @@ protected TokenTree operationResponseToDafnyFunction( ) { final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); StructureShape outputShape = model.expectShape( @@ -473,7 +468,6 @@ protected TokenTree operationErrorToDafnyFunction( final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); variables.put("errorCases", errorCases.toString()); @@ -511,7 +505,6 @@ protected TokenTree errorVariantToDafny( ) { final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); String errorName = toPascalCase(errorShape.getId().getName()); @@ -538,7 +531,7 @@ private RustFile errorConversionModule(final Shape errorStructure) { """ #[allow(dead_code)] pub fn to_dafny( - value: $sdkCrate:L::types::error::$pascalCaseName:L, + value: $rustTypesModuleName:L::error::$pascalCaseName:L, ) -> ::std::rc::Rc{ ::std::rc::Rc::new( crate::r#$dafnyTypesModuleName:L::Error::$structureName:L { @@ -547,34 +540,14 @@ pub fn to_dafny( ) } """; - final Map variables = MapUtils.merge( - serviceVariables(), - dafnyModuleVariables() - ); + final Map variables = serviceVariables(); variables.put("structureName", structureName); variables.put("pascalCaseName", pascalCaseName); variables.put( "variants", toDafnyVariantsForStructure(errorStructure).toString() ); - String evaluated = evalTemplate(template, variables); - return new RustFile(path, TokenTree.of(evaluated)); - } - - private RustFile enumConversionModule(final Shape enumShape) { - Path path = Path.of( - "src", - "conversions", - toSnakeCase(enumShape.getId().getName()) + ".rs" - ); - - return new RustFile( - path, - TokenTree.of( - enumToDafnyFunction(enumShape), - enumFromDafnyFunction(enumShape) - ) - ); + return new RustFile(path, TokenTree.of(evalTemplate(template, variables))); } @Override @@ -584,6 +557,11 @@ protected String getDafnyModuleName() { ); } + @Override + protected String getRustTypesModuleName() { + return "%s::types".formatted(getSdkCrate()); + } + private String getSdkId() { return service.expectTrait(ServiceTrait.class).getSdkId(); } @@ -595,8 +573,10 @@ private String getSdkCrate() { @Override protected HashMap serviceVariables() { final HashMap variables = super.serviceVariables(); - variables.put("sdkId", getSdkId()); + final String sdkId = getSdkId(); + variables.put("sdkId", sdkId); variables.put("sdkCrate", getSdkCrate()); + variables.put("clientName", "%sClient".formatted(sdkId)); return variables; } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustLibraryShimGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustLibraryShimGenerator.java index dbf694082e..180fd1b8dd 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustLibraryShimGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithyrust/generator/RustLibraryShimGenerator.java @@ -1,6 +1,7 @@ package software.amazon.polymorph.smithyrust.generator; import static software.amazon.polymorph.utils.IOUtils.evalTemplate; +import static software.amazon.smithy.rust.codegen.core.util.StringsKt.toPascalCase; import static software.amazon.smithy.rust.codegen.core.util.StringsKt.toSnakeCase; import java.nio.file.Path; @@ -17,12 +18,14 @@ import software.amazon.polymorph.utils.ModelUtils; import software.amazon.polymorph.utils.TokenTree; import software.amazon.smithy.model.Model; +import software.amazon.smithy.model.shapes.EnumShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.StructureShape; +import software.amazon.smithy.model.traits.EnumTrait; /** * Generates all Rust modules needed to wrap a Dafny library as a Rust library. @@ -62,6 +65,12 @@ protected Set rustFiles() { // types result.add(typesModule()); result.add(typesConfigModule()); + result.addAll( + ModelUtils + .streamEnumShapes(model, service.getId().getNamespace()) + .map(this::enumTypeModule) + .toList() + ); // errors result.add(errorModule()); @@ -81,8 +90,13 @@ protected Set rustFiles() { result.add(conversionsErrorModule()); result.addAll(configConversionModules()); result.addAll(allOperationConversionModules()); + result.addAll( + ModelUtils + .streamEnumShapes(model, service.getId().getNamespace()) + .map(this::enumConversionModule) + .toList() + ); // TODO structure conversion modules - // TODO enum conversion modules // TODO union conversion modules // wrapped client @@ -93,10 +107,7 @@ protected Set rustFiles() { } private RustFile clientModule() { - final Map variables = MapUtils.merge( - dafnyModuleVariables(), - serviceVariables() - ); + final Map variables = serviceVariables(); variables.put( "operationModules", serviceOperationShapes() @@ -191,10 +202,26 @@ private String operationClientOutputDoc(final OperationShape operationShape) { } private RustFile typesModule() { + final Map variables = serviceVariables(); + + final String enumModules = ModelUtils + .streamEnumShapes(model, service.getId().getNamespace()) + .map(enumShape -> + IOUtils.evalTemplate( + """ + mod _$snakeCaseEnumName:L; + pub use crate::types::_$snakeCaseEnumName:L::$rustEnumName:L; + """, + enumVariables(enumShape) + ) + ) + .collect(Collectors.joining("\n")); + variables.put("enumModules", enumModules); + final String content = IOUtils.evalTemplate( getClass(), "runtimes/rust/types.rs", - serviceVariables() + variables ); return new RustFile(Path.of("src", "types.rs"), TokenTree.of(content)); } @@ -214,6 +241,46 @@ private RustFile typesConfigModule() { return new RustFile(path, TokenTree.of(content)); } + private RustFile enumTypeModule(final EnumShape enumShape) { + final Map variables = MapUtils.merge( + serviceVariables(), + enumVariables(enumShape) + ); + + final Set memberNames = enumShape.getEnumValues().keySet(); + + final String variants = memberNames + .stream() + .map(this::rustEnumMemberName) + .map("%s,"::formatted) + .collect(Collectors.joining("\n")); + variables.put("variants", variants); + + final String displayVariants = memberNames + .stream() + .map(memberName -> + IOUtils.evalTemplate( + "$rustEnumName:L::$rustEnumMemberName:L => write!(f, \"$enumMemberName:L\"),", + MapUtils.merge(variables, enumMemberVariables(memberName)) + ) + ) + .collect(Collectors.joining("\n")); + variables.put("displayVariants", displayVariants); + + final String content = IOUtils.evalTemplate( + getClass(), + "runtimes/rust/types/enum.rs", + variables + ); + + final Path path = Path.of( + "src", + "types", + "_%s.rs".formatted(toSnakeCase(enumName(enumShape))) + ); + return new RustFile(path, TokenTree.of(content)); + } + private RustFile operationModule() { final String opTemplate = """ @@ -319,14 +386,22 @@ private String operationStructureField(final MemberShape memberShape) { } private String operationStructureGetter(final MemberShape memberShape) { + final Map variables = memberVariables(memberShape); + + // for some simple shapes, the Rust runtime types are not Copy + final Shape targetShape = model.expectShape(memberShape.getTarget()); + final boolean needsClone = + targetShape.isBlobShape() || targetShape.isStringShape(); + variables.put("fieldClone", needsClone ? ".clone()" : ""); + final String template = """ #[allow(missing_docs)] // documentation missing in model pub fn $fieldName:L(&self) -> ::std::option::Option<$fieldType:L> { - self.$fieldName:L + self.$fieldName:L$fieldClone:L } """; - return IOUtils.evalTemplate(template, memberVariables(memberShape)); + return IOUtils.evalTemplate(template, variables); } private String operationStructureBuilderField(final MemberShape memberShape) { @@ -440,10 +515,7 @@ private RustFile errorConversionModule( } private Set configConversionModules() { - final Map variables = MapUtils.merge( - serviceVariables(), - dafnyModuleVariables() - ); + final Map variables = serviceVariables(); final String snakeCaseConfigName = variables.get("snakeCaseConfigName"); final String outerContent = IOUtils.evalTemplate( @@ -486,7 +558,6 @@ protected Set operationConversionModules( ) { final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); @@ -543,7 +614,6 @@ private TokenTree operationStructureToDafnyFunction( ); final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); variables.put("structureName", structureId.getName(service)); @@ -601,7 +671,6 @@ private TokenTree operationStructureFromDafnyFunction( ); final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); variables.put("structureName", structureId.getName(service)); @@ -635,16 +704,13 @@ private RustFile wrappedModule() { final String content = IOUtils.evalTemplate( getClass(), "runtimes/rust/wrapped.rs", - MapUtils.merge(serviceVariables(), dafnyModuleVariables()) + serviceVariables() ); return new RustFile(Path.of("src", "wrapped.rs"), TokenTree.of(content)); } private RustFile wrappedClientModule() { - final Map variables = MapUtils.merge( - serviceVariables(), - dafnyModuleVariables() - ); + final Map variables = serviceVariables(); variables.put( "operationImpls", serviceOperationShapes() @@ -667,7 +733,6 @@ private String wrappedClientOperationImpl( ) { final Map variables = MapUtils.merge( serviceVariables(), - dafnyModuleVariables(), operationVariables(operationShape) ); return IOUtils.evalTemplate( @@ -704,6 +769,11 @@ protected HashMap serviceVariables() { return variables; } + @Override + protected String getRustTypesModuleName() { + return "crate::types"; + } + @Override protected String syntheticOperationInputName(OperationShape operationShape) { return operationName(operationShape) + "Input"; @@ -713,4 +783,55 @@ protected String syntheticOperationInputName(OperationShape operationShape) { protected String syntheticOperationOutputName(OperationShape operationShape) { return operationName(operationShape) + "Output"; } + + /** + * Generates values for variables commonly used in structure-member-specific templates. + */ + private HashMap memberVariables( + final MemberShape memberShape + ) { + final HashMap variables = new HashMap<>(); + variables.put("fieldName", toSnakeCase(memberShape.getMemberName())); + variables.put( + "fieldType", + rustTypeForShape(model.expectShape(memberShape.getTarget())) + ); + return variables; + } + + // Currently only handles simple types and enums, and doesn't account for any traits + private String rustTypeForShape(final Shape shape) { + return switch (shape.getType()) { + case BOOLEAN -> "::std::primitive::bool"; + // integral + case BYTE -> "::std::primitive::i8"; + case SHORT -> "::std::primitive::i16"; + case INTEGER -> "::std::primitive::i32"; + case LONG -> "::std::primitive::i64"; + // floats + case FLOAT -> "::std::primitive::f32"; + case DOUBLE -> "::std::primitive::f64"; + // special numerics + case BIG_INTEGER -> "::num::bigint::BigInt"; + case BIG_DECIMAL -> "::num::rational::BigRational"; + // special collections + case BLOB -> "::aws_smithy_types::Blob"; + case STRING -> { + //noinspection deprecation + if (shape.hasTrait(EnumTrait.class)) { + yield qualifiedRustEnumType( + ModelUtils.stringToEnumShape(shape.asStringShape().orElseThrow()) + ); + } + yield "::std::string::String"; + } + case ENUM -> qualifiedRustEnumType(shape.asEnumShape().orElseThrow()); + // everything else + case TIMESTAMP -> "::aws_smithy_types::DateTime"; + // TODO: list, map, structure, union + default -> throw new UnsupportedOperationException( + "Unsupported shape type: " + shape.getType() + ); + }; + } } diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/utils/ModelUtils.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/utils/ModelUtils.java index 47e50c7340..0795b6a8c8 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/utils/ModelUtils.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/utils/ModelUtils.java @@ -110,6 +110,36 @@ public static Stream streamNamespaceErrors( ); } + /** + * Returns a stream of enum shapes in the given namespace. + * These include both Smithy v2 enums, + * and Smithy v1 @enum strings converted to {@link EnumShape}s. + */ + public static Stream streamEnumShapes( + final Model model, + final String namespace + ) { + @SuppressWarnings("deprecation") + final Stream v1Enums = model + .getStringShapesWithTrait(EnumTrait.class) + .stream() + .map(ModelUtils::stringToEnumShape); + final Stream v2Enums = model.getEnumShapes().stream(); + return Stream + .concat(v1Enums, v2Enums) + .filter(shape -> shape.getId().getNamespace().equals(namespace)); + } + + public static EnumShape stringToEnumShape(final StringShape stringShape) { + return EnumShape + .fromStringShape(stringShape) + .orElseThrow(() -> + new UnsupportedOperationException( + "Could not convert %s to an enum".formatted(stringShape.getId()) + ) + ); + } + /** * @return true if the given shape ID is in the given service's namespace */ diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/conversions/operation.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/conversions/operation.rs index 874db88a83..9919295c45 100644 --- a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/conversions/operation.rs +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/conversions/operation.rs @@ -25,6 +25,6 @@ pub fn from_dafny_error( } } -pub mod _$snakeCaseOperationInputName:L; +pub mod _$snakeCaseSyntheticOperationInputName:L; -pub mod _$snakeCaseOperationOutputName:L; \ No newline at end of file +pub mod _$snakeCaseSyntheticOperationOutputName:L; \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/operation/outer.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/operation/outer.rs index 5d5817d737..0aea337ee7 100644 --- a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/operation/outer.rs +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/operation/outer.rs @@ -14,7 +14,7 @@ impl $operationName:L { crate::operation::$snakeCaseOperationName:L::$operationOutputName:L, crate::operation::$snakeCaseOperationName:L::$operationErrorName:L, > { - let inner_input = crate::conversions::$snakeCaseOperationName:L::_$snakeCaseOperationInputName:L::to_dafny(input); + let inner_input = crate::conversions::$snakeCaseOperationName:L::_$snakeCaseSyntheticOperationInputName:L::to_dafny(input); let inner_result = ::dafny_runtime::md!(client.dafny_client.clone()).$operationName:L(&inner_input); if matches!( @@ -22,7 +22,7 @@ impl $operationName:L { crate::r#_Wrappers_Compile::Result::Success { .. } ) { Ok( - crate::conversions::$snakeCaseOperationName:L::_$snakeCaseOperationOutputName:L::from_dafny( + crate::conversions::$snakeCaseOperationName:L::_$snakeCaseSyntheticOperationOutputName:L::from_dafny( inner_result.value().clone(), ), ) diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/src/standard_library_externs.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/src/standard_library_externs.rs new file mode 100644 index 0000000000..eca6a29803 --- /dev/null +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/src/standard_library_externs.rs @@ -0,0 +1,80 @@ +// Annotation to ignore the case of this module +use crate::r#_Wrappers_Compile; +use crate::UTF8; + +impl crate::UTF8::_default { + pub fn Encode( + s: &::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let v = s.to_array(); + let mut _accumulator: Vec = vec![]; + // Use of .encode_utf8 method. + let mut surrogate: Option = None; + for c in v.iter() { + let s = if let Some(s) = surrogate { + String::from_utf16(&[s, c.0]) + } else { + String::from_utf16(&[c.0]) + }; + surrogate = None; + match s { + Ok(value) => { + _accumulator.extend(value.as_bytes()); + continue; + } + Err(e) => { + if 0xD800 <= c.0 && c.0 <= 0xDFFF { + surrogate = Some(c.0); + continue; + } + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }); + } + } + } + if let Some(s) = surrogate { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &format!("Surrogate pair missing: 0x{:04x}", s)) + }); + } + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::< + UTF8::ValidUTF8Bytes, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >::Success { + value: ::dafny_runtime::Sequence::from_array_owned(_accumulator), + }) + } + pub fn Decode( + b: &::dafny_runtime::Sequence, + ) -> ::std::rc::Rc< + r#_Wrappers_Compile::Result< + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + >, + > { + let b = String::from_utf8(b.to_array().as_ref().clone()); + match b { + Ok(s) => { + ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Success { + value: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string(&s) + }) + }, + Err(e) => { + return ::std::rc::Rc::new(r#_Wrappers_Compile::Result::<::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>, + ::dafny_runtime::Sequence<::dafny_runtime::DafnyCharUTF16>>::Failure { + error: ::dafny_runtime::dafny_runtime_conversions::unicode_chars_false::string_to_dafny_string( + &e.to_string()) + }) + } + } + } +} diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types.rs index 2627a01b4a..94630df9d1 100644 --- a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types.rs +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types.rs @@ -1,2 +1,4 @@ /// Types for the `$configName:L` -pub mod $snakeCaseConfigName:L; \ No newline at end of file +pub mod $snakeCaseConfigName:L; + +$enumModules:L \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types/enum.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types/enum.rs new file mode 100644 index 0000000000..0c74b9c52d --- /dev/null +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/types/enum.rs @@ -0,0 +1,12 @@ +#[derive(Debug, PartialEq, Copy, Clone)] +pub enum $rustEnumName:L { + $variants:L +} + +impl ::std::fmt::Display for $rustEnumName:L { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match self { + $displayVariants:L + } + } +} \ No newline at end of file diff --git a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/wrapped/client_operation_impl.part.rs b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/wrapped/client_operation_impl.part.rs index ce6976a530..ad3ac5afc9 100644 --- a/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/wrapped/client_operation_impl.part.rs +++ b/codegen/smithy-dafny-codegen/src/main/resources/templates/runtimes/rust/wrapped/client_operation_impl.part.rs @@ -12,7 +12,7 @@ >, >{ let inner_input = - crate::conversions::$snakeCaseOperationName:L::_$snakeCaseOperationInputName:L::from_dafny(input.clone()); + crate::conversions::$snakeCaseOperationName:L::_$snakeCaseSyntheticOperationInputName:L::from_dafny(input.clone()); let result = self.rt.block_on(crate::operation::$snakeCaseOperationName:L::$operationName:L::send(&self.wrapped, inner_input)); match result { Err(error) => ::std::rc::Rc::new( @@ -22,7 +22,7 @@ ), Ok(client) => ::std::rc::Rc::new( crate::_Wrappers_Compile::Result::Success { - value: crate::conversions::$snakeCaseOperationName:L::_$snakeCaseOperationOutputName:L::to_dafny(client), + value: crate::conversions::$snakeCaseOperationName:L::_$snakeCaseSyntheticOperationOutputName:L::to_dafny(client), }, ), } diff --git a/codegen/smithy-dafny-codegen/src/test/java/software/amazon/polymorph/smithyjava/ForEachDafnyTest.java b/codegen/smithy-dafny-codegen/src/test/java/software/amazon/polymorph/smithyjava/ForEachDafnyTest.java index 20ace96be3..61f032a862 100644 --- a/codegen/smithy-dafny-codegen/src/test/java/software/amazon/polymorph/smithyjava/ForEachDafnyTest.java +++ b/codegen/smithy-dafny-codegen/src/test/java/software/amazon/polymorph/smithyjava/ForEachDafnyTest.java @@ -17,6 +17,7 @@ public static Collection dafnies() { new Object[][] { { new DafnyVersion(4, 1, 0) }, { new DafnyVersion(4, 3, 0) }, + { new DafnyVersion(4, 8, 0) }, } ); } From 32f4f29505d76a64c494523d5ebd4637884bd26f Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 9 Sep 2024 11:24:59 -0700 Subject: [PATCH 43/44] Merge fix structure generator --- .../smithygo/codegen/StructureGenerator.java | 469 ++++++++---------- 1 file changed, 215 insertions(+), 254 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java index ecf9687753..c34832abbd 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java @@ -13,257 +13,218 @@ * permissions and limitations under the License. */ -package software.amazon.polymorph.smithygo.codegen; - -import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - -import java.math.BigDecimal; -import java.util.HashSet; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; -import software.amazon.polymorph.smithygo.localservice.nameresolver.SmithyNameResolver; -import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; -import software.amazon.polymorph.traits.ReferenceTrait; -import software.amazon.smithy.codegen.core.Symbol; -import software.amazon.smithy.codegen.core.SymbolProvider; -import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.shapes.MemberShape; -import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.StructureShape; -import software.amazon.smithy.model.traits.ErrorTrait; -import software.amazon.smithy.model.traits.LengthTrait; -import software.amazon.smithy.model.traits.RangeTrait; -import software.amazon.smithy.model.traits.RequiredTrait; -import software.amazon.smithy.model.traits.StreamingTrait; -import software.amazon.smithy.utils.SetUtils; - -/** - * Renders structures. - */ -public final class StructureGenerator implements Runnable { - - private static final Set ERROR_MEMBER_NAMES = SetUtils.of( - "ErrorMessage", - "Message", - "ErrorCodeOverride" - ); - - private final Model model; - private final SymbolProvider symbolProvider; - private final GoWriter writer; - private final StructureShape shape; - private final GenerationContext context; - private final ValidationGenerator validationGenerator; - - public StructureGenerator( - final GenerationContext context, - GoWriter writer, - StructureShape shape - ) { - this.context = context; - this.model = context.model(); - this.symbolProvider = context.symbolProvider(); - this.writer = writer; - this.shape = shape; - this.validationGenerator = - new ValidationGenerator(model, symbolProvider, writer); - } - - @Override - public void run() { - if (!shape.hasTrait(ErrorTrait.class)) { - renderStructure(() -> {}); - } else { - renderErrorStructure(); - } - } - - /** - * Renders a non-error structure. - * - * @param runnable A runnable that runs before the structure definition is closed. This can be used to write - * additional members. - */ - public void renderStructure(Runnable runnable) { - renderStructure(runnable, false); - } - - /** - * Renders a non-error structure. - * - * @param runnable A runnable that runs before the structure definition is closed. This can be used to write - * additional members. - * @param isInputStructure A boolean indicating if input variants for member symbols should be used. - */ - public void renderStructure(Runnable runnable, boolean isInputStructure) { - writer.addImport("fmt"); - Symbol symbol = symbolProvider.toSymbol(shape); - writer.openBlock("type $L struct {", symbol.getName()); - CodegenUtils.SortedMembers sortedMembers = new CodegenUtils.SortedMembers( - symbolProvider - ); - shape - .getAllMembers() - .values() - .stream() - .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) - .sorted(sortedMembers) - .forEach(member -> { - writer.write(""); - - String memberName = symbolProvider.toMemberName(member); - - Symbol memberSymbol = symbolProvider.toSymbol(member); - - var targetShape = model.expectShape(member.getTarget()); - - if (isInputStructure) { - memberSymbol = - memberSymbol - .getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) - .orElse(memberSymbol); - } - var namespace = SmithyNameResolver.smithyTypesNamespace(targetShape); - - if (targetShape.hasTrait(ReferenceTrait.class)) { - memberSymbol = - memberSymbol.getProperty("Referred", Symbol.class).get(); - var refShape = targetShape.expectTrait(ReferenceTrait.class); - if (refShape.isService()) { - namespace = - SmithyNameResolver.shapeNamespace( - model.expectShape(refShape.getReferentId()) - ); - } - if ( - !member - .toShapeId() - .getNamespace() - .equals(refShape.getReferentId().getNamespace()) - ) { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - refShape.getReferentId().getNamespace() - ), - namespace - ); - } - } else { - if ( - !member - .toShapeId() - .getNamespace() - .equals(targetShape.toShapeId().getNamespace()) && - !targetShape.toShapeId().getNamespace().startsWith("smithy") && - targetShape.asStructureShape().isPresent() - ) { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - targetShape.toShapeId().getNamespace() - ), - namespace - ); - } - } - - /** - * Renders a non-error structure. - * - * @param runnable A runnable that runs before the structure definition is closed. This can be used to write - * additional members. - */ - public void renderStructure(Runnable runnable) { - renderStructure(runnable, false); - } - - /** - * Renders a non-error structure. - * - * @param runnable A runnable that runs before the structure definition is closed. This can be used to write - * additional members. - * @param isInputStructure A boolean indicating if input variants for member symbols should be used. - */ - public void renderStructure(Runnable runnable, boolean isInputStructure) { - writer.addImport("fmt"); - Symbol symbol = symbolProvider.toSymbol(shape); - writer.openBlock("type $L struct {", symbol.getName()); - CodegenUtils.SortedMembers sortedMembers = new CodegenUtils.SortedMembers(symbolProvider); - shape.getAllMembers().values().stream() - .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) - .sorted(sortedMembers) - .forEach((member) -> { - writer.write(""); - - String memberName = symbolProvider.toMemberName(member); - - Symbol memberSymbol = symbolProvider.toSymbol(member); - - var targetShape = model.expectShape(member.getTarget()); - - if (isInputStructure) { - memberSymbol = memberSymbol.getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) - .orElse(memberSymbol); - } - var namespace = SmithyNameResolver.smithyTypesNamespace(targetShape); - - if (targetShape.hasTrait(ReferenceTrait.class)) { - memberSymbol = memberSymbol.getProperty("Referred", Symbol.class).get(); - - var refShape = targetShape.expectTrait(ReferenceTrait.class); - if (refShape.isService()) { - namespace = SmithyNameResolver.shapeNamespace(model.expectShape(refShape.getReferentId())); - } - if (!member.toShapeId().getNamespace().equals(refShape.getReferentId().getNamespace())) { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(refShape.getReferentId().getNamespace()), namespace); - } - } else { - if (!member.toShapeId().getNamespace().equals(targetShape.toShapeId().getNamespace()) && !targetShape.toShapeId().getNamespace().startsWith("smithy") && targetShape.asStructureShape().isPresent()) { - writer.addImportFromModule(SmithyNameResolver.getGoModuleNameForSmithyNamespace(targetShape.toShapeId().getNamespace()), namespace); - } - } - writer.write("$L $P", memberName, memberSymbol); - }); - writer.closeBlock("}").write(""); - validationGenerator.renderValidator(shape, isInputStructure); - } - - /** - * Renders an error structure and supporting methods. - */ - private void renderErrorStructure() { - Symbol structureSymbol = symbolProvider.toSymbol(shape); - writer.addUseImports(SmithyGoDependency.FMT); - ErrorTrait errorTrait = shape.expectTrait(ErrorTrait.class); - - // Write out a struct to hold the error data. - writer.openBlock("type $L struct {", "}", structureSymbol.getName(), () -> { - writer.write("$LBaseException", context.settings().getService().getName()); - Set memberNameSet = new HashSet<>(); - // TODO: Revisit if message has to be strictly pointer or not (even with required trait). - // When any shape is required we don't add pointer in local service but AWS SDK does. - for (MemberShape member : shape.getAllMembers().values()) { - String memberName = symbolProvider.toMemberName(member); - memberNameSet.add(memberName); - writer.write("$L $P", memberName, symbolProvider.toSymbol(member)); - } - - // The message is the only part of the standard APIError interface that isn't known ahead of time. - // Message is a pointer mostly for the sake of consistency. - - // If Message and ErrorCodeOverride is not defined in model. - if (!memberNameSet.contains("Message")) { - writer.write("Message *string").write(""); - } - if (!memberNameSet.contains("ErrorCodeOverride")) { - writer.write("ErrorCodeOverride *string").write(""); - } - - }).write(""); - - // write the Error method to satisfy the standard error interface - writer.openBlock("func (e $L) Error() string {", "}", structureSymbol.getName(), () -> { - writer.write("return fmt.Sprintf(\"%s: %s\", e.ErrorCodeOverride, e.Message)"); - }); - } -} + package software.amazon.polymorph.smithygo.codegen; + + import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + + import java.math.BigDecimal; + import java.util.HashSet; + import java.util.HashSet; + import java.util.Optional; + import java.util.Set; + import software.amazon.polymorph.smithygo.localservice.nameresolver.SmithyNameResolver; + import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; + import software.amazon.polymorph.traits.ReferenceTrait; + import software.amazon.smithy.codegen.core.Symbol; + import software.amazon.smithy.codegen.core.SymbolProvider; + import software.amazon.smithy.model.Model; + import software.amazon.smithy.model.shapes.MemberShape; + import software.amazon.smithy.model.shapes.Shape; + import software.amazon.smithy.model.shapes.StructureShape; + import software.amazon.smithy.model.traits.ErrorTrait; + import software.amazon.smithy.model.traits.LengthTrait; + import software.amazon.smithy.model.traits.RangeTrait; + import software.amazon.smithy.model.traits.RequiredTrait; + import software.amazon.smithy.model.traits.StreamingTrait; + import software.amazon.smithy.utils.SetUtils; + + /** + * Renders structures. + */ + public final class StructureGenerator implements Runnable { + + private static final Set ERROR_MEMBER_NAMES = SetUtils.of( + "ErrorMessage", + "Message", + "ErrorCodeOverride" + ); + + private final Model model; + private final SymbolProvider symbolProvider; + private final GoWriter writer; + private final StructureShape shape; + private final GenerationContext context; + private final ValidationGenerator validationGenerator; + + public StructureGenerator( + final GenerationContext context, + GoWriter writer, + StructureShape shape + ) { + this.context = context; + this.model = context.model(); + this.symbolProvider = context.symbolProvider(); + this.writer = writer; + this.shape = shape; + this.validationGenerator = + new ValidationGenerator(model, symbolProvider, writer); + } + + @Override + public void run() { + if (!shape.hasTrait(ErrorTrait.class)) { + renderStructure(() -> {}); + } else { + renderErrorStructure(); + } + } + + /** + * Renders a non-error structure. + * + * @param runnable A runnable that runs before the structure definition is closed. This can be used to write + * additional members. + */ + public void renderStructure(Runnable runnable) { + renderStructure(runnable, false); + } + + /** + * Renders a non-error structure. + * + * @param runnable A runnable that runs before the structure definition is closed. This can be used to write + * additional members. + * @param isInputStructure A boolean indicating if input variants for member symbols should be used. + */ + public void renderStructure(Runnable runnable, boolean isInputStructure) { + writer.addImport("fmt"); + Symbol symbol = symbolProvider.toSymbol(shape); + writer.openBlock("type $L struct {", symbol.getName()); + CodegenUtils.SortedMembers sortedMembers = new CodegenUtils.SortedMembers( + symbolProvider + ); + shape + .getAllMembers() + .values() + .stream() + .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) + .sorted(sortedMembers) + .forEach(member -> { + writer.write(""); + + String memberName = symbolProvider.toMemberName(member); + + Symbol memberSymbol = symbolProvider.toSymbol(member); + + var targetShape = model.expectShape(member.getTarget()); + + if (isInputStructure) { + memberSymbol = + memberSymbol + .getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) + .orElse(memberSymbol); + } + var namespace = SmithyNameResolver.smithyTypesNamespace(targetShape); + + if (targetShape.hasTrait(ReferenceTrait.class)) { + memberSymbol = + memberSymbol.getProperty("Referred", Symbol.class).get(); + var refShape = targetShape.expectTrait(ReferenceTrait.class); + if (refShape.isService()) { + namespace = + SmithyNameResolver.shapeNamespace( + model.expectShape(refShape.getReferentId()) + ); + } + if ( + !member + .toShapeId() + .getNamespace() + .equals(refShape.getReferentId().getNamespace()) + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + refShape.getReferentId().getNamespace() + ), + namespace + ); + } + } else { + if ( + !member + .toShapeId() + .getNamespace() + .equals(targetShape.toShapeId().getNamespace()) && + !targetShape.toShapeId().getNamespace().startsWith("smithy") && + targetShape.asStructureShape().isPresent() + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + targetShape.toShapeId().getNamespace() + ), + namespace + ); + } + } + + writer.write("$L $P", memberName, memberSymbol); + }); + writer.closeBlock("}").write(""); + validationGenerator.renderValidator(shape, isInputStructure); + } + + /** + * Renders an error structure and supporting methods. + */ + private void renderErrorStructure() { + Symbol structureSymbol = symbolProvider.toSymbol(shape); + writer.addUseImports(SmithyGoDependency.FMT); + ErrorTrait errorTrait = shape.expectTrait(ErrorTrait.class); + + // Write out a struct to hold the error data. + writer + .openBlock( + "type $L struct {", + "}", + structureSymbol.getName(), + () -> { + writer.write( + "$LBaseException", + context.settings().getService().getName() + ); + Set memberNameSet = new HashSet<>(); + // TODO: Revisit if message has to be strictly pointer or not (even with required trait). + // When any shape is required we don't add pointer in local service but AWS SDK does. + for (MemberShape member : shape.getAllMembers().values()) { + String memberName = symbolProvider.toMemberName(member); + memberNameSet.add(memberName); + writer.write("$L $P", memberName, symbolProvider.toSymbol(member)); + } + + // The message is the only part of the standard APIError interface that isn't known ahead of time. + // Message is a pointer mostly for the sake of consistency. + + // If Message and ErrorCodeOverride is not defined in model. + if (!memberNameSet.contains("Message")) { + writer.write("Message *string").write(""); + } + if (!memberNameSet.contains("ErrorCodeOverride")) { + writer.write("ErrorCodeOverride *string").write(""); + } + } + ) + .write(""); + + // write the Error method to satisfy the standard error interface + writer.openBlock( + "func (e $L) Error() string {", + "}", + structureSymbol.getName(), + () -> { + writer.write( + "return fmt.Sprintf(\"%s: %s\", e.ErrorCodeOverride, e.Message)" + ); + } + ); + } + } \ No newline at end of file From 14ccc65f90a315e6e7bb0a1fcfb685dba70707bb Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 9 Sep 2024 11:28:45 -0700 Subject: [PATCH 44/44] Format --- .../smithygo/codegen/StructureGenerator.java | 430 +++++++++--------- 1 file changed, 215 insertions(+), 215 deletions(-) diff --git a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java index c34832abbd..74ef4633e8 100644 --- a/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java +++ b/codegen/smithy-dafny-codegen/src/main/java/software/amazon/polymorph/smithygo/codegen/StructureGenerator.java @@ -13,218 +13,218 @@ * permissions and limitations under the License. */ - package software.amazon.polymorph.smithygo.codegen; - - import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; - - import java.math.BigDecimal; - import java.util.HashSet; - import java.util.HashSet; - import java.util.Optional; - import java.util.Set; - import software.amazon.polymorph.smithygo.localservice.nameresolver.SmithyNameResolver; - import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; - import software.amazon.polymorph.traits.ReferenceTrait; - import software.amazon.smithy.codegen.core.Symbol; - import software.amazon.smithy.codegen.core.SymbolProvider; - import software.amazon.smithy.model.Model; - import software.amazon.smithy.model.shapes.MemberShape; - import software.amazon.smithy.model.shapes.Shape; - import software.amazon.smithy.model.shapes.StructureShape; - import software.amazon.smithy.model.traits.ErrorTrait; - import software.amazon.smithy.model.traits.LengthTrait; - import software.amazon.smithy.model.traits.RangeTrait; - import software.amazon.smithy.model.traits.RequiredTrait; - import software.amazon.smithy.model.traits.StreamingTrait; - import software.amazon.smithy.utils.SetUtils; - - /** - * Renders structures. - */ - public final class StructureGenerator implements Runnable { - - private static final Set ERROR_MEMBER_NAMES = SetUtils.of( - "ErrorMessage", - "Message", - "ErrorCodeOverride" - ); - - private final Model model; - private final SymbolProvider symbolProvider; - private final GoWriter writer; - private final StructureShape shape; - private final GenerationContext context; - private final ValidationGenerator validationGenerator; - - public StructureGenerator( - final GenerationContext context, - GoWriter writer, - StructureShape shape - ) { - this.context = context; - this.model = context.model(); - this.symbolProvider = context.symbolProvider(); - this.writer = writer; - this.shape = shape; - this.validationGenerator = - new ValidationGenerator(model, symbolProvider, writer); - } - - @Override - public void run() { - if (!shape.hasTrait(ErrorTrait.class)) { - renderStructure(() -> {}); - } else { - renderErrorStructure(); - } - } - - /** - * Renders a non-error structure. - * - * @param runnable A runnable that runs before the structure definition is closed. This can be used to write - * additional members. - */ - public void renderStructure(Runnable runnable) { - renderStructure(runnable, false); - } - - /** - * Renders a non-error structure. - * - * @param runnable A runnable that runs before the structure definition is closed. This can be used to write - * additional members. - * @param isInputStructure A boolean indicating if input variants for member symbols should be used. - */ - public void renderStructure(Runnable runnable, boolean isInputStructure) { - writer.addImport("fmt"); - Symbol symbol = symbolProvider.toSymbol(shape); - writer.openBlock("type $L struct {", symbol.getName()); - CodegenUtils.SortedMembers sortedMembers = new CodegenUtils.SortedMembers( - symbolProvider - ); - shape - .getAllMembers() - .values() - .stream() - .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) - .sorted(sortedMembers) - .forEach(member -> { - writer.write(""); - - String memberName = symbolProvider.toMemberName(member); - - Symbol memberSymbol = symbolProvider.toSymbol(member); - - var targetShape = model.expectShape(member.getTarget()); - - if (isInputStructure) { - memberSymbol = - memberSymbol - .getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) - .orElse(memberSymbol); - } - var namespace = SmithyNameResolver.smithyTypesNamespace(targetShape); - - if (targetShape.hasTrait(ReferenceTrait.class)) { - memberSymbol = - memberSymbol.getProperty("Referred", Symbol.class).get(); - var refShape = targetShape.expectTrait(ReferenceTrait.class); - if (refShape.isService()) { - namespace = - SmithyNameResolver.shapeNamespace( - model.expectShape(refShape.getReferentId()) - ); - } - if ( - !member - .toShapeId() - .getNamespace() - .equals(refShape.getReferentId().getNamespace()) - ) { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - refShape.getReferentId().getNamespace() - ), - namespace - ); - } - } else { - if ( - !member - .toShapeId() - .getNamespace() - .equals(targetShape.toShapeId().getNamespace()) && - !targetShape.toShapeId().getNamespace().startsWith("smithy") && - targetShape.asStructureShape().isPresent() - ) { - writer.addImportFromModule( - SmithyNameResolver.getGoModuleNameForSmithyNamespace( - targetShape.toShapeId().getNamespace() - ), - namespace - ); - } - } - - writer.write("$L $P", memberName, memberSymbol); - }); - writer.closeBlock("}").write(""); - validationGenerator.renderValidator(shape, isInputStructure); - } - - /** - * Renders an error structure and supporting methods. - */ - private void renderErrorStructure() { - Symbol structureSymbol = symbolProvider.toSymbol(shape); - writer.addUseImports(SmithyGoDependency.FMT); - ErrorTrait errorTrait = shape.expectTrait(ErrorTrait.class); - - // Write out a struct to hold the error data. - writer - .openBlock( - "type $L struct {", - "}", - structureSymbol.getName(), - () -> { - writer.write( - "$LBaseException", - context.settings().getService().getName() - ); - Set memberNameSet = new HashSet<>(); - // TODO: Revisit if message has to be strictly pointer or not (even with required trait). - // When any shape is required we don't add pointer in local service but AWS SDK does. - for (MemberShape member : shape.getAllMembers().values()) { - String memberName = symbolProvider.toMemberName(member); - memberNameSet.add(memberName); - writer.write("$L $P", memberName, symbolProvider.toSymbol(member)); - } - - // The message is the only part of the standard APIError interface that isn't known ahead of time. - // Message is a pointer mostly for the sake of consistency. - - // If Message and ErrorCodeOverride is not defined in model. - if (!memberNameSet.contains("Message")) { - writer.write("Message *string").write(""); - } - if (!memberNameSet.contains("ErrorCodeOverride")) { - writer.write("ErrorCodeOverride *string").write(""); - } - } - ) - .write(""); - - // write the Error method to satisfy the standard error interface - writer.openBlock( - "func (e $L) Error() string {", - "}", - structureSymbol.getName(), - () -> { - writer.write( - "return fmt.Sprintf(\"%s: %s\", e.ErrorCodeOverride, e.Message)" - ); - } - ); - } - } \ No newline at end of file +package software.amazon.polymorph.smithygo.codegen; + +import static software.amazon.polymorph.smithygo.codegen.SymbolUtils.POINTABLE; + +import java.math.BigDecimal; +import java.util.HashSet; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import software.amazon.polymorph.smithygo.localservice.nameresolver.SmithyNameResolver; +import software.amazon.polymorph.traits.DafnyUtf8BytesTrait; +import software.amazon.polymorph.traits.ReferenceTrait; +import software.amazon.smithy.codegen.core.Symbol; +import software.amazon.smithy.codegen.core.SymbolProvider; +import software.amazon.smithy.model.Model; +import software.amazon.smithy.model.shapes.MemberShape; +import software.amazon.smithy.model.shapes.Shape; +import software.amazon.smithy.model.shapes.StructureShape; +import software.amazon.smithy.model.traits.ErrorTrait; +import software.amazon.smithy.model.traits.LengthTrait; +import software.amazon.smithy.model.traits.RangeTrait; +import software.amazon.smithy.model.traits.RequiredTrait; +import software.amazon.smithy.model.traits.StreamingTrait; +import software.amazon.smithy.utils.SetUtils; + +/** + * Renders structures. + */ +public final class StructureGenerator implements Runnable { + + private static final Set ERROR_MEMBER_NAMES = SetUtils.of( + "ErrorMessage", + "Message", + "ErrorCodeOverride" + ); + + private final Model model; + private final SymbolProvider symbolProvider; + private final GoWriter writer; + private final StructureShape shape; + private final GenerationContext context; + private final ValidationGenerator validationGenerator; + + public StructureGenerator( + final GenerationContext context, + GoWriter writer, + StructureShape shape + ) { + this.context = context; + this.model = context.model(); + this.symbolProvider = context.symbolProvider(); + this.writer = writer; + this.shape = shape; + this.validationGenerator = + new ValidationGenerator(model, symbolProvider, writer); + } + + @Override + public void run() { + if (!shape.hasTrait(ErrorTrait.class)) { + renderStructure(() -> {}); + } else { + renderErrorStructure(); + } + } + + /** + * Renders a non-error structure. + * + * @param runnable A runnable that runs before the structure definition is closed. This can be used to write + * additional members. + */ + public void renderStructure(Runnable runnable) { + renderStructure(runnable, false); + } + + /** + * Renders a non-error structure. + * + * @param runnable A runnable that runs before the structure definition is closed. This can be used to write + * additional members. + * @param isInputStructure A boolean indicating if input variants for member symbols should be used. + */ + public void renderStructure(Runnable runnable, boolean isInputStructure) { + writer.addImport("fmt"); + Symbol symbol = symbolProvider.toSymbol(shape); + writer.openBlock("type $L struct {", symbol.getName()); + CodegenUtils.SortedMembers sortedMembers = new CodegenUtils.SortedMembers( + symbolProvider + ); + shape + .getAllMembers() + .values() + .stream() + .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) + .sorted(sortedMembers) + .forEach(member -> { + writer.write(""); + + String memberName = symbolProvider.toMemberName(member); + + Symbol memberSymbol = symbolProvider.toSymbol(member); + + var targetShape = model.expectShape(member.getTarget()); + + if (isInputStructure) { + memberSymbol = + memberSymbol + .getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) + .orElse(memberSymbol); + } + var namespace = SmithyNameResolver.smithyTypesNamespace(targetShape); + + if (targetShape.hasTrait(ReferenceTrait.class)) { + memberSymbol = + memberSymbol.getProperty("Referred", Symbol.class).get(); + var refShape = targetShape.expectTrait(ReferenceTrait.class); + if (refShape.isService()) { + namespace = + SmithyNameResolver.shapeNamespace( + model.expectShape(refShape.getReferentId()) + ); + } + if ( + !member + .toShapeId() + .getNamespace() + .equals(refShape.getReferentId().getNamespace()) + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + refShape.getReferentId().getNamespace() + ), + namespace + ); + } + } else { + if ( + !member + .toShapeId() + .getNamespace() + .equals(targetShape.toShapeId().getNamespace()) && + !targetShape.toShapeId().getNamespace().startsWith("smithy") && + targetShape.asStructureShape().isPresent() + ) { + writer.addImportFromModule( + SmithyNameResolver.getGoModuleNameForSmithyNamespace( + targetShape.toShapeId().getNamespace() + ), + namespace + ); + } + } + + writer.write("$L $P", memberName, memberSymbol); + }); + writer.closeBlock("}").write(""); + validationGenerator.renderValidator(shape, isInputStructure); + } + + /** + * Renders an error structure and supporting methods. + */ + private void renderErrorStructure() { + Symbol structureSymbol = symbolProvider.toSymbol(shape); + writer.addUseImports(SmithyGoDependency.FMT); + ErrorTrait errorTrait = shape.expectTrait(ErrorTrait.class); + + // Write out a struct to hold the error data. + writer + .openBlock( + "type $L struct {", + "}", + structureSymbol.getName(), + () -> { + writer.write( + "$LBaseException", + context.settings().getService().getName() + ); + Set memberNameSet = new HashSet<>(); + // TODO: Revisit if message has to be strictly pointer or not (even with required trait). + // When any shape is required we don't add pointer in local service but AWS SDK does. + for (MemberShape member : shape.getAllMembers().values()) { + String memberName = symbolProvider.toMemberName(member); + memberNameSet.add(memberName); + writer.write("$L $P", memberName, symbolProvider.toSymbol(member)); + } + + // The message is the only part of the standard APIError interface that isn't known ahead of time. + // Message is a pointer mostly for the sake of consistency. + + // If Message and ErrorCodeOverride is not defined in model. + if (!memberNameSet.contains("Message")) { + writer.write("Message *string").write(""); + } + if (!memberNameSet.contains("ErrorCodeOverride")) { + writer.write("ErrorCodeOverride *string").write(""); + } + } + ) + .write(""); + + // write the Error method to satisfy the standard error interface + writer.openBlock( + "func (e $L) Error() string {", + "}", + structureSymbol.getName(), + () -> { + writer.write( + "return fmt.Sprintf(\"%s: %s\", e.ErrorCodeOverride, e.Message)" + ); + } + ); + } +}