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

Remove reserved types #1052

Merged
merged 16 commits into from
Jul 24, 2023
Merged
Show file tree
Hide file tree
Changes from 7 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
6 changes: 4 additions & 2 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -805,7 +805,8 @@ lazy val example = projectMatrix
"smithy4s.example.imp",
"smithy4s.example.error",
"smithy4s.example.common",
"smithy4s.example.collision"
"smithy4s.example.collision",
"smithy4s.example.reservedNameOverride",
),
smithySpecs := Seq(
(ThisBuild / baseDirectory).value / "sampleSpecs" / "example.smithy",
Expand All @@ -825,7 +826,8 @@ lazy val example = projectMatrix
(ThisBuild / baseDirectory).value / "sampleSpecs" / "mixins.smithy",
(ThisBuild / baseDirectory).value / "sampleSpecs" / "defaults.smithy",
(ThisBuild / baseDirectory).value / "sampleSpecs" / "quoted_string.smithy",
(ThisBuild / baseDirectory).value / "sampleSpecs" / "numeric.smithy"
(ThisBuild / baseDirectory).value / "sampleSpecs" / "numeric.smithy",
(ThisBuild / baseDirectory).value / "sampleSpecs" / "reservedNameOverride.smithy",
),
Compile / resourceDirectory := (ThisBuild / baseDirectory).value / "modules" / "example" / "resources",
isCE3 := true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ private[internals] object CollisionAvoidance {
) =>
Operation(
opId,
protectType(name.capitalize),
protectKeyword(name.capitalize),
protectKeyword(methodName),
params.map(modField),
modType(input),
Expand All @@ -57,7 +57,7 @@ private[internals] object CollisionAvoidance {
}
Service(
serviceId,
protectType(name.capitalize),
protectKeyword(name.capitalize),
newOps,
hints.map(modHint),
version
Expand All @@ -67,19 +67,19 @@ private[internals] object CollisionAvoidance {
case Union(shapeId, name, alts, mixins, recursive, hints) =>
Union(
shapeId,
protectType(name.capitalize),
protectKeyword(name.capitalize),
alts.map(modAlt),
mixins.map(modType),
recursive,
hints.map(modHint)
)
case TypeAlias(shapeId, name, tpe, isUnwrapped, rec, hints) =>
val protectedName = protectType(name.capitalize)
val protectedName = protectKeyword(name.capitalize)
// If we had to amend the type
val unwrapped = isUnwrapped | (protectedName != name.capitalize)
TypeAlias(
shapeId,
protectType(name.capitalize),
protectKeyword(name.capitalize),
modType(tpe),
unwrapped,
rec,
Expand Down Expand Up @@ -115,15 +115,15 @@ private[internals] object CollisionAvoidance {
valueHints = valueHints.map(modHint(_))
)
case Type.Ref(namespace, name) =>
Type.Ref(namespace, protectType(name.capitalize))
Type.Ref(namespace, protectKeyword(name.capitalize))
case Alias(namespace, name, tpe, isUnwrapped) =>
val protectedName = protectType(name.capitalize)
val protectedName = protectKeyword(name.capitalize)
val unwrapped = isUnwrapped | (protectedName != name.capitalize)
Alias(namespace, protectType(name.capitalize), modType(tpe), unwrapped)
Alias(namespace, protectKeyword(name.capitalize), modType(tpe), unwrapped)
case PrimitiveType(prim) => PrimitiveType(prim)
case ExternalType(name, fqn, typeParams, pFqn, under, refinementHint) =>
ExternalType(
protectType(name.capitalize),
protectKeyword(name.capitalize),
fqn,
typeParams,
pFqn,
Expand Down Expand Up @@ -162,7 +162,7 @@ private[internals] object CollisionAvoidance {
}

private def modRef(ref: Type.Ref): Type.Ref =
Type.Ref(ref.namespace, protectType(ref.name.capitalize))
Type.Ref(ref.namespace, protectKeyword(ref.name.capitalize))

private def modNativeHint(hint: Hint.Native): Hint.Native =
Hint.Native(recursion.preprocess(modTypedNode)(hint.typedNode))
Expand Down Expand Up @@ -215,10 +215,6 @@ private[internals] object CollisionAvoidance {
private def protectKeyword(str: String): String =
if (reservedKeywords(str)) s"_$str" else str

private val names = new Names()
private def protectType(str: String): String =
if (names.getReservedNames(str)) "_" + str else protectKeyword(str)

private val reservedKeywords: Set[String] = Set(
"abstract",
"case",
Expand Down Expand Up @@ -263,15 +259,6 @@ private[internals] object CollisionAvoidance {

class Names() {

// Using mutation to avoid repetition.
private var reservedNames: Set[String] = Set.empty
private def reserved(pkg: String, name: String) = {
reservedNames = reservedNames + name
NameRef(pkg, name)
}

def getReservedNames: Set[String] = reservedNames

val Transformation = NameRef("smithy4s", "Transformation")
val PolyFunction5_ = NameRef("smithy4s.kinds", "PolyFunction5")
val Service_ = NameRef("smithy4s", "Service")
Expand Down Expand Up @@ -310,27 +297,27 @@ private[internals] object CollisionAvoidance {

// We reserve these keywords as they collide with types that the
// users are bound to manipulate when using Smithy4s .
val short_ = reserved("scala", "Short")
val int_ = reserved("scala", "Int")
val javaInt_ = reserved("java.lang", "Integer")
val long_ = reserved("scala", "Long")
val double_ = reserved("scala", "Double")
val float_ = reserved("scala", "Float")
val bigint_ = reserved("scala.math", "BigInteger")
val bigdecimal_ = reserved("scala.math", "BigDecimal")
val string_ = reserved("scala.Predef", "String")
val boolean_ = reserved("scala", "Boolean")
val byte_ = reserved("scala", "Byte")
val unit_ = reserved("scala", "Unit")
val timestamp_ = reserved("smithy4s", "Timestamp")
val document_ = reserved("smithy4s", "Document")
val uuid_ = reserved("smithy4s", "UUID")
val list = reserved("scala", "List")
val set = reserved("scala.collection.immutable", "Set")
val map = reserved("scala.collection.immutable", "Map")
val option = reserved("scala", "Option")
val none = reserved("scala", "None")
val some = reserved("scala", "Some")
val short_ = NameRef("scala", "Short")
val int_ = NameRef("scala", "Int")
val javaInt_ = NameRef("java.lang", "Integer")
val long_ = NameRef("scala", "Long")
val double_ = NameRef("scala", "Double")
val float_ = NameRef("scala", "Float")
val bigint_ = NameRef("scala.math", "BigInteger")
val bigdecimal_ = NameRef("scala.math", "BigDecimal")
val string_ = NameRef("java.lang", "String")
val boolean_ = NameRef("scala", "Boolean")
val byte_ = NameRef("scala", "Byte")
val unit_ = NameRef("scala", "Unit")
val timestamp_ = NameRef("smithy4s", "Timestamp")
val document_ = NameRef("smithy4s", "Document")
val uuid_ = NameRef("smithy4s", "UUID")
val list = NameRef("scala", "List")
val set = NameRef("scala.collection.immutable", "Set")
val map = NameRef("scala.collection.immutable", "Map")
val option = NameRef("scala", "Option")
val none = NameRef("scala", "None")
val some = NameRef("scala", "Some")

}

Expand Down
18 changes: 9 additions & 9 deletions modules/codegen/src/smithy4s/codegen/internals/Renderer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ private[internals] class Renderer(compilationUnit: CompilationUnit) { self =>
)(
newline,
renderId(shapeId),
line"""val version: String = "$version"""",
line"""val version: $string_ = "$version"""",
newline,
renderHintsVal(hints),
newline,
Expand Down Expand Up @@ -658,13 +658,13 @@ private[internals] class Renderer(compilationUnit: CompilationUnit) { self =>

private def renderGetMessage(field: Field) = field match {
case field if field.tpe.isResolved && field.required =>
line"override def getMessage(): String = ${field.name}"
line"override def getMessage(): $string_ = ${field.name}"
case field if field.tpe.isResolved =>
line"override def getMessage(): String = ${field.name}.orNull"
line"override def getMessage(): $string_ = ${field.name}.orNull"
case field if field.required =>
line"override def getMessage(): String = ${field.name}.value"
line"override def getMessage(): $string_ = ${field.name}.value"
case field =>
line"override def getMessage(): String = ${field.name}.map(_.value).orNull"
line"override def getMessage(): $string_ = ${field.name}.map(_.value).orNull"
Baccata marked this conversation as resolved.
Show resolved Hide resolved
}

private def renderErrorable(op: Operation): Lines = {
Expand Down Expand Up @@ -901,12 +901,12 @@ private[internals] class Renderer(compilationUnit: CompilationUnit) { self =>
documentationAnnotation(hints),
deprecationAnnotation(hints),
block(
line"sealed abstract class ${name.name}(_value: String, _name: String, _intValue: Int, _hints: $Hints_) extends $Enumeration_.Value"
line"sealed abstract class ${name.name}(_value: $string_, _name: $string_, _intValue: $int_, _hints: $Hints_) extends $Enumeration_.Value"
)(
line"override type EnumType = $name",
line"override val value: String = _value",
line"override val name: String = _name",
line"override val intValue: Int = _intValue",
line"override val value: $string_ = _value",
line"override val name: $string_ = _name",
line"override val intValue: $int_ = _intValue",
line"override val hints: $Hints_ = _hints",
line"override def enumeration: $Enumeration_[EnumType] = $name",
line"@inline final def widen: $name = this"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -496,9 +496,6 @@ private[codegen] class SmithyToIR(model: Model, namespace: String) {
//format: on
}

private val reservedNames = new CollisionAvoidance.Names().getReservedNames
private def isReservedName(str: String): Boolean = reservedNames(str)

private val toType: ShapeVisitor[Option[Type]] =
new ShapeVisitor[Option[Type]] {
// See https://awslabs.github.io/smithy/1.0/spec/core/prelude-model.html?highlight=primitiveboolean#prelude-shapes
Expand Down Expand Up @@ -571,8 +568,7 @@ private[codegen] class SmithyToIR(model: Model, namespace: String) {
getExternalOrBase(shape, Type.PrimitiveType(primitive))
if (
shape.getId() != ShapeId.from(primitiveId) &&
!isUnboxedPrimitive(shape.getId()) &&
!isReservedName(shape.getId().getName())
!isUnboxedPrimitive(shape.getId())
) {
Type
.Alias(
Expand Down
18 changes: 9 additions & 9 deletions modules/core/test/src/smithy4s/ReservedTypeSmokeSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,23 @@
package smithy4s

import munit._
import smithy4s.example.collision.ReservedNameService
import smithy4s.example.collision.{String => SString, _}

class ReservedTypeSmokeSpec() extends FunSuite {

test(
"Names from the Scala stdlib can be used in smithy spec without hurting UX"
) {
val service = new ReservedNameService[Option] {
def list(value: List[String]): Option[Unit] = None
def map(value: Map[String, String]): Option[Unit] = None
def option(value: Option[String]): Option[Unit] = None
def set(set: Set[String]): Option[Unit] = None
def list(value: List[SString]): Option[Unit] = None
def map(value: Map[SString, SString]): Option[Unit] = None
def option(value: Option[SString]): Option[Unit] = None
def set(set: Set[SString]): Option[Unit] = None
}
assertEquals(service.list(List("foo")), None)
assertEquals(service.map(Map("foo" -> "bar")), None)
assertEquals(service.option(Some("foo")), None)
assertEquals(service.set(Set("foo")), None)
assertEquals(service.list(List(SString("foo"))), None)
assertEquals(service.map(Map(SString("foo") -> SString("bar"))), None)
assertEquals(service.option(Some(SString("foo"))), None)
assertEquals(service.set(Set(SString("foo"))), None)
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
{
"openapi": "3.0.2",
"info": {
"title": "ReservedNameOverrideService",
"version": "1.0.0"
},
"paths": {
"/api/set/": {
"post": {
"operationId": "SetOp",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/SetOpRequestContent"
}
}
},
"required": true
},
"responses": {
"204": {
"description": "SetOp 204 response"
}
}
}
}
},
"components": {
"schemas": {
"Set": {
"type": "object",
"properties": {
"someField": {
"type": "string"
},
"otherField": {
"type": "integer",
"format": "int32"
}
},
"required": [
"otherField",
"someField"
]
},
"SetOpRequestContent": {
"type": "object",
"properties": {
"set": {
"$ref": "#/components/schemas/Set"
}
},
"required": [
"set"
]
}
}
}
}
2 changes: 1 addition & 1 deletion modules/example/src/smithy4s/example/ServerError.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import smithy4s.schema.Schema.string
import smithy4s.schema.Schema.struct

case class ServerError(message: Option[String] = None) extends Throwable {
override def getMessage(): String = message.orNull
override def getMessage(): String = message.orNull
}
object ServerError extends ShapeTag.Companion[ServerError] {
val id: ShapeId = ShapeId("smithy4s.example", "ServerError")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import smithy4s.schema.Schema.string
import smithy4s.schema.Schema.struct

case class ServerErrorCustomMessage(messageField: Option[String] = None) extends Throwable {
override def getMessage(): String = messageField.orNull
override def getMessage(): String = messageField.orNull
}
object ServerErrorCustomMessage extends ShapeTag.Companion[ServerErrorCustomMessage] {
val id: ShapeId = ShapeId("smithy4s.example", "ServerErrorCustomMessage")
Expand Down
3 changes: 1 addition & 2 deletions modules/example/src/smithy4s/example/collision/MyList.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@ import smithy4s.Schema
import smithy4s.ShapeId
import smithy4s.schema.Schema.bijection
import smithy4s.schema.Schema.list
import smithy4s.schema.Schema.string

object MyList extends Newtype[List[String]] {
val id: ShapeId = ShapeId("smithy4s.example.collision", "MyList")
val hints: Hints = Hints.empty
val underlyingSchema: Schema[List[String]] = list(string).withId(id).addHints(hints)
val underlyingSchema: Schema[List[String]] = list(String.schema).withId(id).addHints(hints)
implicit val schema: Schema[MyList] = bijection(underlyingSchema, asBijection)
}
3 changes: 1 addition & 2 deletions modules/example/src/smithy4s/example/collision/MyMap.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@ import smithy4s.Schema
import smithy4s.ShapeId
import smithy4s.schema.Schema.bijection
import smithy4s.schema.Schema.map
import smithy4s.schema.Schema.string

object MyMap extends Newtype[Map[String, String]] {
val id: ShapeId = ShapeId("smithy4s.example.collision", "MyMap")
val hints: Hints = Hints.empty
val underlyingSchema: Schema[Map[String, String]] = map(string, string).withId(id).addHints(hints)
val underlyingSchema: Schema[Map[String, String]] = map(String.schema, String.schema).withId(id).addHints(hints)
implicit val schema: Schema[MyMap] = bijection(underlyingSchema, asBijection)
}
3 changes: 1 addition & 2 deletions modules/example/src/smithy4s/example/collision/MySet.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ import smithy4s.Schema
import smithy4s.ShapeId
import smithy4s.schema.Schema.bijection
import smithy4s.schema.Schema.set
import smithy4s.schema.Schema.string

object MySet extends Newtype[Set[String]] {
val id: ShapeId = ShapeId("smithy4s.example.collision", "MySet")
val hints: Hints = Hints(
smithy.api.UniqueItems(),
)
val underlyingSchema: Schema[Set[String]] = set(string).withId(id).addHints(hints)
val underlyingSchema: Schema[Set[String]] = set(String.schema).withId(id).addHints(hints)
implicit val schema: Schema[MySet] = bijection(underlyingSchema, asBijection)
}
Loading