Skip to content

Commit

Permalink
Non-functional miscellaneous improvements (#1445)
Browse files Browse the repository at this point in the history
This commit contains non-functional (i.e. mostly stylistic, small
refactors, documentation and consistency) improvements that I've batched
and rolled up while working on #1342.

* Make `extraDependencies` from `InlineDependency` class private
* Miscellaneous improvements to `RustTypes.kt`
* Remove dead code from `RuntimeTypes.kt`
* Style change in `RuntimeTypes.kt`
* Miscellaneous improvements to `SymbolVisitor.kt`
* Miscellaneous improvements to `BuilderGenerator.kt`
    - Make it consistent with the `ServerBuilderGenerator` from #1342.
* Miscellaneous improvements to `TestHelpers.kt`
* Add docs to `headers_for_prefix` function
    - I keep rereading the implementation to see what this returns; it's
      not intuitive from the function name.
  • Loading branch information
david-perez authored Jun 27, 2022
1 parent a89a083 commit ae2a74b
Show file tree
Hide file tree
Showing 7 changed files with 75 additions and 85 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ sealed class RustDependency(open val name: String) : SymbolDependencyContainer {
class InlineDependency(
name: String,
val module: RustModule,
val extraDependencies: List<RustDependency> = listOf(),
private val extraDependencies: List<RustDependency> = listOf(),
val renderer: (RustWriter) -> Unit
) : RustDependency(name) {
override fun version(): String {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,11 @@ sealed class RustType {
}

data class Reference(val lifetime: kotlin.String?, override val member: RustType) : RustType(), Container {
override val name: kotlin.String = member.name
override val name = member.name
}

data class Option(override val member: RustType) : RustType(), Container {
override val name: kotlin.String = "Option"
override val name = "Option"
override val namespace = "std::option"

/** Convert `Option<T>` to `Option<&T>` **/
Expand All @@ -105,7 +105,7 @@ sealed class RustType {
}

data class Box(override val member: RustType) : RustType(), Container {
override val name: kotlin.String = "Box"
override val name = "Box"
override val namespace = "std::boxed"
}

Expand All @@ -115,7 +115,7 @@ sealed class RustType {
}

data class Vec(override val member: RustType) : RustType(), Container {
override val name: kotlin.String = "Vec"
override val name = "Vec"
override val namespace = "std::vec"
}

Expand Down Expand Up @@ -148,25 +148,21 @@ fun RustType.asArgumentType(fullyQualified: Boolean = true): String {
}

/** Format this Rust type so that it may be used as an argument type in a function definition */
fun RustType.asArgumentValue(name: String): String {
return when (this) {
is RustType.String,
is RustType.Box -> "$name.into()"
fun RustType.asArgumentValue(name: String) =
when (this) {
is RustType.String, is RustType.Box -> "$name.into()"
else -> name
}
}

/**
* For a given name, generate an `Argument` data class containing pre-formatted strings for using this type when
* writing a Rust function
* writing a Rust function.
*/
fun RustType.asArgument(name: String): Argument {
return Argument(
"$name: ${this.asArgumentType()}",
this.asArgumentValue(name),
this.render(),
)
}
fun RustType.asArgument(name: String) = Argument(
"$name: ${this.asArgumentType()}",
this.asArgumentValue(name),
this.render(),
)

/**
* Render this type, including references and generic parameters.
Expand Down Expand Up @@ -298,7 +294,7 @@ data class RustMetadata(
return this
}

fun renderVisibility(writer: RustWriter): RustMetadata {
private fun renderVisibility(writer: RustWriter): RustMetadata {
writer.writeInline(
when (visibility) {
Visibility.PRIVATE -> ""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,6 @@ data class RuntimeType(val name: String?, val dependency: RustDependency?, val n
val Display = stdfmt.member("Display")
val From = RuntimeType("From", dependency = null, namespace = "std::convert")
val TryFrom = RuntimeType("TryFrom", dependency = null, namespace = "std::convert")
val Infallible = RuntimeType("Infallible", dependency = null, namespace = "std::convert")
val PartialEq = std.member("cmp::PartialEq")
val StdError = RuntimeType("Error", dependency = null, namespace = "std::error")
val String = RuntimeType("String", dependency = null, namespace = "std::string")
Expand Down Expand Up @@ -235,17 +234,14 @@ data class RuntimeType(val name: String?, val dependency: RustDependency?, val n
val HttpRequestBuilder = Http("request::Builder")
val HttpResponseBuilder = Http("response::Builder")

val Hyper = CargoDependency.Hyper.asType()

fun eventStreamReceiver(runtimeConfig: RuntimeConfig): RuntimeType =
RuntimeType(
"Receiver",
dependency = CargoDependency.SmithyHttp(runtimeConfig),
"aws_smithy_http::event_stream"
)

fun jsonErrors(runtimeConfig: RuntimeConfig) =
forInlineDependency(InlineDependency.jsonErrors(runtimeConfig))
fun jsonErrors(runtimeConfig: RuntimeConfig) = forInlineDependency(InlineDependency.jsonErrors(runtimeConfig))

val IdempotencyToken by lazy { forInlineDependency(InlineDependency.idempotencyToken()) }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,9 @@ fun Symbol.mapRustType(f: (RustType) -> RustType): Symbol {
/** Set the symbolLocation for this symbol builder */
fun Symbol.Builder.locatedIn(symbolLocation: SymbolLocation): Symbol.Builder {
val currentRustType = this.build().rustType()
check(currentRustType is RustType.Opaque) { "Only Opaque can have their namespace updated" }
check(currentRustType is RustType.Opaque) {
"Only `Opaque` can have their namespace updated"
}
val newRustType = currentRustType.copy(namespace = "crate::${symbolLocation.namespace}")
return this.definitionFile("src/${symbolLocation.filename}")
.namespace("crate::${symbolLocation.namespace}", "::")
Expand Down Expand Up @@ -148,6 +150,18 @@ fun SymbolProvider.wrapOptional(member: MemberShape, value: String): String = va
*/
fun SymbolProvider.toOptional(member: MemberShape, value: String): String = value.letIf(!toSymbol(member).isOptional()) { "Some($value)" }

/**
* Services can rename their contained shapes. See https://awslabs.github.io/smithy/1.0/spec/core/model.html#service
* specifically, `rename`
*/
fun Shape.contextName(serviceShape: ServiceShape?): String {
return if (serviceShape != null) {
id.getName(serviceShape)
} else {
id.name
}
}

/**
* Base converter from `Shape` to `Symbol`. Shapes are the direct contents of the `Smithy` model. `Symbols` carry information
* about Rust types, namespaces, dependencies, metadata as well as other information required to render a symbol.
Expand All @@ -168,18 +182,6 @@ class SymbolVisitor(
return shape.accept(this)
}

/**
* Services can rename their contained shapes. See https://awslabs.github.io/smithy/1.0/spec/core/model.html#service
* specifically, `rename`
*/
private fun Shape.contextName(): String {
return if (serviceShape != null) {
id.getName(serviceShape)
} else {
id.name
}
}

/**
* Return the name of a given `enum` variant. Note that this refers to `enum` in the Smithy context
* where enum is a trait that can be applied to [StringShape] and not in the Rust context of an algebraic data type.
Expand Down Expand Up @@ -238,7 +240,8 @@ class SymbolVisitor(
override fun doubleShape(shape: DoubleShape): Symbol = simpleShape(shape)
override fun stringShape(shape: StringShape): Symbol {
return if (shape.hasTrait<EnumTrait>()) {
symbolBuilder(shape, RustType.Opaque(shape.contextName().toPascalCase())).locatedIn(Models).build()
val rustType = RustType.Opaque(shape.contextName(serviceShape).toPascalCase())
symbolBuilder(shape, rustType).locatedIn(Models).build()
} else {
simpleShape(shape)
}
Expand Down Expand Up @@ -285,7 +288,7 @@ class SymbolVisitor(
return symbolBuilder(
shape,
RustType.Opaque(
shape.contextName()
shape.contextName(serviceShape)
.replaceFirstChar { it.uppercase() }
)
)
Expand All @@ -305,7 +308,7 @@ class SymbolVisitor(
val isError = shape.hasTrait<ErrorTrait>()
val isInput = shape.hasTrait<SyntheticInputTrait>()
val isOutput = shape.hasTrait<SyntheticOutputTrait>()
val name = shape.contextName().toPascalCase().letIf(isError && config.renameExceptions) {
val name = shape.contextName(serviceShape).toPascalCase().letIf(isError && config.renameExceptions) {
it.replace("Exception", "Error")
}
val builder = symbolBuilder(shape, RustType.Opaque(name))
Expand All @@ -318,7 +321,7 @@ class SymbolVisitor(
}

override fun unionShape(shape: UnionShape): Symbol {
val name = shape.contextName().toPascalCase()
val name = shape.contextName(serviceShape).toPascalCase()
val builder = symbolBuilder(shape, RustType.Opaque(name)).locatedIn(Models)

return builder.build()
Expand Down Expand Up @@ -355,9 +358,7 @@ private const val SHAPE_KEY = "shape"
private const val SYMBOL_DEFAULT = "symboldefault"
private const val RENAMED_FROM_KEY = "renamedfrom"

fun Symbol.Builder.rustType(rustType: RustType): Symbol.Builder {
return this.putProperty(RUST_TYPE_KEY, rustType)
}
fun Symbol.Builder.rustType(rustType: RustType): Symbol.Builder = this.putProperty(RUST_TYPE_KEY, rustType)

fun Symbol.Builder.renamedFrom(name: String): Symbol.Builder {
return this.putProperty(RENAMED_FROM_KEY, name)
Expand All @@ -366,9 +367,7 @@ fun Symbol.Builder.renamedFrom(name: String): Symbol.Builder {
fun Symbol.renamedFrom(): String? = this.getProperty(RENAMED_FROM_KEY, String::class.java).orNull()

fun Symbol.defaultValue(): Default = this.getProperty(SYMBOL_DEFAULT, Default::class.java).orElse(Default.NoDefault)
fun Symbol.Builder.setDefault(default: Default): Symbol.Builder {
return this.putProperty(SYMBOL_DEFAULT, default)
}
fun Symbol.Builder.setDefault(default: Default): Symbol.Builder = this.putProperty(SYMBOL_DEFAULT, default)

/**
* Type representing the default value for a given type. (eg. for Strings, this is `""`)
Expand Down Expand Up @@ -406,7 +405,7 @@ fun Symbol.extractSymbolFromOption(): Symbol = this.mapRustType { it.stripOuter<
fun Symbol.isRustBoxed(): Boolean = rustType().stripOuter<RustType.Option>() is RustType.Box

// Symbols should _always_ be created with a Rust type & shape attached
fun Symbol.rustType(): RustType = this.getProperty(RUST_TYPE_KEY, RustType::class.java).get()
fun Symbol.rustType(): RustType = this.expectProperty(RUST_TYPE_KEY, RustType::class.java)
fun Symbol.shape(): Shape = this.expectProperty(SHAPE_KEY, Shape::class.java)

/**
Expand Down
Loading

0 comments on commit ae2a74b

Please sign in to comment.