Each port's generators write text through a code writer, as that port's writer lands
(ADR-0063); docs/CONFORMANCE.md
records which ports have one. The generator says what a line
contains, and the writer decides where it sits. This document is the contract the writers
share. The cases in fixtures/writer-conformance/ pin it.
A writer has two parts:
- The core, which is language-neutral: lines, indentation, blocks, blank-line requests,
snippets, fit-or-break lists and the output form. Every port's core runs the
corecases. - A dialect for the language being written: import collection and ordering, string
quoting, doc comments and expression helpers. A dialect runs the cases for its language,
such as
typescriptorpython.
The writer never parses text. It lays out the structure the generator handed it. When a shape comes out badly, the generator breaks it explicitly with a block. The writer is not made smarter.
| 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.
line(parts...)writes one line at the current indent. Its parts are concatenated. There is no unindented variant.open(parts...)writes the line, then indents one level.close(parts...)dedents one level, then writes the line.block(head, body, tail)isopen(head), then the body, thenclose(tail). A port givesblockits idiomatic scoped form: a callback in TypeScript,try (var b = ...)in Java,within Python,usingin C#.- Indentation comes only from open blocks, so a line's indent is the depth of the blocks around
it times
indent. closewith no block open isERR_WRITER_UNBALANCED_CLOSE. Finishing the file with a block still open isERR_WRITER_UNCLOSED_BLOCK, and the message quotes the line that opened the innermost open block.- Line text containing a line break (
\n,\r\nor\r) isERR_WRITER_NEWLINE_IN_LINE. Write each line separately, or usetext. - Text passed to
line,openorclose(and a dialect'sreopen) whose first character is a space or tab isERR_WRITER_LEADING_WHITESPACE: the writer adds the indent, so a caller-indented piece would sit deeper than its siblings.textkeeps indentation beyond the common margin, and a dialect's doc-comment, header and import helpers write their own lines (such as* foo) without the check.
blank()asks for one blank line before whatever is written next.- Two or more requests in a row give one blank line.
- A request gives nothing at the start of the file, directly after a line that opens a block, directly before a line that closes a block, or at the end of the file.
- A line whose text is empty is a blank-line request, not a written line.
text(snippet) writes a block of fixed code as it should read. The writer splits it on
line breaks (\n, \r\n and \r). It drops the first line when that line is blank, and the
last line when that line is blank. It removes the common left margin of the non-blank lines and
writes each line at the current indent, keeping the line's indentation beyond the margin. A
blank line inside the snippet is a blank-line request. Every line is re-indented, including a
line inside a multi-line string literal in the snippet.
A list is an opener, items and a closer. On one line its items are separated by , . A
padded list puts a space inside its brackets ({ a, b }); an unpadded one does not
([a, b], f(a, b)). An empty list prints as its opener and closer ({}, [], ()) and
never breaks.
When a line's indent plus its text is at most width, the line prints as it is. When it is
longer:
- The last non-empty list on the line breaks. Everything before it, flattened, plus its
opener, is a line that opens a block. Each item is a line followed by a comma, except the
last item when
trailingCommais false. The closer plus everything after it closes the block. - Each item line is held to the same rule, so an item that still does not fit breaks its own last list.
- A line with no non-empty list prints as it is, however long.
Width is counted in Unicode code points, so an emoji counts as one even though it is two UTF-16
units. The comparison includes the indent, and a line exactly width long fits.
- Lines end with
\non every platform. - No line has trailing whitespace.
- A file with any content ends with exactly one
\n. A file with no content is the empty string. - Text is UTF-8 when it is written to disk.
- Imports are collected while the body is written.
use(name, from)records a value import and returns the name to write;use(name, from, as)binds it locally asas(import { name as as }) and returnsas.useTyperecords a type-only import and takes the same optionalas.useDefault,useNamespaceanduseSideEffectrecord the other forms. Imports print before the body, after anyheader(...)lines, with one blank line between each of the three sections. - Order. Package modules come first, then relative ones (those starting with
.). Each group is in code-unit order, with no blank line between the groups. Within a module, names are in code-unit order. - One line per module.
import * as ns from "m";prints on its own line. Default and named imports share a line:import D, { a, type B } from "m";. A module whose every named import is type-only, with no default, prints asimport type { A, B } from "m";. A name used both as a type and as a value is imported as a value. A side-effect import (import "m";) prints only when nothing else is imported from that module. - The named list is a padded list and fits or breaks like any other. A single name never breaks.
- One local name imported from two modules, or naming two different exports, is
ERR_WRITER_IMPORT_CONFLICT. reopen(parts...)closes the open block and opens the next on one line: it dedents, writes the line, and indents again, as in}).superRefine((row, ctx) => {or} else {. With no block open it isERR_WRITER_UNBALANCED_CLOSE.commentLine(parts...)writes one line of a block comment the generator lays out itself, such as* text: its leading space is kept and the line is still indented from the open blocks.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. A*/inside the text is written as*\/.- No
Codeinterop. The vendored ts-poet printer (poet.ts) and itscode,impandCodeexports were removed in 1.3.0; a part is text or an import the writer itself owns. - Helpers:
str(a quoted string literal),arr,call,props()(an object literal built with.set(name, value)and.add(member)) andkey(an object key, quoted only when it is not an identifier). json(value)writes a JSON value as a literal. Arrays and objects are breakable lists (an object is padded,{ "k": v }), and object keys stay quoted, as JSON writes them.docSample(writer)turns a code sample laid out by another writer into doc-comment lines, each indented four spaces, for a worked example inside adoc(...)comment.legacyMemberLines(members, indent)is the 1.2 string form of a member list (a line break before each member, atindent). It exists only for the deprecated*Linehelpers an owned 1.2 generator still calls; new code spreads the members into the writer.indented(body)writes nothing itself and writes the body one level in. It is a block delimited by indentation alone, as C#'sHanging()and Python's suites are, and is used where no line closes the block: the clauses of a SQL view body, or a YAML mapping. The TypeScript port'sCodeWriterhas it, so every TypeScript writer inherits it.
The TypeScript port also writes YAML (the Cube data model). It has no conformance cases, since no other port writes YAML. Defaults: two-space indent, no width limit (a flow list is written as the generator gives it), and no trailing comma.
key(name, body)writesname:and the body under it, one level in, with no closing line.item(body)writes one block-list entry. The first line the body writes carries-, and the entry's other lines align under that line's text.
JavaWriter is in codegen-base (com.metaobjects.generator.writer), beside the core
CodeWriter. Its block(head) is the scoped form: try (var b = w.block("class A {")) { ... }
writes the head, indents, and on leaving the try dedents and writes }.
- The package line is set with
packageName(name)and prints after theheader(...)lines and before the imports, with one blank line between each section. - Imports are collected while the body is written.
use("pkg.Type")records an import and returns the name to write, which is the type's last segment (a nested type,java.util.Map.Entry, is imported as written and writtenEntry).useStatic("pkg.Type.member")records a static import and returns the member name. A type injava.lang, or in the file's own package, imports nothing, whichever order the package and the types were named in. - Order. Static imports first, then one blank line, then the other imports. Each group is in code-unit order, with no blank line between packages. A name used twice is imported once.
- One local name imported from two types, or one static member name from two types, is
ERR_WRITER_IMPORT_CONFLICT. A generator that needs both writes one of them fully qualified. 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. A*/inside the text is written as*/.commentLine(parts...)works as in the TypeScript dialect: it writes a hand-laid block-comment line, such as* text.- Helpers:
str(a quoted string literal) andcall(fn(a, b), a list that breaks one item per line with no trailing comma). - A part is a
String, a list (Group, built withCodeWriter.listorCodeWriter.padded) or aListor array of parts, which are concatenated. Anything else (a number,null, another object) isERR_WRITER_UNKNOWN_PIECE: the writer never guesses how to print it.
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 theheader(...)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)recordsimport pkg.Name as aliasand returns the alias. A name in a package Kotlin imports by default (kotlin,kotlin.collections,kotlin.io,java.langand the rest of the language's default imports), or in the file's own package, prints no line. A name with no dot is in the root package: it prints a line unless the file is in the root package too. 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 nameusereturns. 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 (*/,/*).commentLine(parts...)works as in the TypeScript dialect: it writes a hand-laid block-comment line, such as* text.- 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 isERR_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) andcall(fn(a, b), a list that breaks one item per line with a trailing comma).
Defaults: four-space indent, 88 columns, a trailing comma on a broken list.
- Imports are collected while the body is written.
use(name, from)recordsfrom m import nameand returns the name to write;use(name, from, as)recordsfrom m import name as as.use_module(m)anduse_module(m, as)recordimport mandimport m as as.use_future(name)recordsfrom __future__ import name. Imports print before the body, after anyheader(...)lines, with one blank line between each section. - Order. Three sections:
__future__, then absolute modules, then relative ones (those starting with.). Each section is in code-point order, with one blank line between the sections. In a section the plainimport mlines come first, then thefrom m import ...lines, each group in code-point order, and names in code-point order. - Long import lines.
from m import a, bstays on one line when it fits; otherwise it prints asfrom m import (, one name per line, each followed by a comma, and). A single name never breaks. - One local name imported from two modules, or naming two different exports, is
ERR_WRITER_IMPORT_CONFLICT. - Suites. A Python block has no closing token: the block ends when the indent drops.
openstarts a suite anddedentends it without writing a line. A pending blank-line request survives a dedent, so the gap before the next definition is kept. (closestill writes its line and drops a pending request, as in the core.) A suite still open when the file is finished ends there: Python needs no closing token, so this is notERR_WRITER_UNCLOSED_BLOCK.closewith no suite open, anddedentwith none open, areERR_WRITER_UNBALANCED_CLOSE. gap()asks for two blank lines before whatever is written next (the gap between top-level definitions). A laterblank()does not shrink it. Asked for before the first body line, it is the gap after the imports: two blank lines instead of one, so a top-levelclassordefright after the imports is set off as PEP 8 asks.doc(lines...)writes"""text"""when there is one entry and it fits. Otherwise it writes the opening quotes with the first entry, each further entry on its own line (an empty entry is a blank line) and the closing quotes on their own line. A backslash is written as\\and"""as\"\"\". On one line, a double quote at the end of the text is written\", so it cannot join the closing quotes.- Helpers:
str_lit(a double-quoted string literal),call,seq,mappingandkwarg.
Case dialect is csharp. The defaults are four-space indent, width 120 and a trailing comma.
- Usings are collected while the body is written.
Using(ns),UsingStatic(type)andUsingAlias(alias, target)record ausing, once. They print after anyHeader(...)lines (#nullable enableis a header line,GeneratedFileHeader(name)writes the generated-file marker, the generator's name and#nullable enable), with one blank line before the body. A file with no usings prints no blank line for them. - Order.
AsWritten(the default) prints the usings in the order they were recorded, so a generator converted to the writer keeps its output.SortedprintsSystemnamespaces first, then the rest, each group in ordinal order of the namespace. - One alias naming two different targets is
ERR_WRITER_IMPORT_CONFLICT. Braced(head)writeshead, then a{on its own line, indents, and writes}when the scope ends: the Allman form C# generators emit. An empty head writes only the{, an anonymous block.Piece.Args(open, items, close)is a list for a parameter or argument list. It is unpadded and, broken, puts no comma after its last item, whatevertrailingCommasays: C# accepts a trailing comma in an initializer or a collection expression, and refuses one in a parameter or argument list. In a case it is a list with"trailingComma": false.DocSummary(lines...)writes/// <summary>, one/// textline per entry (a bare///for an empty entry) and/// </summary>, at the current indent.Hanging()is a scope for a statement that carries on after a line that is not finished. It writes nothing, and indents the lines written inside it by one level. A block opened inside it must be closed inside it.
Case dialect is rust. The defaults are four-space indent, width 100 and a trailing comma:
rustfmt's. The Rust writer is one type, the core plus these methods. Generated Rust is held to
rustfmt under the rustfmt.toml every generated crate carries (use_small_heuristics = "Max",
short_array_element_width_threshold = 0), so each rule below is rustfmt's under those
settings, and every rust case's expected output is a rustfmt fixed point under them.
use_list(path, names)writesuse path::{a, b};when it fits anduse path::a;for one name. Otherwise it writesuse path::{, fills the names onto lines one level in (each followed by a comma, as many to a line as fit) and};. Imports are not collected or sorted: a generator writes them in rustfmt's order (stdandcratepaths among the rest, in code-point order).doc(text)writes an author's text as///lines, one per line of the text, a bare///for an empty line, never re-wrapped.prose(text)writes text the generator composed: each line of the text is a paragraph, wrapped at a word boundary so no line passes the width.doc_break()writes the bare///between two paragraphs.assign(head, rhs)writeshead rhswhen it fits. Otherwise, when the right-hand side fits alone on the next line one level in, it writes the head and then the right-hand side there, an array as well as a call. Otherwise it keeps the right-hand side on the head's line and breaks its last list.
A writer and the generators built on it are meant to be extended in place (ADR-0063, item 7):
- A writer class is not final. Every method is public or protected, never private, so a
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) andfits.TsWriteraddswriteHeader,writeImports,writeImportandorderModules.JavaWriterandKotlinWriteraddwriteHeader,writePackage,writeImportsandneedsImport. - 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 reference generator was configured.
- Overridable methods are not a stability contract. They may change between minor versions. The conformance cases pin the output of the methods as shipped, not their names.
Each case in fixtures/writer-conformance/cases/ is one JSON file:
- An op is an array: its name, then its arguments. The core ops are
line,openandclose(whose arguments are parts),blankandtext. The TypeScript ops areuse,useType,useDefault,useNamespaceanduseSideEffect(name, then module;useSideEffecttakes only the module),headeranddoc(lines). The Python ops areuse(name, module),useAs(name, module, alias),useModule(module, optional alias),useFuture(optional name),headeranddoc(lines),dedentandgap. The Kotlin ops arepackage(name),use(name),useAs(name, alias),headeranddoc(lines), andreopen(parts). The Rust ops areuse(path, then names),docandprose(text),docBreakandassign(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. expectedis the output's lines. The file is those lines joined with\nplus a final\n, or the empty string when the array is empty.- A case that must fail has
"error"(the error code) in place ofexpected. It may also have"errorQuotes", text the error message must contain.
{ "description": "What the case pins, in one sentence.", "dialect": "core", // or a language: "typescript" "options": { "indent": " ", "width": 40, "trailingComma": true }, // required for core "ops": [ ["open", "class A {"], ["line", "f", { "list": { "open": "(", "items": ["a", "b"], "close": ")" } }, ";"], ["blank"], ["text", "fixed\ncode"], ["close", "}"] ], "expected": ["class A {", " f(a, b);", " fixed", " code", "}"] }