From cac45bd27a246c12042f5a75ecfcb2276c3a8131 Mon Sep 17 00:00:00 2001 From: Julius van Dis Date: Wed, 7 Aug 2024 21:33:02 +0200 Subject: [PATCH] Allow to generate primitives as well for a given AST (#249) Co-authored-by: Willem Veelenturf --- .../community/flock/wirespec/generator/Generator.kt | 4 ++-- .../flock/wirespec/generator/GeneratorTest.kt | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/tools/generator/src/commonMain/kotlin/community/flock/wirespec/generator/Generator.kt b/src/tools/generator/src/commonMain/kotlin/community/flock/wirespec/generator/Generator.kt index 79a0d2b2..e4f65340 100644 --- a/src/tools/generator/src/commonMain/kotlin/community/flock/wirespec/generator/Generator.kt +++ b/src/tools/generator/src/commonMain/kotlin/community/flock/wirespec/generator/Generator.kt @@ -24,8 +24,8 @@ fun AST.generate(type: String, random: Random = Random.Default): JsonElement = R isDictionary = false ).let { generate(it, random) } -fun AST.generate(type: Reference, random: Random = Random.Default): JsonElement = resolveReference(type) - .let { if (type.isIterable) generateIterator(it, random) else generateObject(it, random) } +fun AST.generate(type: Reference, random: Random = Random.Default): JsonElement = + generateReference(type, random) private fun AST.resolveReference(type: Reference) = filterIsInstance() .find { it.identifier.value == type.value } diff --git a/src/tools/generator/src/commonTest/kotlin/community/flock/wirespec/generator/GeneratorTest.kt b/src/tools/generator/src/commonTest/kotlin/community/flock/wirespec/generator/GeneratorTest.kt index 95a7dcba..530e42a5 100644 --- a/src/tools/generator/src/commonTest/kotlin/community/flock/wirespec/generator/GeneratorTest.kt +++ b/src/tools/generator/src/commonTest/kotlin/community/flock/wirespec/generator/GeneratorTest.kt @@ -3,8 +3,11 @@ package community.flock.wirespec.generator import arrow.core.getOrElse import community.flock.wirespec.compiler.core.WirespecSpec import community.flock.wirespec.compiler.core.parse +import community.flock.wirespec.compiler.core.parse.Field.Reference.Primitive +import community.flock.wirespec.compiler.core.parse.Field.Reference.Primitive.Type import community.flock.wirespec.compiler.utils.noLogger import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonPrimitive import kotlin.random.Random import kotlin.test.Test import kotlin.test.assertEquals @@ -54,6 +57,15 @@ class GeneratorTest { assertEquals(expect, res.toString()) } + @Test + fun generatePrimitive() { + val ast = parser(src) + val random = Random(0L) + val res = ast.generate(Primitive(Type.String, false, false), random) + val expect = "ZKN8V5p8ktkmmMX" + assertEquals(expect, res.jsonPrimitive.content) + } + @Test fun shouldBeEqualWhenSameAttributes() { val ast = parser(src)