diff --git a/CHANGELOG.md b/CHANGELOG.md index 573f8a5ffa..de4afd796e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1617,6 +1617,26 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru and no longer call `ruff`; the others convert one at a time, and `ruff_format` stays exported for owned generators that call it. +- **A code writer for Kotlin generators: `KotlinWriter` in `codegen-kotlin`** (ADR-0063), on the + same `codegen-base` core the Java writer extends. It collects imports while the body is written + (`use("pkg.Name")`, `use("pkg.Name", alias)`), skips Kotlin's default imports and same-package + names, sorts them in one group, backticks keyword segments, writes KDoc, quotes strings with `$` + escaped, and breaks a call that does not fit 120 columns with a trailing comma; `block { }`, + `reopen` (`} else {`) and `indented { }` are the scoped forms. It runs the shared `core` cases + and ten new `kotlin` cases, and is on the engine surface an ejected Kotlin generator may + reference (`eject.engineSurface.kotlin.engine`). A layout ratchet (`KotlinLayoutRatchetTest`, + which reads generator source with the Kotlin compiler's lexer) fails on a string holding a line + break or starting with indentation, a repeated-space indent and a KotlinPoet import; every file + that still types its layout is on a shrink-only allowlist naming the change that converts it. + The fourteen small generators now write through it: names, filter allowlist, decimal and + duration wire, validation issues, unknown body keys, validator, extractor, output parser, + output prompt, render helper, stored proc, report export and requirement tests. **Their output + changes in layout only:** imports in sorted order, a list that fits written on one line, a + trailing comma on a broken list, a one-entry KDoc on one line, no blank line at the start of a + block, and a blank line after a file header. Regenerating shows those diffs and nothing else. Every public method an owned copy + ejected at an earlier version calls (each emitter's `write`, `BODY`, `body(wire)`, + `KotlinNaming.packageHeader`) is kept. + - **Python publishes a shared model (FR-023).** A `shared-model` generator, wired in `metaobjects.config.yaml` like any other (`metaobjects gen --list` names its options), writes `.metaobjects.json` and `metaobjects.pkg.json` for a consumer's `deps sync`: `name` and diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index eff49c2fa5..a99424e333 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -71,7 +71,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/codegen-skip-conformance/`](../fixtures/codegen-skip-conformance/) (when `gen` may skip and what a local `verify --codegen` may answer, ADR-0064) | one case table in `cases.json`, plus the manifest layout vectors in `manifests.json` (ADR-0064 Amendment 1) | ✓ | ✓ | ✓ (through the Java runner) | ✓ | ✓ | ✓ (every case but the three-way merge one) | | [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (vocabulary with no lowering yet: FR-044 reporting, what is lowered and what stays inert; ADR-0066 business rules, inert everywhere) | 2 model pairs (`reporting/` and `rules/`, each `with` vs `without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | `rules/` (the layer generators lower it; the flat ones stay inert) | | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | — | -| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 76 cases (31 core + 10 TypeScript + 9 Java + 6 C# + 12 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | — (writer not built yet) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | +| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 86 cases (31 core + 10 TypeScript + 9 Java + 10 Kotlin + 6 C# + 12 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | ✓ (core and Kotlin dialect; `KotlinWriter` in `codegen-kotlin`) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 22 cases (17 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | — | | [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the `explorer.json` data spine: `meta export --effective` + `meta verify --format json` + the generated-file manifest in, one explorer document out) | 1 case (`shop`) | ✓ (the builder is TypeScript, and reads only port-neutral inputs) | — | — | — | — | — | diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index e0eb252c9e..5290820de3 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -1334,7 +1334,8 @@ runner types, the naming and type-mapping tables (`SpringNaming`, `SpringTypeMap `KotlinNaming`, `KotlinTypeMapper`), the questions a generator asks of the model (`FindInbound`, `TphPlan`, the M:N support, `RestSurfaceGate`), the code writer the Java generators lay their output out with (`CodeWriter`, `JavaWriter`, `WriterOptions`, and -`SpringJavaWriter` for Spring source), and the Kotlin +`SpringJavaWriter` for Spring source), the code writer the Kotlin generators lay their output +out with (`KotlinWriter`, on the same `CodeWriter`), and the Kotlin `Fr019SharedEnum`. Anything that returns emitted text is handed over; a table or a model question is not. The Kotlin `Fr019SharedEnum` writes no output. It answers where a shared or `@provided` enum lives, and the type mapper and the generator utilities take its diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index ae92849e61..89e3d43a9e 100644 --- a/docs/ports/kotlin.md +++ b/docs/ports/kotlin.md @@ -159,6 +159,11 @@ your own ``, `` and ``: ## Configure +Generators that have moved to the code writer lay their output out with `KotlinWriter` +(ADR-0063; the dialect and its ops are in [spec/code-writer.md](../../spec/code-writer.md#kotlin-dialect-kotlinwriter)). +The layout ratchet (`KotlinLayoutRatchetTest`) keeps the emitters still on KotlinPoet on a +shrink-only allowlist. + The 18 generators registered in `codegen-kotlin` (`GeneratorRegistry.kt`): | Generator | Output | Per | diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index b1f75e4e51..35daccbe49 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -572,12 +572,16 @@ "com.metaobjects.generator.kotlin.KotlinTphPlan", "com.metaobjects.generator.kotlin.KotlinTypeMapper", "com.metaobjects.generator.kotlin.PackageMapping", + "com.metaobjects.generator.kotlin.writer.KotlinWriter", "com.metaobjects.generator.requirement.RenderedTest", "com.metaobjects.generator.requirement.RequirementTestArgs", "com.metaobjects.generator.requirement.RequirementTestRenderer", "com.metaobjects.generator.util.GeneratedFileWriter", "com.metaobjects.generator.util.GeneratorUtil", - "com.metaobjects.generator.util.RestSurfaceGate" + "com.metaobjects.generator.util.RestSurfaceGate", + "com.metaobjects.generator.writer.CodeWriter", + "com.metaobjects.generator.writer.Group", + "com.metaobjects.generator.writer.WriterOptions" ] }, "python": { diff --git a/fixtures/writer-conformance/README.md b/fixtures/writer-conformance/README.md index 46b995ea62..954505e1cd 100644 --- a/fixtures/writer-conformance/README.md +++ b/fixtures/writer-conformance/README.md @@ -7,7 +7,7 @@ format are in [`spec/code-writer.md`](../../spec/code-writer.md). - `cases/*.json` with `"dialect": "core"` pin the language-neutral core: indentation, blocks, blank-line requests, snippets, fit-or-break lists, line endings and the error codes. Every port's writer runs them with the options the case states. -- Cases with a language dialect (`"dialect": "typescript"`, `"java"`, `"python"`, `"csharp"`, `"rust"`) pin that +- Cases with a language dialect (`"dialect": "typescript"`, `"java"`, `"kotlin"`, `"python"`, `"csharp"`, `"rust"`) pin that language's writer: import or `using` collection and ordering, doc comments and its defaults. A runner runs the `core` cases and its own dialect's, and skips the others by name. @@ -15,12 +15,14 @@ Runners: - TypeScript, `server/typescript/packages/codegen-ts/test/writer-conformance.test.ts` (`core` and `typescript`). - Java, `server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/WriterConformanceTest.java` (`core` and `java`). +- Kotlin, `server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/writer/KotlinWriterConformanceTest.kt` (`core` and `kotlin`). - Python, `server/python/tests/codegen/test_writer_conformance.py` (`core` and `python`). - Rust, `server/rust/metaobjects-codegen/tests/writer_conformance.rs` (`core` and `rust`). - C#, `server/csharp/MetaObjects.Codegen.Tests/WriterConformanceTests.cs` (`core` and `csharp`). -The ports without a writer yet (Kotlin) run the `core` cases when their writers -land, and add cases for their own dialect beside these. +The `kotlin` ops are `package` (a name), `use` (a name), `useAs` (a name, then the alias), +`header` and `doc` (lines) and `reopen` (parts), beside the core ops. A `kotlin` case takes the +dialect's defaults unless it states options. The `csharp` ops are `header` (lines), `using`, `usingStatic` (a namespace or type), `usingAlias` (alias, target) and `docSummary` (lines), beside the core ops. A `csharp` case may state diff --git a/fixtures/writer-conformance/cases/kotlin-defaults.json b/fixtures/writer-conformance/cases/kotlin-defaults.json new file mode 100644 index 0000000000..a600cc4a24 --- /dev/null +++ b/fixtures/writer-conformance/cases/kotlin-defaults.json @@ -0,0 +1,60 @@ +{ + "description": "The Kotlin dialect indents four spaces, breaks at 120 columns and puts a comma after the last item of a broken list, as Kotlin's coding conventions write it.", + "dialect": "kotlin", + "ops": [ + [ + "open", + "object A {" + ], + [ + "line", + "val NAMES: List = ", + { + "list": { + "open": "listOf(", + "items": [ + "\"n00\"", + "\"n01\"", + "\"n02\"", + "\"n03\"", + "\"n04\"", + "\"n05\"", + "\"n06\"", + "\"n07\"", + "\"n08\"", + "\"n09\"", + "\"n10\"", + "\"n11\"", + "\"n12\"", + "\"n13\"" + ], + "close": ")" + } + } + ], + [ + "close", + "}" + ] + ], + "expected": [ + "object A {", + " val NAMES: List = listOf(", + " \"n00\",", + " \"n01\",", + " \"n02\",", + " \"n03\",", + " \"n04\",", + " \"n05\",", + " \"n06\",", + " \"n07\",", + " \"n08\",", + " \"n09\",", + " \"n10\",", + " \"n11\",", + " \"n12\",", + " \"n13\",", + " )", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/kotlin-doc-comment.json b/fixtures/writer-conformance/cases/kotlin-doc-comment.json new file mode 100644 index 0000000000..58509805e5 --- /dev/null +++ b/fixtures/writer-conformance/cases/kotlin-doc-comment.json @@ -0,0 +1,44 @@ +{ + "description": "A one-entry KDoc that fits is one line; more entries, or one that does not fit, make a block. An empty entry is a bare ` *` line. Kotlin comments nest, so a comment opener or terminator inside the text is neutralised.", + "dialect": "kotlin", + "ops": [ + [ + "doc", + "The user." + ], + [ + "line", + "a()" + ], + [ + "doc", + "First line.", + "", + "@see other" + ], + [ + "line", + "b()" + ], + [ + "doc", + "ends */ here, opens /* there" + ], + [ + "line", + "c()" + ] + ], + "expected": [ + "/** The user. */", + "a()", + "/**", + " * First line.", + " *", + " * @see other", + " */", + "b()", + "/** ends */ here, opens /* there */", + "c()" + ] +} diff --git a/fixtures/writer-conformance/cases/kotlin-error-reopen-without-open.json b/fixtures/writer-conformance/cases/kotlin-error-reopen-without-open.json new file mode 100644 index 0000000000..7041a8b280 --- /dev/null +++ b/fixtures/writer-conformance/cases/kotlin-error-reopen-without-open.json @@ -0,0 +1,11 @@ +{ + "description": "reopen() with no block open is an unbalanced close.", + "dialect": "kotlin", + "ops": [ + [ + "reopen", + "} else {" + ] + ], + "error": "ERR_WRITER_UNBALANCED_CLOSE" +} diff --git a/fixtures/writer-conformance/cases/kotlin-header-package-imports-body.json b/fixtures/writer-conformance/cases/kotlin-header-package-imports-body.json new file mode 100644 index 0000000000..3d26107e56 --- /dev/null +++ b/fixtures/writer-conformance/cases/kotlin-header-package-imports-body.json @@ -0,0 +1,41 @@ +{ + "description": "Header lines print first, then a blank line, the package line (no semicolon), a blank line, the imports, a blank line and the body.", + "dialect": "kotlin", + "ops": [ + [ + "header", + "// Generated by MetaObjects. Do not edit." + ], + [ + "package", + "com.acme.api" + ], + [ + "use", + "java.time.Instant" + ], + [ + "open", + "interface A {" + ], + [ + "line", + "fun at(): Instant" + ], + [ + "close", + "}" + ] + ], + "expected": [ + "// Generated by MetaObjects. Do not edit.", + "", + "package com.acme.api", + "", + "import java.time.Instant", + "", + "interface A {", + " fun at(): Instant", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/kotlin-imports-collected-and-sorted.json b/fixtures/writer-conformance/cases/kotlin-imports-collected-and-sorted.json new file mode 100644 index 0000000000..e3dbd3eec3 --- /dev/null +++ b/fixtures/writer-conformance/cases/kotlin-imports-collected-and-sorted.json @@ -0,0 +1,45 @@ +{ + "description": "Imports print in code-unit order, one per line, with no blank line between packages. A name used twice is imported once, and an aliased import sorts by its qualified name.", + "dialect": "kotlin", + "ops": [ + [ + "package", + "com.acme" + ], + [ + "use", + "java.util.UUID" + ], + [ + "use", + "com.acme.other.Zed" + ], + [ + "useAs", + "org.jetbrains.exposed.sql.Table", + "ExposedTable" + ], + [ + "use", + "java.time.Instant" + ], + [ + "use", + "java.time.Instant" + ], + [ + "line", + "class A" + ] + ], + "expected": [ + "package com.acme", + "", + "import com.acme.other.Zed", + "import java.time.Instant", + "import java.util.UUID", + "import org.jetbrains.exposed.sql.Table as ExposedTable", + "", + "class A" + ] +} diff --git a/fixtures/writer-conformance/cases/kotlin-imports-conflict.json b/fixtures/writer-conformance/cases/kotlin-imports-conflict.json new file mode 100644 index 0000000000..26fabc2108 --- /dev/null +++ b/fixtures/writer-conformance/cases/kotlin-imports-conflict.json @@ -0,0 +1,15 @@ +{ + "description": "One local name imported from two places is an error, not a silent shadow; an alias is how a generator says both.", + "dialect": "kotlin", + "ops": [ + [ + "use", + "java.util.Date" + ], + [ + "use", + "java.sql.Date" + ] + ], + "error": "ERR_WRITER_IMPORT_CONFLICT" +} diff --git a/fixtures/writer-conformance/cases/kotlin-imports-skip-default-and-package.json b/fixtures/writer-conformance/cases/kotlin-imports-skip-default-and-package.json new file mode 100644 index 0000000000..f5753178f8 --- /dev/null +++ b/fixtures/writer-conformance/cases/kotlin-imports-skip-default-and-package.json @@ -0,0 +1,37 @@ +{ + "description": "A name in a package Kotlin imports by default (kotlin, kotlin.collections, java.lang and the rest) or in the file's own package imports nothing, whichever order the package and the names were given in; a subpackage of a default package is imported.", + "dialect": "kotlin", + "ops": [ + [ + "use", + "kotlin.collections.LinkedHashMap" + ], + [ + "use", + "java.lang.IllegalStateException" + ], + [ + "use", + "com.acme.Sibling" + ], + [ + "use", + "kotlin.math.abs" + ], + [ + "package", + "com.acme" + ], + [ + "line", + "class A" + ] + ], + "expected": [ + "package com.acme", + "", + "import kotlin.math.abs", + "", + "class A" + ] +} diff --git a/fixtures/writer-conformance/cases/kotlin-keyword-segments-escaped.json b/fixtures/writer-conformance/cases/kotlin-keyword-segments-escaped.json new file mode 100644 index 0000000000..a71c60d339 --- /dev/null +++ b/fixtures/writer-conformance/cases/kotlin-keyword-segments-escaped.json @@ -0,0 +1,25 @@ +{ + "description": "A hard keyword used as a package or import segment is written in backticks, so the line parses.", + "dialect": "kotlin", + "ops": [ + [ + "package", + "com.acme.object" + ], + [ + "use", + "com.metaobjects.object.MetaObject" + ], + [ + "line", + "class A" + ] + ], + "expected": [ + "package com.acme.`object`", + "", + "import com.metaobjects.`object`.MetaObject", + "", + "class A" + ] +} diff --git a/fixtures/writer-conformance/cases/kotlin-package-without-imports.json b/fixtures/writer-conformance/cases/kotlin-package-without-imports.json new file mode 100644 index 0000000000..8e63e86271 --- /dev/null +++ b/fixtures/writer-conformance/cases/kotlin-package-without-imports.json @@ -0,0 +1,19 @@ +{ + "description": "A file with a package line and no imports has no import block; an empty package prints no package line.", + "dialect": "kotlin", + "ops": [ + [ + "package", + "com.acme.api" + ], + [ + "line", + "interface A" + ] + ], + "expected": [ + "package com.acme.api", + "", + "interface A" + ] +} diff --git a/fixtures/writer-conformance/cases/kotlin-reopen.json b/fixtures/writer-conformance/cases/kotlin-reopen.json new file mode 100644 index 0000000000..7a72ad520e --- /dev/null +++ b/fixtures/writer-conformance/cases/kotlin-reopen.json @@ -0,0 +1,36 @@ +{ + "description": "reopen() closes the open block and opens the next on one line, as in `} else {`; a blank-line request before it is dropped.", + "dialect": "kotlin", + "ops": [ + [ + "open", + "if (ready) {" + ], + [ + "line", + "go()" + ], + [ + "blank" + ], + [ + "reopen", + "} else {" + ], + [ + "line", + "wait()" + ], + [ + "close", + "}" + ] + ], + "expected": [ + "if (ready) {", + " go()", + "} else {", + " wait()", + "}" + ] +} diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 961e8b5f78..b101f6aa3f 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -1010,7 +1010,7 @@ gate_conf_kotlin() { local k=com.metaobjects.generator.kotlin ( cd server/java \ && mvn -pl codegen-kotlin -am test -q -Dsurefire.failIfNoSpecifiedTests=false \ - -Dtest="$k.ObjectModelConformanceTest,$k.OutputPromptConformanceTest,$k.ValidationConformanceTest,$k.GeneratorRegistryConformanceTest,$k.RegistryManifestConformanceTest,$k.NoMagicPhysicalNamesTest,$k.CodegenCompileConformanceTest,$k.EjectContractTest" ) + -Dtest="$k.ObjectModelConformanceTest,$k.OutputPromptConformanceTest,$k.ValidationConformanceTest,$k.GeneratorRegistryConformanceTest,$k.RegistryManifestConformanceTest,$k.NoMagicPhysicalNamesTest,$k.CodegenCompileConformanceTest,$k.EjectContractTest,$k.writer.KotlinWriterConformanceTest,$k.writer.layout.KotlinLayoutRatchetTest" ) } # ── conformance.yml — full reactor + drift/mutation gates ───────────────────── diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDecimalWireEmitter.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDecimalWireEmitter.kt index 3c3f13449d..dbe65197a3 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDecimalWireEmitter.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDecimalWireEmitter.kt @@ -1,6 +1,7 @@ package com.metaobjects.generator.kotlin import com.metaobjects.config.WireFormat +import com.metaobjects.generator.kotlin.writer.KotlinWriter import com.metaobjects.generator.util.GeneratedFileWriter import java.nio.file.Path @@ -21,221 +22,238 @@ object KotlinDecimalWireEmitter { /** Write `MetaDecimalWire.kt` into [pkg] under [outRoot]. */ fun write(pkg: String, outRoot: Path, wire: WireFormat) { - val header = if (pkg.isEmpty()) "" else "package $pkg\n\n" val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve("$FILE_NAME.kt") - GeneratedFileWriter.write(outFile, header + body(wire) + "\n") + GeneratedFileWriter.write(outFile, render(pkg, wire)) } - /** - * The body for [wire] (ADR-0019 Amendment 2): the output [MetaDecimalWire.Serializer] exists only - * under `decimals: string`; under `native` Jackson writes a BigDecimal as the host configures it. - * The strict input half (parse, range checks, [MetaDecimalWire.Deserializer]) is in every mode. - */ - fun body(wire: WireFormat): String { - if (wire.decimalsAsString()) return BODY - val start = BODY.indexOf(SERIALIZER_START) - val end = BODY.indexOf(SERIALIZER_END, start) - check(start >= 0 && end > start) { "serializer block markers missing from the decimal wire body" } - var out = BODY.substring(0, start) + BODY.substring(end + SERIALIZER_END.length) - for (imp in SERIALIZER_IMPORTS) out = out.replace(imp, "") - return out.replace("written as a canonical string (plain notation, no trailing fraction zeros, zero as \"0\"),\n * and read", - "written as the host serializer writes it,\n * and read") + /** The file for [pkg] under [wire]: its package line, the imports and the body. */ + fun render(pkg: String, wire: WireFormat): String { + val w = KotlinWriter().packageName(pkg) + writeBody(w, wire) + return w.toString() } - private const val SERIALIZER_START = " /** Writes a decimal as its canonical string. */\n" - private const val SERIALIZER_END = "\n }\n\n" - private val SERIALIZER_IMPORTS = listOf( - "import com.fasterxml.jackson.core.JsonGenerator\n", - "import com.fasterxml.jackson.databind.SerializerProvider\n", - "import com.fasterxml.jackson.databind.ser.std.StdSerializer\n", - ) + /** The file for [wire] with no package line, for a caller that places it in a package of its own. */ + fun body(wire: WireFormat): String = render("", wire) + + /** The file under `decimals: string` with no package line. */ + val BODY: String get() = render("", WireFormat(WireFormat.Decimals.STRING, null, null)) /** - * The fixed body. `+`-concatenated messages and no Kotlin string templates, so this raw string - * needs no `$` escaping. Depends on Jackson only, which a generated entity already imports. + * The imports and the body for [wire] (ADR-0019 Amendment 2): the output + * [MetaDecimalWire.Serializer] exists only under `decimals: string`; under `native` Jackson + * writes a BigDecimal as the host configures it. The strict input half (parse, range checks, + * [MetaDecimalWire.Deserializer]) is in every mode. No Kotlin string templates, so the + * snippets need no `$` escaping. */ - val BODY: String = """ - |import com.fasterxml.jackson.core.JsonGenerator - |import com.fasterxml.jackson.core.JsonParser - |import com.fasterxml.jackson.core.JsonToken - |import com.fasterxml.jackson.databind.DeserializationContext - |import com.fasterxml.jackson.databind.BeanProperty - |import com.fasterxml.jackson.databind.JsonDeserializer - |import com.fasterxml.jackson.databind.JsonMappingException - |import com.fasterxml.jackson.databind.JsonNode - |import com.fasterxml.jackson.databind.SerializerProvider - |import com.fasterxml.jackson.databind.deser.ContextualDeserializer - |import com.fasterxml.jackson.databind.deser.std.StdDeserializer - |import com.fasterxml.jackson.databind.exc.InvalidFormatException - |import com.fasterxml.jackson.databind.ser.std.StdSerializer - |import java.math.BigDecimal - |import java.math.MathContext - |import java.math.RoundingMode - | - |/** - | * GENERATED (ADR-0019 Amendment 1) — do not hand-edit. The decimal wire rule: a decimal is - | * written as a canonical string (plain notation, no trailing fraction zeros, zero as "0"), - | * and read from a string or number in the JSON-number grammar, exactly, never through a - | * binary float. Dependency-free (Jackson only). - | */ - |internal object MetaDecimalWire { - | private val JSON_NUMBER = Regex("-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE][+-]?[0-9]+)?") - | private const val MAX_INTEGER_DIGITS = 131072 - | private const val MAX_FRACTION_DIGITS = 16383 - | private const val SQLITE_SIGNIFICANT_DIGITS = 15 - | - | /** The canonical string of a decimal: plain notation, no trailing fraction zeros, zero as "0". */ - | fun format(value: BigDecimal?): String? { - | if (value == null) return null - | if (value.signum() == 0) return "0" - | return value.stripTrailingZeros().toPlainString() - | } - | - | /** Strict read of a decimal string (the JSON-number grammar; an exponent is allowed). */ - | fun parse(text: String?): BigDecimal { - | require(text != null && JSON_NUMBER.matches(text)) { "not a decimal: " + text } - | val value = try { - | BigDecimal(text) - | } catch (e: NumberFormatException) { - | throw IllegalArgumentException("decimal out of range: " + text) - | } - | return checkRange(value, text) - | } - | - | /** A filter operand: parsed exactly, the same grammar as a body value. */ - | fun parseFilterOperand(text: String): BigDecimal = parse(text) - | - | /** A JSON number token already parsed as a decimal (never a double). */ - | fun fromJsonNumber(value: BigDecimal): BigDecimal = checkRange(value, value.toString()) - | - | /** A decimal from a JSON node: a string or a number, anything else is rejected. */ - | fun fromNode(node: JsonNode): BigDecimal { - | if (node.isTextual) return parse(node.asText()) - | if (node.isNumber) return fromJsonNumber(node.decimalValue()) - | throw IllegalArgumentException("not a decimal: " + node) - | } - | - | /** SQLite keeps a REAL: a stored double reads at 15 significant digits, so 0.1 + 0.2 reads 0.3. */ - | fun fromDouble15(value: Double): BigDecimal { - | require(!value.isNaN() && !value.isInfinite()) { "not a finite decimal: " + value } - | if (value == 0.0) return BigDecimal.ZERO - | val rounded = BigDecimal(value).round(MathContext(SQLITE_SIGNIFICANT_DIGITS, RoundingMode.HALF_EVEN)) - | return if (rounded.signum() == 0) BigDecimal.ZERO else rounded.stripTrailingZeros() - | } - | - | /** True when [value] fits decimal(precision, scale): at most scale fraction digits and precision - scale integer digits. */ - | fun fits(value: BigDecimal?, precision: Int, scale: Int): Boolean { - | if (value == null || value.signum() == 0) return true - | val stripped = value.stripTrailingZeros() - | val integerDigits = maxOf(0L, stripped.precision().toLong() - stripped.scale()) - | val fractionDigits = maxOf(0, stripped.scale()) - | return fractionDigits <= scale && integerDigits <= precision.toLong() - scale - | } - | - | private fun checkRange(value: BigDecimal, shown: String): BigDecimal { - | if (value.signum() == 0) return BigDecimal.ZERO - | val stripped = value.stripTrailingZeros() - | val integerDigits = stripped.precision().toLong() - stripped.scale() - | require(integerDigits <= MAX_INTEGER_DIGITS && stripped.scale() <= MAX_FRACTION_DIGITS) { - | "decimal out of range: " + shown - | } - | return value - | } - | - | /** - | * The Zod-style code for a binding failure: a decimal over its precision/scale or range is too_big, an - | * unknown enum member invalid_value, a malformed date/time/uuid/uri invalid_format, anything else (a - | * wrong JSON type, an unparseable value) invalid_type. - | */ - | fun failureCode(failure: Throwable): String { - | var t: Throwable? = failure - | while (t != null) { - | val message = t.message - | if (t is InvalidFormatException) { - | val target = t.targetType - | if (target != null) { - | if (target.isEnum) return "invalid_value" - | val n = target.name - | if (n.startsWith("java.time.") || n == "java.util.UUID" || n == "java.net.URI" || - | n == "java.net.URL" || n == "java.util.Date") return "invalid_format" - | } - | if (message != null && message.contains(": decimal out of range: ")) return "too_big" - | } - | if (t is IllegalArgumentException && message != null && message.startsWith("decimal out of range: ")) return "too_big" - | t = if (t.cause === t) null else t.cause - | } - | return "invalid_type" - | } - | - | /** - | * The validation envelope for a request body Jackson could not read: one issue whose path is every property - | * Jackson was binding (empty when the body as a whole cannot be read), plus the last field name as `field`. - | */ - | fun unreadableBody(failure: Throwable): Map { - | val path = ArrayList() - | var t: Throwable? = failure - | while (t != null) { - | if (t is JsonMappingException && t.path.isNotEmpty()) { - | for (ref in t.path) { - | if (ref.fieldName != null) path.add(ref.fieldName) else if (ref.index >= 0) path.add(ref.index) - | } - | break - | } - | t = if (t.cause === t) null else t.cause - | } - | val message = if (path.isEmpty()) "request body is not readable" else "field '" + path[path.size - 1] + "' is not a valid value" - | val issue = linkedMapOf("code" to failureCode(failure), "path" to path, "message" to message) - | val out = LinkedHashMap() - | out["error"] = "validation" - | out["issues"] = listOf(issue) - | val field = path.lastOrNull { it is String } - | if (field != null) out["field"] = field - | return out - | } - | - | /** Writes a decimal as its canonical string. */ - | class Serializer : StdSerializer(BigDecimal::class.java) { - | override fun serialize(value: BigDecimal, gen: JsonGenerator, provider: SerializerProvider) { - | gen.writeString(format(value)) - | } - | } - | - | /** - | * The `@precision` and `@scale` a decimal inside a value object declares. [Deserializer] reads it - | * from the property it is bound to and refuses, with a 400, a value the field cannot hold - | * (more fraction digits than [scale], or more integer digits than precision - scale). Trailing - | * zeros do not count and nothing is rounded. - | */ - | @Retention(AnnotationRetention.RUNTIME) - | @Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.PROPERTY, AnnotationTarget.FIELD) - | annotation class Declared(val precision: Int, val scale: Int) - | - | /** - | * Reads a decimal from a string or a number, exactly; anything else is a 400-shaped mapping - | * error. A property carrying [Declared] is also range-checked against it. - | */ - | class Deserializer(private val precision: Int? = null, private val scale: Int = 0) : - | StdDeserializer(BigDecimal::class.java), ContextualDeserializer { - | override fun createContextual(ctxt: DeserializationContext, property: BeanProperty?): JsonDeserializer<*> { - | val declared = property?.getAnnotation(Declared::class.java) ?: return this - | return Deserializer(declared.precision, declared.scale) - | } - | - | override fun deserialize(p: JsonParser, ctxt: DeserializationContext): BigDecimal? { - | val token = p.currentToken() - | try { - | val value = when (token) { - | JsonToken.VALUE_STRING -> parse(p.text) - | JsonToken.VALUE_NUMBER_INT, JsonToken.VALUE_NUMBER_FLOAT -> fromJsonNumber(p.decimalValue) - | else -> return ctxt.handleUnexpectedToken(BigDecimal::class.java, p) as BigDecimal? - | } - | require(precision == null || fits(value, precision, scale)) { "decimal out of range: " + value } - | return value - | } catch (e: IllegalArgumentException) { - | return ctxt.handleWeirdStringValue(BigDecimal::class.java, p.text, "%s", e.message) as BigDecimal? - | } - | } - | } - |} - |""".trimMargin() + fun writeBody(w: KotlinWriter, wire: WireFormat) { + val asString = wire.decimalsAsString() + w.use("com.fasterxml.jackson.core.JsonParser") + w.use("com.fasterxml.jackson.core.JsonToken") + w.use("com.fasterxml.jackson.databind.DeserializationContext") + w.use("com.fasterxml.jackson.databind.BeanProperty") + w.use("com.fasterxml.jackson.databind.JsonDeserializer") + w.use("com.fasterxml.jackson.databind.JsonMappingException") + w.use("com.fasterxml.jackson.databind.JsonNode") + w.use("com.fasterxml.jackson.databind.deser.ContextualDeserializer") + w.use("com.fasterxml.jackson.databind.deser.std.StdDeserializer") + w.use("com.fasterxml.jackson.databind.exc.InvalidFormatException") + w.use("java.math.BigDecimal") + w.use("java.math.MathContext") + w.use("java.math.RoundingMode") + if (asString) { + w.use("com.fasterxml.jackson.core.JsonGenerator") + w.use("com.fasterxml.jackson.databind.SerializerProvider") + w.use("com.fasterxml.jackson.databind.ser.std.StdSerializer") + } + w.text( + """ + /** + * GENERATED (ADR-0019 Amendment 1) — do not hand-edit. The decimal wire rule: a decimal is + """ + ) + w.line( + if (asString) " * written as a canonical string (plain notation, no trailing fraction zeros, zero as \"0\")," + else " * written as the host serializer writes it,", + ) + w.text( + """ + * and read from a string or number in the JSON-number grammar, exactly, never through a + * binary float. Dependency-free (Jackson only). + */ + internal object MetaDecimalWire { + private val JSON_NUMBER = Regex("-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE][+-]?[0-9]+)?") + private const val MAX_INTEGER_DIGITS = 131072 + private const val MAX_FRACTION_DIGITS = 16383 + private const val SQLITE_SIGNIFICANT_DIGITS = 15 + + /** The canonical string of a decimal: plain notation, no trailing fraction zeros, zero as "0". */ + fun format(value: BigDecimal?): String? { + if (value == null) return null + if (value.signum() == 0) return "0" + return value.stripTrailingZeros().toPlainString() + } + + /** Strict read of a decimal string (the JSON-number grammar; an exponent is allowed). */ + fun parse(text: String?): BigDecimal { + require(text != null && JSON_NUMBER.matches(text)) { "not a decimal: " + text } + val value = try { + BigDecimal(text) + } catch (e: NumberFormatException) { + throw IllegalArgumentException("decimal out of range: " + text) + } + return checkRange(value, text) + } + + /** A filter operand: parsed exactly, the same grammar as a body value. */ + fun parseFilterOperand(text: String): BigDecimal = parse(text) + + /** A JSON number token already parsed as a decimal (never a double). */ + fun fromJsonNumber(value: BigDecimal): BigDecimal = checkRange(value, value.toString()) + + /** A decimal from a JSON node: a string or a number, anything else is rejected. */ + fun fromNode(node: JsonNode): BigDecimal { + if (node.isTextual) return parse(node.asText()) + if (node.isNumber) return fromJsonNumber(node.decimalValue()) + throw IllegalArgumentException("not a decimal: " + node) + } + + /** SQLite keeps a REAL: a stored double reads at 15 significant digits, so 0.1 + 0.2 reads 0.3. */ + fun fromDouble15(value: Double): BigDecimal { + require(!value.isNaN() && !value.isInfinite()) { "not a finite decimal: " + value } + if (value == 0.0) return BigDecimal.ZERO + val rounded = BigDecimal(value).round(MathContext(SQLITE_SIGNIFICANT_DIGITS, RoundingMode.HALF_EVEN)) + return if (rounded.signum() == 0) BigDecimal.ZERO else rounded.stripTrailingZeros() + } + + /** True when [value] fits decimal(precision, scale): at most scale fraction digits and precision - scale integer digits. */ + fun fits(value: BigDecimal?, precision: Int, scale: Int): Boolean { + if (value == null || value.signum() == 0) return true + val stripped = value.stripTrailingZeros() + val integerDigits = maxOf(0L, stripped.precision().toLong() - stripped.scale()) + val fractionDigits = maxOf(0, stripped.scale()) + return fractionDigits <= scale && integerDigits <= precision.toLong() - scale + } + + private fun checkRange(value: BigDecimal, shown: String): BigDecimal { + if (value.signum() == 0) return BigDecimal.ZERO + val stripped = value.stripTrailingZeros() + val integerDigits = stripped.precision().toLong() - stripped.scale() + require(integerDigits <= MAX_INTEGER_DIGITS && stripped.scale() <= MAX_FRACTION_DIGITS) { + "decimal out of range: " + shown + } + return value + } + + /** + * The Zod-style code for a binding failure: a decimal over its precision/scale or range is too_big, an + * unknown enum member invalid_value, a malformed date/time/uuid/uri invalid_format, anything else (a + * wrong JSON type, an unparseable value) invalid_type. + */ + fun failureCode(failure: Throwable): String { + var t: Throwable? = failure + while (t != null) { + val message = t.message + if (t is InvalidFormatException) { + val target = t.targetType + if (target != null) { + if (target.isEnum) return "invalid_value" + val n = target.name + if (n.startsWith("java.time.") || n == "java.util.UUID" || n == "java.net.URI" || + n == "java.net.URL" || n == "java.util.Date") return "invalid_format" + } + if (message != null && message.contains(": decimal out of range: ")) return "too_big" + } + if (t is IllegalArgumentException && message != null && message.startsWith("decimal out of range: ")) return "too_big" + t = if (t.cause === t) null else t.cause + } + return "invalid_type" + } + + /** + * The validation envelope for a request body Jackson could not read: one issue whose path is every property + * Jackson was binding (empty when the body as a whole cannot be read), plus the last field name as `field`. + */ + fun unreadableBody(failure: Throwable): Map { + val path = ArrayList() + var t: Throwable? = failure + while (t != null) { + if (t is JsonMappingException && t.path.isNotEmpty()) { + for (ref in t.path) { + if (ref.fieldName != null) path.add(ref.fieldName) else if (ref.index >= 0) path.add(ref.index) + } + break + } + t = if (t.cause === t) null else t.cause + } + val message = if (path.isEmpty()) "request body is not readable" else "field '" + path[path.size - 1] + "' is not a valid value" + val issue = linkedMapOf("code" to failureCode(failure), "path" to path, "message" to message) + val out = LinkedHashMap() + out["error"] = "validation" + out["issues"] = listOf(issue) + val field = path.lastOrNull { it is String } + if (field != null) out["field"] = field + return out + } + """ + ) + w.blank() + if (asString) { + // The snippet is a member of the object, one level in. + w.indented { + w.text( + """ + /** Writes a decimal as its canonical string. */ + class Serializer : StdSerializer(BigDecimal::class.java) { + override fun serialize(value: BigDecimal, gen: JsonGenerator, provider: SerializerProvider) { + gen.writeString(format(value)) + } + } + """ + ) + } + w.blank() + } + w.text( + """ + /** + * The `@precision` and `@scale` a decimal inside a value object declares. [Deserializer] reads it + * from the property it is bound to and refuses, with a 400, a value the field cannot hold + * (more fraction digits than [scale], or more integer digits than precision - scale). Trailing + * zeros do not count and nothing is rounded. + */ + @Retention(AnnotationRetention.RUNTIME) + @Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.PROPERTY, AnnotationTarget.FIELD) + annotation class Declared(val precision: Int, val scale: Int) + + /** + * Reads a decimal from a string or a number, exactly; anything else is a 400-shaped mapping + * error. A property carrying [Declared] is also range-checked against it. + */ + class Deserializer(private val precision: Int? = null, private val scale: Int = 0) : + StdDeserializer(BigDecimal::class.java), ContextualDeserializer { + override fun createContextual(ctxt: DeserializationContext, property: BeanProperty?): JsonDeserializer<*> { + val declared = property?.getAnnotation(Declared::class.java) ?: return this + return Deserializer(declared.precision, declared.scale) + } + + override fun deserialize(p: JsonParser, ctxt: DeserializationContext): BigDecimal? { + val token = p.currentToken() + try { + val value = when (token) { + JsonToken.VALUE_STRING -> parse(p.text) + JsonToken.VALUE_NUMBER_INT, JsonToken.VALUE_NUMBER_FLOAT -> fromJsonNumber(p.decimalValue) + else -> return ctxt.handleUnexpectedToken(BigDecimal::class.java, p) as BigDecimal? + } + require(precision == null || fits(value, precision, scale)) { "decimal out of range: " + value } + return value + } catch (e: IllegalArgumentException) { + return ctxt.handleWeirdStringValue(BigDecimal::class.java, p.text, "%s", e.message) as BigDecimal? + } + } + } + } + """ + ) + } } diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDurationWireEmitter.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDurationWireEmitter.kt index 5ae52ab1aa..4f3877d397 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDurationWireEmitter.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDurationWireEmitter.kt @@ -1,5 +1,6 @@ package com.metaobjects.generator.kotlin +import com.metaobjects.generator.kotlin.writer.KotlinWriter import com.metaobjects.generator.util.GeneratedFileWriter import java.nio.file.Path @@ -28,176 +29,187 @@ object KotlinDurationWireEmitter { /** Write `MetaDurationWire.kt` into [pkg] under [outRoot]. */ fun write(pkg: String, outRoot: Path) { - val header = if (pkg.isEmpty()) "" else "package $pkg\n\n" val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve("$FILE_NAME.kt") - GeneratedFileWriter.write(outFile, header + BODY + "\n") + GeneratedFileWriter.write(outFile, render(pkg)) } + /** The file for [pkg]: its package line, the imports and the fixed body. */ + fun render(pkg: String): String { + val w = KotlinWriter().packageName(pkg) + writeBody(w) + return w.toString() + } + + /** The file with no package line, for a caller that places it in a package of its own. */ + val BODY: String get() = render("") + /** - * The fixed body. `+`-concatenated messages and no Kotlin string templates (every `$` below is - * a regex anchor followed by `)` or `"`), so this raw string needs no `$` escaping. Depends on - * Jackson only, which a generated entity already imports. + * The imports and the fixed body. No Kotlin string templates, so the snippet needs no `$` + * escaping. */ - val BODY: String = """ - |import com.fasterxml.jackson.core.JsonGenerator - |import com.fasterxml.jackson.core.JsonParser - |import com.fasterxml.jackson.core.JsonToken - |import com.fasterxml.jackson.databind.DeserializationContext - |import com.fasterxml.jackson.databind.JsonNode - |import com.fasterxml.jackson.databind.SerializerProvider - |import com.fasterxml.jackson.databind.deser.std.StdDeserializer - |import com.fasterxml.jackson.databind.ser.std.StdSerializer - |import java.time.Duration - | - |/** - | * GENERATED — do not hand-edit. The field.duration wire rule: a duration is written as the - | * canonical ISO-8601 string [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to nine - | * fractional digits, zero as PT0S) and read from the accepted form only: an optional sign, P, an - | * optional week count (W = exactly 7 days), an optional day count (D = exactly 24 hours), T and - | * hours/minutes/seconds (a fraction of any length, truncated toward zero to the nanosecond). - | * Years and months are refused: a calendar span has no fixed length. Dependency-free (Jackson only). - | */ - |internal object MetaDurationWire { - | private val ACCEPTED = Regex("^([-+])?P(?!$)(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?=\\d)(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)(?:\\.(\\d+))?S)?)?$") - | /** The text of pgjdbc's PGInterval: what a JDBC read of an interval column, or of an interval[] element, hands back. */ - | private val PG_INTERVAL = Regex("^(-?\\d+) years (-?\\d+) mons (-?\\d+) days (-?\\d+) hours (-?\\d+) mins (-?)(\\d+)(?:\\.(\\d+))? secs$") - | - | /** What a refused value should have been. */ - | const val EXPECTED = "an ISO-8601 duration such as PT1H30M (no years or months)" - | - | /** True when [text] is in the accepted ISO-8601 form and fits a Duration (refused past it, never wrapped). */ - | fun isDuration(text: String?): Boolean = - | text != null && ACCEPTED.matches(text) && runCatching { parse(text) }.isSuccess - | - | /** Strict read of an accepted ISO-8601 duration (digits past a nanosecond truncated toward zero). */ - | fun parse(text: String?): Duration { - | val m = (if (text == null) null else ACCEPTED.matchEntire(text)) - | ?: throw IllegalArgumentException("field.duration: not " + EXPECTED + ": " + text) - | try { - | val g = m.groupValues - | val seconds = Math.addExact( - | Math.addExact(Math.multiplyExact(num(g[2]), 604_800L), Math.multiplyExact(num(g[3]), 86_400L)), - | Math.addExact(Math.multiplyExact(num(g[4]), 3_600L), Math.addExact(Math.multiplyExact(num(g[5]), 60L), num(g[6])))) - | val d = Duration.ofSeconds(seconds, nanos(g[7])) - | return if (g[1] == "-") d.negated() else d - | } catch (e: ArithmeticException) { - | throw IllegalArgumentException("field.duration: out of range: " + text) - | } catch (e: NumberFormatException) { - | throw IllegalArgumentException("field.duration: out of range: " + text) - | } - | } - | - | /** The canonical wire form of [value], to the nanosecond (trailing zeros dropped). */ - | fun format(value: Duration): String { - | val negative = value.isNegative - | val mag = if (negative) value.negated() else value - | val total = mag.seconds - | val nanos = mag.nano.toLong() - | if (total == 0L && nanos == 0L) return "PT0S" - | val b = StringBuilder(if (negative) "-PT" else "PT") - | if (total / 3_600L > 0) b.append(total / 3_600L).append('H') - | if (total % 3_600L / 60L > 0) b.append(total % 3_600L / 60L).append('M') - | if (total % 60L > 0 || nanos > 0) { - | b.append(total % 60L) - | fraction(b, nanos, 9) - | b.append('S') - | } - | return b.toString() - | } - | - | /** - | * The Postgres interval input spelling `[-]HH:MM:SS[.f]`: Postgres refuses a signed ISO-8601 - | * duration. An interval holds microseconds, so a sub-microsecond part is truncated toward zero. - | */ - | fun formatPostgres(value: Duration): String { - | val mag = if (value.isNegative) value.negated() else value - | val total = mag.seconds - | val micros = mag.nano / 1_000L - | val b = StringBuilder(if (value.isNegative && (total != 0L || micros != 0L)) "-" else "") - | val h = total / 3_600L - | if (h < 10) b.append('0') - | b.append(h).append(':') - | if (total % 3_600L / 60L < 10) b.append('0') - | b.append(total % 3_600L / 60L).append(':') - | if (total % 60L < 10) b.append('0') - | b.append(total % 60L) - | fraction(b, micros, 6) - | return b.toString() - | } - | - | /** - | * A stored value: the ISO-8601 string a text column holds, or the text of the PGInterval pgjdbc - | * reads a Postgres interval as. An interval with a year or month part is refused, never - | * guessed at: a calendar span is not a duration. - | */ - | fun fromStored(text: String): Duration { - | if (ACCEPTED.matches(text)) return parse(text) - | val pg = PG_INTERVAL.matchEntire(text) ?: throw IllegalArgumentException("field.duration: not a stored duration: " + text) - | val g = pg.groupValues - | require(g[1].toLong() == 0L && g[2].toLong() == 0L) { - | "field.duration: the interval " + text + " has a year or month part; a calendar span is not a duration" - | } - | val secs = Duration.ofSeconds(g[7].toLong(), nanos(g[8])) - | return Duration.ofDays(g[3].toLong()).plusHours(g[4].toLong()).plusMinutes(g[5].toLong()) - | .plus(if (g[6] == "-") secs.negated() else secs) - | } - | - | /** - | * The 64-bit count of microseconds a SQLite / MySQL column stores (sub-microsecond precision - | * truncated toward zero); past the 64-bit range (that column's limit) it is refused. - | */ - | fun toMicros(value: Duration): Long { - | try { - | val mag = if (value.isNegative) value.negated() else value - | val micros = Math.addExact(Math.multiplyExact(mag.seconds, 1_000_000L), mag.nano / 1_000L) - | return if (value.isNegative) -micros else micros - | } catch (e: ArithmeticException) { - | throw IllegalArgumentException("field.duration: " + value + " is past a 64-bit count of microseconds") - | } - | } - | - | /** A stored count of microseconds as a duration. */ - | fun fromMicros(micros: Long): Duration = - | Duration.ofSeconds(Math.floorDiv(micros, 1_000_000L), Math.floorMod(micros, 1_000_000L) * 1_000L) - | - | /** A duration from a JSON node: an accepted string, anything else is rejected. */ - | fun fromNode(node: JsonNode): Duration { - | if (node.isTextual) return parse(node.asText()) - | throw IllegalArgumentException("field.duration: not a string: " + node) - | } - | - | private fun num(digits: String): Long = if (digits.isEmpty()) 0L else digits.toLong() - | - | /** A fraction of any length as whole nanoseconds, the digits past the ninth truncated toward zero. */ - | private fun nanos(frac: String): Long = - | if (frac.isEmpty()) 0L else (frac + "000000000").substring(0, 9).toLong() - | - | /** [value] as [width] zero-padded ASCII digits after a `.`, trailing zeros dropped. */ - | private fun fraction(b: StringBuilder, value: Long, width: Int) { - | if (value == 0L) return - | b.append('.').append(value.toString().padStart(width, '0').trimEnd('0')) - | } - | - | /** Writes a duration as its canonical ISO-8601 string, whatever the host ObjectMapper would do. */ - | class Serializer : StdSerializer(Duration::class.java) { - | override fun serialize(value: Duration, gen: JsonGenerator, provider: SerializerProvider) { - | gen.writeString(format(value)) - | } - | } - | - | /** Reads the accepted form only; a number of seconds, a calendar span or a clock string is a 400. */ - | class Deserializer : StdDeserializer(Duration::class.java) { - | override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Duration { - | if (p.currentToken() != JsonToken.VALUE_STRING) { - | return ctxt.handleUnexpectedToken(Duration::class.java, p) as Duration - | } - | return try { - | parse(p.text) - | } catch (e: IllegalArgumentException) { - | ctxt.handleWeirdStringValue(Duration::class.java, p.text, "%s", e.message) as Duration - | } - | } - | } - |} - """.trimMargin() + fun writeBody(w: KotlinWriter) { + w.use("com.fasterxml.jackson.core.JsonGenerator") + w.use("com.fasterxml.jackson.core.JsonParser") + w.use("com.fasterxml.jackson.core.JsonToken") + w.use("com.fasterxml.jackson.databind.DeserializationContext") + w.use("com.fasterxml.jackson.databind.JsonNode") + w.use("com.fasterxml.jackson.databind.SerializerProvider") + w.use("com.fasterxml.jackson.databind.deser.std.StdDeserializer") + w.use("com.fasterxml.jackson.databind.ser.std.StdSerializer") + w.use("java.time.Duration") + w.text( + """ + /** + * GENERATED — do not hand-edit. The field.duration wire rule: a duration is written as the + * canonical ISO-8601 string [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to nine + * fractional digits, zero as PT0S) and read from the accepted form only: an optional sign, P, an + * optional week count (W = exactly 7 days), an optional day count (D = exactly 24 hours), T and + * hours/minutes/seconds (a fraction of any length, truncated toward zero to the nanosecond). + * Years and months are refused: a calendar span has no fixed length. Dependency-free (Jackson only). + */ + internal object MetaDurationWire { + private val ACCEPTED = Regex("^([-+])?P(?!$)(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?=\\d)(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)(?:\\.(\\d+))?S)?)?$") + /** The text of pgjdbc's PGInterval: what a JDBC read of an interval column, or of an interval[] element, hands back. */ + private val PG_INTERVAL = Regex("^(-?\\d+) years (-?\\d+) mons (-?\\d+) days (-?\\d+) hours (-?\\d+) mins (-?)(\\d+)(?:\\.(\\d+))? secs$") + + /** What a refused value should have been. */ + const val EXPECTED = "an ISO-8601 duration such as PT1H30M (no years or months)" + + /** True when [text] is in the accepted ISO-8601 form and fits a Duration (refused past it, never wrapped). */ + fun isDuration(text: String?): Boolean = + text != null && ACCEPTED.matches(text) && runCatching { parse(text) }.isSuccess + + /** Strict read of an accepted ISO-8601 duration (digits past a nanosecond truncated toward zero). */ + fun parse(text: String?): Duration { + val m = (if (text == null) null else ACCEPTED.matchEntire(text)) + ?: throw IllegalArgumentException("field.duration: not " + EXPECTED + ": " + text) + try { + val g = m.groupValues + val seconds = Math.addExact( + Math.addExact(Math.multiplyExact(num(g[2]), 604_800L), Math.multiplyExact(num(g[3]), 86_400L)), + Math.addExact(Math.multiplyExact(num(g[4]), 3_600L), Math.addExact(Math.multiplyExact(num(g[5]), 60L), num(g[6])))) + val d = Duration.ofSeconds(seconds, nanos(g[7])) + return if (g[1] == "-") d.negated() else d + } catch (e: ArithmeticException) { + throw IllegalArgumentException("field.duration: out of range: " + text) + } catch (e: NumberFormatException) { + throw IllegalArgumentException("field.duration: out of range: " + text) + } + } + + /** The canonical wire form of [value], to the nanosecond (trailing zeros dropped). */ + fun format(value: Duration): String { + val negative = value.isNegative + val mag = if (negative) value.negated() else value + val total = mag.seconds + val nanos = mag.nano.toLong() + if (total == 0L && nanos == 0L) return "PT0S" + val b = StringBuilder(if (negative) "-PT" else "PT") + if (total / 3_600L > 0) b.append(total / 3_600L).append('H') + if (total % 3_600L / 60L > 0) b.append(total % 3_600L / 60L).append('M') + if (total % 60L > 0 || nanos > 0) { + b.append(total % 60L) + fraction(b, nanos, 9) + b.append('S') + } + return b.toString() + } + + /** + * The Postgres interval input spelling `[-]HH:MM:SS[.f]`: Postgres refuses a signed ISO-8601 + * duration. An interval holds microseconds, so a sub-microsecond part is truncated toward zero. + */ + fun formatPostgres(value: Duration): String { + val mag = if (value.isNegative) value.negated() else value + val total = mag.seconds + val micros = mag.nano / 1_000L + val b = StringBuilder(if (value.isNegative && (total != 0L || micros != 0L)) "-" else "") + val h = total / 3_600L + if (h < 10) b.append('0') + b.append(h).append(':') + if (total % 3_600L / 60L < 10) b.append('0') + b.append(total % 3_600L / 60L).append(':') + if (total % 60L < 10) b.append('0') + b.append(total % 60L) + fraction(b, micros, 6) + return b.toString() + } + + /** + * A stored value: the ISO-8601 string a text column holds, or the text of the PGInterval pgjdbc + * reads a Postgres interval as. An interval with a year or month part is refused, never + * guessed at: a calendar span is not a duration. + */ + fun fromStored(text: String): Duration { + if (ACCEPTED.matches(text)) return parse(text) + val pg = PG_INTERVAL.matchEntire(text) ?: throw IllegalArgumentException("field.duration: not a stored duration: " + text) + val g = pg.groupValues + require(g[1].toLong() == 0L && g[2].toLong() == 0L) { + "field.duration: the interval " + text + " has a year or month part; a calendar span is not a duration" + } + val secs = Duration.ofSeconds(g[7].toLong(), nanos(g[8])) + return Duration.ofDays(g[3].toLong()).plusHours(g[4].toLong()).plusMinutes(g[5].toLong()) + .plus(if (g[6] == "-") secs.negated() else secs) + } + + /** + * The 64-bit count of microseconds a SQLite / MySQL column stores (sub-microsecond precision + * truncated toward zero); past the 64-bit range (that column's limit) it is refused. + */ + fun toMicros(value: Duration): Long { + try { + val mag = if (value.isNegative) value.negated() else value + val micros = Math.addExact(Math.multiplyExact(mag.seconds, 1_000_000L), mag.nano / 1_000L) + return if (value.isNegative) -micros else micros + } catch (e: ArithmeticException) { + throw IllegalArgumentException("field.duration: " + value + " is past a 64-bit count of microseconds") + } + } + + /** A stored count of microseconds as a duration. */ + fun fromMicros(micros: Long): Duration = + Duration.ofSeconds(Math.floorDiv(micros, 1_000_000L), Math.floorMod(micros, 1_000_000L) * 1_000L) + + /** A duration from a JSON node: an accepted string, anything else is rejected. */ + fun fromNode(node: JsonNode): Duration { + if (node.isTextual) return parse(node.asText()) + throw IllegalArgumentException("field.duration: not a string: " + node) + } + + private fun num(digits: String): Long = if (digits.isEmpty()) 0L else digits.toLong() + + /** A fraction of any length as whole nanoseconds, the digits past the ninth truncated toward zero. */ + private fun nanos(frac: String): Long = + if (frac.isEmpty()) 0L else (frac + "000000000").substring(0, 9).toLong() + + /** [value] as [width] zero-padded ASCII digits after a `.`, trailing zeros dropped. */ + private fun fraction(b: StringBuilder, value: Long, width: Int) { + if (value == 0L) return + b.append('.').append(value.toString().padStart(width, '0').trimEnd('0')) + } + + /** Writes a duration as its canonical ISO-8601 string, whatever the host ObjectMapper would do. */ + class Serializer : StdSerializer(Duration::class.java) { + override fun serialize(value: Duration, gen: JsonGenerator, provider: SerializerProvider) { + gen.writeString(format(value)) + } + } + + /** Reads the accepted form only; a number of seconds, a calendar span or a clock string is a 400. */ + class Deserializer : StdDeserializer(Duration::class.java) { + override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Duration { + if (p.currentToken() != JsonToken.VALUE_STRING) { + return ctxt.handleUnexpectedToken(Duration::class.java, p) as Duration + } + return try { + parse(p.text) + } catch (e: IllegalArgumentException) { + ctxt.handleWeirdStringValue(Duration::class.java, p.text, "%s", e.message) as Duration + } + } + } + } + """ + ) + } } diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExtractorGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExtractorGenerator.kt index 66ffdbff75..75ec578731 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExtractorGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExtractorGenerator.kt @@ -7,6 +7,7 @@ package com.metaobjects.generator.kotlin import com.metaobjects.generator.kotlin.FindInbound import com.metaobjects.generator.kotlin.KotlinNaming import com.metaobjects.generator.kotlin.PackageMapping +import com.metaobjects.generator.kotlin.writer.KotlinWriter import com.metaobjects.generator.GeneratorIOWriter import com.metaobjects.generator.direct.MultiFileDirectGeneratorBase @@ -76,65 +77,42 @@ open class KotlinExtractorGenerator : MultiFileDirectGeneratorBase() val strict = KotlinNaming.strictRef(responseVo) val mirror = KotlinNaming.mirrorRef(responseVo) - val src = buildString { - append("// GENERATED — DO NOT EDIT — extractor for template.prompt `") - append(template.name) - append("`\n") - append(KotlinNaming.packageHeader(outPkg)) - append("import com.metaobjects.loader.MetaDataLoader\n") - append("import com.metaobjects.render.extract.ExtractException\n") - append("import com.metaobjects.render.extract.ExtractOptions\n") - append("import com.metaobjects.render.extract.ExtractionResult\n") - append("\n") - append("/**\n") - append(" * The `extract` tier for the `") - append(templateShort) - append("` template.prompt — turns dirty LLM text into a fully-typed\n") - append(" * [") - append(strict) - append("] graph (nested objects + arrays-of-objects populated) in one call.\n") - append(" */\n") - append("object ") - append(extractorClass) - append(" {\n") - append("\n") - append(" /**\n") - append(" * Extract a fully-typed [") - append(strict) - append("] from dirty [text], resolving the response shape's MetaObject\n") - append(" * from [loader]. Runs the tolerant extract, then converts the mirror to the strict value object.\n") - append(" *\n") - append(" * @throws ExtractException iff a `@required` field was lost, or present but unusable\n") - append(" * (MALFORMED — an undeclared enum member, text where a number belongs): the strict opt-in gate.\n") - append(" */\n") - append(" @JvmOverloads\n") - append(" fun extract(loader: MetaDataLoader, text: String, opts: ExtractOptions = ExtractOptions.defaults()): ") - append(strict) - append(" {\n") - append(" val r = ") - append(parserClass) - append(".extractLenient(loader, text, opts)\n") - append(" if (r.report.hasLostRequired() || r.report.hasMalformedRequired()) {\n") - append(" throw ExtractException(r.report.lostRequired(), r.report.malformedRequired())\n") - append(" }\n") - append(" return r.data!!.toStrict()\n") - append(" }\n") - append("\n") - append(" /**\n") - append(" * Re-exposes the nested-capable tolerant extract; never throws. Inspect `report` for\n") - append(" * lost/malformed/defaulted fields. Returns the all-nullable [") - append(mirror) - append("] mirror (not the strict value object).\n") - append(" */\n") - append(" @JvmOverloads\n") - append(" fun extractLenient(loader: MetaDataLoader, text: String, opts: ExtractOptions = ExtractOptions.defaults()): ExtractionResult<") - append(mirror) - append("> =\n") - append(" ") - append(parserClass) - append(".extractLenient(loader, text, opts)\n") - append("}\n") + val w = KotlinWriter().packageName(outPkg) + w.header("// GENERATED — DO NOT EDIT — extractor for template.prompt `${template.name}`") + w.use("com.metaobjects.loader.MetaDataLoader") + w.use("com.metaobjects.render.extract.ExtractException") + w.use("com.metaobjects.render.extract.ExtractOptions") + w.use("com.metaobjects.render.extract.ExtractionResult") + w.doc( + "The `extract` tier for the `$templateShort` template.prompt — turns dirty LLM text into a fully-typed", + "[$strict] graph (nested objects + arrays-of-objects populated) in one call.", + ) + w.block("object $extractorClass {") { + w.doc( + "Extract a fully-typed [$strict] from dirty [text], resolving the response shape's MetaObject", + "from [loader]. Runs the tolerant extract, then converts the mirror to the strict value object.", + "", + "@throws ExtractException iff a `@required` field was lost, or present but unusable (MALFORMED — an", + "undeclared enum member, text where a number belongs): the strict opt-in gate.", + ) + w.line("@JvmOverloads") + w.block("fun extract(loader: MetaDataLoader, text: String, opts: ExtractOptions = ExtractOptions.defaults()): $strict {") { + w.line("val r = $parserClass.extractLenient(loader, text, opts)") + w.block("if (r.report.hasLostRequired() || r.report.hasMalformedRequired()) {") { + w.line("throw ExtractException(r.report.lostRequired(), r.report.malformedRequired())") + } + w.line("return r.data!!.toStrict()") + } + w.blank() + w.doc( + "Re-exposes the nested-capable tolerant extract; never throws. Inspect `report` for", + "lost/malformed/defaulted fields. Returns the all-nullable [$mirror] mirror (not the strict value object).", + ) + w.line("@JvmOverloads") + w.line("fun extractLenient(loader: MetaDataLoader, text: String, opts: ExtractOptions = ExtractOptions.defaults()): ExtractionResult<$mirror> =") + w.indented { w.line("$parserClass.extractLenient(loader, text, opts)") } } + val src = w.toString() val outFile = outRoot.resolve(outPkg.replace('.', '/')).resolve("$extractorClass.kt") GeneratedFileWriter.write(outFile, src) diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinFilterAllowlistGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinFilterAllowlistGenerator.kt index 8b1415455e..59094d9ea0 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinFilterAllowlistGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinFilterAllowlistGenerator.kt @@ -8,6 +8,7 @@ import com.metaobjects.generator.kotlin.KotlinGenUtil import com.metaobjects.generator.kotlin.KotlinNaming import com.metaobjects.generator.kotlin.KotlinTphPlan import com.metaobjects.generator.kotlin.PackageMapping +import com.metaobjects.generator.kotlin.writer.KotlinWriter import com.metaobjects.field.MetaField import com.metaobjects.field.MapField @@ -116,58 +117,38 @@ open class KotlinFilterAllowlistGenerator : MultiFileDirectGeneratorBase()` so the property has an inferable type even when no fields - // are filterable (the controller's generated parser binds against this). - append(" val FIELDS: Set = ") - if (opsByField.isEmpty()) { - append("emptySet()\n\n") - } else { - append("setOf(\n") - for (f in opsByField.keys) { - append(" \"$f\",\n") - } - append(" )\n\n") - } + val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve("$className.kt") + GeneratedFileWriter.write(outFile, render(pkg, shortName, className, opsByField)) + } - // OPS_BY_FIELD — `Map>`. Empty map uses `emptyMap()` for - // the same type-inferability reason; populated case uses mapOf("name" to setOf(...)). - append(" val OPS_BY_FIELD: Map> = ") - if (opsByField.isEmpty()) { - append("emptyMap()\n") - } else { - append("mapOf(\n") - val entries = opsByField.entries.toList() - for ((i, e) in entries.withIndex()) { - append(" \"${e.key}\" to setOf(") - var firstOp = true - for (op in e.value) { - if (!firstOp) append(", ") - firstOp = false - append("\"$op\"") - } - append(")") - if (i < entries.size - 1) append(",") - append("\n") - } - append(" )\n") - } - append("}\n") + /** The allowlist file: the package line, its KDoc and the `object` holding the two constants. */ + protected open fun render(pkg: String, shortName: String, className: String, opsByField: Map>): String { + val w = KotlinWriter().packageName(pkg) + w.doc( + "GENERATED — per-entity FR-009 filter allowlist for $shortName.", + "FIELDS lists the filterable field names; OPS_BY_FIELD constrains the", + "operator vocabulary for each field by its subtype.", + ) + w.block("object $className {") { + // The empty cases use `emptySet()` / `emptyMap()` so each property has an inferable type even + // when no fields are filterable (the controller's generated parser binds against this). + w.line( + "val FIELDS: Set = ", + if (opsByField.isEmpty()) "emptySet()" else KotlinWriter.call("setOf", *opsByField.keys.map { KotlinWriter.str(it) }.toTypedArray()), + ) + w.blank() + w.line( + "val OPS_BY_FIELD: Map> = ", + if (opsByField.isEmpty()) "emptyMap()" + else KotlinWriter.call( + "mapOf", + *opsByField.map { (field, ops) -> + listOf(KotlinWriter.str(field), " to ", KotlinWriter.call("setOf", *ops.map { KotlinWriter.str(it) }.toTypedArray())) + }.toTypedArray(), + ), + ) } - - val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve("$className.kt") - GeneratedFileWriter.write(outFile, src) + return w.toString() } private companion object { diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt index 166c19f788..76e71527d1 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt @@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory import com.metaobjects.generator.kotlin.KotlinGenUtil import com.metaobjects.generator.kotlin.KotlinNaming import com.metaobjects.generator.kotlin.PackageMapping +import com.metaobjects.generator.kotlin.writer.KotlinWriter import com.metaobjects.generator.EmitsPhysicalNameConstants import com.metaobjects.generator.GeneratorException @@ -231,49 +232,32 @@ open class KotlinNamesGenerator : val inherited = if (superRef == null) emptyList() else resolved.filter { it.member !in declaredMembers } - val out = buildString { - if (pkg.isNotEmpty()) append("package $pkg\n\n") - append("/**\n") - append(" * GENERATED — per-object physical database names for $shortName.\n") - append(" */\n") - append("object $className {\n") + val skippedMembers = collidingFlattenedMembers(names) + val rows = names.fields.values.flatMap { f -> + (if (f.members == null) listOf(f.name to "${KotlinNaming.namesMember(f.name)}_COLUMN") else emptyList()) + + f.members.orEmpty().values + .map { m -> "${f.name}.${m.name}" to KotlinNaming.flattenedColumnMember(f.name, m.name) } + .filter { (_, constant) -> constant !in skippedMembers } + }.sortedBy { it.first } + + val w = KotlinWriter().packageName(pkg) + w.doc("GENERATED — per-object physical database names for $shortName.") + w.block("object $className {") { var section: String? = null for (c in declared) { - if (section != null && section != c.section) append("\n") + if (section != null && section != c.section) w.blank() section = c.section - append(" const val ${c.member}: String = \"${c.value}\"\n") - } - // Inherited constants, re-exported by REFERENCE — the literal is spelled once, - // on the base. `const val` folds the reference at compile time, so a consumer - // reading `CouponAuthNames.ID_COLUMN` is unaffected by which object declared it. - // A TPH subtype's SOURCE members arrive here for the same reason its inherited - // columns do: it declares no source of its own, so the own set has none. - if (inherited.isNotEmpty()) append("\n") - for (c in inherited) { - append(" const val ${c.member}: String = $superRef.${c.member}\n") - } - // The map's values reference the constants rather than repeating the - // literals -- the artifact must not spell a physical name twice inside itself. - // It stays COMPLETE — every field, inherited included — because it is the - // lookup surface, and a miss on an inherited field is exactly the - // fallback-to-literal this artifact removes. - append("\n") - append(" val COLUMNS_BY_FIELD: Map = mapOf(\n") - val skippedMembers = collidingFlattenedMembers(names) - val rows = names.fields.values.flatMap { f -> - // A flattened field has no column of its own: only its members are keyed. - (if (f.members == null) listOf(f.name to "${KotlinNaming.namesMember(f.name)}_COLUMN") else emptyList()) + - // A flattened member is keyed `.`, the path the naming corpus uses. - f.members.orEmpty().values - .map { m -> "${f.name}.${m.name}" to KotlinNaming.flattenedColumnMember(f.name, m.name) } - .filter { (_, constant) -> constant !in skippedMembers } - }.sortedBy { it.first } - for ((key, constant) in rows) { - append(" \"$key\" to $constant,\n") + w.line("const val ${c.member}: String = ", KotlinWriter.str(c.value)) } - append(" )\n") - append("}\n") + w.blank() + for (c in inherited) w.line("const val ${c.member}: String = $superRef.${c.member}") + w.blank() + w.line( + "val COLUMNS_BY_FIELD: Map = ", + KotlinWriter.call("mapOf", *rows.map { (key, constant) -> listOf(KotlinWriter.str(key), " to ", constant) }.toTypedArray()), + ) } + val out = w.toString() GeneratedFileWriter.write(outRoot.resolve(pkg.replace('.', '/')).resolve("$className.kt"), out) return true diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinOutputParserGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinOutputParserGenerator.kt index beeb1b267f..02a75ab79d 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinOutputParserGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinOutputParserGenerator.kt @@ -9,6 +9,7 @@ import com.metaobjects.generator.kotlin.Fr019SharedEnum import com.metaobjects.generator.kotlin.KotlinExtractSchemaEmitter import com.metaobjects.generator.kotlin.KotlinNaming import com.metaobjects.generator.kotlin.PackageMapping +import com.metaobjects.generator.kotlin.writer.KotlinWriter import com.metaobjects.generator.GeneratorIOWriter import com.metaobjects.generator.direct.MultiFileDirectGeneratorBase @@ -58,9 +59,7 @@ import com.metaobjects.generator.util.GeneratedFileWriter * brings Jackson; add the Kotlin module if it is absent). The lenient tier needs the MetaObjects * runtime (`metaobjects-render`, `metaobjects-om`). * - *

Substrate justification (hand-rolled string builder rather than KotlinPoet): the parser file - * is short, straight-line Kotlin, so the hand-rolled emit is clearer than the equivalent KotlinPoet - * dance. Same trade-off as [KotlinSpringControllerGenerator] / [KotlinExposedTableGenerator]. + *

The file is laid out by [com.metaobjects.generator.kotlin.writer.KotlinWriter] (ADR-0063). * *

Args: *

    @@ -132,87 +131,54 @@ open class KotlinOutputParserGenerator : MultiFileDirectGeneratorBase =\n") - append(" runCatching { ") - append(parseFn) - append("(text) }\n") - append("\n") + w.line("// Fails on an unknown property: a reply carrying a field the response shape does not") + w.line("// declare is a contract break, not something to drop silently.") + w.line("private val mapper = jacksonObjectMapper().findAndRegisterModules()") + w.blank() + w.doc( + "Parse an LLM response into a typed [$responseClass].", + "", + "@throws com.fasterxml.jackson.core.JsonProcessingException when the input is not valid JSON for the response shape.", + ) + w.line("fun $parseFn(text: String): $responseClass =") + w.indented { w.line("mapper.readValue(text, $responseClass::class.java)") } + w.blank() + w.doc("Parse with explicit error handling (Result-style — does not throw).") + w.line("fun $safeParseFn(text: String): Result<$responseClass> =") + w.indented { w.line("runCatching { $parseFn(text) }") } + w.blank() + } + w.doc("Payload FQN this parser extracts — resolved against the supplied loader at runtime.") + w.line("const val PAYLOAD_FQN: String = ", KotlinWriter.str(responseVo.name)) + w.blank() + w.doc( + "Tolerant best-effort extraction delegating to the runtime MetaObjectExtractor;", + "never throws. Fully populates nested-object and array-of-object components by", + "reading the live metadata directly. Resolves this payload's", + "MetaObject by [PAYLOAD_FQN] from [loader].", + ) + w.block("fun extractLenient(loader: MetaDataLoader, text: String, opts: ExtractOptions = ExtractOptions.defaults()): ExtractionResult<$mirrorClass> {") { + w.line("val mo = loader.getMetaObjectByName(PAYLOAD_FQN)") + w.line("val raw = MetaObjectExtractor.extract(mo, text, $formatEnum, opts)") + w.line("// The assembled graph is a ValueObject (a Map) with nested") + w.line("// ValueObjects / List — map it onto the typed mirror graph.") + w.line("@Suppress(", KotlinWriter.str("UNCHECKED_CAST"), ")") + w.line("val d = raw.data as? Map") + w.line("return ExtractionResult($mirrorClass.fromMap(d), raw.report)") } - append(" /** Payload FQN this parser extracts — resolved against the supplied loader at runtime. */\n") - append(" const val PAYLOAD_FQN: String = \"") - append(KotlinExtractSchemaEmitter.kotlinStringLiteral(responseVo.name)) - append("\"\n") - append("\n") - append(" /**\n") - append(" * Tolerant best-effort extraction delegating to the runtime MetaObjectExtractor;\n") - append(" * never throws. Fully populates nested-object and array-of-object components by\n") - append(" * reading the live metadata directly. Resolves this payload's\n") - append(" * MetaObject by [PAYLOAD_FQN] from [loader].\n") - append(" */\n") - append(" fun extractLenient(loader: MetaDataLoader, text: String, opts: ExtractOptions = ExtractOptions.defaults()): ExtractionResult<") - append(mirrorClass) - append("> {\n") - append(" val mo = loader.getMetaObjectByName(PAYLOAD_FQN)\n") - append(" val raw = MetaObjectExtractor.extract(mo, text, ") - append(formatEnum) - append(", opts)\n") - append(" // The assembled graph is a ValueObject (a Map) with nested\n") - append(" // ValueObjects / List — map it onto the typed mirror graph.\n") - append(" @Suppress(\"UNCHECKED_CAST\")\n") - append(" val d = raw.data as? Map\n") - append(" return ExtractionResult(") - append(mirrorClass) - append(".fromMap(d), raw.report)\n") - append(" }\n") - append("}\n") } + val src = w.toString() val outFile = outRoot.resolve(outPkg.replace('.', '/')).resolve("$parserClass.kt") GeneratedFileWriter.write(outFile, src) diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinOutputPromptGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinOutputPromptGenerator.kt index dd492e124a..f4d83d170d 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinOutputPromptGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinOutputPromptGenerator.kt @@ -8,6 +8,7 @@ import com.metaobjects.generator.kotlin.FindInbound import com.metaobjects.generator.kotlin.KotlinNaming import com.metaobjects.generator.kotlin.KotlinOutputFormatSpecEmitter import com.metaobjects.generator.kotlin.PackageMapping +import com.metaobjects.generator.kotlin.writer.KotlinWriter import com.metaobjects.generator.GeneratorIOWriter import com.metaobjects.generator.direct.MultiFileDirectGeneratorBase @@ -106,33 +107,22 @@ open class KotlinOutputPromptGenerator : MultiFileDirectGeneratorBase`) expects and mirrors the Java render-helper's literal. */ - private fun fieldTreeLiteral(fields: List): String { - if (fields.isEmpty()) return "java.util.List.of()" - val sb = StringBuilder("java.util.List.of(") - for ((i, f) in fields.withIndex()) { - if (i > 0) sb.append(", ") - if (f.fields() != null) { - sb.append("com.metaobjects.render.PayloadField.`object`(") - .append(quote(f.name())).append(", ") - .append(fieldTreeLiteral(f.fields())).append(if (f.isArray()) ", true)" else ")") - } else { - sb.append("com.metaobjects.render.PayloadField.scalar(") - .append(quote(f.name())).append(if (f.isArray()) ", true)" else ")") - } - } - sb.append(")") - return sb.toString() + private fun fieldTreeLiteral(fields: List): Any { + if (fields.isEmpty()) return "java.util.List.of<$RENDER.PayloadField>()" + return KotlinWriter.call( + "java.util.List.of", + *fields.map { f -> + val array = if (f.isArray()) listOf("true") else emptyList() + if (f.fields() != null) { + KotlinWriter.call("$RENDER.PayloadField.`object`", quote(f.name()), fieldTreeLiteral(f.fields()), *array.toTypedArray()) + } else { + KotlinWriter.call("$RENDER.PayloadField.scalar", quote(f.name()), *array.toTypedArray()) + } + }.toTypedArray(), + ) } // ------------------------------------------------------------------------- @@ -334,26 +322,8 @@ open class KotlinRenderHelperGenerator : MultiFileDirectGeneratorBase sb.append("\\\\") - '"' -> sb.append("\\\"") - '$' -> sb.append("\\$") - '\n' -> sb.append("\\n") - '\r' -> sb.append("\\r") - '\t' -> sb.append("\\t") - else -> sb.append(c) - } - } - sb.append('"') - return sb.toString() - } - + /** A Kotlin string literal for [s], or `null`. */ + private fun quote(s: String?): String = if (s == null) "null" else KotlinWriter.str(s) // === MultiFileDirectGeneratorBase abstract-method stubs ==================== override fun writeSingleFile(md: MetaObject, writer: GeneratorIOWriter<*>?) { /* unused */ } @@ -369,6 +339,9 @@ open class KotlinRenderHelperGenerator : MultiFileDirectGeneratorBase = listOf(${fields.joinToString(", ") { "\"${it.name}\"" }})\n\n") - append(" /** One row's cells in wire form: currency as integer minor units, a date as YYYY-MM-DD,\n") - append(" * a decimal as the wire setting writes it, a boolean as true/false, null as null. */\n") - append(" fun cells(row: $shortName): List<$w.Cell> = listOf(\n") - for (f in fields) append(" $w.${cellFactory(f)}(row.${f.name}),\n") - append(" )\n\n") - append(" /** The rows as RFC 4180 CSV bytes (UTF-8). */\n") - append(" fun csv(rows: List<$shortName>): ByteArray = $w.csv(FIELDS, rows.map { cells(it) })\n\n") - append(" /** The rows as XML bytes (UTF-8, no declaration). */\n") - append(" fun xml(rows: List<$shortName>): ByteArray = $w.xml(ROOT, FIELDS, rows.map { cells(it) })\n\n") - append(" /** Whether [format] names a wired format. Case-sensitive; null and empty are not. */\n") - append(" fun isFormat(format: String?): Boolean = $w.isFormat(format)\n\n") - append(" /** `withCount` as an export request spells a truthy flag: 1 or true. */\n") - append(" fun isTruthy(flag: String?): Boolean = $w.isTruthy(flag)\n\n") - append(" /** The 400 body for a format this route does not wire. */\n") - append(" fun invalidFormat(): Map = $w.invalidFormat()\n\n") - append(" /** The 400 body for withCount on a CSV or XML export. */\n") - append(" fun withCountRefused(): Map = $w.withCountRefused()\n\n") - append(" /** The 400 body for an export of more than [MAX_ROWS] rows. */\n") - append(" fun tooLarge(): Map = $w.tooLarge(MAX_ROWS)\n\n") - append(" /** The Content-Disposition of a successful export in [format]. */\n") - append(" fun contentDisposition(format: String): String = $w.contentDisposition(SEGMENT, format)\n\n") - append(" /** The Content-Type of a successful export in [format]. */\n") - append(" fun contentType(format: String): String = $w.contentType(format)\n") - append("}\n") + val x = WRITER_NAME + val w = KotlinWriter().packageName(pkg) + w.use("$writerPackage.$x") + w.doc( + "GENERATED — the export of the $shortName report: its columns in derived-field order,", + "each cell's wire form, and the CSV and XML bodies. The route reads [MAX_ROWS] and", + "the request-side answers below; the shared [$x] writes the bytes.", + ) + w.block("object $className {") { + w.doc("The most rows one export answers; one more is 400 export_too_large.") + w.line("const val MAX_ROWS: Int = $maxRows") + w.blank() + w.doc("The XML root element: the report's name.") + w.line("const val ROOT: String = ", KotlinWriter.str(shortName)) + w.blank() + w.doc("The route's last path segment, the stem of the download's file name.") + w.line("const val SEGMENT: String = ", KotlinWriter.str(segment)) + w.blank() + w.doc("The derived fields, in order: the CSV header row and the XML element names.") + w.line("val FIELDS: List = ", KotlinWriter.call("listOf", *fields.map { KotlinWriter.str(it.name) }.toTypedArray())) + w.blank() + w.doc( + "One row's cells in wire form: currency as integer minor units, a date as YYYY-MM-DD,", + "a decimal as the wire setting writes it, a boolean as true/false, null as null.", + ) + w.line( + "fun cells(row: $shortName): List<$x.Cell> = ", + KotlinWriter.call("listOf", *fields.map { f -> "$x.${cellFactory(f)}(row.${f.name})" }.toTypedArray()), + ) + w.blank() + w.doc("The rows as RFC 4180 CSV bytes (UTF-8).") + w.line("fun csv(rows: List<$shortName>): ByteArray = $x.csv(FIELDS, rows.map { cells(it) })") + w.blank() + w.doc("The rows as XML bytes (UTF-8, no declaration).") + w.line("fun xml(rows: List<$shortName>): ByteArray = $x.xml(ROOT, FIELDS, rows.map { cells(it) })") + w.blank() + w.doc("Whether [format] names a wired format. Case-sensitive; null and empty are not.") + w.line("fun isFormat(format: String?): Boolean = $x.isFormat(format)") + w.blank() + w.doc("`withCount` as an export request spells a truthy flag: 1 or true.") + w.line("fun isTruthy(flag: String?): Boolean = $x.isTruthy(flag)") + w.blank() + w.doc("The 400 body for a format this route does not wire.") + w.line("fun invalidFormat(): Map = $x.invalidFormat()") + w.blank() + w.doc("The 400 body for withCount on a CSV or XML export.") + w.line("fun withCountRefused(): Map = $x.withCountRefused()") + w.blank() + w.doc("The 400 body for an export of more than [MAX_ROWS] rows.") + w.line("fun tooLarge(): Map = $x.tooLarge(MAX_ROWS)") + w.blank() + w.doc("The Content-Disposition of a successful export in [format].") + w.line("fun contentDisposition(format: String): String = $x.contentDisposition(SEGMENT, format)") + w.blank() + w.doc("The Content-Type of a successful export in [format].") + w.line("fun contentType(format: String): String = $x.contentType(format)") } + return w.toString() } /** Which `ReportExportWriter` factory turns this field's value into a cell. */ @@ -203,242 +219,246 @@ open class KotlinReportExportGenerator : MultiFileDirectGeneratorBase 0) b.append(total / 3600).append('H') - if (total % 3600 / 60 > 0) b.append(total % 3600 / 60).append('M') - if (total % 60 > 0 || nanos > 0) { - b.append(total % 60) - if (nanos > 0) b.append('.').append(nanos.toString().padStart(9, '0').trimEnd('0')) - b.append('S') - } - return Cell(b.toString(), false) - } - -""" - - /** The simple name of the shared writer. */ - const val WRITER_NAME = "ReportExportWriter" - - /** - * The shared writer, verbatim but for the four substitutions in [writerSource]. A raw - * string with no Kotlin templates: the emitted code concatenates with `+`. - */ - const val WRITER_TEMPLATE: String = """@PACKAGE@import com.fasterxml.jackson.databind.ObjectMapper -import com.fasterxml.jackson.databind.SerializationFeature -import java.io.ByteArrayOutputStream -import java.math.BigDecimal -import java.time.LocalDateTime -import java.time.LocalTime -import java.time.format.DateTimeFormatter -import javax.xml.stream.XMLOutputFactory - -/** - * GENERATED — the one writer every report export shares: CSV quoting, CRLF, the byte order - * mark constant, the formula-injection guard, XML over the JDK's StAX writer, and the - * request-side answers (which formats are wired, the 400 envelopes, the headers). - * - * The guard applies to string-valued cells only (a string, an enum symbol, a uri): a value - * starting with =, +, -, @, TAB or CR gets a leading ', then the cell is quoted if it holds a - * quote, comma, CR or LF. A number, a decimal, a date or a boolean is never guarded, so a - * negative number stays a number. - */ -object ReportExportWriter { - - /** Write a UTF-8 byte order mark before the CSV (Excel on Windows wants one). */ - const val EXPORT_CSV_BOM: Boolean = @BOM@ - - /** Write a null field as an empty element with xsi:nil="true" (true) or as an empty element (false). */ - const val EXPORT_XML_NIL: Boolean = @NIL@ - - /** The project's wire.decimals: the canonical string (true, "string") or as Jackson writes a - * BigDecimal number (false, "native"), so a decimal cell matches the list route. */ - const val DECIMALS_AS_STRING: Boolean = @DECIMALS_AS_STRING@ - - private const val XSI_NS = "http://www.w3.org/2001/XMLSchema-instance" - - const val CSV = "csv" - const val JSON = "json" - const val XML = "xml" - - /** The wired formats, in the order the invalid_format envelope lists them. */ - val FORMATS: List = listOf(CSV, JSON, XML) - - private val JSON_MAPPER: ObjectMapper = ObjectMapper() - .findAndRegisterModules() - .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) - - // ----------------------------------------------------------------------- - // The request side - // ----------------------------------------------------------------------- - - /** Whether [format] names a wired format. Case-sensitive; null and empty are not. */ - fun isFormat(format: String?): Boolean = format != null && format in FORMATS - - /** withCount as an export request spells a truthy flag: 1 or true. */ - fun isTruthy(flag: String?): Boolean = flag == "1" || flag.equals("true", ignoreCase = true) - - /** The 400 body for a format this route does not wire. */ - fun invalidFormat(): Map = linkedMapOf("error" to "invalid_format", "expected" to FORMATS) - - /** The 400 body for withCount on a CSV or XML export: only JSON carries the { rows, total } envelope. */ - fun withCountRefused(): Map = linkedMapOf( - "error" to "export_with_count", - "message" to "withCount is not supported with format=csv or format=xml: only JSON carries the { rows, total } envelope.", - ) - - /** The 400 body for an export of more than [maxRows] rows. */ - fun tooLarge(maxRows: Int): Map = linkedMapOf("error" to "export_too_large", "maxRows" to maxRows) + private fun writerSource(pkg: String, xmlNulls: String, csvBom: Boolean, decimalsAsString: Boolean, duration: Boolean = false): String { + val xmlNil = xmlNulls == XML_NULLS_NIL + val w = KotlinWriter().packageName(pkg) + w.use("com.fasterxml.jackson.databind.ObjectMapper") + w.use("com.fasterxml.jackson.databind.SerializationFeature") + w.use("java.io.ByteArrayOutputStream") + w.use("java.math.BigDecimal") + w.use("java.time.LocalDateTime") + w.use("java.time.LocalTime") + w.use("java.time.format.DateTimeFormatter") + w.use("javax.xml.stream.XMLOutputFactory") + w.text( + """ + /** + * GENERATED — the one writer every report export shares: CSV quoting, CRLF, the byte order + * mark constant, the formula-injection guard, XML over the JDK's StAX writer, and the + * request-side answers (which formats are wired, the 400 envelopes, the headers). + * + * The guard applies to string-valued cells only (a string, an enum symbol, a uri): a value + * starting with =, +, -, @, TAB or CR gets a leading ', then the cell is quoted if it holds a + * quote, comma, CR or LF. A number, a decimal, a date or a boolean is never guarded, so a + * negative number stays a number. + */ + object ReportExportWriter { + + /** Write a UTF-8 byte order mark before the CSV (Excel on Windows wants one). */ + const val EXPORT_CSV_BOM: Boolean = $csvBom + + /** Write a null field as an empty element with xsi:nil="true" (true) or as an empty element (false). */ + const val EXPORT_XML_NIL: Boolean = $xmlNil + + /** The project's wire.decimals: the canonical string (true, "string") or as Jackson writes a + * BigDecimal number (false, "native"), so a decimal cell matches the list route. */ + const val DECIMALS_AS_STRING: Boolean = $decimalsAsString + + private const val XSI_NS = "http://www.w3.org/2001/XMLSchema-instance" + + const val CSV = "csv" + const val JSON = "json" + const val XML = "xml" + + /** The wired formats, in the order the invalid_format envelope lists them. */ + val FORMATS: List = listOf(CSV, JSON, XML) + + private val JSON_MAPPER: ObjectMapper = ObjectMapper() + .findAndRegisterModules() + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + + // ----------------------------------------------------------------------- + // The request side + // ----------------------------------------------------------------------- + + /** Whether [format] names a wired format. Case-sensitive; null and empty are not. */ + fun isFormat(format: String?): Boolean = format != null && format in FORMATS + + /** withCount as an export request spells a truthy flag: 1 or true. */ + fun isTruthy(flag: String?): Boolean = flag == "1" || flag.equals("true", ignoreCase = true) + + /** The 400 body for a format this route does not wire. */ + fun invalidFormat(): Map = linkedMapOf("error" to "invalid_format", "expected" to FORMATS) + + /** The 400 body for withCount on a CSV or XML export: only JSON carries the { rows, total } envelope. */ + fun withCountRefused(): Map = linkedMapOf( + "error" to "export_with_count", + "message" to "withCount is not supported with format=csv or format=xml: only JSON carries the { rows, total } envelope.", + ) + + /** The 400 body for an export of more than [maxRows] rows. */ + fun tooLarge(maxRows: Int): Map = linkedMapOf("error" to "export_too_large", "maxRows" to maxRows) + + /** attachment; filename=".". */ + fun contentDisposition(segment: String, format: String): String = + "attachment; filename=\"" + segment + "." + format + "\"" + + /** The Content-Type of a successful export. */ + fun contentType(format: String): String = when (format) { + CSV -> "text/csv; charset=utf-8" + XML -> "application/xml" + JSON -> "application/json" + else -> throw IllegalArgumentException("not an export format: " + format) + } - /** attachment; filename=".". */ - fun contentDisposition(segment: String, format: String): String = - "attachment; filename=\"" + segment + "." + format + "\"" + // ----------------------------------------------------------------------- + // Cells + // ----------------------------------------------------------------------- - /** The Content-Type of a successful export. */ - fun contentType(format: String): String = when (format) { - CSV -> "text/csv; charset=utf-8" - XML -> "application/xml" - JSON -> "application/json" - else -> throw IllegalArgumentException("not an export format: " + format) - } + /** One cell in wire form: its text, or null for a null; [guarded] marks a string-valued cell. */ + class Cell(val text: String?, val guarded: Boolean) - // ----------------------------------------------------------------------- - // Cells - // ----------------------------------------------------------------------- + private val NULL = Cell(null, false) - /** One cell in wire form: its text, or null for a null; [guarded] marks a string-valued cell. */ - class Cell(val text: String?, val guarded: Boolean) + /** A string-valued cell (string, enum symbol, uri): subject to the formula-injection guard. */ + fun text(value: Any?): Cell = if (value == null) NULL else Cell(value.toString(), true) - private val NULL = Cell(null, false) + /** A cell that is never guarded (number, date, time, timestamp, uuid, boolean, currency). + * A time and a zone-less timestamp keep their seconds, as Jackson's JSR-310 serializers write them. */ + fun raw(value: Any?): Cell = when (value) { + null -> NULL + is LocalTime -> Cell(value.format(DateTimeFormatter.ISO_LOCAL_TIME), false) + is LocalDateTime -> Cell(value.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME), false) + else -> Cell(value.toString(), false) + } + """ + ) + w.blank() + if (duration) { + // A member of the object, one level in. + w.indented { + w.text( + """ + /** A field.duration in its canonical ISO-8601 wire form ([-]PT[nH][nM][n[.f]S], to the + * nanosecond), as the list route writes it; Duration.toString() differs for a negative span. */ + fun duration(value: java.time.Duration?): Cell { + if (value == null) return NULL + val mag = if (value.isNegative) value.negated() else value + val total = mag.seconds + val nanos = mag.nano.toLong() + if (total == 0L && nanos == 0L) return Cell("PT0S", false) + val b = StringBuilder(if (value.isNegative) "-PT" else "PT") + if (total / 3600 > 0) b.append(total / 3600).append('H') + if (total % 3600 / 60 > 0) b.append(total % 3600 / 60).append('M') + if (total % 60 > 0 || nanos > 0) { + b.append(total % 60) + if (nanos > 0) b.append('.').append(nanos.toString().padStart(9, '0').trimEnd('0')) + b.append('S') + } + return Cell(b.toString(), false) + } + """ + ) + } + w.blank() + } + w.text( + """ + /** A decimal as the wire setting writes it: under "string" canonical plain notation (no + * exponent, no trailing fraction zeros, zero as 0), under "native" as Jackson writes it. */ + fun decimal(value: BigDecimal?): Cell { + if (value == null) return NULL + if (!DECIMALS_AS_STRING) return Cell(value.toString(), false) + return Cell(if (value.signum() == 0) "0" else value.stripTrailingZeros().toPlainString(), false) + } - /** A string-valued cell (string, enum symbol, uri): subject to the formula-injection guard. */ - fun text(value: Any?): Cell = if (value == null) NULL else Cell(value.toString(), true) + /** An array or a map, as compact JSON text. */ + fun json(value: Any?): Cell = if (value == null) NULL else Cell(JSON_MAPPER.writeValueAsString(value), false) - /** A cell that is never guarded (number, date, time, timestamp, uuid, boolean, currency). - * A time and a zone-less timestamp keep their seconds, as Jackson's JSR-310 serializers write them. */ - fun raw(value: Any?): Cell = when (value) { - null -> NULL - is LocalTime -> Cell(value.format(DateTimeFormatter.ISO_LOCAL_TIME), false) - is LocalDateTime -> Cell(value.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME), false) - else -> Cell(value.toString(), false) - } + // ----------------------------------------------------------------------- + // CSV + // ----------------------------------------------------------------------- - /** A decimal as the wire setting writes it: under "string" canonical plain notation (no - * exponent, no trailing fraction zeros, zero as 0), under "native" as Jackson writes it. */ - fun decimal(value: BigDecimal?): Cell { - if (value == null) return NULL - if (!DECIMALS_AS_STRING) return Cell(value.toString(), false) - return Cell(if (value.signum() == 0) "0" else value.stripTrailingZeros().toPlainString(), false) - } + /** RFC 4180 CSV: a header row, then one record per row, CRLF after every record. */ + fun csv(names: List, rows: List>): ByteArray { + val out = StringBuilder() + if (EXPORT_CSV_BOM) out.append('') + out.append(names.joinToString(",") { quote(it) }).append("\r\n") + for (row in rows) out.append(row.joinToString(",") { csvCell(it) }).append("\r\n") + return out.toString().toByteArray(Charsets.UTF_8) + } - /** An array or a map, as compact JSON text. */ - fun json(value: Any?): Cell = if (value == null) NULL else Cell(JSON_MAPPER.writeValueAsString(value), false) + /** One cell: null is empty, a guarded string is prefixed with an apostrophe when it starts + * like a formula, then the text is quoted when it needs to be. */ + internal fun csvCell(cell: Cell): String { + var value = cell.text ?: return "" + if (cell.guarded && value.isNotEmpty()) { + val first = value[0] + if (first == '=' || first == '+' || first == '-' || first == '@' || first == '\t' || first == '\r') { + value = "'" + value + } + } + return quote(value) + } - // ----------------------------------------------------------------------- - // CSV - // ----------------------------------------------------------------------- + private fun quote(value: String): String = + if (value.any { it == '"' || it == ',' || it == '\r' || it == '\n' }) { + "\"" + value.replace("\"", "\"\"") + "\"" + } else { + value + } + + // ----------------------------------------------------------------------- + // XML + // ----------------------------------------------------------------------- + + /** value......: UTF-8, no declaration, no indentation. */ + fun xml(root: String, names: List, rows: List>): ByteArray { + val bytes = ByteArrayOutputStream() + val w = XMLOutputFactory.newFactory().createXMLStreamWriter(bytes, "UTF-8") + w.writeStartElement(root) + if (EXPORT_XML_NIL) w.writeNamespace("xsi", XSI_NS) + for (row in rows) { + w.writeStartElement("row") + for (i in names.indices) { + val value = row[i].text + if (value == null) { + w.writeEmptyElement(names[i]) + if (EXPORT_XML_NIL) w.writeAttribute("xsi", XSI_NS, "nil", "true") + } else { + w.writeStartElement(names[i]) + w.writeCharacters(xmlText(value)) + w.writeEndElement() + } + } + w.writeEndElement() + } + w.writeEndElement() + w.close() + return bytes.toByteArray() + } - /** RFC 4180 CSV: a header row, then one record per row, CRLF after every record. */ - fun csv(names: List, rows: List>): ByteArray { - val out = StringBuilder() - if (EXPORT_CSV_BOM) out.append('') - out.append(names.joinToString(",") { quote(it) }).append("\r\n") - for (row in rows) out.append(row.joinToString(",") { csvCell(it) }).append("\r\n") - return out.toString().toByteArray(Charsets.UTF_8) - } + /** A character XML 1.0 cannot hold becomes U+FFFD; the writer escapes & < >. */ + private fun xmlText(value: String): String { + if (value.all { xmlOk(it) }) return value + return value.map { if (xmlOk(it)) it else '�' }.joinToString("") + } - /** One cell: null is empty, a guarded string is prefixed with an apostrophe when it starts - * like a formula, then the text is quoted when it needs to be. */ - internal fun csvCell(cell: Cell): String { - var value = cell.text ?: return "" - if (cell.guarded && value.isNotEmpty()) { - val first = value[0] - if (first == '=' || first == '+' || first == '-' || first == '@' || first == '\t' || first == '\r') { - value = "'" + value + private fun xmlOk(c: Char): Boolean = + c == '\t' || c == '\n' || c == '\r' || (c in ' '..'퟿') || (c in ''..'�') || c.isSurrogate() } - } - return quote(value) + """ + ) + return w.toString() } - private fun quote(value: String): String = - if (value.any { it == '"' || it == ',' || it == '\r' || it == '\n' }) { - "\"" + value.replace("\"", "\"\"") + "\"" - } else { - value - } - - // ----------------------------------------------------------------------- - // XML - // ----------------------------------------------------------------------- + private companion object { + const val ARG_MAX_ROWS = "maxRows" + const val ARG_XML_NULLS = "xmlNulls" + const val ARG_CSV_BOM = "csvBom" + const val ARG_WRITER_PACKAGE = "writerPackage" - /** value......: UTF-8, no declaration, no indentation. */ - fun xml(root: String, names: List, rows: List>): ByteArray { - val bytes = ByteArrayOutputStream() - val w = XMLOutputFactory.newFactory().createXMLStreamWriter(bytes, "UTF-8") - w.writeStartElement(root) - if (EXPORT_XML_NIL) w.writeNamespace("xsi", XSI_NS) - for (row in rows) { - w.writeStartElement("row") - for (i in names.indices) { - val value = row[i].text - if (value == null) { - w.writeEmptyElement(names[i]) - if (EXPORT_XML_NIL) w.writeAttribute("xsi", XSI_NS, "nil", "true") - } else { - w.writeStartElement(names[i]) - w.writeCharacters(xmlText(value)) - w.writeEndElement() - } - } - w.writeEndElement() - } - w.writeEndElement() - w.close() - return bytes.toByteArray() - } + /** The most rows one export answers when no [ARG_MAX_ROWS] is given. */ + const val DEFAULT_MAX_ROWS = 100_000 - /** A character XML 1.0 cannot hold becomes U+FFFD; the writer escapes & < >. */ - private fun xmlText(value: String): String { - if (value.all { xmlOk(it) }) return value - return value.map { if (xmlOk(it)) it else '�' }.joinToString("") - } + const val XML_NULLS_EMPTY = "empty" + const val XML_NULLS_NIL = "nil" - private fun xmlOk(c: Char): Boolean = - c == '\t' || c == '\n' || c == '\r' || (c in ' '..'퟿') || (c in ''..'�') || c.isSurrogate() -} -""" + /** The simple name of the shared writer. */ + const val WRITER_NAME = "ReportExportWriter" } // === MultiFileDirectGeneratorBase abstract-method stubs ==================== diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementTestsGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementTestsGenerator.kt index 9b638cc656..f2d9b50a46 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementTestsGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementTestsGenerator.kt @@ -4,8 +4,10 @@ import com.metaobjects.generator.FileEmittingGenerator import com.metaobjects.generator.FileEmittingGenerator.EmittedFile import com.metaobjects.generator.GeneratorException import com.metaobjects.generator.ProjectClassLoaderAware +import com.metaobjects.generator.kotlin.writer.KotlinWriter import com.metaobjects.generator.requirement.RequirementTestArgs import com.metaobjects.generator.requirement.RequirementTestRenderer +import com.metaobjects.generator.writer.CodeWriter import com.metaobjects.loader.MetaDataLoader import com.metaobjects.requirement.MetaRequirement import com.metaobjects.requirement.RequirementTestFilter @@ -225,11 +227,8 @@ open class KotlinRequirementTestsGenerator : FileEmittingGenerator(), ProjectCla if (pairs.isEmpty()) return val sb = StringBuilder(ERR_WITNESS_KEY_COLLISION) .append(": two requirement tests map to one witness key, so one witness could not serve both. ") - .append("Rename one so the names differ in more than punctuation:") - for (pair in pairs) { - sb.append("\n '").append(pair[0]).append("' and '").append(pair[1]) - .append("' (witness key ").append(keyById[pair[0]]).append(')') - } + .append("Rename one so the names differ in more than punctuation: ") + .append(pairs.joinToString("; ") { pair -> "'${pair[0]}' and '${pair[1]}' (witness key ${keyById[pair[0]]})" }) throw GeneratorException(sb.toString()) } @@ -248,26 +247,25 @@ open class KotlinRequirementTestsGenerator : FileEmittingGenerator(), ProjectCla // ------------------------------------------------------------------ private fun witnessInterface(testPackage: String, name: String, witnessClass: String, tests: List): String { - val sb = StringBuilder(GENERATED_HEADER) - .append("// Witnesses are project-owned: implement this interface in ").append(commentText(witnessClass)) - .append(" and override the members it has witnesses for.\n") - .append("package ").append(sourceName(testPackage)).append("\n\n") - .append("interface ").append(name).append(" {\n") - for (p in tests) { - val id = p.identity - if (id.skip() != null) continue // a skipped test claims nothing works yet: no member - sb.append('\n').append(indent(testComments(p.args))).append('\n') - .append(" fun ").append(id.witnessKey()).append("() {\n") - .append(" throw AssertionError(\"") - .append( - stringLiteral( - "unimplemented requirement: ${id.id()} - write $witnessClass.${id.witnessKey()}() " + - "so that it fails when: ${p.args.counterexample()}", - ), - ) - .append("\")\n }\n") + val w = KotlinWriter().packageName(testPackage) + w.header( + GENERATED_HEADER, + "// Witnesses are project-owned: implement this interface in ${commentText(witnessClass)} and override the members it has witnesses for.", + ) + w.block("interface $name {") { + for (p in tests) { + val id = p.identity + if (id.skip() != null) continue // a skipped test claims nothing works yet: no member + w.blank() + testComments(p.args).forEach { w.line(it) } + w.block("fun ${id.witnessKey()}() {") { + val message = "unimplemented requirement: ${id.id()} - write $witnessClass.${id.witnessKey()}() " + + "so that it fails when: ${p.args.counterexample()}" + w.line("throw AssertionError(", KotlinWriter.str(message), ")") + } + } } - return sb.append("}\n").toString() + return w.toString() } private fun testClass( @@ -278,41 +276,45 @@ open class KotlinRequirementTestsGenerator : FileEmittingGenerator(), ProjectCla tests: List, renderer: RequirementTestRenderer?, ): String { + // A renderer names its imports as free text (an alias, a wildcard), so they print as given. val imports = TreeSet() imports += "org.junit.jupiter.api.Test" - val body = StringBuilder() - for (p in tests) { - val rendered = renderer?.render(p.args) - val source: String - if (rendered != null) { - imports += rendered.imports() - source = rendered.source() - } else { - source = defaultTest(p) - if (p.identity.skip() != null) imports += "org.junit.jupiter.api.Disabled" + val w = object : KotlinWriter() { + override fun writeImports(w: CodeWriter) { + for (i in imports) w.line("import ", i) + } + } + w.packageName(testPackage) + w.header(GENERATED_HEADER, "// The witnesses are project-owned, in ${commentText(witnessClass)}.") + w.block("class $name {") { + w.line("private val witnesses: $witnesses = ", KotlinWriter.escapeName(witnessClass), "()") + for (p in tests) { + w.blank() + val rendered = renderer?.render(p.args) + if (rendered != null) { + imports += rendered.imports() + w.text(rendered.source().trimEnd()) + } else { + if (p.identity.skip() != null) imports += "org.junit.jupiter.api.Disabled" + writeDefaultTest(w, p) + } } - body.append('\n').append(indent(source.trimEnd())).append('\n') } - val sb = StringBuilder(GENERATED_HEADER) - .append("// The witnesses are project-owned, in ").append(commentText(witnessClass)).append(".\n") - .append("package ").append(sourceName(testPackage)).append("\n\n") - for (i in imports) sb.append("import ").append(i).append('\n') - return sb.append("\nclass ").append(name).append(" {\n\n") - .append(" private val witnesses: ").append(witnesses).append(" = ").append(sourceName(witnessClass)).append("()\n") - .append(body).append("}\n").toString() + return w.toString() } /** The default rendering of one test: its comments, then a `@Test` calling the witness. */ - private fun defaultTest(p: Planned): String { + private fun writeDefaultTest(w: KotlinWriter, p: Planned) { val id = p.identity - val sb = StringBuilder(testComments(p.args)).append("\n@Test\n") + testComments(p.args).forEach { w.line(it) } + w.line("@Test") if (id.skip() == null) { - sb.append("fun ").append(id.witnessKey()).append("() {\n witnesses.").append(id.witnessKey()).append("()\n}") + w.block("fun ${id.witnessKey()}() {") { w.line("witnesses.${id.witnessKey()}()") } } else { - sb.append("@Disabled(\"").append(stringLiteral(skipReason(id.skip()))).append("\")\n") - .append("fun ").append(id.witnessKey()).append("() {\n}") + w.line("@Disabled(", KotlinWriter.str(skipReason(id.skip())), ")") + w.line("fun ${id.witnessKey()}() {") + w.line("}") } - return sb.toString() } private fun skipReason(skip: String): String = when (skip) { @@ -321,15 +323,15 @@ open class KotlinRequirementTestsGenerator : FileEmittingGenerator(), ProjectCla else -> "$skip - skipped" } - /** The comment block above a test: id, statement, counterexample, status, claims, digest. */ - private fun testComments(a: RequirementTestArgs): String { + /** The comment lines above a test: id, statement, counterexample, status, claims, digest. */ + private fun testComments(a: RequirementTestArgs): List { val id = a.identity() val claims = a.targets().joinToString(", ") { "${it.ref()} (${it.concern()})" } - return commentLines(id.id()) + "\n" + - commentLines(a.statement()) + "\n" + - commentLines("Counterexample: " + a.counterexample()) + "\n" + - commentLines("Status: " + (id.status() ?: "(none)")) + "\n" + - commentLines("Claims: " + claims.ifEmpty { "(none)" }) + "\n" + + return commentLines(id.id()) + + commentLines(a.statement()) + + commentLines("Counterexample: " + a.counterexample()) + + commentLines("Status: " + (id.status() ?: "(none)")) + + commentLines("Claims: " + claims.ifEmpty { "(none)" }) + commentLines("Digest: " + id.digest()) } @@ -337,54 +339,15 @@ open class KotlinRequirementTestsGenerator : FileEmittingGenerator(), ProjectCla // escaping: author prose lands in string literals and comments, and must not break either // ------------------------------------------------------------------ - /** - * A dotted name as it is written in Kotlin source: a segment that is a hard keyword (`in`, - * `is` and `as` are real country-code prefixes in a reversed domain) is wrapped in - * backticks, since `package in.co.acme` does not parse. The file's directory and every - * comment and message keep the plain name. - */ - private fun sourceName(dotted: String): String = - dotted.split('.').joinToString(".") { if (it in HARD_KEYWORDS) "`$it`" else it } - - private fun indent(block: String): String { - val sb = StringBuilder() - for (line in block.split("\n")) { - if (sb.isNotEmpty()) sb.append('\n') - if (line.isNotEmpty()) sb.append(" ").append(line) - } - return sb.toString() - } - /** * One `//` marker per line. A carriage return ends a Kotlin line as a line feed does, so * both split; the comment terminator is broken as `* /` by contract. */ - private fun commentLines(text: String): String = - text.split(Regex("\r\n|\r|\n")).joinToString("\n") { "// " + commentText(it) } + private fun commentLines(text: String): List = + text.split(LINE_BREAK).map { "// " + commentText(it) } private fun commentText(line: String): String = line.replace("*/", "* /") - /** - * The text of a double-quoted string literal. Every control character is escaped, so no - * value can end the literal, and so is `$`, which would otherwise start a string template. - */ - private fun stringLiteral(s: String): String { - val sb = StringBuilder() - for (c in s) { - when { - c == '\\' -> sb.append("\\\\") - c == '"' -> sb.append("\\\"") - c == '$' -> sb.append("\\$") - c == '\n' -> sb.append("\\n") - c == '\r' -> sb.append("\\r") - c == '\t' -> sb.append("\\t") - c.code < 0x20 || c.code == 0x7f -> sb.append("\\u%04x".format(c.code)) - else -> sb.append(c) - } - } - return sb.toString() - } - companion object { private val LOG = LoggerFactory.getLogger(KotlinRequirementTestsGenerator::class.java) @@ -404,16 +367,12 @@ open class KotlinRequirementTestsGenerator : FileEmittingGenerator(), ProjectCla private const val SKIP_PLANNED = "planned - not built yet" private const val SKIP_RETIRED = "retired - the capability was deliberately removed; assert it stays removed" - /** Kotlin's hard keywords: the ones that cannot be an identifier without backticks. */ - private val HARD_KEYWORDS = setOf( - "as", "break", "class", "continue", "do", "else", "false", "for", "fun", "if", "in", - "interface", "is", "null", "object", "package", "return", "super", "this", "throw", - "true", "try", "typealias", "typeof", "val", "var", "when", "while", - ) - private val KOTLIN_NAME = Regex("[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)*") private const val GENERATED_HEADER = - "// GENERATED by metaobjects (requirement-tests). DO NOT EDIT: this file is rewritten whole.\n" + "// GENERATED by metaobjects (requirement-tests). DO NOT EDIT: this file is rewritten whole." + + /** A carriage return ends a Kotlin line as a line feed does, so both split a comment. */ + private val LINE_BREAK = Regex("\r\n|\r|\n") } } diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinStoredProcGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinStoredProcGenerator.kt index 97e25e7c53..36e87cec4c 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinStoredProcGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinStoredProcGenerator.kt @@ -11,6 +11,8 @@ import com.metaobjects.generator.kotlin.KotlinGenUtil import com.metaobjects.generator.kotlin.KotlinNaming import com.metaobjects.generator.kotlin.KotlinTypeMapper import com.metaobjects.generator.kotlin.PackageMapping +import com.metaobjects.generator.kotlin.writer.KotlinWriter +import com.metaobjects.generator.writer.CodeWriter import com.metaobjects.field.BooleanField import com.metaobjects.field.CurrencyField @@ -246,34 +248,38 @@ open class KotlinStoredProcGenerator : MultiFileDirectGeneratorBase( procNameExpr: String, procNameDoc: String, exposedApi: ExposedApi = ExposedApi.V0, - ): String = buildString { - if (pkg.isNotEmpty()) { - append("package $pkg\n\n") - } + ): String { + val w = KotlinWriter().packageName(pkg) // issue #390: `Transaction` is abstract under 1.x — the JDBC implementation (and the // receiver `transaction { }` actually hands the hand-write example below) is // `JdbcTransaction`. This import (and the KDoc's receiver type) is the only thing that // changes; the stub is otherwise a worked EXAMPLE in a comment, never compiled. val transactionReceiver = if (exposedApi == ExposedApi.V1) "JdbcTransaction" else "Transaction" - append("import ${ExposedImports.jdbc(exposedApi, transactionReceiver)}\n\n") - append("/**\n") - append(" * GENERATED — stub for $procNameDoc.\n") - append(" *\n") - append(" * The $shortName entity carries no field declarations, so the call signature\n") - append(" * and row-mapping body are consumer-specific. Fill in the wrapper with your\n") - append(" * procedure's parameter set:\n") - append(" *\n") - append(" * fun $transactionReceiver.call$shortName(/* params */): List<$shortName> {\n") - append(" * val results = mutableListOf<$shortName>()\n") - append(" * exec(\"SELECT * FROM ${'$'}{${objectName}.PROC_NAME}(?)\") { rs ->\n") - append(" * while (rs.next()) results.add($shortName(/* map fields */))\n") - append(" * }\n") - append(" * return results\n") - append(" * }\n") - append(" */\n") - append("object $objectName {\n") - append(" const val PROC_NAME = $procNameExpr\n") - append("}\n") + w.use(ExposedImports.jdbc(exposedApi, transactionReceiver)) + // The KDoc carries a worked example; its indentation is the example's own. + w.text( + """ + /** + * GENERATED — stub for $procNameDoc. + * + * The $shortName entity carries no field declarations, so the call signature + * and row-mapping body are consumer-specific. Fill in the wrapper with your + * procedure's parameter set: + * + * fun $transactionReceiver.call$shortName(/* params */): List<$shortName> { + * val results = mutableListOf<$shortName>() + * exec("SELECT * FROM ${'$'}{$objectName.PROC_NAME}(?)") { rs -> + * while (rs.next()) results.add($shortName(/* map fields */)) + * } + * return results + * } + */ + """ + ) + w.block("object $objectName {") { + w.line("const val PROC_NAME = $procNameExpr") + } + return w.toString() } /** @@ -291,62 +297,56 @@ open class KotlinStoredProcGenerator : MultiFileDirectGeneratorBase( params: List>, resultFields: List>, exposedApi: ExposedApi = ExposedApi.V0, - ): String = buildString { - if (pkg.isNotEmpty()) { - append("package $pkg\n\n") - } + ): String { + val w = KotlinWriter().packageName(pkg) // issue #390: `Transaction` is unused in the emitted body below (only the top-level // `transaction { }` function is called) — kept as-is for V0 byte-identity; under V1 it // becomes `JdbcTransaction`, the concrete type `transaction { }` actually hands the // block (`Transaction` itself is abstract in 1.x). val transactionType = if (exposedApi == ExposedApi.V1) "JdbcTransaction" else "Transaction" - append("import ${ExposedImports.jdbc(exposedApi, transactionType)}\n") - append("import ${ExposedImports.transactions(exposedApi, "transaction")}\n\n") - - append("/** GENERATED — wrapper for $procNameDoc. */\n") - append("object $objectName {\n") - append(" const val PROC_NAME = $procNameExpr\n\n") - append(" /** Call the procedure and map result rows into [$shortName]. */\n") - - // Function signature. - val paramSig = params.joinToString(", ") { f -> "${f.name}: ${kotlinParamTypeFqn(f)}" } - append(" fun call($paramSig): List<$shortName> = transaction {\n") - append(" val results = mutableListOf<$shortName>()\n") + w.use(ExposedImports.jdbc(exposedApi, transactionType)) + w.use(ExposedImports.transactions(exposedApi, "transaction")) - // SQL + placeholder list — empty parens when no params. - val placeholders = params.joinToString(", ") { "?" } - append(" exec(\"SELECT * FROM \${PROC_NAME}($placeholders)\"") - if (params.isEmpty()) { - // No-arg path: omit the bindings list entirely; Exposed's `exec(stmt, body)` is fine. - append(") { rs ->\n") - } else { - val bindings = params.joinToString(",\n") { p -> - " ${exposedColumnTypeCtor(p, exposedApi)} to ${p.name}" - } - append(", listOf(\n") - append(bindings) - append("\n )) { rs ->\n") - } - - append(" while (rs.next()) {\n") - if (resultFields.isEmpty()) { - // Edge case: every field is a @param. Emit a no-arg ctor invocation; - // if the data class requires arguments this will fail to compile and the - // author can adjust their metadata. Per spec, we still produce a typed call. - append(" results.add($shortName())\n") - } else { - val rowMapping = resultFields.joinToString(",\n") { rf -> - " ${rf.name} = ${rsGetterCall(rf, columnExpr(shortName, rf))}" + w.doc("GENERATED — wrapper for $procNameDoc.") + w.block("object $objectName {") { + w.line("const val PROC_NAME = $procNameExpr") + w.blank() + w.doc("Call the procedure and map result rows into [$shortName].") + val paramSig = params.joinToString(", ") { f -> "${f.name}: ${kotlinParamTypeFqn(f)}" } + w.block("fun call($paramSig): List<$shortName> = transaction {") { + w.line("val results = mutableListOf<$shortName>()") + // SQL + placeholder list — empty parens when no params. + val placeholders = params.joinToString(", ") { "?" } + val sql = "\"SELECT * FROM \${PROC_NAME}($placeholders)\"" + // No-arg path: omit the bindings list entirely; Exposed's `exec(stmt, body)` is fine. + val exec: Any = if (params.isEmpty()) "exec($sql)" + else CodeWriter.list( + "exec($sql, listOf(", + params.map { p -> "${exposedColumnTypeCtor(p, exposedApi)} to ${p.name}" }, + "))", + ) + w.block(listOf(exec, " { rs ->")) { + w.block("while (rs.next()) {") { + if (resultFields.isEmpty()) { + // Edge case: every field is a @param. Emit a no-arg ctor invocation; + // if the data class requires arguments this will fail to compile and the + // author can adjust their metadata. Per spec, we still produce a typed call. + w.line("results.add($shortName())") + } else { + w.line( + CodeWriter.list( + "results.add($shortName(", + resultFields.map { rf -> "${rf.name} = ${rsGetterCall(rf, columnExpr(shortName, rf))}" }, + "))", + ), + ) + } + } + } + w.line("results") } - append(" results.add($shortName(\n") - append(rowMapping) - append("\n ))\n") } - append(" }\n") - append(" }\n") - append(" results\n") - append(" }\n") - append("}\n") + return w.toString() } /** diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinUnknownBodyKeysEmitter.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinUnknownBodyKeysEmitter.kt index ed87ed1b5c..dac4e1d693 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinUnknownBodyKeysEmitter.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinUnknownBodyKeysEmitter.kt @@ -1,5 +1,6 @@ package com.metaobjects.generator.kotlin +import com.metaobjects.generator.kotlin.writer.KotlinWriter import com.metaobjects.generator.util.GeneratedFileWriter import java.nio.file.Path @@ -20,49 +21,64 @@ object KotlinUnknownBodyKeysEmitter { /** Write `MetaUnknownBodyKeys.kt` into [pkg] under [outRoot]. */ fun write(pkg: String, outRoot: Path) { - val header = if (pkg.isEmpty()) "" else "package $pkg\n\n" val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve("$FILE_NAME.kt") - GeneratedFileWriter.write(outFile, header + BODY + "\n") + GeneratedFileWriter.write(outFile, render(pkg)) } - /** The fixed body. No Kotlin string templates, so this raw string needs no `$` escaping. */ - val BODY: String = """ - |import com.fasterxml.jackson.databind.JsonNode - | - |/** - | * GENERATED — do not hand-edit. The answer for a write body naming a key the entity does not declare. - | */ - |internal object MetaUnknownBodyKeys { - | /** - | * The 400 body for [body]'s top-level keys outside [known], or null when there are none or [body] is not - | * a JSON object (a body that is not an object is left to the handler's own reading of it). - | */ - | fun refusal(body: JsonNode, known: Set): Map? { - | if (!body.isObject) return null - | val unknown = ArrayList() - | val names = body.fieldNames() - | while (names.hasNext()) { - | val name = names.next() - | if (name !in known) unknown.add(name) - | } - | if (unknown.isEmpty()) return null - | unknown.sortWith { a, b -> compareCodePoints(a, b) } - | return linkedMapOf("error" to "unknown_fields", "fields" to unknown) - | } - | - | /** Ordinal order by Unicode code point (not UTF-16 unit), the order every port answers in. */ - | private fun compareCodePoints(a: String, b: String): Int { - | var i = 0 - | var j = 0 - | while (i < a.length && j < b.length) { - | val ca = a.codePointAt(i) - | val cb = b.codePointAt(j) - | if (ca != cb) return ca.compareTo(cb) - | i += Character.charCount(ca) - | j += Character.charCount(cb) - | } - | return (a.length - i).compareTo(b.length - j) - | } - |} - """.trimMargin() + /** The file for [pkg]: its package line, the imports and the fixed body. */ + fun render(pkg: String): String { + val w = KotlinWriter().packageName(pkg) + writeBody(w) + return w.toString() + } + + /** The file with no package line, for a caller that places it in a package of its own. */ + val BODY: String get() = render("") + + /** + * The imports and the fixed body. No Kotlin string templates, so the snippet needs no `$` + * escaping. + */ + fun writeBody(w: KotlinWriter) { + w.use("com.fasterxml.jackson.databind.JsonNode") + w.text( + """ + /** + * GENERATED — do not hand-edit. The answer for a write body naming a key the entity does not declare. + */ + internal object MetaUnknownBodyKeys { + /** + * The 400 body for [body]'s top-level keys outside [known], or null when there are none or [body] is not + * a JSON object (a body that is not an object is left to the handler's own reading of it). + */ + fun refusal(body: JsonNode, known: Set): Map? { + if (!body.isObject) return null + val unknown = ArrayList() + val names = body.fieldNames() + while (names.hasNext()) { + val name = names.next() + if (name !in known) unknown.add(name) + } + if (unknown.isEmpty()) return null + unknown.sortWith { a, b -> compareCodePoints(a, b) } + return linkedMapOf("error" to "unknown_fields", "fields" to unknown) + } + + /** Ordinal order by Unicode code point (not UTF-16 unit), the order every port answers in. */ + private fun compareCodePoints(a: String, b: String): Int { + var i = 0 + var j = 0 + while (i < a.length && j < b.length) { + val ca = a.codePointAt(i) + val cb = b.codePointAt(j) + if (ca != cb) return ca.compareTo(cb) + i += Character.charCount(ca) + j += Character.charCount(cb) + } + return (a.length - i).compareTo(b.length - j) + } + } + """ + ) + } } diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinValidationIssuesEmitter.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinValidationIssuesEmitter.kt index 6c6e83915d..4e653a662d 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinValidationIssuesEmitter.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinValidationIssuesEmitter.kt @@ -1,5 +1,6 @@ package com.metaobjects.generator.kotlin +import com.metaobjects.generator.kotlin.writer.KotlinWriter import com.metaobjects.generator.util.GeneratedFileWriter import java.nio.file.Path @@ -22,114 +23,129 @@ object KotlinValidationIssuesEmitter { /** Write `MetaValidationIssues.kt` into [pkg] under [outRoot]. */ fun write(pkg: String, outRoot: Path) { - val header = if (pkg.isEmpty()) "" else "package $pkg\n\n" val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve("$FILE_NAME.kt") - GeneratedFileWriter.write(outFile, header + BODY + "\n") + GeneratedFileWriter.write(outFile, render(pkg)) } - /** The fixed body. No Kotlin string templates, so this raw string needs no `$` escaping. */ - val BODY: String = """ - |import com.fasterxml.jackson.databind.JsonMappingException - |import jakarta.validation.ConstraintViolation - |import jakarta.validation.Path - | - |/** - | * GENERATED — do not hand-edit. The validation envelope a controller collects every issue into - | * before answering `400 {"error": "validation", "issues": [...]}`. - | */ - |internal object MetaValidationIssues { - | /** Collects issues; [body] is the response body. */ - | class Collector { - | private val issues = ArrayList>() - | - | fun isEmpty(): Boolean = issues.isEmpty() - | - | fun add(code: String, path: List, message: String): Collector { - | issues.add(linkedMapOf("code" to code, "path" to ArrayList(path), "message" to message)) - | return this - | } - | - | /** Every violation of a whole-bean validate, its path read from the violation after [prefix]. */ - | fun addViolations(violations: Collection>, vararg prefix: Any): Collector { - | for (v in violations) add(codeOf(v), prefix.toList() + pathOf(v.propertyPath), v.message) - | return this - | } - | - | /** Every violation of a single-property validateValue, at exactly [path]. */ - | fun addAt(violations: Collection>, vararg path: Any): Collector { - | for (v in violations) add(codeOf(v), path.toList(), v.message) - | return this - | } - | - | /** Run [read]; a failure becomes an issue at [field] and yields null. */ - | fun bind(field: String, read: () -> T): T? = - | try { - | read() - | } catch (e: Exception) { - | add(MetaDecimalWire.failureCode(e), listOf(field), "field '" + field + "' is not a valid value") - | null - | } - | - | /** A body that could not be bound as a whole: an issue at the field it names (skipped if already listed). */ - | fun addFailure(failure: Throwable): Collector { - | val path = ArrayList() - | var t: Throwable? = failure - | while (t != null) { - | if (t is JsonMappingException && t.path.isNotEmpty()) { - | for (ref in t.path) { - | if (ref.fieldName != null) path.add(ref.fieldName) else if (ref.index >= 0) path.add(ref.index) - | } - | break - | } - | t = if (t.cause === t) null else t.cause - | } - | if (issues.any { it["path"] == path }) return this - | val message = if (path.isEmpty()) "request body is not readable" else "field '" + path[path.size - 1] + "' is not a valid value" - | return add(MetaDecimalWire.failureCode(failure), path, message) - | } - | - | fun body(): Map = linkedMapOf("error" to "validation", "issues" to issues) - | } - | - | /** A path as wire elements: property names, with array indexes and map keys. */ - | fun pathOf(path: Path): List { - | val out = ArrayList() - | for (node in path) { - | if (node.isInIterable) { - | val index = node.index - | val key = node.key - | if (index != null) out.add(index) else if (key != null) out.add(key.toString()) - | } - | val name = node.name - | if (name != null) out.add(name) - | } - | return out - | } - | - | /** The Zod-style code for a Bean Validation violation, from the constraint's annotation. */ - | fun codeOf(v: ConstraintViolation<*>): String { - | val descriptor = v.constraintDescriptor - | val value = v.invalidValue - | val attrs = descriptor.attributes - | return when (descriptor.annotation.annotationClass.java.simpleName) { - | "NotNull" -> "invalid_type" - | "NotBlank", "NotEmpty" -> if (value == null) "invalid_type" else "too_small" - | "Size", "Length" -> { - | val max = attrs["max"] as? Number - | val length: Long? = when (value) { - | is CharSequence -> value.length.toLong() - | is Collection<*> -> value.size.toLong() - | is Map<*, *> -> value.size.toLong() - | else -> null - | } - | if (max != null && length != null && length > max.toLong()) "too_big" else "too_small" - | } - | "Max", "DecimalMax", "Digits", "Negative", "NegativeOrZero" -> "too_big" - | "Min", "DecimalMin", "Positive", "PositiveOrZero" -> "too_small" - | "Pattern", "Email", "URL" -> "invalid_format" - | else -> "custom" - | } - | } - |} - |""".trimMargin() + /** The file for [pkg]: its package line, the imports and the fixed body. */ + fun render(pkg: String): String { + val w = KotlinWriter().packageName(pkg) + writeBody(w) + return w.toString() + } + + /** The file with no package line, for a caller that places it in a package of its own. */ + val BODY: String get() = render("") + + /** + * The imports and the fixed body. No Kotlin string templates, so the snippet needs no `$` + * escaping. + */ + fun writeBody(w: KotlinWriter) { + w.use("com.fasterxml.jackson.databind.JsonMappingException") + w.use("jakarta.validation.ConstraintViolation") + w.use("jakarta.validation.Path") + w.text( + """ + /** + * GENERATED — do not hand-edit. The validation envelope a controller collects every issue into + * before answering `400 {"error": "validation", "issues": [...]}`. + */ + internal object MetaValidationIssues { + /** Collects issues; [body] is the response body. */ + class Collector { + private val issues = ArrayList>() + + fun isEmpty(): Boolean = issues.isEmpty() + + fun add(code: String, path: List, message: String): Collector { + issues.add(linkedMapOf("code" to code, "path" to ArrayList(path), "message" to message)) + return this + } + + /** Every violation of a whole-bean validate, its path read from the violation after [prefix]. */ + fun addViolations(violations: Collection>, vararg prefix: Any): Collector { + for (v in violations) add(codeOf(v), prefix.toList() + pathOf(v.propertyPath), v.message) + return this + } + + /** Every violation of a single-property validateValue, at exactly [path]. */ + fun addAt(violations: Collection>, vararg path: Any): Collector { + for (v in violations) add(codeOf(v), path.toList(), v.message) + return this + } + + /** Run [read]; a failure becomes an issue at [field] and yields null. */ + fun bind(field: String, read: () -> T): T? = + try { + read() + } catch (e: Exception) { + add(MetaDecimalWire.failureCode(e), listOf(field), "field '" + field + "' is not a valid value") + null + } + + /** A body that could not be bound as a whole: an issue at the field it names (skipped if already listed). */ + fun addFailure(failure: Throwable): Collector { + val path = ArrayList() + var t: Throwable? = failure + while (t != null) { + if (t is JsonMappingException && t.path.isNotEmpty()) { + for (ref in t.path) { + if (ref.fieldName != null) path.add(ref.fieldName) else if (ref.index >= 0) path.add(ref.index) + } + break + } + t = if (t.cause === t) null else t.cause + } + if (issues.any { it["path"] == path }) return this + val message = if (path.isEmpty()) "request body is not readable" else "field '" + path[path.size - 1] + "' is not a valid value" + return add(MetaDecimalWire.failureCode(failure), path, message) + } + + fun body(): Map = linkedMapOf("error" to "validation", "issues" to issues) + } + + /** A path as wire elements: property names, with array indexes and map keys. */ + fun pathOf(path: Path): List { + val out = ArrayList() + for (node in path) { + if (node.isInIterable) { + val index = node.index + val key = node.key + if (index != null) out.add(index) else if (key != null) out.add(key.toString()) + } + val name = node.name + if (name != null) out.add(name) + } + return out + } + + /** The Zod-style code for a Bean Validation violation, from the constraint's annotation. */ + fun codeOf(v: ConstraintViolation<*>): String { + val descriptor = v.constraintDescriptor + val value = v.invalidValue + val attrs = descriptor.attributes + return when (descriptor.annotation.annotationClass.java.simpleName) { + "NotNull" -> "invalid_type" + "NotBlank", "NotEmpty" -> if (value == null) "invalid_type" else "too_small" + "Size", "Length" -> { + val max = attrs["max"] as? Number + val length: Long? = when (value) { + is CharSequence -> value.length.toLong() + is Collection<*> -> value.size.toLong() + is Map<*, *> -> value.size.toLong() + else -> null + } + if (max != null && length != null && length > max.toLong()) "too_big" else "too_small" + } + "Max", "DecimalMax", "Digits", "Negative", "NegativeOrZero" -> "too_big" + "Min", "DecimalMin", "Positive", "PositiveOrZero" -> "too_small" + "Pattern", "Email", "URL" -> "invalid_format" + else -> "custom" + } + } + } + """ + ) + } } diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinValidatorGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinValidatorGenerator.kt index 53022c151d..28c6e81d73 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinValidatorGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinValidatorGenerator.kt @@ -10,6 +10,7 @@ import com.metaobjects.generator.kotlin.ExposedImports import com.metaobjects.generator.kotlin.KotlinGenUtil import com.metaobjects.generator.kotlin.KotlinTphPlan import com.metaobjects.generator.kotlin.PackageMapping +import com.metaobjects.generator.kotlin.writer.KotlinWriter import com.metaobjects.generator.GeneratorException import com.metaobjects.generator.GeneratorIOWriter @@ -28,9 +29,7 @@ import com.metaobjects.generator.util.GeneratedFileWriter * - MetadataStartupValidator.kt — registry of (FQN, Table) pairs + a validate(loader) entry point * - ExposedTableValidator.kt — substrate-specific helper that compares one MetaObject to one Table * - *

    Output is emitted as hand-rolled Kotlin source (rather than KotlinPoet) to keep - * generated-code template-string escapes readable and to avoid wrestling with - * `ParameterizedTypeName` quoting for `List>`. + *

    Output is laid out by [KotlinWriter] (ADR-0063), not KotlinPoet. * *

    Args: *

      @@ -80,83 +79,70 @@ open class KotlinValidatorGenerator : MultiFileDirectGeneratorBase() outRoot: Path, exposedApi: ExposedApi = ExposedApi.V0, ) { - val registry = entries.joinToString(",\n ") { (fqn, table, _) -> "\"$fqn\" to $table" } - // The Table objects live in their entity's own package; import any that - // are NOT in this validator's package or the bare reference won't resolve. - val tableImports = entries - .filter { (_, _, tablePkg) -> tablePkg.isNotEmpty() && tablePkg != pkg } - .map { (_, table, tablePkg) -> "$tablePkg.$table" } - .toSortedSet() - - val source = buildString { - if (pkg.isNotEmpty()) { - append("package $pkg\n\n") + val w = KotlinWriter().packageName(pkg) + w.use("com.metaobjects.loader.MetaDataLoader") + w.use("com.metaobjects.metadata.ktx.metaObjectOrNull") + w.use(ExposedImports.core(exposedApi, "Table")) + // The Table objects live in their entity's own package; the writer imports any that are + // NOT in this validator's package, or the bare reference would not resolve. + val registry = entries.map { (fqn, table, tablePkg) -> + val ref = if (tablePkg.isEmpty()) table else w.use("$tablePkg.$table") + listOf(KotlinWriter.str(fqn), " to ", ref) + } + w.doc( + "GENERATED — runtime drift gate. Call [validate] from a Spring `@PostConstruct` or", + "`ApplicationReadyEvent` listener to fail-fast when generated Tables drift from metadata.", + ) + w.block("object MetadataStartupValidator {") { + w.line("private val tablesToValidate: List> = ", KotlinWriter.call("listOf", *registry.toTypedArray())) + w.blank() + w.block("fun validate(loader: MetaDataLoader) {") { + w.line("val errors = mutableListOf()") + w.block("for ((fqn, table) in tablesToValidate) {") { + w.line("val obj = loader.metaObjectOrNull(fqn)") + w.block("if (obj == null) {") { + w.line("errors.add(\"metadata missing \$fqn (generated table: \${table.tableName})\")") + w.line("continue") + } + w.line("ExposedTableValidator.check(obj, table, errors)") + } + w.block("check(errors.isEmpty()) {") { + w.line("\"MetadataStartupValidator: \${errors.size} drift(s):\\n - \" +") + w.indented { w.line("errors.joinToString(\"\\n - \")") } + } } - append("import com.metaobjects.loader.MetaDataLoader\n") - append("import com.metaobjects.metadata.ktx.metaObjectOrNull\n") - append("import ${ExposedImports.core(exposedApi, "Table")}\n") - for (imp in tableImports) append("import $imp\n") - append("\n") - append("/**\n") - append(" * GENERATED — runtime drift gate. Call [validate] from a Spring `@PostConstruct` or\n") - append(" * `ApplicationReadyEvent` listener to fail-fast when generated Tables drift from metadata.\n") - append(" */\n") - append("object MetadataStartupValidator {\n\n") - append(" private val tablesToValidate: List> = listOf(\n ") - append(registry) - append("\n )\n\n") - append(" fun validate(loader: MetaDataLoader) {\n") - append(" val errors = mutableListOf()\n") - append(" for ((fqn, table) in tablesToValidate) {\n") - append(" val obj = loader.metaObjectOrNull(fqn)\n") - append(" if (obj == null) {\n") - append(" errors.add(\"metadata missing \$fqn (generated table: \${table.tableName})\")\n") - append(" continue\n") - append(" }\n") - append(" ExposedTableValidator.check(obj, table, errors)\n") - append(" }\n") - append(" check(errors.isEmpty()) {\n") - append(" \"MetadataStartupValidator: \${errors.size} drift(s):\\n - \" +\n") - append(" errors.joinToString(\"\\n - \")\n") - append(" }\n") - append(" }\n") - append("}\n") } val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve("MetadataStartupValidator.kt") - GeneratedFileWriter.write(outFile, source) + GeneratedFileWriter.write(outFile, w.toString()) } protected open fun emitHelper(pkg: String, outRoot: Path, exposedApi: ExposedApi = ExposedApi.V0) { - val source = buildString { - if (pkg.isNotEmpty()) { - append("package $pkg\n\n") + val w = KotlinWriter().packageName(pkg) + w.use("com.metaobjects.`object`.MetaObject") + w.use("com.metaobjects.field.MetaField") + w.use(ExposedImports.core(exposedApi, "Table")) + w.doc( + "GENERATED — compares a [MetaObject]'s field set vs an Exposed [Table]'s column set", + "and records any discrepancies into the supplied `errors` list.", + ) + w.block("object ExposedTableValidator {") { + w.block("fun check(obj: MetaObject, table: Table, errors: MutableList) {") { + w.line("val expectedCols = obj.metaFields.map { it.name }.toSet()") + w.line("val actualCols = table.columns.map { it.name }.toSet()") + w.line("val missing = expectedCols - actualCols") + w.line("val extra = actualCols - expectedCols") + w.block("if (missing.isNotEmpty()) {") { + w.line("errors.add(\"\${obj.name}: metadata declares fields not in generated table: \$missing\")") + } + w.block("if (extra.isNotEmpty()) {") { + w.line("errors.add(\"\${obj.name}: generated table has columns not in metadata: \$extra\")") + } } - append("import com.metaobjects.`object`.MetaObject\n") - append("import com.metaobjects.field.MetaField\n") - append("import ${ExposedImports.core(exposedApi, "Table")}\n\n") - append("/**\n") - append(" * GENERATED — compares a [MetaObject]'s field set vs an Exposed [Table]'s column set\n") - append(" * and records any discrepancies into the supplied `errors` list.\n") - append(" */\n") - append("object ExposedTableValidator {\n\n") - append(" fun check(obj: MetaObject, table: Table, errors: MutableList) {\n") - append(" val expectedCols = obj.metaFields.map { it.name }.toSet()\n") - append(" val actualCols = table.columns.map { it.name }.toSet()\n") - append(" val missing = expectedCols - actualCols\n") - append(" val extra = actualCols - expectedCols\n") - append(" if (missing.isNotEmpty()) {\n") - append(" errors.add(\"\${obj.name}: metadata declares fields not in generated table: \$missing\")\n") - append(" }\n") - append(" if (extra.isNotEmpty()) {\n") - append(" errors.add(\"\${obj.name}: generated table has columns not in metadata: \$extra\")\n") - append(" }\n") - append(" }\n") - append("}\n") } val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve("ExposedTableValidator.kt") - GeneratedFileWriter.write(outFile, source) + GeneratedFileWriter.write(outFile, w.toString()) } // === MultiFileDirectGeneratorBase abstract-method stubs ==================== diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/writer/KotlinWriter.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/writer/KotlinWriter.kt new file mode 100644 index 0000000000..0407e0ae01 --- /dev/null +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/writer/KotlinWriter.kt @@ -0,0 +1,237 @@ +package com.metaobjects.generator.kotlin.writer + +import com.metaobjects.generator.writer.CodeWriter +import com.metaobjects.generator.writer.Group +import com.metaobjects.generator.writer.WriterException +import com.metaobjects.generator.writer.WriterOptions +import java.util.TreeMap +import java.util.TreeSet + +/** + * The Kotlin dialect of the code writer (ADR-0063; contract: `spec/code-writer.md`, "Kotlin + * dialect"). It extends the language-neutral core in `codegen-base` + * ([CodeWriter]), the same core the Java writer extends. + * + * Adds what is Kotlin's own: the `package` line, imports collected while the body is written + * and printed first (with `as` aliases), Kotlin string quoting (a `$` is escaped), KDoc comments, + * and the scoped forms Kotlin source needs: [block] with a trailing lambda, [reopen] for + * `} else {`, and [indented] for a continuation that opens no block. + * + * Built to be extended, like the core: each section of the file ([writeHeader], [writePackage], + * [writeImports]) is its own overridable method, and none of them is a stability contract. + */ +open class KotlinWriter @JvmOverloads constructor(options: WriterOptions = KOTLIN) : CodeWriter(options) { + + /** Local name to the fully qualified name that owns it, so one name cannot come from two types. */ + protected val locals: MutableMap = TreeMap() + + /** What each import line names after `import `: `a.b.C` or `a.b.C as D`. */ + protected val imports: MutableSet = TreeSet() + + /** The fully qualified name behind each entry of [imports], to decide whether it needs a line. */ + protected val importTargets: MutableMap = TreeMap() + + protected val headLines: MutableList = ArrayList() + protected var packageName: String? = null + + /** The `package` this file is in; a type in that package needs no import. */ + open fun packageName(name: String): KotlinWriter { + packageName = name + return this + } + + /** + * Reference a type (or a top-level function or property) by its fully qualified name; returns + * the name to write, its last segment. A name in a package Kotlin imports by default, or in + * this file's package, prints no import line. A nested type (`java.util.Map.Entry`) is + * imported as written and written by its last segment. + */ + open fun use(qualifiedName: String): String = record(qualifiedName, simpleName(qualifiedName), null) + + /** Reference [qualifiedName] under the local name [alias]: `import a.b.C as D`; returns [alias]. */ + open fun use(qualifiedName: String, alias: String): String = record(qualifiedName, alias, alias) + + protected open fun record(qualifiedName: String, local: String, alias: String?): String { + val owner = locals[local] + if (owner != null && owner != qualifiedName) { + throw WriterException( + WriterException.IMPORT_CONFLICT, "$local is imported from both $owner and $qualifiedName", + ) + } + locals[local] = qualifiedName + val spec = escapeName(qualifiedName) + if (alias == null) "" else " as " + escapeName(alias) + imports.add(spec) + importTargets[spec] = if (alias == null) qualifiedName else "" + return escapeName(local) + } + + /** Lines printed at the very top, before the package line: a banner comment or a file annotation. */ + open fun header(vararg lines: String): KotlinWriter { + headLines.addAll(lines) + return this + } + + /** + * A KDoc comment: one line when it fits, otherwise a block with one ` * ` line per entry and a + * bare ` *` line for an empty entry. Kotlin comments nest, so both `*` + `/` and `/` + `*` + * inside the text are neutralised. + */ + open fun doc(vararg lines: String): KotlinWriter { + if (lines.isEmpty()) return this + val safe = lines.map { it.replace("*/", "*/").replace("/*", "/*") } + val one = "/** " + safe[0] + " */" + if (safe.size == 1 && fits(one)) { + line(one) + return this + } + line("/**") + for (l in safe) line(if (l.isEmpty()) " *" else " * $l") + line(" */") + return this + } + + /** + * A block written with a trailing lambda: `w.block("class A {") { ... }` writes the head, + * indents, runs [body], dedents and writes [tail]. + */ + @JvmOverloads + open fun block(head: Any, tail: Any = "}", body: () -> Unit): KotlinWriter { + open(head) + body() + close(tail) + return this + } + + /** + * Close the open block and open the next on one line, as in `} else {` or + * `} catch (e: Exception) {`. With no block open it is `ERR_WRITER_UNBALANCED_CLOSE`. + */ + open fun reopen(vararg parts: Any): KotlinWriter { + val p = piece(parts.toList()) + if (openers.isEmpty()) { + throw WriterException(WriterException.UNBALANCED_CLOSE, "reopen(\"" + flat(p) + "\") with no block open") + } + openers.removeAt(openers.size - 1) + wantBlank = false + openPiece(p) + return this + } + + /** + * Write [body] one level in, opening no block and closing none: the continuation of an + * expression body (`fun f() =`), or of a statement broken by the generator. + */ + open fun indented(body: () -> Unit): KotlinWriter { + openers.add(NO_BLOCK) + try { + body() + } finally { + openers.removeAt(openers.size - 1) + } + return this + } + + override fun toString(): String { + val head = sectionWriter() + writeHeader(head) + head.blank() + writePackage(head) + head.blank() + writeImports(head) + val top = head.toString() + val body = super.toString() + if (top.isEmpty()) return body + if (body.isEmpty()) return top + return top + "\n" + body + } + + /** The writer the header, package and import sections are laid out with: same options, no dialect. */ + protected open fun sectionWriter(): CodeWriter = CodeWriter(options) + + /** The [header] lines, as given. */ + protected open fun writeHeader(w: CodeWriter) { + for (l in headLines) w.line(l) + } + + /** The `package` line, when one was set and is not the default (empty) package. */ + protected open fun writePackage(w: CodeWriter) { + val pkg = packageName + if (!pkg.isNullOrEmpty()) w.line("package ", escapeName(pkg)) + } + + /** One `import` line per name, in code-unit order of what follows `import `. */ + protected open fun writeImports(w: CodeWriter) { + for (spec in imports) { + if (needsImport(importTargets.getValue(spec))) w.line("import ", spec) + } + } + + /** + * False for a name in a package Kotlin imports by default or in the file's own package. An + * aliased import ([importTargets] holds `""`) always needs its line, since the alias is the + * only way the file can say the name. + */ + protected open fun needsImport(qualifiedName: String): Boolean { + if (qualifiedName.isEmpty()) return true + val dot = qualifiedName.lastIndexOf('.') + if (dot < 0) return false + val pkg = qualifiedName.substring(0, dot) + return pkg !in DEFAULT_IMPORTS && pkg != (packageName ?: "") + } + + companion object { + /** Four spaces, 120 columns and a trailing comma on a broken list, as Kotlin's coding conventions write it. */ + @JvmField + val KOTLIN: WriterOptions = WriterOptions(" ", 120, true) + + /** The opener text recorded for an indent that opens no block. */ + protected const val NO_BLOCK: String = "" + + /** The packages every Kotlin/JVM file imports by default (Kotlin language spec, "Default imports"). */ + @JvmField + val DEFAULT_IMPORTS: Set = setOf( + "kotlin", "kotlin.annotation", "kotlin.collections", "kotlin.comparisons", "kotlin.io", + "kotlin.ranges", "kotlin.sequences", "kotlin.text", "kotlin.jvm", "java.lang", + ) + + /** Kotlin's hard keywords: as a name segment each must be written in backticks. */ + @JvmField + val HARD_KEYWORDS: Set = setOf( + "as", "break", "class", "continue", "do", "else", "false", "for", "fun", "if", "in", + "interface", "is", "null", "object", "package", "return", "super", "this", "throw", "true", + "try", "typealias", "typeof", "val", "var", "when", "while", + ) + + /** A correctly quoted Kotlin string literal; a `$` is escaped, so the value is never a template. */ + @JvmStatic + fun str(value: String): String { + val sb = StringBuilder(value.length + 2).append('"') + for (c in value) { + when (c) { + '"' -> sb.append("\\\"") + '\\' -> sb.append("\\\\") + '$' -> sb.append("\\$") + '\n' -> sb.append("\\n") + '\r' -> sb.append("\\r") + '\t' -> sb.append("\\t") + '\b' -> sb.append("\\b") + else -> if (c.code < 0x20 || c.code == 0x7f) sb.append(String.format("\\u%04x", c.code)) else sb.append(c) + } + } + return sb.append('"').toString() + } + + /** A call: `fn(a, b)`, a list that breaks one argument per line. */ + @JvmStatic + fun call(fn: String, vararg args: Any): Group = list("$fn(", args.toList(), ")") + + /** A dotted name with each hard-keyword segment in backticks: `com.acme.`object``. */ + @JvmStatic + fun escapeName(name: String): String = + name.split('.').joinToString(".") { if (it in HARD_KEYWORDS) "`$it`" else it } + + /** The last segment of a dotted name. */ + @JvmStatic + fun simpleName(qualified: String): String = qualified.substring(qualified.lastIndexOf('.') + 1) + } +} diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinReportRestSurfaceTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinReportRestSurfaceTest.kt index 0d3e4f920c..bf214182f9 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinReportRestSurfaceTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinReportRestSurfaceTest.kt @@ -286,16 +286,12 @@ class KotlinReportRestSurfaceTest { | * operator vocabulary for each field by its subtype. | */ |object StoreTotalsFilterAllowlist { - | val FIELDS: Set = setOf( - | "purchases", - | "buyers", - | "revenue", - | ) + | val FIELDS: Set = setOf("purchases", "buyers", "revenue") | | val OPS_BY_FIELD: Map> = mapOf( | "purchases" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), | "buyers" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), - | "revenue" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull") + | "revenue" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), | ) |} |""".trimMargin(), diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/writer/KotlinWriterConformanceTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/writer/KotlinWriterConformanceTest.kt new file mode 100644 index 0000000000..8b0b7ba224 --- /dev/null +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/writer/KotlinWriterConformanceTest.kt @@ -0,0 +1,118 @@ +package com.metaobjects.generator.kotlin.writer + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import com.metaobjects.generator.writer.CodeWriter +import com.metaobjects.generator.writer.Group +import com.metaobjects.generator.writer.WriterException +import com.metaobjects.generator.writer.WriterOptions +import java.nio.file.Files +import java.nio.file.Path +import kotlin.io.path.name +import kotlin.io.path.readText +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import kotlin.test.fail +import org.junit.jupiter.api.DynamicTest +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestFactory + +/** + * Runs `fixtures/writer-conformance/` against the Kotlin writer (spec/code-writer.md). `core` + * cases run on the shared [CodeWriter] core with the options the case states; `kotlin` cases run + * on [KotlinWriter] with its own defaults unless the case overrides them. A case of another + * dialect belongs to that port's writer and is skipped here by name. + */ +class KotlinWriterConformanceTest { + + private val cases: Path = Path.of(System.getProperty("user.dir")) + .resolve("../../../fixtures/writer-conformance/cases").normalize() + + private fun corpus(): List> = + Files.list(cases).use { files -> + files.filter { it.name.endsWith(".json") }.sorted().toList() + .map { it.name.removeSuffix(".json") to MAPPER.readTree(it.readText()) } + .filter { it.second.get("dialect").asText() in setOf(CORE, KOTLIN) } + } + + @Test + fun the_corpus_has_core_and_kotlin_cases() { + val dialects = corpus().map { it.second.get("dialect").asText() }.toSet() + assertEquals(setOf(CORE, KOTLIN), dialects) + } + + @TestFactory + fun cases(): List = corpus().map { (name, c) -> DynamicTest.dynamicTest(name) { check(c) } } + + private fun check(c: JsonNode) { + val core = c.get("dialect").asText() == CORE + if (core) assertNotNull(c.get("options"), "a core case states its options") + if (c.has("error")) { + try { + run(c, core) + } catch (e: WriterException) { + assertEquals(c.get("error").asText(), e.code()) + if (c.has("errorQuotes")) assertTrue(e.message!!.contains(c.get("errorQuotes").asText()), e.message) + return + } + fail("expected " + c.get("error").asText()) + } + val lines = c.get("expected").map { it.asText() } + assertEquals(if (lines.isEmpty()) "" else lines.joinToString("\n") + "\n", run(c, core)) + } + + private fun run(c: JsonNode, core: Boolean): String { + val w: CodeWriter = if (core) CodeWriter(options(c, core)) else KotlinWriter(options(c, core)) + for (op in c.get("ops")) { + val name = op.get(0).asText() + val args = (1 until op.size()).map { piece(op.get(it)) } + when (name) { + "line" -> w.line(*args.toTypedArray()) + "open" -> w.open(*args.toTypedArray()) + "close" -> w.close(*args.toTypedArray()) + "blank" -> w.blank() + "text" -> w.text(args[0] as String) + else -> { + val k = w as? KotlinWriter ?: error("op $name is not a core op") + val s = args.map { it as String } + when (name) { + "package" -> k.packageName(s[0]) + "use" -> k.use(s[0]) + "useAs" -> k.use(s[0], s[1]) + "header" -> k.header(*s.toTypedArray()) + "doc" -> k.doc(*s.toTypedArray()) + "reopen" -> k.reopen(*args.toTypedArray()) + else -> error("unknown op $name") + } + } + } + } + return w.toString() + } + + /** The case's options laid over the dialect's defaults (core states all three). */ + private fun options(c: JsonNode, core: Boolean): WriterOptions { + var o = if (core) WriterOptions(" ", 120, true) else KotlinWriter.KOTLIN + val given = c.get("options") ?: return o + given.get("indent")?.let { o = o.withIndent(it.asText()) } + given.get("width")?.let { o = o.withWidth(it.asInt()) } + given.get("trailingComma")?.let { o = o.withTrailingComma(it.asBoolean()) } + return o + } + + private fun piece(p: JsonNode): Any = when { + p.isTextual -> p.asText() + p.isArray -> p.map { piece(it) } + else -> { + val l = p.get("list") + Group(l.get("open").asText(), l.get("items").map { piece(it) }, l.get("close").asText(), l.path("pad").asBoolean(false)) + } + } + + private companion object { + const val CORE = "core" + const val KOTLIN = "kotlin" + val MAPPER = ObjectMapper() + } +} diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/writer/layout/KotlinLayoutAnalyzer.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/writer/layout/KotlinLayoutAnalyzer.kt new file mode 100644 index 0000000000..5096bea8f9 --- /dev/null +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/writer/layout/KotlinLayoutAnalyzer.kt @@ -0,0 +1,174 @@ +package com.metaobjects.generator.kotlin.writer.layout + +import org.jetbrains.kotlin.lexer.KotlinLexer +import org.jetbrains.kotlin.lexer.KtTokens + +/** + * Finds hand-typed layout in Kotlin generator source (ADR-0063): the line breaks and indentation + * the code writer owns. It reads the source with the Kotlin compiler's own lexer, so comments and + * KDoc are never findings, and a string literal is judged by what it contains, template entries + * and all. + * + * What counts: + * - [Kind.NEWLINE_LITERAL]: a string or character literal that holds a line break (a `\n` or `\r` + * escape, or a raw string spanning lines), and a call that writes one (`appendLine`, + * `lineSeparator`). + * - [Kind.INDENT_LITERAL]: a string literal that starts with an indentation run (two spaces or a tab), + * unless it follows a `+` (text inside a line, not the line's start). + * - [Kind.INDENT_REPEAT]: a whitespace-only literal repeated (`" ".repeat(depth)`). + * - [Kind.PRINTER_IMPORT]: an import of KotlinPoet, a printer that lays the text out itself. + * + * What does not: a fixed snippet passed straight to the writer's `text(...)`, which re-indents it, + * and a literal used to search or compare, not to write: the argument of `split`, + * `contains`, `indexOf`, `startsWith`, `Regex` and the like, the first argument of `replace`, an operand of + * `==` or `!=`, and a `when` branch condition. + */ +object KotlinLayoutAnalyzer { + + enum class Kind { INDENT_LITERAL, INDENT_REPEAT, NEWLINE_LITERAL, PRINTER_IMPORT } + + data class Finding(val kind: Kind, val line: Int, val column: Int, val text: String) { + override fun toString(): String = "$line:$column $kind $text" + } + + /** The modules whose main source is generator source. */ + val SCANNED_MODULES: List = listOf("codegen-kotlin") + + /** + * Whether [path] (relative to `server/java/`) is generator source the ratchet holds: Kotlin main + * source of a scanned module, outside the writer package, which is the one place layout lives. + */ + fun isGeneratorSource(path: String): Boolean { + if (!path.endsWith(".kt")) return false + val module = SCANNED_MODULES.firstOrNull { path.startsWith("$it/src/main/kotlin/") } ?: return false + return !path.removePrefix("$module/src/main/kotlin/").contains("/writer/") + } + + /** A function whose literal argument is a pattern to look for, not text to write. */ + private val SEARCHES = setOf( + "split", "contains", "indexOf", "lastIndexOf", "startsWith", "endsWith", "removePrefix", + "removeSuffix", "substringBefore", "substringAfter", "substringBeforeLast", "substringAfterLast", + "trimEnd", "trimStart", "count", "lines", "Regex", "toRegex", + ) + + private val WRITES_A_LINE_BREAK = setOf("appendLine", "lineSeparator") + + private class Tok(val type: String, val text: String, val offset: Int) + + private class Literal(val open: Int) { + val parts = StringBuilder() + var first: String? = null + var newline = false + } + + fun analyze(name: String, source: String): List { + val toks = lex(name, source) + val out = ArrayList() + val stack = ArrayDeque() + for ((i, t) in toks.withIndex()) { + when (t.type) { + OPEN_QUOTE -> stack.addLast(Literal(i)) + REGULAR -> stack.lastOrNull()?.let { l -> + if (l.first == null) l.first = t.text + if ('\n' in t.text || '\r' in t.text) l.newline = true + l.parts.append(t.text) + } + ESCAPE -> stack.lastOrNull()?.let { l -> + if (l.first == null) l.first = t.text + if (t.text == "\\n" || t.text == "\\r") l.newline = true + l.parts.append(if (t.text == "\\t") "\t" else "x") + } + TEMPLATE -> stack.lastOrNull()?.let { l -> + if (l.first == null) l.first = "" + l.parts.append("x") + } + CLOSE_QUOTE -> { + val l = stack.removeLastOrNull() ?: continue + if (searched(toks, l.open, i)) continue + val at = toks[l.open] + val literal = source.substring(at.offset, t.offset + t.text.length) + val first = l.first ?: "" + val ws = l.parts.isNotEmpty() && l.parts.all { it == ' ' || it == '\t' } + when { + l.newline -> out += finding(Kind.NEWLINE_LITERAL, source, at.offset, literal) + ws && toks.getOrNull(i + 1)?.text == "." && toks.getOrNull(i + 2)?.text == "repeat" -> + out += finding(Kind.INDENT_REPEAT, source, at.offset, literal) + toks.getOrNull(l.open - 1)?.text != "+" && + (first.startsWith(" ") || first.startsWith("\t") || first == "\\t") -> + out += finding(Kind.INDENT_LITERAL, source, at.offset, literal) + } + } + CHAR -> if ((t.text == "'\\n'" || t.text == "'\\r'") && !searchedChar(toks, i)) { + out += finding(Kind.NEWLINE_LITERAL, source, t.offset, t.text) + } + // `import` is a soft keyword: the lexer hands it over as an identifier. + IDENT -> if (t.text == "import" && toks.subList(i + 1, minOf(i + 6, toks.size)).joinToString("") { it.text } == "com.squareup.kotlinpoet") { + out += finding(Kind.PRINTER_IMPORT, source, t.offset, "import com.squareup.kotlinpoet") + } else if (t.text in WRITES_A_LINE_BREAK && toks.getOrNull(i + 1)?.text == "(") { + out += finding(Kind.NEWLINE_LITERAL, source, t.offset, t.text) + } + } + } + return out + } + + /** Whether the literal from token [open] to [close] is a search pattern or a comparison operand. */ + private fun searched(toks: List, open: Int, close: Int): Boolean { + val before = toks.getOrNull(open - 1)?.text + val call = toks.getOrNull(open - 2)?.text + val after = toks.getOrNull(close + 1)?.text + if (before == "==" || before == "!=" || after == "==" || after == "!=") return true + if (after == "->") return true + if (before == "(" && call in SEARCHES) return true + // A snippet handed to the writer's `text()`: the writer re-indents it to the current level. + if (before == "(" && call == "text" && after == ")") return true + if (before == "(" && call == "replace" && after == ",") return true + return false + } + + private fun searchedChar(toks: List, i: Int): Boolean = searched(toks, i, i) + + private fun finding(kind: Kind, source: String, offset: Int, text: String): Finding { + var line = 1 + var col = 1 + for (k in 0 until offset) { + if (source[k] == '\n') { line++; col = 1 } else col++ + } + return Finding(kind, line, col, text.lineSequence().first().take(60)) + } + + private const val OPEN_QUOTE = "OPEN_QUOTE" + private const val CLOSE_QUOTE = "CLOSING_QUOTE" + private const val REGULAR = "REGULAR_STRING_PART" + private const val ESCAPE = "ESCAPE_SEQUENCE" + private const val TEMPLATE = "TEMPLATE" + private const val CHAR = "CHARACTER_LITERAL" + private const val IDENT = "IDENTIFIER" + + /** The source's tokens, without whitespace and comments; a lexer error refuses the file. */ + private fun lex(name: String, source: String): List { + val lexer = KotlinLexer() + lexer.start(source) + val out = ArrayList() + while (true) { + val type = lexer.tokenType ?: break + val text = source.substring(lexer.tokenStart, lexer.tokenEnd) + val kind = when { + type == KtTokens.WHITE_SPACE || KtTokens.COMMENTS.contains(type) -> null + type == KtTokens.OPEN_QUOTE -> OPEN_QUOTE + type == KtTokens.CLOSING_QUOTE -> CLOSE_QUOTE + type == KtTokens.REGULAR_STRING_PART -> REGULAR + type == KtTokens.ESCAPE_SEQUENCE -> ESCAPE + type == KtTokens.SHORT_TEMPLATE_ENTRY_START || type == KtTokens.LONG_TEMPLATE_ENTRY_START -> TEMPLATE + type == KtTokens.CHARACTER_LITERAL -> CHAR + type == KtTokens.IDENTIFIER -> IDENT + type.toString() == "BAD_CHARACTER" -> + throw IllegalStateException("cannot lex $name at offset ${lexer.tokenStart}") + else -> type.toString() + } + if (kind != null) out += Tok(kind, text, lexer.tokenStart) + lexer.advance() + } + return out + } +} diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/writer/layout/KotlinLayoutRatchetTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/writer/layout/KotlinLayoutRatchetTest.kt new file mode 100644 index 0000000000..5557ce2ea0 --- /dev/null +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/writer/layout/KotlinLayoutRatchetTest.kt @@ -0,0 +1,287 @@ +package com.metaobjects.generator.kotlin.writer.layout + +import com.fasterxml.jackson.databind.ObjectMapper +import com.metaobjects.generator.kotlin.writer.layout.KotlinLayoutAnalyzer.Kind +import java.nio.file.Files +import java.nio.file.Path +import kotlin.io.path.isRegularFile +import kotlin.io.path.readText +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import kotlin.test.fail +import org.junit.jupiter.api.Assumptions.assumeTrue + +/** + * The Kotlin layout ratchet (ADR-0063): generator source never types layout; the writer does. + * + * Three parts, as in the other ports: the analyzer's own cases (layout it must catch, and + * writer-based code it must pass), the scope rule (which files are generator source, by rule and + * not by list) and the ratchet over the real module: every file with hand-typed layout is on the + * allowlist with a reason, every allowlisted file still needs its entry, and the allowlist only + * shrinks. + */ +class KotlinLayoutRatchetTest { + + private fun kinds(body: String): List = + KotlinLayoutAnalyzer.analyze("Fixture.kt", "fun f() {\n$body\n}").map { it.kind }.sorted() + + // ── 1. the analyzer ────────────────────────────────────────────────────────────────── + + @Test + fun catches_a_newline_escape_and_a_raw_string_over_lines() { + assertEquals(listOf(Kind.NEWLINE_LITERAL), kinds("val s = \"a\\nb\"")) + assertEquals(listOf(Kind.NEWLINE_LITERAL), kinds("val s = \"a\\r\"")) + assertEquals(listOf(Kind.NEWLINE_LITERAL), kinds("sb.append('\\n')")) + assertEquals(listOf(Kind.NEWLINE_LITERAL), kinds("val s = \"\"\"\n a\n\"\"\".trimIndent()")) + assertEquals(listOf(Kind.NEWLINE_LITERAL), kinds("val s = \"\${x}\\n\"")) + } + + @Test + fun catches_a_call_that_writes_a_line_break() { + assertEquals(listOf(Kind.NEWLINE_LITERAL), kinds("sb.appendLine(x)")) + assertEquals(listOf(Kind.NEWLINE_LITERAL), kinds("val nl = System.lineSeparator()")) + } + + @Test + fun catches_a_string_that_starts_with_an_indentation_run() { + assertEquals(listOf(Kind.INDENT_LITERAL), kinds("rows.add(\" \" + name)")) + assertEquals(listOf(Kind.INDENT_LITERAL), kinds("rows.add(\"\\tx\")")) + assertEquals(listOf(Kind.INDENT_LITERAL), kinds("rows.add(\" val \$name: String\")")) + } + + @Test + fun catches_an_indentation_repeat() { + assertEquals(listOf(Kind.INDENT_REPEAT), kinds("val pad = \" \".repeat(depth)")) + assertEquals(listOf(Kind.INDENT_REPEAT), kinds("val pad = \" \".repeat(depth * 2)")) + } + + @Test + fun catches_an_import_of_kotlinpoet() { + val source = "import com.squareup.kotlinpoet.FileSpec\nimport com.squareup.kotlinpoetx.Other\nfun f() = 1" + assertEquals(listOf(Kind.PRINTER_IMPORT), KotlinLayoutAnalyzer.analyze("F.kt", source).map { it.kind }) + } + + @Test + fun a_string_inside_a_template_is_judged_on_its_own() { + assertEquals(listOf(Kind.NEWLINE_LITERAL), kinds("val s = \"a\${xs.joinToString(\"\\n\")}b\"")) + } + + @Test + fun findings_carry_the_line_and_column_of_the_literal() { + val f = KotlinLayoutAnalyzer.analyze("F.kt", "fun f() {\n val s = \"a\\nb\"\n}").single() + assertEquals(2, f.line) + assertEquals(13, f.column) + } + + @Test + fun passes_a_generator_written_on_the_writer() { + val source = """ + import com.metaobjects.generator.kotlin.writer.KotlinWriter + + // Comments may say anything, including "\n" and + // indented text: a comment is never a finding. + /** + * KDoc, indented, with "\n" in it + */ + fun render(name: String): String { + val w = KotlinWriter() + val list = w.use("kotlin.collections.List") + w.block("class ${'$'}name {") { + w.line("val names: ", list, " = emptyList()") + w.blank() + w.line("fun size() = names.size") + w.text(""${'"'} + fun first(): String = + names.first() + ""${'"'}) + } + return w.toString() + } + """.trimIndent() + assertEquals(emptyList(), KotlinLayoutAnalyzer.analyze("Gen.kt", source)) + } + + @Test + fun a_line_break_used_as_a_search_pattern_or_comparison_is_not_output() { + assertEquals(emptyList(), kinds("val p = description.split(\"\\n\")")) + assertEquals(emptyList(), kinds("if (body.contains(\"\\n\")) flag()")) + assertEquals(emptyList(), kinds("val s = body.replace(\"\\r\\n\", \" \")")) + assertEquals(emptyList(), kinds("val at = body.indexOf(\" \")")) + assertEquals(emptyList(), kinds("if (c == '\\n') flag()")) + assertEquals(emptyList(), kinds("when (c) { '\\n' -> flag(); else -> {} }")) + assertEquals(emptyList(), kinds("when (s) { \"\\n\" -> flag(); else -> {} }")) + assertEquals(emptyList(), kinds("val lines = text.split(Regex(\"\\r\\n|\\r|\\n\"))")) + } + + @Test + fun a_replacement_that_writes_a_line_break_is_still_output() { + assertEquals(listOf(Kind.NEWLINE_LITERAL), kinds("val s = body.replace(\";\", \";\\n\")")) + } + + @Test + fun single_spaces_and_text_after_a_concatenation_are_not_layout() { + assertEquals(emptyList(), kinds("val a = names.joinToString(\", \"); val b = left + \" \" + right; val c = \" \" + x")) + } + + // ── 2. the scope rule ──────────────────────────────────────────────────────────────── + + @Test + fun scope_is_decided_by_rule() { + val cases = mapOf( + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt" to true, + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/apidocs/KotlinApiDocsRenderer.kt" to true, + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/writer/KotlinWriter.kt" to false, + "codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt" to false, + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KNOWN_GAPS.md" to false, + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java" to false, + ) + for ((path, expected) in cases) assertEquals(expected, KotlinLayoutAnalyzer.isGeneratorSource(path), path) + } + + // ── 3. the ratchet over the real module ───────────────────────────────────────────────── + + /** The allowlist: `unconverted` and `exempt`, each a map from file to its written reason. */ + data class Allowlist(val unconverted: Map, val exempt: Map) { + val entries: Map get() = (unconverted + exempt).toSortedMap() + } + + @Test + fun it_reads_every_scanned_module() { + for (m in KotlinLayoutAnalyzer.SCANNED_MODULES) assertTrue(findings.keys.any { it.startsWith("$m/") }, m) + } + + @Test + fun no_generator_source_types_layout_unless_its_file_is_allowlisted() { + val entries = allowlist.entries + val offenders = findings.filter { (file, found) -> found.isNotEmpty() && file !in entries } + .map { (file, found) -> file + "\n" + found.joinToString("\n") { " $it" } } + assertEquals( + emptyList(), offenders, + "Write these lines through KotlinWriter (generator/kotlin/writer/) instead of typing line breaks or" + + " indentation. A file is never added to the allowlist: it only shrinks.", + ) + } + + @Test + fun every_allowlisted_file_still_needs_its_entry() { + val stale = allowlist.entries.keys.filter { findings[it].isNullOrEmpty() } + assertEquals(emptyList(), stale, "these files no longer type layout (or no longer exist): remove their allowlist entries") + } + + @Test + fun every_allowlisted_path_is_generator_source_that_exists() { + for (file in allowlist.entries.keys) { + assertTrue(KotlinLayoutAnalyzer.isGeneratorSource(file), "$file is not in the ratchet's scope") + assertTrue(Files.exists(JAVA.resolve(file)), "$file does not exist") + } + } + + @Test + fun every_entry_carries_a_written_reason() { + allowlist.entries.forEach { (file, reason) -> assertTrue(reason.length > 40, "$file needs a reason") } + } + + @Test + fun a_file_is_either_unconverted_or_exempt_never_both_and_each_list_is_sorted() { + for (f in allowlist.unconverted.keys) assertFalse(f in allowlist.exempt, f) + val raw = MAPPER.readTree(ALLOWLIST.readText()) + for (list in listOf("unconverted", "exempt")) { + val keys = raw.path(list).fieldNames().asSequence().toList() + assertEquals(keys.sorted(), keys, "$list is sorted") + } + } + + /** The allowlist may only shrink. Compared with the copy at the merge base of every integration branch this checkout knows. */ + @Test + fun the_allowlist_only_shrinks() { + val bases = mergeBaseAllowlists() + assumeTrue(bases != null, "git or the integration refs are unavailable (an export or a shallow clone)") + for (base in bases!!) { + assertEquals(emptyList(), growth(base, allowlist), "the allowlist grew since the merge base; convert the file to the writer instead") + } + } + + @Test + fun growth_is_an_added_entry_or_an_unconverted_file_relabelled_exempt_and_removal_is_not() { + val before = Allowlist(mapOf("A.kt" to "r", "B.kt" to "r"), mapOf("C.kt" to "r")) + assertEquals(emptyList(), growth(before, Allowlist(mapOf("A.kt" to "r"), emptyMap()))) + assertEquals(listOf("added D.kt"), growth(before, Allowlist(mapOf("A.kt" to "r", "D.kt" to "r"), mapOf("C.kt" to "r")))) + assertEquals( + listOf("relabelled B.kt as exempt"), + growth(before, Allowlist(mapOf("A.kt" to "r"), mapOf("B.kt" to "r", "C.kt" to "r"))), + ) + } + + private companion object { + val MAPPER = ObjectMapper() + + /** `server/java/`: the tests run with the module as the working directory. */ + val JAVA: Path = Path.of(System.getProperty("user.dir")).resolve("..").normalize() + + val ALLOWLIST: Path = Path.of(System.getProperty("user.dir"), "src/test/resources/layout-ratchet/allowlist.json") + + fun readAllowlist(json: String): Allowlist { + val raw = MAPPER.readTree(json) + fun strings(name: String): Map = + raw.path(name).fields().asSequence().associate { it.key to it.value.asText() }.toSortedMap() + return Allowlist(strings("unconverted"), strings("exempt")) + } + + val allowlist: Allowlist = readAllowlist(ALLOWLIST.readText()) + + val findings: Map> = sortedMapOf>().also { out -> + for (module in KotlinLayoutAnalyzer.SCANNED_MODULES) { + Files.walk(JAVA.resolve(module).resolve("src/main/kotlin")).use { files -> + for (f in files.filter { it.isRegularFile() }.toList()) { + val rel = JAVA.relativize(f).toString().replace('\\', '/') + if (KotlinLayoutAnalyzer.isGeneratorSource(rel)) out[rel] = KotlinLayoutAnalyzer.analyze(rel, f.readText()) + } + } + } + // `-Dlayout.dump=` lists every file that types layout, to write or prune allowlist entries. + System.getProperty("layout.dump")?.let { dump -> + Files.write( + Path.of(dump), + out.filterValues { it.isNotEmpty() }.map { (f, found) -> + f + "\t" + found.size + "\t" + found.map { it.kind }.distinct().sorted().joinToString(",") + }, + ) + } + } + + /** How [now] grew relative to [before]: entries that are new, and unconverted files relabelled exempt. */ + fun growth(before: Allowlist, now: Allowlist): List { + val had = before.entries + return now.entries.keys.filter { it !in had }.map { "added $it" } + + now.exempt.keys.filter { it in before.unconverted }.map { "relabelled $it as exempt" } + } + + fun git(vararg args: String): String? = try { + val p = ProcessBuilder(listOf("git", "-C", JAVA.toString()) + args) + .redirectError(ProcessBuilder.Redirect.DISCARD).start() + val out = p.inputStream.readBytes().toString(Charsets.UTF_8).trim() + if (p.waitFor() == 0) out else null + } catch (e: Exception) { + null + } + + /** The allowlist as it stood at the merge base of HEAD with each integration branch; null when git or those refs are unavailable. */ + fun mergeBaseAllowlists(): List? { + val refs = git("for-each-ref", "--format=%(refname:short)", "refs/remotes/origin/main", "refs/remotes/origin/release/") + if (refs.isNullOrEmpty()) return null + val top = git("rev-parse", "--show-toplevel") ?: return null + val rel = Path.of(top).relativize(ALLOWLIST).toString().replace('\\', '/') + var reachable = false + val out = ArrayList() + for (ref in refs.split(Regex("\\s+"))) { + val base = git("merge-base", "HEAD", ref) ?: continue + reachable = true + // Absent at the base (the ratchet is newer than it): nothing to compare against. + git("show", "$base:$rel")?.let { out += readAllowlist(it) } + } + return if (reachable) out else null + } + } +} diff --git a/server/java/codegen-kotlin/src/test/resources/layout-ratchet/allowlist.json b/server/java/codegen-kotlin/src/test/resources/layout-ratchet/allowlist.json new file mode 100644 index 0000000000..b25560bc0b --- /dev/null +++ b/server/java/codegen-kotlin/src/test/resources/layout-ratchet/allowlist.json @@ -0,0 +1,21 @@ +{ + "$comment": "The layout ratchet's allowlist for the Kotlin generators (ADR-0063). `unconverted`: generator source that still types its own layout or lays it out through KotlinPoet; each entry names what it emits and the writer PR that converts it, and is removed when that PR lands (the test fails while a converted file keeps its entry). `exempt`: source that writes text which is not generated code; each says why. Neither list may grow: KotlinLayoutRatchetTest compares it with the copy at the branch's merge base.", + "unconverted": { + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/Fr019SharedEnum.kt": "Lays its output out through KotlinPoet (a KotlinPoet ClassName for a shared enum, read by the entity generator). It moves to KotlinWriter, and KotlinPoet leaves the build, in W-KT-4.", + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinCrossFieldRules.kt": "Lays its output out through KotlinPoet (CodeBlock fragments for cross-field validation, spliced into the entity's init block). It moves to KotlinWriter, and KotlinPoet leaves the build, in W-KT-4.", + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinEntityGenerator.kt": "Lays its output out through KotlinPoet (FileSpec and TypeSpec for the entity data class, its builder and value objects). It moves to KotlinWriter, and KotlinPoet leaves the build, in W-KT-4.", + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinEnumEmitter.kt": "Lays its output out through KotlinPoet (FileSpec for the enum class). It moves to KotlinWriter, and KotlinPoet leaves the build, in W-KT-4.", + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt": "Builds the Exposed table object, its column types and the jsonb helpers with typed line breaks, and names KotlinPoet types. Converted to KotlinWriter in W-KT-2.", + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExtractSchemaEmitter.kt": "Builds the extract schema with typed line breaks and indentation, and names KotlinPoet types. Converted to KotlinWriter in W-KT-2.", + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNaming.kt": "packageHeader() returns a package line with typed line breaks, for the emitters still built as strings and for owned copies ejected at an earlier version. Removed when the last of those callers moves to KotlinWriter.", + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinPoetFileWriter.kt": "Lays its output out through KotlinPoet (the FileSpec-to-disk helper, retired when its last caller moves). It moves to KotlinWriter, and KotlinPoet leaves the build, in W-KT-4.", + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRelationsGenerator.kt": "Builds the relation helpers with typed line breaks and indentation, and names KotlinPoet types. Converted to KotlinWriter in W-KT-2 with the Exposed table generator.", + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRepositoryGenerator.kt": "Builds the repository base with typed line breaks. Converted to KotlinWriter in W-KT-2 with the Exposed table generator it reads and writes through.", + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringConfigGenerator.kt": "Lays its output out through KotlinPoet (FileSpec for the Spring configuration class). It moves to KotlinWriter, and KotlinPoet leaves the build, in W-KT-4.", + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt": "Builds the Spring controller with typed line breaks and indentation throughout. Converted to KotlinWriter in W-KT-3.", + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt": "Lays its output out through KotlinPoet (TypeName values the entity and table generators share). It moves to KotlinWriter, and KotlinPoet leaves the build, in W-KT-4." + }, + "exempt": { + "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/apidocs/KotlinApiDocsRenderer.kt": "Renders the api-docs Markdown pages. Documentation output is exempt from the writer conversion (ADR-0063; the docs and markdown emitters), because it is not code an adopter edits." + } +} diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorFilterAllowlist.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorFilterAllowlist.kt index 9baefaa320..040394ddae 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorFilterAllowlist.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorFilterAllowlist.kt @@ -6,11 +6,7 @@ package acme.blog * operator vocabulary for each field by its subtype. */ object AuthorFilterAllowlist { - val FIELDS: Set = setOf( - "name", - ) + val FIELDS: Set = setOf("name") - val OPS_BY_FIELD: Map> = mapOf( - "name" to setOf("eq", "ne", "in", "like", "isNull") - ) + val OPS_BY_FIELD: Map> = mapOf("name" to setOf("eq", "ne", "in", "like", "isNull")) } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorNames.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorNames.kt index 9e309b2643..4cdd81ad83 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorNames.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorNames.kt @@ -1,8 +1,6 @@ package acme.blog -/** - * GENERATED — per-object physical database names for Author. - */ +/** GENERATED — per-object physical database names for Author. */ object AuthorNames { const val TYPE: String = "object" const val SUB_TYPE: String = "entity" @@ -22,8 +20,5 @@ object AuthorNames { const val IDENTITY_PK_SUB_TYPE: String = "primary" const val IDENTITY_PK_NAME: String = "pk" - val COLUMNS_BY_FIELD: Map = mapOf( - "id" to ID_COLUMN, - "name" to NAME_COLUMN, - ) + val COLUMNS_BY_FIELD: Map = mapOf("id" to ID_COLUMN, "name" to NAME_COLUMN) } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/MetaDecimalWire.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/MetaDecimalWire.kt index cb123d6f03..2581e851ad 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/MetaDecimalWire.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/MetaDecimalWire.kt @@ -2,8 +2,8 @@ package acme.blog import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonToken -import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.BeanProperty +import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.JsonMappingException import com.fasterxml.jackson.databind.JsonNode @@ -172,4 +172,3 @@ internal object MetaDecimalWire { } } } - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/MetaValidationIssues.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/MetaValidationIssues.kt index 2b247a3dd4..0551ff56bf 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/MetaValidationIssues.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/MetaValidationIssues.kt @@ -102,4 +102,3 @@ internal object MetaValidationIssues { } } } - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/MetaDecimalWire.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/MetaDecimalWire.kt index ae04f16d38..3d4e12f17f 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/MetaDecimalWire.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/MetaDecimalWire.kt @@ -3,8 +3,8 @@ package acme.catalog import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonToken -import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.BeanProperty +import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.JsonMappingException import com.fasterxml.jackson.databind.JsonNode @@ -182,4 +182,3 @@ internal object MetaDecimalWire { } } } - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/MetaValidationIssues.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/MetaValidationIssues.kt index 53fdbde3dc..7066790dd8 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/MetaValidationIssues.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/MetaValidationIssues.kt @@ -102,4 +102,3 @@ internal object MetaValidationIssues { } } } - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/ProductFilterAllowlist.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/ProductFilterAllowlist.kt index b5bb53a0e5..933675f9a7 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/ProductFilterAllowlist.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/ProductFilterAllowlist.kt @@ -6,13 +6,10 @@ package acme.catalog * operator vocabulary for each field by its subtype. */ object ProductFilterAllowlist { - val FIELDS: Set = setOf( - "price", - "rating", - ) + val FIELDS: Set = setOf("price", "rating") val OPS_BY_FIELD: Map> = mapOf( "price" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), - "rating" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull") + "rating" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), ) } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/MetaDecimalWire.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/MetaDecimalWire.kt index c34308cfd1..137d0f09d3 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/MetaDecimalWire.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/MetaDecimalWire.kt @@ -2,8 +2,8 @@ package acme.catalog import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonToken -import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.BeanProperty +import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.JsonMappingException import com.fasterxml.jackson.databind.JsonNode @@ -172,4 +172,3 @@ internal object MetaDecimalWire { } } } - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/MetaValidationIssues.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/MetaValidationIssues.kt index 53fdbde3dc..7066790dd8 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/MetaValidationIssues.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/MetaValidationIssues.kt @@ -102,4 +102,3 @@ internal object MetaValidationIssues { } } } - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/ProductFilterAllowlist.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/ProductFilterAllowlist.kt index b5bb53a0e5..933675f9a7 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/ProductFilterAllowlist.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/ProductFilterAllowlist.kt @@ -6,13 +6,10 @@ package acme.catalog * operator vocabulary for each field by its subtype. */ object ProductFilterAllowlist { - val FIELDS: Set = setOf( - "price", - "rating", - ) + val FIELDS: Set = setOf("price", "rating") val OPS_BY_FIELD: Map> = mapOf( "price" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), - "rating" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull") + "rating" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), ) } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-names/acme/demo/AuthorNames.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-names/acme/demo/AuthorNames.kt index d315cd4243..8a6d8ce36a 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-names/acme/demo/AuthorNames.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-names/acme/demo/AuthorNames.kt @@ -1,8 +1,6 @@ package acme.demo -/** - * GENERATED — per-object physical database names for Author. - */ +/** GENERATED — per-object physical database names for Author. */ object AuthorNames { const val TYPE: String = "object" const val SUB_TYPE: String = "entity" @@ -22,8 +20,5 @@ object AuthorNames { const val IDENTITY_PRIMARY_SUB_TYPE: String = "primary" const val IDENTITY_PRIMARY_NAME: String = "primary" - val COLUMNS_BY_FIELD: Map = mapOf( - "callPurpose" to CALL_PURPOSE_COLUMN, - "id" to ID_COLUMN, - ) + val COLUMNS_BY_FIELD: Map = mapOf("callPurpose" to CALL_PURPOSE_COLUMN, "id" to ID_COLUMN) } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-stored-proc/acme/ops/OrderReportProc.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-stored-proc/acme/ops/OrderReportProc.kt index f720d407ab..ebea0c0a8e 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-stored-proc/acme/ops/OrderReportProc.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-stored-proc/acme/ops/OrderReportProc.kt @@ -10,14 +10,9 @@ object OrderReportProc { /** Call the procedure and map result rows into [OrderReport]. */ fun call(orderId: Long): List = transaction { val results = mutableListOf() - exec("SELECT * FROM ${PROC_NAME}(?)", listOf( - org.jetbrains.exposed.sql.LongColumnType() to orderId - )) { rs -> + exec("SELECT * FROM ${PROC_NAME}(?)", listOf(org.jetbrains.exposed.sql.LongColumnType() to orderId)) { rs -> while (rs.next()) { - results.add(OrderReport( - status = rs.getString("status"), - totalCents = rs.getLong("total_cents") - )) + results.add(OrderReport(status = rs.getString("status"), totalCents = rs.getLong("total_cents"))) } } results diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthFilterAllowlist.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthFilterAllowlist.kt index d02fcc202b..7e1bc79d84 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthFilterAllowlist.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthFilterAllowlist.kt @@ -6,14 +6,7 @@ package acme.auth * operator vocabulary for each field by its subtype. */ object AuthFilterAllowlist { - val FIELDS: Set = setOf( - "id", - "type", - "reference", - "quantity", - "couponAmount", - "permitNumber", - ) + val FIELDS: Set = setOf("id", "type", "reference", "quantity", "couponAmount", "permitNumber") val OPS_BY_FIELD: Map> = mapOf( "id" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), @@ -21,6 +14,6 @@ object AuthFilterAllowlist { "reference" to setOf("eq", "ne", "in", "like", "isNull"), "quantity" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), "couponAmount" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), - "permitNumber" to setOf("eq", "ne", "in", "like", "isNull") + "permitNumber" to setOf("eq", "ne", "in", "like", "isNull"), ) } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/MetaDecimalWire.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/MetaDecimalWire.kt index 41ed76a152..53859a6c16 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/MetaDecimalWire.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/MetaDecimalWire.kt @@ -2,8 +2,8 @@ package acme.auth import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonToken -import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.BeanProperty +import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.JsonMappingException import com.fasterxml.jackson.databind.JsonNode @@ -172,4 +172,3 @@ internal object MetaDecimalWire { } } } - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/MetaValidationIssues.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/MetaValidationIssues.kt index d8d44e2696..04e9e2d65f 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/MetaValidationIssues.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/MetaValidationIssues.kt @@ -102,4 +102,3 @@ internal object MetaValidationIssues { } } } - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/validation/ExposedTableValidator.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/validation/ExposedTableValidator.kt index 318c39a71e..c4ebe32076 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/validation/ExposedTableValidator.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/validation/ExposedTableValidator.kt @@ -9,7 +9,6 @@ import org.jetbrains.exposed.sql.Table * and records any discrepancies into the supplied `errors` list. */ object ExposedTableValidator { - fun check(obj: MetaObject, table: Table, errors: MutableList) { val expectedCols = obj.metaFields.map { it.name }.toSet() val actualCols = table.columns.map { it.name }.toSet() diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/validation/MetadataStartupValidator.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/validation/MetadataStartupValidator.kt index f63b913129..ec846430d2 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/validation/MetadataStartupValidator.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/validation/MetadataStartupValidator.kt @@ -1,20 +1,19 @@ package acme.auth.validation +import acme.auth.AuthLineTable +import acme.auth.AuthTable import com.metaobjects.loader.MetaDataLoader import com.metaobjects.metadata.ktx.metaObjectOrNull import org.jetbrains.exposed.sql.Table -import acme.auth.AuthLineTable -import acme.auth.AuthTable /** * GENERATED — runtime drift gate. Call [validate] from a Spring `@PostConstruct` or * `ApplicationReadyEvent` listener to fail-fast when generated Tables drift from metadata. */ object MetadataStartupValidator { - private val tablesToValidate: List> = listOf( "acme::auth::Auth" to AuthTable, - "acme::auth::AuthLine" to AuthLineTable + "acme::auth::AuthLine" to AuthLineTable, ) fun validate(loader: MetaDataLoader) { diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-view/acme/report/MetaDecimalWire.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-view/acme/report/MetaDecimalWire.kt index 21e15124fc..619b4be402 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-view/acme/report/MetaDecimalWire.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-view/acme/report/MetaDecimalWire.kt @@ -2,8 +2,8 @@ package acme.report import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonToken -import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.BeanProperty +import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.JsonMappingException import com.fasterxml.jackson.databind.JsonNode @@ -172,4 +172,3 @@ internal object MetaDecimalWire { } } } - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-view/acme/report/MetaValidationIssues.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-view/acme/report/MetaValidationIssues.kt index ffdeba44c2..48d48b765e 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-view/acme/report/MetaValidationIssues.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-view/acme/report/MetaValidationIssues.kt @@ -102,4 +102,3 @@ internal object MetaValidationIssues { } } } - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/ExposedTableValidator.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/ExposedTableValidator.kt index 3fd7b7d9c7..1b8ca269a9 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/ExposedTableValidator.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/ExposedTableValidator.kt @@ -9,7 +9,6 @@ import org.jetbrains.exposed.sql.Table * and records any discrepancies into the supplied `errors` list. */ object ExposedTableValidator { - fun check(obj: MetaObject, table: Table, errors: MutableList) { val expectedCols = obj.metaFields.map { it.name }.toSet() val actualCols = table.columns.map { it.name }.toSet() diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/MetadataStartupValidator.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/MetadataStartupValidator.kt index 3f586a8185..27890b7f66 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/MetadataStartupValidator.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/MetadataStartupValidator.kt @@ -9,10 +9,7 @@ import org.jetbrains.exposed.sql.Table * `ApplicationReadyEvent` listener to fail-fast when generated Tables drift from metadata. */ object MetadataStartupValidator { - - private val tablesToValidate: List> = listOf( - "acme::demo::Author" to AuthorTable - ) + private val tablesToValidate: List> = listOf("acme::demo::Author" to AuthorTable) fun validate(loader: MetaDataLoader) { val errors = mutableListOf() diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-fr010/acme/ai/prompts/OpinionParser.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-fr010/acme/ai/prompts/OpinionParser.kt index e763013146..c52e82ad51 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-fr010/acme/ai/prompts/OpinionParser.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-fr010/acme/ai/prompts/OpinionParser.kt @@ -1,16 +1,16 @@ // GENERATED — DO NOT EDIT — response parser for template.prompt `acme::ai::Opinion` + package acme.ai.prompts import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper -import com.metaobjects.loader.MetaDataLoader import com.metaobjects.`object`.extract.MetaObjectExtractor -import com.metaobjects.render.extract.Format +import com.metaobjects.loader.MetaDataLoader import com.metaobjects.render.extract.ExtractOptions import com.metaobjects.render.extract.ExtractionResult +import com.metaobjects.render.extract.Format /** Parser for LLM responses matching the `Opinion` template.prompt. */ object OpinionParser { - // Fails on an unknown property: a reply carrying a field the response shape does not // declare is a contract break, not something to drop silently. private val mapper = jacksonObjectMapper().findAndRegisterModules() @@ -23,9 +23,7 @@ object OpinionParser { fun parseOpinion(text: String): acme.ai.OpinionOutputPayload = mapper.readValue(text, acme.ai.OpinionOutputPayload::class.java) - /** - * Parse with explicit error handling (Result-style — does not throw). - */ + /** Parse with explicit error handling (Result-style — does not throw). */ fun safeParseOpinion(text: String): Result = runCatching { parseOpinion(text) } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-fr010/acme/ai/prompts/OpinionResponseFormat.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-fr010/acme/ai/prompts/OpinionResponseFormat.kt index 8f9b47848a..f59f05810b 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-fr010/acme/ai/prompts/OpinionResponseFormat.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-fr010/acme/ai/prompts/OpinionResponseFormat.kt @@ -1,13 +1,14 @@ // GENERATED — DO NOT EDIT — output-format prompt for template.output `acme::ai::Opinion` + package acme.ai.prompts +import com.metaobjects.render.extract.FieldKind +import com.metaobjects.render.extract.Format import com.metaobjects.render.prompt.OutputFormatRenderer import com.metaobjects.render.prompt.OutputFormatSpec import com.metaobjects.render.prompt.PromptField import com.metaobjects.render.prompt.PromptOverrides import com.metaobjects.render.prompt.PromptStyle -import com.metaobjects.render.extract.FieldKind -import com.metaobjects.render.extract.Format /** Output-format prompt fragment for the `Opinion` template.output. */ object OpinionResponseFormat { diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-parser/acme/ai/prompts/ReplyParser.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-parser/acme/ai/prompts/ReplyParser.kt index 2599a8f86b..f59ddfcfd0 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-parser/acme/ai/prompts/ReplyParser.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-parser/acme/ai/prompts/ReplyParser.kt @@ -1,16 +1,16 @@ // GENERATED — DO NOT EDIT — response parser for template.prompt `acme::ai::Reply` + package acme.ai.prompts import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper -import com.metaobjects.loader.MetaDataLoader import com.metaobjects.`object`.extract.MetaObjectExtractor -import com.metaobjects.render.extract.Format +import com.metaobjects.loader.MetaDataLoader import com.metaobjects.render.extract.ExtractOptions import com.metaobjects.render.extract.ExtractionResult +import com.metaobjects.render.extract.Format /** Parser for LLM responses matching the `Reply` template.prompt. */ object ReplyParser { - // Fails on an unknown property: a reply carrying a field the response shape does not // declare is a contract break, not something to drop silently. private val mapper = jacksonObjectMapper().findAndRegisterModules() @@ -23,9 +23,7 @@ object ReplyParser { fun parseReply(text: String): acme.ai.Greeting = mapper.readValue(text, acme.ai.Greeting::class.java) - /** - * Parse with explicit error handling (Result-style — does not throw). - */ + /** Parse with explicit error handling (Result-style — does not throw). */ fun safeParseReply(text: String): Result = runCatching { parseReply(text) } diff --git a/spec/code-writer.md b/spec/code-writer.md index 2113ba65a5..cd1c85de2c 100644 --- a/spec/code-writer.md +++ b/spec/code-writer.md @@ -22,11 +22,11 @@ smarter. ### Options -| Option | Meaning | TypeScript default | Java default | -|---|---|---|---| -| `indent` | One level of indentation | two spaces | four spaces | -| `width` | The last column a line may reach before its last list breaks | 120 | 120 | -| `trailingComma` | Whether a broken list puts a comma after its last item too | true | false | +| Option | Meaning | TypeScript default | Java default | Kotlin default | +|---|---|---|---|---| +| `indent` | One level of indentation | two spaces | four spaces | four spaces | +| `width` | The last column a line may reach before its last list breaks | 120 | 120 | 120 | +| `trailingComma` | Whether a broken list puts a comma after its last item too | true | false | true | A dialect sets the defaults for its language. A `core` case always states all three, so it means the same thing in every port. @@ -176,6 +176,36 @@ writes the head, indents, and on leaving the `try` dedents and writes `}`. `List` or array of parts, which are concatenated. Anything else (a number, `null`, another object) is **`ERR_WRITER_UNKNOWN_PIECE`**: the writer never guesses how to print it. +## Kotlin dialect (`KotlinWriter`) + +Case `dialect` is `kotlin`. `KotlinWriter` is in `codegen-kotlin` +(`com.metaobjects.generator.kotlin.writer`) and extends the same core `CodeWriter` the Java writer +does. The defaults are four-space indent, width 120 and a trailing comma, as Kotlin's coding +conventions write them. + +- **The package line** is set with `packageName(name)` and prints after the `header(...)` lines + and before the imports, with one blank line between each section. An empty package prints no + line. +- **Imports are collected while the body is written.** `use("pkg.Name")` records an import and + returns the name to write, its last segment. `use("pkg.Name", alias)` records + `import pkg.Name as alias` and returns the alias. A name in a package Kotlin imports by default + (`kotlin`, `kotlin.collections`, `kotlin.io`, `java.lang` and the rest of the language's default + imports), or in the file's own package, prints no line. An aliased import always prints. +- **Order.** One group, in code-unit order of what follows `import `, with no blank lines. A name + used twice is imported once. +- One local name imported from two names is **`ERR_WRITER_IMPORT_CONFLICT`**. +- **Names.** A segment that is a hard keyword (`object`, `in`, `is`, ...) is written in backticks, + in the package line, in an import and in the name `use` returns. +- **`doc(lines...)`** writes `/** text */` when there is one entry and it fits. Otherwise it + writes a block of ` * ` lines, with a bare ` *` line for an empty entry. Kotlin comments nest, so + both `*/` and `/*` inside the text are neutralised (`*/`, `/*`). +- **Scoped forms.** `block(head) { ... }` writes the head, indents, runs the lambda, dedents and + writes `}`. `reopen(parts)` closes the open block and opens the next on one line (`} else {`); + with no block open it is `ERR_WRITER_UNBALANCED_CLOSE`. `indented { ... }` writes its lines one + level in and opens no block: the continuation of an expression body. +- Helpers: `str` (a quoted string literal, with `$` escaped so it is never a template) and `call` + (`fn(a, b)`, a list that breaks one item per line with a trailing comma). + ## Python dialect (`PyWriter`) Defaults: four-space indent, 88 columns, a trailing comma on a broken list. @@ -264,7 +294,7 @@ A writer and the generators built on it are meant to be extended in place subclass can override one step and keep the rest. In TypeScript the core's steps include `piece` (what a part becomes), `breakAt` (where a line that does not fit breaks) and `fits`. `TsWriter` adds `writeHeader`, `writeImports`, `writeImport` and `orderModules`. `JavaWriter` - adds `writeHeader`, `writePackage`, `writeImports` and `needsImport`. + and `KotlinWriter` add `writeHeader`, `writePackage`, `writeImports` and `needsImport`. - A reference generator is a class whose output comes from one overridable method per meaningful piece: the file header, the imports, and each section or member. An adopter overrides the method for the piece it wants changed, and passes its subclass where the @@ -297,7 +327,8 @@ Each case in `fixtures/writer-conformance/cases/` is one JSON file: `useDefault`, `useNamespace` and `useSideEffect` (name, then module; `useSideEffect` takes only the module), `header` and `doc` (lines). The Python ops are `use` (name, module), `useAs` (name, module, alias), `useModule` (module, optional alias), `useFuture` (optional name), `header` and `doc` - (lines), `dedent` and `gap`. The Rust ops are `use` (path, then names), `doc` and `prose` + (lines), `dedent` and `gap`. The Kotlin ops are `package` (name), `use` (name), `useAs` (name, + alias), `header` and `doc` (lines), and `reopen` (parts). The Rust ops are `use` (path, then names), `doc` and `prose` (text), `docBreak` and `assign` (head, then parts). - A part is a string, a list (`{"list": {"open", "items", "close", "pad"?}}`, where items are parts) or an array of parts, which are concatenated.