Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat!: Remove model namespace #703

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -154,33 +154,30 @@ class HttpResponseBindingErrorGenerator : HttpResponseBindingErrorGeneratable {
with(writer) {
addImport(SwiftDependency.CLIENT_RUNTIME.target)
addImport(SwiftDependency.SMITHY_TEST_UTIL.target)

openBlock("extension ${ctx.symbolProvider.toSymbol(ctx.service).name}Types {", "}") {
openBlock(
"static func makeServiceError(_ httpResponse: \$N, _ decoder: \$D, _ error: \$N, _ id: String?) async throws -> \$N? {",
"}",
ClientRuntimeTypes.Http.HttpResponse,
ClientRuntimeTypes.Serde.ResponseDecoder,
JSON_ERROR_SYMBOL,
SwiftTypes.Error
) {
openBlock("switch error.errorType {", "}") {
val serviceErrorShapes =
serviceShape.errors
.map { ctx.model.expectShape(it) as StructureShape }
.toSet()
.sorted()
serviceErrorShapes.forEach { errorShape ->
val errorShapeName = errorShape.errorShapeName(ctx.symbolProvider)
val errorShapeType = ctx.symbolProvider.toSymbol(errorShape).name
write(
"case \$S: return try await \$L(httpResponse: httpResponse, decoder: decoder, message: error.errorMessage, requestID: id)",
errorShapeName,
errorShapeType
)
}
write("default: return nil")
openBlock(
"func makeServiceError(_ httpResponse: \$N, _ decoder: \$D, _ error: \$N, _ id: String?) async throws -> \$N? {",
"}",
ClientRuntimeTypes.Http.HttpResponse,
ClientRuntimeTypes.Serde.ResponseDecoder,
JSON_ERROR_SYMBOL,
SwiftTypes.Error
) {
openBlock("switch error.errorType {", "}") {
val serviceErrorShapes =
serviceShape.errors
.map { ctx.model.expectShape(it) as StructureShape }
.toSet()
.sorted()
serviceErrorShapes.forEach { errorShape ->
val errorShapeName = errorShape.errorShapeName(ctx.symbolProvider)
val errorShapeType = ctx.symbolProvider.toSymbol(errorShape).name
write(
"case \$S: return try await \$L(httpResponse: httpResponse, decoder: decoder, message: error.errorMessage, requestID: id)",
errorShapeName,
errorShapeType
)
}
write("default: return nil")
}
}
}
Expand Down Expand Up @@ -219,7 +216,7 @@ class HttpResponseBindingErrorGenerator : HttpResponseBindingErrorGeneratable {
write("let defaultError = try await \$N(httpResponse: httpResponse)", JSON_ERROR_SYMBOL)

if (ctx.service.errors.isNotEmpty()) {
write("let serviceError = try await ${ctx.symbolProvider.toSymbol(ctx.service).name}Types.makeServiceError(httpResponse, decoder, restJSONError, requestID)")
write("let serviceError = try await makeServiceError(httpResponse, decoder, restJSONError, requestID)")
write("if let error = serviceError { return error }")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -236,9 +236,10 @@ class AuthSchemeResolverGenerator {
) {
writer.apply {
openBlock(
"public func constructParameters(context: HttpContext) throws -> \$L {",
"public func constructParameters(context: \$N) throws -> \$L {",
"}",
ClientRuntimeTypes.Auth.AuthSchemeResolverParams
ClientRuntimeTypes.Http.HttpContext,
ClientRuntimeTypes.Auth.AuthSchemeResolverParams,
) {
if (usesRulesBasedAuthResolver(ctx)) {
write("return try Default${getSdkId(ctx) + AUTH_SCHEME_RESOLVER}().constructParameters(context: context)")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ object ClientRuntimeTypes {
val HttpResponseErrorBinding = runtimeSymbol("HttpResponseErrorBinding")
val HttpError = runtimeSymbol("HTTPError")
val UnknownHttpServiceError = runtimeSymbol("UnknownHTTPServiceError")
val HttpContext = runtimeSymbol("HttpContext")
val HttpContextBuilder = runtimeSymbol("HttpContextBuilder")
val HTTPResponseOutputBinding = runtimeSymbol("HTTPResponseOutputBinding")
val HTTPResponseErrorBinding = runtimeSymbol("HTTPResponseErrorBinding")
Expand Down Expand Up @@ -126,6 +127,7 @@ object ClientRuntimeTypes {
val DateFormatter = runtimeSymbol("DateFormatter")
val PaginateToken = runtimeSymbol("PaginateToken")
val PaginatorSequence = runtimeSymbol("PaginatorSequence")
val Plugin = runtimeSymbol("Plugin")
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,9 @@ package software.amazon.smithy.swift.codegen

import software.amazon.smithy.codegen.core.SymbolProvider
import software.amazon.smithy.model.Model
import software.amazon.smithy.model.shapes.ServiceShape
import software.amazon.smithy.model.shapes.Shape
import software.amazon.smithy.model.traits.EnumDefinition
import software.amazon.smithy.model.traits.EnumTrait
import software.amazon.smithy.swift.codegen.customtraits.NestedTrait
import software.amazon.smithy.swift.codegen.model.expectShape
import software.amazon.smithy.swift.codegen.model.hasTrait
import software.amazon.smithy.swift.codegen.model.nestedNamespaceType

/**
* Generates an appropriate Swift type for a Smithy enum string.
Expand Down Expand Up @@ -125,15 +120,7 @@ class EnumGenerator(
fun render() {
val symbol = symbolProvider.toSymbol(shape)
writer.putContext("enum.name", symbol.name)
val isNestedType = shape.hasTrait<NestedTrait>()
if (isNestedType) {
val service = model.expectShape<ServiceShape>(settings.service)
writer.openBlock("extension ${service.nestedNamespaceType(symbolProvider)} {", "}") {
renderEnum()
}
} else {
renderEnum()
}
renderEnum()
writer.removeContext("enum.name")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,8 @@ import software.amazon.smithy.codegen.core.SymbolProvider
import software.amazon.smithy.model.Model
import software.amazon.smithy.model.shapes.IntEnumShape
import software.amazon.smithy.model.shapes.MemberShape
import software.amazon.smithy.model.shapes.ServiceShape
import software.amazon.smithy.model.traits.EnumValueTrait
import software.amazon.smithy.swift.codegen.customtraits.NestedTrait
import software.amazon.smithy.swift.codegen.model.expectShape
import software.amazon.smithy.swift.codegen.model.hasTrait
import software.amazon.smithy.swift.codegen.model.nestedNamespaceType

class IntEnumGenerator(
private val model: Model,
Expand All @@ -24,15 +20,7 @@ class IntEnumGenerator(
fun render() {
val symbol = symbolProvider.toSymbol(shape)
writer.putContext("enum.name", symbol.name)
val isNestedType = shape.hasTrait<NestedTrait>()
if (isNestedType) {
val service = model.expectShape<ServiceShape>(settings.service)
writer.openBlock("extension ${service.nestedNamespaceType(symbolProvider)} {", "}") {
renderEnum()
}
} else {
renderEnum()
}
renderEnum()
writer.removeContext("enum.name")
}

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,16 @@ 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.ServiceShape
import software.amazon.smithy.model.shapes.StructureShape
import software.amazon.smithy.model.traits.ErrorTrait
import software.amazon.smithy.model.traits.RetryableTrait
import software.amazon.smithy.swift.codegen.customtraits.EquatableConformanceTrait
import software.amazon.smithy.swift.codegen.customtraits.NestedTrait
import software.amazon.smithy.swift.codegen.customtraits.SwiftBoxTrait
import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator
import software.amazon.smithy.swift.codegen.integration.SectionId
import software.amazon.smithy.swift.codegen.model.expectShape
import software.amazon.smithy.swift.codegen.model.getTrait
import software.amazon.smithy.swift.codegen.model.hasTrait
import software.amazon.smithy.swift.codegen.model.isError
import software.amazon.smithy.swift.codegen.model.nestedNamespaceType
import software.amazon.smithy.swift.codegen.model.toLowerCamelCase
import software.amazon.smithy.swift.codegen.utils.errorShapeName
import software.amazon.smithy.swift.codegen.utils.toUpperCamelCase
Expand Down Expand Up @@ -98,15 +94,7 @@ class StructureGenerator(
* ```
*/
private fun renderNonErrorStructure() {
val isNestedType = shape.hasTrait<NestedTrait>()
if (isNestedType) {
val service = model.expectShape<ServiceShape>(settings.service)
writer.openBlock("extension ${service.nestedNamespaceType(symbolProvider)} {", "}") {
generateStruct()
}
} else {
generateStruct()
}
generateStruct()
}

private fun generateStruct() {
Expand Down Expand Up @@ -137,7 +125,8 @@ class StructureGenerator(

if (hasMembers) {
writer.addImport(SwiftDependency.CLIENT_RUNTIME.target)
writer.openBlock("public init(", ")") {
writer.write("public init(")
writer.indent {
for ((index, member) in membersSortedByName.withIndex()) {
val (memberName, memberSymbol) = memberShapeDataContainer.getOrElse(member) { Pair(null, null) }
if (memberName == null || memberSymbol == null) continue
Expand All @@ -146,15 +135,17 @@ class StructureGenerator(
writer.write("\$L: \$D$terminator", memberName, symbolToUse)
}
}
writer.openBlock("{", "}") {
writer.write(") {")
writer.indent {
val path = "properties.".takeIf { error } ?: ""
membersSortedByName.forEach {
val (memberName, _) = memberShapeDataContainer.getOrElse(it) { return@forEach }
writer.write("self.$path\$L = \$L", memberName, memberName)
}
}
writer.write("}")
} else {
writer.write("public init() { }")
writer.write("public init() {}")
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import software.amazon.smithy.swift.codegen.core.GenerationContext
import software.amazon.smithy.swift.codegen.integration.SwiftIntegration
import software.amazon.smithy.swift.codegen.model.AddOperationShapes
import software.amazon.smithy.swift.codegen.model.EquatableConformanceTransformer
import software.amazon.smithy.swift.codegen.model.NestedShapeTransformer
import software.amazon.smithy.swift.codegen.model.RecursiveShapeBoxer
import software.amazon.smithy.swift.codegen.model.UnionIndirectivizer
import java.util.ServiceLoader
Expand Down Expand Up @@ -52,7 +51,6 @@ class SwiftCodegenPlugin : SmithyBuildPlugin {
resolvedModel = ModelTransformer.create().flattenAndRemoveMixins(resolvedModel)
resolvedModel = AddOperationShapes.execute(resolvedModel, settings.getService(resolvedModel), settings.moduleName)
resolvedModel = RecursiveShapeBoxer.transform(resolvedModel)
resolvedModel = NestedShapeTransformer.transform(resolvedModel, settings.getService(resolvedModel))
resolvedModel = UnionIndirectivizer.transform(resolvedModel)
resolvedModel = EquatableConformanceTransformer.transform(resolvedModel, settings.getService(resolvedModel))
return resolvedModel
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,12 @@ import software.amazon.smithy.model.traits.EnumTrait
import software.amazon.smithy.model.traits.ErrorTrait
import software.amazon.smithy.model.traits.SparseTrait
import software.amazon.smithy.model.traits.StreamingTrait
import software.amazon.smithy.swift.codegen.customtraits.NestedTrait
import software.amazon.smithy.swift.codegen.lang.swiftReservedWords
import software.amazon.smithy.swift.codegen.model.SymbolProperty
import software.amazon.smithy.swift.codegen.model.boxed
import software.amazon.smithy.swift.codegen.model.buildSymbol
import software.amazon.smithy.swift.codegen.model.defaultName
import software.amazon.smithy.swift.codegen.model.hasTrait
import software.amazon.smithy.swift.codegen.model.nestedNamespaceType
import software.amazon.smithy.swift.codegen.utils.clientName
import software.amazon.smithy.swift.codegen.utils.toLowerCamelCase
import software.amazon.smithy.utils.StringUtils.lowerCase
Expand Down Expand Up @@ -141,17 +139,14 @@ class SwiftSymbolProvider(private val model: Model, swiftSettings: SwiftSettings

private fun createEnumSymbol(shape: Shape): Symbol {
val name = shape.defaultName(service)
val builder = createSymbolBuilder(shape, name, boxed = true)
val builder = createSymbolBuilder(shape, name, null, boxed = true)
.definitionFile(formatModuleName(shape.type, name))

// add a reference to each member symbol
if (shape is UnionShape) {
addDeclareMemberReferences(builder, shape.allMembers.values)
}

if (shape.hasTrait<NestedTrait>() && service != null) {
builder.namespace(service.nestedNamespaceType(this).name, ".")
}
return builder.build()
}

Expand All @@ -161,16 +156,12 @@ class SwiftSymbolProvider(private val model: Model, swiftSettings: SwiftSettings

override fun structureShape(shape: StructureShape): Symbol {
val name = shape.defaultName(service)
val builder = createSymbolBuilder(shape, name, boxed = true)
val builder = createSymbolBuilder(shape, name, null, boxed = true)
.definitionFile(formatModuleName(shape.type, name))

// add a reference to each member symbol
addDeclareMemberReferences(builder, shape.allMembers.values)

if (shape.hasTrait<NestedTrait>() && service != null && !shape.hasTrait<ErrorTrait>()) {
builder.namespace(service.nestedNamespaceType(this).name, ".")
}

if (shape.hasTrait<ErrorTrait>()) {
builder.addDependency(SwiftDependency.CLIENT_RUNTIME)
}
Expand All @@ -180,13 +171,13 @@ class SwiftSymbolProvider(private val model: Model, swiftSettings: SwiftSettings
override fun listShape(shape: ListShape): Symbol {
val reference = toSymbol(shape.member)
val referenceTypeName = if (shape.hasTrait<SparseTrait>()) "$reference?" else "$reference"
return createSymbolBuilder(shape, "[$referenceTypeName]", true).addReference(reference).build()
return createSymbolBuilder(shape, "[$referenceTypeName]", null, true).addReference(reference).build()
}

override fun mapShape(shape: MapShape): Symbol {
val reference = toSymbol(shape.value)
val referenceTypeName = if (shape.hasTrait<SparseTrait>()) "$reference?" else "$reference"
return createSymbolBuilder(shape, "[${SwiftTypes.String}:$referenceTypeName]", true)
return createSymbolBuilder(shape, "[${SwiftTypes.String}: $referenceTypeName]", null, true)
.addReference(reference)
.putProperty(SymbolProperty.ENTRY_EXPRESSION, "(String, $referenceTypeName)")
.build()
Expand All @@ -200,7 +191,7 @@ class SwiftSymbolProvider(private val model: Model, swiftSettings: SwiftSettings

override fun resourceShape(shape: ResourceShape): Symbol {
// May implement a resource type in future
return createSymbolBuilder(shape, "Any", true).build()
return createSymbolBuilder(shape, "Any", null, true).build()
}

override fun memberShape(shape: MemberShape): Symbol {
Expand All @@ -212,7 +203,7 @@ class SwiftSymbolProvider(private val model: Model, swiftSettings: SwiftSettings

val isEventStream = targetShape.isStreaming && targetShape.isUnionShape
if (isEventStream) {
return createSymbolBuilder(shape, "AsyncThrowingStream<${symbol.fullName}, Swift.Error>", true)
return createSymbolBuilder(shape, "AsyncThrowingStream<${symbol.fullName}, Swift.Error>", null, true)
.putProperty(SymbolProperty.NESTED_SYMBOL, symbol)
.build()
}
Expand Down Expand Up @@ -262,17 +253,6 @@ class SwiftSymbolProvider(private val model: Model, swiftSettings: SwiftSettings
return createSymbolBuilder(shape, typeName, "Swift").putProperty(SymbolProperty.DEFAULT_VALUE_KEY, defaultValue).build()
}

/**
* Creates a symbol builder for the shape with the given type name in the root namespace.
*/
private fun createSymbolBuilder(shape: Shape?, typeName: String, boxed: Boolean = false): Symbol.Builder {
val builder = Symbol.builder().putProperty("shape", shape).name(typeName)
if (boxed) {
builder.boxed()
}
return builder
}

/**
* Creates a symbol builder for the shape with the given type name in a child namespace relative
* to the root namespace e.g. `relativeNamespace = bar` with a root namespace of `foo` would set
Expand All @@ -281,11 +261,13 @@ class SwiftSymbolProvider(private val model: Model, swiftSettings: SwiftSettings
private fun createSymbolBuilder(
shape: Shape?,
typeName: String,
namespace: String,
namespace: String?,
boxed: Boolean = false
): Symbol.Builder {
return createSymbolBuilder(shape, typeName, boxed)
.namespace(namespace, ".")
val builder = Symbol.builder().putProperty("shape", shape).name(typeName)
if (boxed) { builder.boxed() }
namespace?.let { builder.namespace(it, ".") }
return builder
}

private fun formatModuleName(shapeType: ShapeType, name: String): String? {
Expand Down
Loading
Loading