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) }, } ); }