Smithy
zio-blocks-smithy is a Smithy IDL parser and AST library providing a complete representation of Smithy 2.0 API models. It enables parsing Smithy IDL text into rich data structures, querying shape definitions, and pretty-printing models back to valid IDL syntax—all without external dependencies.
Installation
Add the library to your build configuration:
libraryDependencies += "dev.zio" %% "zio-blocks-smithy" % "0.0.56"
Supported Scala versions: 2.13.x and 3.x
Quick Start
Parse Smithy IDL text into a model, query shapes, and serialize back:
import zio.blocks.smithy._
val smithyText = """$version: "2"
namespace com.example.api
structure User {
@required
id: String
name: String
}
operation GetUser {
input: GetUserInput
output: User
}
structure GetUserInput {
@required
id: String
}
"""
// Parse IDL text into a model
val result = SmithyModel.parse(smithyText)
// Access shapes and data
result match {
case Right(model) =>
model.findShape("User").foreach { userDef =>
println(s"Found shape: ${userDef.name}")
}
case Left(error) =>
println(s"Parse error: ${error.message}")
}
// Serialize back to IDL
result.foreach { model =>
val idlText = model.prettyPrint
println(idlText)
}
Core Types
The library provides core types that work together to parse, query, and serialize Smithy models. The main types work together in a parsing → querying → serialization pipeline:
Smithy IDL Text
↓
SmithyModel.parse (public API)
↓
SmithyModel (contains shapes, metadata, traits)
├─ shapes: List[ShapeDefinition]
│ └─ shape: Shape (sealed trait — central type)
│ ├─ StructureShape(members: List[MemberDefinition])
│ ├─ ListShape(member: MemberDefinition)
│ ├─ MapShape(key: MemberDefinition, value: MemberDefinition)
│ ├─ ServiceShape(operations, resources, errors)
│ ├─ OperationShape(input, output, errors)
│ ├─ UnionShape(members: List[MemberDefinition])
│ ├─ EnumShape(members: List[EnumMember])
│ ├─ ResourceShape(identifiers, create, read, update, delete, list, ...)
│ ├─ StringShape, BooleanShape, IntegerShape, and 10 more simple shapes
│ └─ ... (20 subtypes in total — see the Shape Catalog below)
├─ MemberDefinition(name: String, target: ShapeId, traits: List[TraitApplication])
├─ TraitApplication(id: ShapeId, value: Option[NodeValue])
├─ ShapeId (namespace + name identifier)
└─ NodeValue (metadata values: String, Number, Boolean, Array, Object, Null)
↓
SmithyModel.prettyPrint (public API)
↓
Smithy IDL Text
The root container for a Smithy model. Contains version, namespace, shapes, metadata, and trait applications. The case class and companion object expose the following API:
case class SmithyModel(
version: String, // Smithy version (e.g., "2")
namespace: String,
useStatements: List[ShapeId],
metadata: Map[String, NodeValue],
shapes: List[ShapeDefinition],
applyStatements: List[ApplyStatement] = Nil
) {
def findShape(name: String): Option[ShapeDefinition]
def allShapeIds: List[ShapeId]
def prettyPrint: String
def prettyPrint(indent: Int): String
}
object SmithyModel {
def parse(input: String): Either[SmithyError, SmithyModel]
}
Shape Catalog
Shape is a sealed trait with 20 subtypes, covering the shape categories the Smithy specification defines. Every shape carries a Shape#name and a list of applied Shape#traits; the families differ in what else they hold:
sealed trait Shape {
def name: String
def traits: List[TraitApplication]
}
| Family | Subtypes | What they add |
|---|---|---|
| Simple | 13 | Nothing — name and traits only |
| Enum | 2 | A member list of allowed values |
| Aggregate | 4 | Member definitions naming target shapes |
| Service | 3 | ShapeId references to other shapes |
A parsed shape is wrapped in a ShapeDefinition, which pairs the name with the shape. Shape also carries its own Shape#name, so the two agree and either can be read:
final case class ShapeDefinition(name: String, shape: Shape)
Simple Shapes
Thirteen shapes carry no structure beyond their name and traits. They differ only in which IDL keyword produces them and what the target protocol is expected to do with them:
| Type | IDL keyword | Represents |
|---|---|---|
BlobShape | blob | Arbitrary binary data |
BooleanShape | boolean | True/false values |
StringShape | string | UTF-8 text |
ByteShape | byte | 8-bit signed integer |
ShortShape | short | 16-bit signed integer |
IntegerShape | integer | 32-bit signed integer |
LongShape | long | 64-bit signed integer |
FloatShape | float | Single-precision IEEE 754 |
DoubleShape | double | Double-precision IEEE 754 |
BigIntegerShape | bigInteger | Arbitrarily large signed integer |
BigDecimalShape | bigDecimal | Arbitrary-precision decimal |
TimestampShape | timestamp | A point in time |
DocumentShape | document | Protocol-agnostic open content |
Because they share one shape, parsing them produces values that differ only in their type:
import zio.blocks.smithy._
val simpleModel = SmithyModel.parse(
"""$version: "2"
|namespace com.example
|blob Payload
|timestamp CreatedAt
|document Metadata
|""".stripMargin
).toOption.get
Each definition names the shape and holds the corresponding subtype:
simpleModel.shapes
// res1: List[ShapeDefinition] = List(
// ShapeDefinition(
// name = "Payload",
// shape = BlobShape(name = "Payload", traits = List())
// ),
// ShapeDefinition(
// name = "CreatedAt",
// shape = TimestampShape(name = "CreatedAt", traits = List())
// ),
// ShapeDefinition(
// name = "Metadata",
// shape = DocumentShape(name = "Metadata", traits = List())
// )
// )
DocumentShape is the one to reach for when a field's contents are not known at model time — it is the Smithy equivalent of an open JSON value, and no member list constrains it.
Enum Shapes
EnumShape and IntEnumShape each hold a fixed set of permitted values. They differ in the value type and in whether the value is optional:
final case class EnumShape(
name: String,
traits: List[TraitApplication] = Nil,
members: List[EnumMember] = Nil
) extends Shape
final case class IntEnumShape(
name: String,
traits: List[TraitApplication] = Nil,
members: List[IntEnumMember] = Nil
) extends Shape
EnumMember carries an Option[String], because the IDL allows a bare member name; IntEnumMember carries a required Int, because an integer enum has no name to fall back on:
final case class EnumMember(name: String, value: Option[String] = None, traits: List[TraitApplication] = Nil)
final case class IntEnumMember(name: String, value: Int, traits: List[TraitApplication] = Nil)
A string enum with explicit values fills in each value:
val colorModel = SmithyModel.parse(
"""$version: "2"
|namespace com.example
|enum Color {
| RED = "red"
| GREEN = "green"
|}
|""".stripMargin
).toOption.get
Each member pairs the declared name with the string it maps to:
colorModel.shapes
// res2: List[ShapeDefinition] = List(
// ShapeDefinition(
// name = "Color",
// shape = EnumShape(
// name = "Color",
// traits = List(),
// members = List(
// EnumMember(name = "RED", value = Some("red"), traits = List()),
// EnumMember(name = "GREEN", value = Some("green"), traits = List())
// )
// )
// )
// )
Omitting the values leaves value absent rather than duplicating the name, so a consumer wanting the effective wire value reads EnumMember#value and falls back to EnumMember#name:
val suitModel = SmithyModel.parse(
"""$version: "2"
|namespace com.example
|enum Suit {
| CLUB
| HEART
|}
|""".stripMargin
).toOption.get
The distinction survives parsing, which is what lets a round trip reproduce the original document:
suitModel.shapes
// res3: List[ShapeDefinition] = List(
// ShapeDefinition(
// name = "Suit",
// shape = EnumShape(
// name = "Suit",
// traits = List(),
// members = List(
// EnumMember(name = "CLUB", value = None, traits = List()),
// EnumMember(name = "HEART", value = None, traits = List())
// )
// )
// )
// )
An integer enum requires a value for every member, so IntEnumMember holds an Int rather than an option:
val cardModel = SmithyModel.parse(
"""$version: "2"
|namespace com.example
|intEnum FaceCard {
| JACK = 11
| QUEEN = 12
|}
|""".stripMargin
).toOption.get
Reading the members gives the integers directly:
cardModel.shapes
// res4: List[ShapeDefinition] = List(
// ShapeDefinition(
// name = "FaceCard",
// shape = IntEnumShape(
// name = "FaceCard",
// traits = List(),
// members = List(
// IntEnumMember(name = "JACK", value = 11, traits = List()),
// IntEnumMember(name = "QUEEN", value = 12, traits = List())
// )
// )
// )
// )
Aggregate Shapes
Four shapes compose other shapes, and all of them do it through MemberDefinition — a name, the ShapeId of the target, and any traits on the member itself:
| Type | IDL keyword | Members |
|---|---|---|
ListShape | list | member: MemberDefinition |
MapShape | map | key and value, both MemberDefinition |
StructureShape | structure | members: List[MemberDefinition] |
UnionShape | union | members: List[MemberDefinition], one set at a time |
A structure's members name their targets by ShapeId, not by nested shape, so the model stays flat and a member's target is resolved by lookup:
val userModel = SmithyModel.parse(
"""$version: "2"
|namespace com.example
|structure User {
| @required
| id: String
| tags: TagList
|}
|list TagList {
| member: String
|}
|""".stripMargin
).toOption.get
Both shapes appear at the top level, and the tags member of User points at TagList by reference:
userModel.shapes
// res5: List[ShapeDefinition] = List(
// ShapeDefinition(
// name = "User",
// shape = StructureShape(
// name = "User",
// traits = List(),
// members = List(
// MemberDefinition(
// name = "id",
// target = ShapeId(namespace = "", name = "String"),
// traits = List(
// TraitApplication(
// id = ShapeId(namespace = "smithy.api", name = "required"),
// value = None
// )
// )
// ),
// MemberDefinition(
// name = "tags",
// target = ShapeId(namespace = "", name = "TagList"),
// traits = List()
// )
// )
// )
// ),
// ShapeDefinition(
// name = "TagList",
// shape = ListShape(
// name = "TagList",
// traits = List(),
// member = MemberDefinition(
// name = "member",
// target = ShapeId(namespace = "", name = "String"),
// traits = List()
// )
// )
// )
// )
member has no default, traits doesListShape and MapShape declare their Shape#traits parameter with a default before the parameters that have none, so positional construction does not work — ListShape("TagList", member = m) compiles while ListShape("TagList", m) does not. StructureShape and UnionShape default their member lists, so both forms work there.