Skip to content

Commit

Permalink
Use std::result::Result instead of Result (#4010)
Browse files Browse the repository at this point in the history
When the model contains a shape by the name of `Result`, the generated
code fails to compile. For instance the following model fails:

```smithy
@restJson1
service ConstrainedService {
    operations: [SampleOperation]
}

@http(uri: "/anOperation", method: "POST")
operation SampleOperation {
    output: SampleInputOutput
    input: SampleInputOutput
    errors: [ValidationException]
}

structure SampleInputOutput {
    result: Result
}

structure Result {
    @pattern("^a-z$")
    chat: String
}
```

This PR ensures:

1. If `rustTemplate` is being used, then `#{Result}` is used
2. If `rust` is being used, then that is changed to `rustTemplate` and
then `#{Result}` is used.
3. If `rustBlock` is being used, then the generated code should use
`std::result::Result`

---------

Co-authored-by: Fahad Zubair <[email protected]>
Co-authored-by: AWS SDK Rust Bot <[email protected]>
Co-authored-by: Russell Cohen <[email protected]>
Co-authored-by: david-perez <[email protected]>
Co-authored-by: Landon James <[email protected]>
  • Loading branch information
6 people authored Feb 20, 2025
1 parent 891a82b commit ad119f6
Show file tree
Hide file tree
Showing 35 changed files with 120 additions and 78 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import software.amazon.smithy.rust.codegen.core.rustlang.Visibility
import software.amazon.smithy.rust.codegen.core.rustlang.rustTemplate
import software.amazon.smithy.rust.codegen.core.rustlang.toType
import software.amazon.smithy.rust.codegen.core.smithy.RuntimeType
import software.amazon.smithy.rust.codegen.core.smithy.RuntimeType.Companion.std
import software.amazon.smithy.rust.codegen.core.smithy.RustCrate
import software.amazon.smithy.rust.codegen.core.smithy.customize.AdHocCustomization
import software.amazon.smithy.rust.codegen.core.smithy.customize.adhocCustomization
Expand Down Expand Up @@ -60,7 +61,7 @@ class TimestreamDecorator : ClientCodegenDecorator {
// helper function to resolve an endpoint given a base client
rustTemplate(
"""
async fn resolve_endpoint(client: &crate::Client) -> Result<(#{Endpoint}, #{SystemTime}), #{BoxError}> {
async fn resolve_endpoint(client: &crate::Client) -> #{Result}<(#{Endpoint}, #{SystemTime}), #{BoxError}> {
let describe_endpoints =
client.describe_endpoints().send().await?;
let endpoint = describe_endpoints.endpoints().first().unwrap();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ internal class EndpointResolverGenerator(
"EndpointError" to types.resolveEndpointError,
"ServiceSpecificEndpointResolver" to codegenContext.serviceSpecificEndpointResolver(),
"DiagnosticCollector" to EndpointsLib.DiagnosticCollector,
*preludeScope,
)

private val allowLintsForResolver =
Expand Down Expand Up @@ -195,7 +196,7 @@ internal class EndpointResolverGenerator(
Self { #{custom_fields_init:W} }
}
fn resolve_endpoint(&self, params: &#{Params}) -> Result<#{SmithyEndpoint}, #{BoxError}> {
fn resolve_endpoint(&self, params: &#{Params}) -> #{Result}<#{SmithyEndpoint}, #{BoxError}> {
let mut diagnostic_collector = #{DiagnosticCollector}::new();
Ok(#{resolver_fn}(params, &mut diagnostic_collector, #{additional_args})
.map_err(|err|err.with_source(diagnostic_collector.take_last_error()))?)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ class FluentClientGenerator(
&self.handle.conf
}
fn validate_config(handle: &Handle) -> Result<(), #{BoxError}> {
fn validate_config(handle: &Handle) -> #{Result}<(), #{BoxError}> {
let mut cfg = #{ConfigBag}::base();
handle.runtime_plugins
.apply_client_configuration(&mut cfg)?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ class AwsJsonSerializerGenerator(
arrayOf(
"Error" to runtimeConfig.serializationError(),
"SdkBody" to RuntimeType.sdkBody(runtimeConfig),
*RuntimeType.preludeScope,
)
private val protocolFunctions = ProtocolFunctions(codegenContext)

Expand All @@ -113,7 +114,7 @@ class AwsJsonSerializerGenerator(
serializer =
protocolFunctions.serializeFn(operationShape, fnNameSuffix = "input") { fnName ->
rustBlockTemplate(
"pub fn $fnName(_input: &#{target}) -> Result<#{SdkBody}, #{Error}>",
"pub fn $fnName(_input: &#{target}) -> #{Result}<#{SdkBody}, #{Error}>",
*codegenScope, "target" to codegenContext.symbolProvider.toSymbol(inputShape),
) {
rustTemplate("""Ok(#{SdkBody}::from("{}"))""", *codegenScope)
Expand All @@ -138,6 +139,7 @@ open class AwsJson(
CargoDependency.smithyJson(runtimeConfig).toType()
.resolve("deserialize::error::DeserializeError"),
"json_errors" to RuntimeType.jsonErrors(runtimeConfig),
*RuntimeType.preludeScope,
)

val version: AwsJsonVersion get() = awsJsonVersion
Expand All @@ -164,7 +166,7 @@ open class AwsJson(
ProtocolFunctions.crossOperationFn("parse_http_error_metadata") { fnName ->
rustTemplate(
"""
pub fn $fnName(_response_status: u16, response_headers: &#{Headers}, response_body: &[u8]) -> Result<#{ErrorMetadataBuilder}, #{JsonError}> {
pub fn $fnName(_response_status: u16, response_headers: &#{Headers}, response_body: &[u8]) -> #{Result}<#{ErrorMetadataBuilder}, #{JsonError}> {
#{json_errors}::parse_error_metadata(response_body, response_headers)
}
""",
Expand All @@ -177,7 +179,7 @@ open class AwsJson(
// `HeaderMap::new()` doesn't allocate.
rustTemplate(
"""
pub fn $fnName(payload: &#{Bytes}) -> Result<#{ErrorMetadataBuilder}, #{JsonError}> {
pub fn $fnName(payload: &#{Bytes}) -> #{Result}<#{ErrorMetadataBuilder}, #{JsonError}> {
#{json_errors}::parse_error_metadata(payload, &#{Headers}::new())
}
""",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ class AwsQueryProtocol(private val codegenContext: CodegenContext) : Protocol {
"ErrorMetadataBuilder" to RuntimeType.errorMetadataBuilder(runtimeConfig),
"Headers" to RuntimeType.headers(runtimeConfig),
"XmlDecodeError" to RuntimeType.smithyXml(runtimeConfig).resolve("decode::XmlDecodeError"),
*RuntimeType.preludeScope,
)

override val httpBindingResolver: HttpBindingResolver = AwsQueryBindingResolver(codegenContext.model)
Expand All @@ -61,7 +62,7 @@ class AwsQueryProtocol(private val codegenContext: CodegenContext) : Protocol {
override fun parseHttpErrorMetadata(operationShape: OperationShape): RuntimeType =
ProtocolFunctions.crossOperationFn("parse_http_error_metadata") { fnName ->
rustBlockTemplate(
"pub fn $fnName(_response_status: u16, _response_headers: &#{Headers}, response_body: &[u8]) -> Result<#{ErrorMetadataBuilder}, #{XmlDecodeError}>",
"pub fn $fnName(_response_status: u16, _response_headers: &#{Headers}, response_body: &[u8]) -> #{Result}<#{ErrorMetadataBuilder}, #{XmlDecodeError}>",
*errorScope,
) {
rust("#T::parse_error_metadata(response_body)", awsQueryErrors)
Expand All @@ -71,7 +72,7 @@ class AwsQueryProtocol(private val codegenContext: CodegenContext) : Protocol {
override fun parseEventStreamErrorMetadata(operationShape: OperationShape): RuntimeType =
ProtocolFunctions.crossOperationFn("parse_event_stream_error_metadata") { fnName ->
rustBlockTemplate(
"pub fn $fnName(payload: &#{Bytes}) -> Result<#{ErrorMetadataBuilder}, #{XmlDecodeError}>",
"pub fn $fnName(payload: &#{Bytes}) -> #{Result}<#{ErrorMetadataBuilder}, #{XmlDecodeError}>",
*errorScope,
) {
rust("#T::parse_error_metadata(payload.as_ref())", awsQueryErrors)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ class AwsQueryCompatible(
.resolve("deserialize::error::DeserializeError"),
"aws_query_compatible_errors" to RuntimeType.awsQueryCompatibleErrors(runtimeConfig),
"json_errors" to RuntimeType.jsonErrors(runtimeConfig),
*RuntimeType.preludeScope,
)

override val httpBindingResolver: HttpBindingResolver =
Expand All @@ -77,7 +78,7 @@ class AwsQueryCompatible(
ProtocolFunctions.crossOperationFn("parse_http_error_metadata") { fnName ->
rustTemplate(
"""
pub fn $fnName(_response_status: u16, response_headers: &#{Headers}, response_body: &[u8]) -> Result<#{ErrorMetadataBuilder}, #{JsonError}> {
pub fn $fnName(_response_status: u16, response_headers: &#{Headers}, response_body: &[u8]) -> #{Result}<#{ErrorMetadataBuilder}, #{JsonError}> {
let mut builder =
#{json_errors}::parse_error_metadata(response_body, response_headers)?;
if let Some((error_code, error_type)) =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class Ec2QueryProtocol(private val codegenContext: CodegenContext) : Protocol {
"ErrorMetadataBuilder" to RuntimeType.errorMetadataBuilder(runtimeConfig),
"Headers" to RuntimeType.headers(runtimeConfig),
"XmlDecodeError" to RuntimeType.smithyXml(runtimeConfig).resolve("decode::XmlDecodeError"),
*RuntimeType.preludeScope,
)

override val httpBindingResolver: HttpBindingResolver =
Expand All @@ -52,7 +53,7 @@ class Ec2QueryProtocol(private val codegenContext: CodegenContext) : Protocol {
override fun parseHttpErrorMetadata(operationShape: OperationShape): RuntimeType =
ProtocolFunctions.crossOperationFn("parse_http_error_metadata") { fnName ->
rustBlockTemplate(
"pub fn $fnName(_response_status: u16, _response_headers: &#{Headers}, response_body: &[u8]) -> Result<#{ErrorMetadataBuilder}, #{XmlDecodeError}>",
"pub fn $fnName(_response_status: u16, _response_headers: &#{Headers}, response_body: &[u8]) -> #{Result}<#{ErrorMetadataBuilder}, #{XmlDecodeError}>",
*errorScope,
) {
rust("#T::parse_error_metadata(response_body)", ec2QueryErrors)
Expand All @@ -62,7 +63,7 @@ class Ec2QueryProtocol(private val codegenContext: CodegenContext) : Protocol {
override fun parseEventStreamErrorMetadata(operationShape: OperationShape): RuntimeType =
ProtocolFunctions.crossOperationFn("parse_event_stream_error_metadata") {
rustBlockTemplate(
"pub fn parse_event_stream_error_metadata(payload: &#{Bytes}) -> Result<#{ErrorMetadataBuilder}, #{XmlDecodeError}>",
"pub fn parse_event_stream_error_metadata(payload: &#{Bytes}) -> #{Result}<#{ErrorMetadataBuilder}, #{XmlDecodeError}>",
*errorScope,
) {
rust("#T::parse_error_metadata(payload.as_ref())", ec2QueryErrors)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ class HttpBoundProtocolPayloadGenerator(
"BuildError" to runtimeConfig.operationBuildError(),
"SmithyHttp" to RuntimeType.smithyHttp(runtimeConfig),
"NoOpSigner" to smithyEventStream.resolve("frame::NoOpSigner"),
*RuntimeType.preludeScope,
)
private val protocolFunctions = ProtocolFunctions(codegenContext)

Expand Down Expand Up @@ -300,7 +301,7 @@ class HttpBoundProtocolPayloadGenerator(
RuntimeType.ByteSlab.toSymbol()
}
rustBlockTemplate(
"pub fn $fnName(payload: $ref#{Member}) -> Result<#{outputT}, #{BuildError}>",
"pub fn $fnName(payload: $ref#{Member}) -> #{Result}<#{outputT}, #{BuildError}>",
"Member" to symbolProvider.toSymbol(member),
"outputT" to outputT,
*codegenScope,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ open class RestJson(val codegenContext: CodegenContext) : Protocol {
CargoDependency.smithyJson(runtimeConfig).toType()
.resolve("deserialize::error::DeserializeError"),
"json_errors" to RuntimeType.jsonErrors(runtimeConfig),
*RuntimeType.preludeScope,
)

override val httpBindingResolver: HttpBindingResolver =
Expand Down Expand Up @@ -120,7 +121,7 @@ open class RestJson(val codegenContext: CodegenContext) : Protocol {
ProtocolFunctions.crossOperationFn("parse_http_error_metadata") { fnName ->
rustTemplate(
"""
pub fn $fnName(_response_status: u16, response_headers: &#{Headers}, response_body: &[u8]) -> Result<#{ErrorMetadataBuilder}, #{JsonError}> {
pub fn $fnName(_response_status: u16, response_headers: &#{Headers}, response_body: &[u8]) -> #{Result}<#{ErrorMetadataBuilder}, #{JsonError}> {
#{json_errors}::parse_error_metadata(response_body, response_headers)
}
""",
Expand All @@ -133,7 +134,7 @@ open class RestJson(val codegenContext: CodegenContext) : Protocol {
// `HeaderMap::new()` doesn't allocate.
rustTemplate(
"""
pub fn $fnName(payload: &#{Bytes}) -> Result<#{ErrorMetadataBuilder}, #{JsonError}> {
pub fn $fnName(payload: &#{Bytes}) -> #{Result}<#{ErrorMetadataBuilder}, #{JsonError}> {
#{json_errors}::parse_error_metadata(payload, &#{Headers}::new())
}
""",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ open class RestXml(val codegenContext: CodegenContext) : Protocol {
"ErrorMetadataBuilder" to RuntimeType.errorMetadataBuilder(runtimeConfig),
"Headers" to RuntimeType.headers(runtimeConfig),
"XmlDecodeError" to RuntimeType.smithyXml(runtimeConfig).resolve("decode::XmlDecodeError"),
*RuntimeType.preludeScope,
)

protected val restXmlErrors: RuntimeType =
Expand Down Expand Up @@ -58,7 +59,7 @@ open class RestXml(val codegenContext: CodegenContext) : Protocol {
override fun parseHttpErrorMetadata(operationShape: OperationShape): RuntimeType =
ProtocolFunctions.crossOperationFn("parse_http_error_metadata") { fnName ->
rustBlockTemplate(
"pub fn $fnName(_response_status: u16, _response_headers: &#{Headers}, response_body: &[u8]) -> Result<#{ErrorMetadataBuilder}, #{XmlDecodeError}>",
"pub fn $fnName(_response_status: u16, _response_headers: &#{Headers}, response_body: &[u8]) -> #{Result}<#{ErrorMetadataBuilder}, #{XmlDecodeError}>",
*errorScope,
) {
rust("#T::parse_error_metadata(response_body)", restXmlErrors)
Expand All @@ -68,7 +69,7 @@ open class RestXml(val codegenContext: CodegenContext) : Protocol {
override fun parseEventStreamErrorMetadata(operationShape: OperationShape): RuntimeType =
ProtocolFunctions.crossOperationFn("parse_event_stream_error_metadata") { fnName ->
rustBlockTemplate(
"pub fn $fnName(payload: &#{Bytes}) -> Result<#{ErrorMetadataBuilder}, #{XmlDecodeError}>",
"pub fn $fnName(payload: &#{Bytes}) -> #{Result}<#{ErrorMetadataBuilder}, #{XmlDecodeError}>",
*errorScope,
) {
rust("#T::parse_error_metadata(payload.as_ref())", restXmlErrors)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ open class RpcV2Cbor(
ProtocolFunctions.crossOperationFn("parse_event_stream_error_metadata") { fnName ->
rustTemplate(
"""
pub fn $fnName(payload: &#{Bytes}) -> Result<#{ErrorMetadataBuilder}, #{DeserializeError}> {
pub fn $fnName(payload: &#{Bytes}) -> #{Result}<#{ErrorMetadataBuilder}, #{DeserializeError}> {
#{cbor_errors}::parse_error_metadata(0, &#{Headers}::new(), payload)
}
""",
Expand All @@ -164,6 +164,7 @@ open class RpcV2Cbor(
CargoDependency.smithyCbor(runtimeConfig).toType()
.resolve("decode::DeserializeError"),
"Headers" to RuntimeType.headers(runtimeConfig),
*RuntimeType.preludeScope,
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import software.amazon.smithy.rust.codegen.core.smithy.CodegenContext
import software.amazon.smithy.rust.codegen.core.smithy.CodegenTarget
import software.amazon.smithy.rust.codegen.core.smithy.RuntimeType
import software.amazon.smithy.rust.codegen.core.smithy.RuntimeType.Companion.preludeScope
import software.amazon.smithy.rust.codegen.core.smithy.RuntimeType.Companion.std
import software.amazon.smithy.rust.codegen.core.smithy.canUseDefault
import software.amazon.smithy.rust.codegen.core.smithy.customize.NamedCustomization
import software.amazon.smithy.rust.codegen.core.smithy.customize.Section
Expand Down Expand Up @@ -145,7 +146,7 @@ class JsonParserGenerator(
return protocolFunctions.deserializeFn(shape, fnNameSuffix) { fnName ->
val unusedMut = if (includedMembers.isEmpty()) "##[allow(unused_mut)] " else ""
rustBlockTemplate(
"pub(crate) fn $fnName(value: &[u8], ${unusedMut}mut builder: #{Builder}) -> Result<#{Builder}, #{Error}>",
"pub(crate) fn $fnName(value: &[u8], ${unusedMut}mut builder: #{Builder}) -> #{Result}<#{Builder}, #{Error}>",
"Builder" to builderSymbol,
*codegenScope,
) {
Expand All @@ -172,7 +173,7 @@ class JsonParserGenerator(
}
return protocolFunctions.deserializeFn(shape, fnNameSuffix = "payload") { fnName ->
rustBlockTemplate(
"pub(crate) fn $fnName(input: &[u8]) -> Result<#{ReturnType}, #{Error}>",
"pub(crate) fn $fnName(input: &[u8]) -> #{Result}<#{ReturnType}, #{Error}>",
*codegenScope,
"ReturnType" to returnSymbolToParse.symbol,
) {
Expand Down Expand Up @@ -396,7 +397,7 @@ class JsonParserGenerator(
protocolFunctions.deserializeFn(shape) { fnName ->
rustBlockTemplate(
"""
pub(crate) fn $fnName<'a, I>(tokens: &mut #{Peekable}<I>) -> Result<Option<#{ReturnType}>, #{Error}>
pub(crate) fn $fnName<'a, I>(tokens: &mut #{Peekable}<I>) -> #{Result}<Option<#{ReturnType}>, #{Error}>
where I: Iterator<Item = Result<#{Token}<'a>, #{Error}>>
""",
"ReturnType" to returnSymbol,
Expand Down Expand Up @@ -458,7 +459,7 @@ class JsonParserGenerator(
protocolFunctions.deserializeFn(shape) { fnName ->
rustBlockTemplate(
"""
pub(crate) fn $fnName<'a, I>(tokens: &mut #{Peekable}<I>) -> Result<Option<#{ReturnType}>, #{Error}>
pub(crate) fn $fnName<'a, I>(tokens: &mut #{Peekable}<I>) -> #{Result}<Option<#{ReturnType}>, #{Error}>
where I: Iterator<Item = Result<#{Token}<'a>, #{Error}>>
""",
"ReturnType" to returnSymbolToParse.symbol,
Expand Down Expand Up @@ -514,7 +515,7 @@ class JsonParserGenerator(
protocolFunctions.deserializeFn(shape) { fnName ->
rustBlockTemplate(
"""
pub(crate) fn $fnName<'a, I>(tokens: &mut #{Peekable}<I>) -> Result<Option<#{ReturnType}>, #{Error}>
pub(crate) fn $fnName<'a, I>(tokens: &mut #{Peekable}<I>) -> #{Result}<Option<#{ReturnType}>, #{Error}>
where I: Iterator<Item = Result<#{Token}<'a>, #{Error}>>
""",
"ReturnType" to returnSymbolToParse.symbol,
Expand Down Expand Up @@ -549,7 +550,7 @@ class JsonParserGenerator(
protocolFunctions.deserializeFn(shape) { fnName ->
rustBlockTemplate(
"""
pub(crate) fn $fnName<'a, I>(tokens: &mut #{Peekable}<I>) -> Result<Option<#{Shape}>, #{Error}>
pub(crate) fn $fnName<'a, I>(tokens: &mut #{Peekable}<I>) -> #{Result}<Option<#{Shape}>, #{Error}>
where I: Iterator<Item = Result<#{Token}<'a>, #{Error}>>
""",
*codegenScope,
Expand Down
Loading

0 comments on commit ad119f6

Please sign in to comment.