-
Notifications
You must be signed in to change notification settings - Fork 152
docs: add runnable examples and SourceFile embedding for Allows reference #1179
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
Open
khajavi
wants to merge
37
commits into
zio:main
Choose a base branch
from
khajavi:allow-examples
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
37 commits
Select commit
Hold shift + click to select a range
91aa9ca
docs: add runnable examples for Allows reference page
khajavi f19b525
docs: embed example files via SourceFile.print in allows.md
khajavi 52267e3
Update zio-blocks-docs/src/main/scala/SourceFile.scala
khajavi 1125035
Documentation of Structural Types (#1171)
khajavi c61e4f2
fix(Allows): harden Scala 2 macro type extraction and add regression …
jdegoes c97beaf
docs(allows): add structural type definition
khajavi 9548af8
docs(allows): add Creating Instances section
khajavi 8697b7a
docs(allows): add Core Operations section
khajavi 4392469
docs(allows): add Integration section with Schema
khajavi d81765c
docs(allows): fix prose introduction for error message and code blocks
khajavi 64d0a72
docs(allows): remove redundancy from Motivation section
khajavi 6a67406
docs(allows): fix mdoc modifiers and Scala 2/3 syntax consistency
khajavi e121865
docs(allows): fix code block compilation errors (escape and imports)
khajavi 8cabc8c
docs: integrate allows.md into sidebar and documentation index
khajavi 3217cd3
docs: add scalafmt lint step to documentation skills
khajavi 3f938a2
docs(allows): apply scalafmt to examples
khajavi f3569f2
docs(skills): stage example files before lint check to catch untracke…
khajavi 8d30f53
docs(allows): clarify compile-only examples and remove misleading sbt…
khajavi fc8c1d3
fix(docs): improve SourceFile resource management and error handling
khajavi fa972db
Merge main into allow-examples: resolve step numbering conflict
khajavi 240f91b
docs(allows): explain capability token concept
khajavi 02d42f6
docs(allows): explain structural preconditions vs runtime checks
khajavi af41164
docs(allows): replace 'ZIO Schema 2' with 'ZIO Blocks' and explain da…
khajavi d7bae0c
docs(allows): explain DynamicValue in JSON context
khajavi 39e2c21
docs(allows): explain upper bound semantics rationale
khajavi 11ea3f4
docs(allows): improve upper bound code example with UserRow cases
khajavi 35a3a6a
docs(allows): remove tabbed code blocks comment
khajavi eb3dbb8
docs(allows): restructure grammar nodes table into three groups
khajavi d8951dc
docs(allows): clarify 'catch-all Primitive' terminology
khajavi 8e77319
docs(allows): add MDX Tabs imports
khajavi dbcfc6c
docs(allows): convert 'Creating Instances' examples to tabs
khajavi 7c3bcc1
docs(allows): convert 'Union Syntax' examples to tabs
khajavi 5cc8a18
docs(skills): add Scala 2/3 tabs pattern to docs-mdoc-conventions
khajavi 8b6d95c
docs(skills): update Scala version rule to allow tabs for version-spe…
khajavi e9ed137
Update .claude/skills/docs-data-type-ref/SKILL.md
khajavi 0b93ec2
Update docs/reference/allows.md
khajavi e8e3aa9
docs(skills): fix nested fence in tabbed code example
khajavi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
98 changes: 98 additions & 0 deletions
98
schema-examples/src/main/scala/comptime/AllowsCsvExample.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| package comptime | ||
|
|
||
| import zio.blocks.schema._ | ||
| import zio.blocks.schema.comptime.Allows | ||
| import Allows.{Primitive, Record, `|`} | ||
| import Allows.{Optional => AOptional} | ||
| import util.ShowExpr.show | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // CSV serializer example using Allows[A, S] compile-time shape constraints | ||
| // | ||
| // A CSV row is a flat record: every field must be a primitive scalar or an | ||
| // optional primitive (for nullable columns). Nested records, sequences, and | ||
| // maps are all rejected at compile time. | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| // Compatible: flat record of primitives and optional primitives | ||
| case class Employee(name: String, department: String, salary: BigDecimal, active: Boolean) | ||
| object Employee { implicit val schema: Schema[Employee] = Schema.derived } | ||
|
|
||
| case class SensorReading(sensorId: String, timestamp: Long, value: Double, unit: Option[String]) | ||
| object SensorReading { implicit val schema: Schema[SensorReading] = Schema.derived } | ||
|
|
||
| object CsvSerializer { | ||
|
|
||
| type FlatRow = Primitive | AOptional[Primitive] | ||
|
|
||
| /** Serialize a sequence of flat records to CSV format. */ | ||
| def toCsv[A](rows: Seq[A])(implicit schema: Schema[A], ev: Allows[A, Record[FlatRow]]): String = { | ||
| val reflect = schema.reflect.asRecord.get | ||
| val header = reflect.fields.map(_.name).mkString(",") | ||
| val lines = rows.map { row => | ||
| val dv = schema.toDynamicValue(row) | ||
| dv match { | ||
| case DynamicValue.Record(fields) => | ||
| fields.map { case (_, v) => csvEscape(dvToString(v)) }.mkString(",") | ||
| case _ => "" | ||
| } | ||
| } | ||
| (header +: lines).mkString("\n") | ||
| } | ||
|
|
||
| private def dvToString(dv: DynamicValue): String = dv match { | ||
| case DynamicValue.Primitive(PrimitiveValue.String(s)) => s | ||
| case DynamicValue.Primitive(PrimitiveValue.Boolean(b)) => b.toString | ||
| case DynamicValue.Primitive(PrimitiveValue.Int(n)) => n.toString | ||
| case DynamicValue.Primitive(PrimitiveValue.Long(n)) => n.toString | ||
| case DynamicValue.Primitive(PrimitiveValue.Double(n)) => n.toString | ||
| case DynamicValue.Primitive(PrimitiveValue.Float(n)) => n.toString | ||
| case DynamicValue.Primitive(PrimitiveValue.BigDecimal(n)) => n.toString | ||
| case DynamicValue.Primitive(v) => v.toString | ||
| case DynamicValue.Null => "" | ||
| case DynamicValue.Variant(tag, inner) if tag == "Some" => dvToString(inner) | ||
| case DynamicValue.Variant(tag, _) if tag == "None" => "" | ||
| case DynamicValue.Record(fields) => | ||
| fields.headOption.map { case (_, v) => dvToString(v) }.getOrElse("") | ||
| case other => other.toString | ||
| } | ||
|
|
||
| private def csvEscape(s: String): String = | ||
| if (s.contains(",") || s.contains("\"") || s.contains("\n")) | ||
| "\"" + s.replace("\"", "\"\"") + "\"" | ||
| else s | ||
| } | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Demonstration | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| object AllowsCsvExample extends App { | ||
|
|
||
| // Flat records of primitives — compiles fine | ||
| val employees = Seq( | ||
| Employee("Alice", "Engineering", BigDecimal("120000.00"), true), | ||
| Employee("Bob", "Marketing", BigDecimal("95000.50"), true), | ||
| Employee("Carol", "Engineering", BigDecimal("115000.00"), false) | ||
| ) | ||
|
|
||
| // CSV output for a flat record of primitives | ||
| show(CsvSerializer.toCsv(employees)) | ||
|
|
||
| // Flat record with optional fields — also compiles | ||
| val readings = Seq( | ||
| SensorReading("temp-01", 1709712000L, 23.5, Some("celsius")), | ||
| SensorReading("temp-02", 1709712060L, 72.1, None) | ||
| ) | ||
|
|
||
| // Optional fields become empty CSV cells when None | ||
| show(CsvSerializer.toCsv(readings)) | ||
|
|
||
| // The following would NOT compile — uncomment to see the error: | ||
| // | ||
| // case class Nested(name: String, address: Address) | ||
| // object Nested { implicit val schema: Schema[Nested] = Schema.derived } | ||
| // CsvSerializer.toCsv(Seq(Nested("Alice", Address("1 Main St", "NY", "10001")))) | ||
| // [error] Schema shape violation at Nested.address: found Record(Address), | ||
| // required Primitive | Optional[Primitive] | ||
| } |
92 changes: 92 additions & 0 deletions
92
schema-examples/src/main/scala/comptime/AllowsEventBusExample.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| package comptime | ||
|
|
||
| import zio.blocks.schema._ | ||
| import zio.blocks.schema.comptime.Allows | ||
| import Allows.{Primitive, Record, Sequence, `|`} | ||
| import Allows.{Optional => AOptional} | ||
| import util.ShowExpr.show | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Event bus / message broker example using Allows[A, S] | ||
| // | ||
| // Published events are typically sealed traits of flat record cases. Sealed | ||
| // traits are automatically unwrapped by the Allows macro — each case is | ||
| // checked individually against the grammar. No Variant node is needed. | ||
| // | ||
| // This example also shows nested sealed traits (auto-unwrap is recursive). | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| // Domain events — a sealed trait hierarchy | ||
| sealed trait AccountEvent | ||
| case class AccountOpened(accountId: String, owner: String, initialBalance: BigDecimal) extends AccountEvent | ||
| case class FundsDeposited(accountId: String, amount: BigDecimal) extends AccountEvent | ||
| case class FundsWithdrawn(accountId: String, amount: BigDecimal) extends AccountEvent | ||
| case class AccountClosed(accountId: String, reason: Option[String]) extends AccountEvent | ||
| object AccountEvent { implicit val schema: Schema[AccountEvent] = Schema.derived } | ||
|
|
||
| // Nested sealed trait — InventoryEvent has a sub-hierarchy | ||
| sealed trait InventoryEvent | ||
| case class ItemAdded(sku: String, quantity: Int) extends InventoryEvent | ||
| case class ItemRemoved(sku: String, quantity: Int) extends InventoryEvent | ||
|
|
||
| sealed trait InventoryAlert extends InventoryEvent | ||
| case class LowStock(sku: String, remaining: Int) extends InventoryAlert | ||
| case class OutOfStock(sku: String) extends InventoryAlert | ||
|
|
||
| object InventoryEvent { implicit val schema: Schema[InventoryEvent] = Schema.derived } | ||
|
|
||
| // Event with sequence fields (e.g. tags or batch items) | ||
| sealed trait BatchEvent | ||
| case class BatchImport(batchId: String, itemIds: List[String]) extends BatchEvent | ||
| case class BatchComplete(batchId: String, count: Int) extends BatchEvent | ||
| object BatchEvent { implicit val schema: Schema[BatchEvent] = Schema.derived } | ||
|
|
||
| object EventBus { | ||
|
|
||
| type EventShape = Primitive | AOptional[Primitive] | ||
|
|
||
| /** Publish a domain event. All cases of the sealed trait must be flat records. */ | ||
| def publish[A](event: A)(implicit schema: Schema[A], ev: Allows[A, Record[EventShape]]): String = { | ||
| val dv = schema.toDynamicValue(event) | ||
| val (typeName, payload) = dv match { | ||
| case DynamicValue.Variant(name, inner) => (name, inner.toJson.toString) | ||
| case _ => (schema.reflect.typeId.name, dv.toJson.toString) | ||
| } | ||
| s"PUBLISH topic=${schema.reflect.typeId.name} type=$typeName payload=$payload" | ||
| } | ||
|
|
||
| /** Publish events that may contain sequence fields (e.g. batch operations). */ | ||
| def publishBatch[A](event: A)(implicit | ||
| schema: Schema[A], | ||
| ev: Allows[A, Record[Primitive | Sequence[Primitive]]] | ||
| ): String = { | ||
| val dv = schema.toDynamicValue(event) | ||
| val (typeName, payload) = dv match { | ||
| case DynamicValue.Variant(name, inner) => (name, inner.toJson.toString) | ||
| case _ => (schema.reflect.typeId.name, dv.toJson.toString) | ||
| } | ||
| s"PUBLISH topic=${schema.reflect.typeId.name} type=$typeName payload=$payload" | ||
| } | ||
| } | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Demonstration | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| object AllowsEventBusExample extends App { | ||
|
|
||
| // Flat sealed trait — all cases are records of primitives/optionals | ||
| show(EventBus.publish[AccountEvent](AccountOpened("acc-001", "Alice", BigDecimal("1000.00")))) | ||
| show(EventBus.publish[AccountEvent](FundsDeposited("acc-001", BigDecimal("500.00")))) | ||
| show(EventBus.publish[AccountEvent](AccountClosed("acc-001", Some("customer request")))) | ||
|
|
||
| // Nested sealed trait — auto-unwrap is recursive | ||
| // InventoryAlert extends InventoryEvent, both are unwrapped | ||
| show(EventBus.publish[InventoryEvent](ItemAdded("SKU-100", 50))) | ||
| show(EventBus.publish[InventoryEvent](LowStock("SKU-100", 3))) | ||
| show(EventBus.publish[InventoryEvent](OutOfStock("SKU-100"))) | ||
|
|
||
| // Events with sequence fields use a wider grammar | ||
| show(EventBus.publishBatch[BatchEvent](BatchImport("batch-42", List("item-1", "item-2", "item-3")))) | ||
| show(EventBus.publishBatch[BatchEvent](BatchComplete("batch-42", 3))) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.