formatter 0.0.2-preview.1

A code formatter for Zena

Readme Files Dependencies Versions

formatter#

A code formatter for Zena source code, built on a Wadler/Prettier-style document intermediate representation (Doc).

Usage#

Formatting Zena Source#

import { format } from 'formatter';

let formatted = format('export function add(a:i32,b:i32):i32{return a+b;}');

Building Custom Documents#

You can also construct and print Doc trees directly using formatter/doc and formatter/doc-printer:

import { group, concat, text, line } from 'formatter/doc';
import { printDocToString, PrintOptions } from 'formatter/doc-printer';

let doc = group(concat([text('a,'), line, text('b')]));
let rendered = printDocToString(doc, new PrintOptions(80));

Libraries#

  • formatter / formatter/printer — Zena AST printer (format, printModuleToDoc)
  • formatter/doc — document IR builders (Doc, text, concat, group, indent, line, softline, hardline, ifBreak, join, fill, lineSuffix)
  • formatter/doc-printer — line-breaking document renderer (printDocToString, PrintOptions)

License#

MIT

87.0 KiB Raw
/**
 * Printer — converts Zena AST nodes into Doc IR.
 *
 * This is the language-specific component. Each AST node type has a
 * printing function that produces Doc IR, which the doc-printer then
 * converts to a string.
 */

import { StringBuilder, growable } from 'zena:core';
import { parseAllowingStatements } from 'compiler/parser';
import {
  Comment, Node, Module, // Expressions
  Expression, Identifier, NumberLiteral, StringLiteral, BooleanLiteral, NullLiteral, TemplateLiteral, TaggedTemplateExpression, BinaryExpression, UnaryExpression, AssignmentExpression, AsExpression, IsExpression, RangeExpression, PipelineExpression, PipePlaceholder, FunctionExpression, CallExpression, MemberExpression, IndexExpression, ThisExpression, SuperExpression, NewExpression, ArrayLiteral, RecordLiteral, MapLiteral, TupleLiteral, MatchExpression, IfExpression, ThrowExpression, TryExpression, AwaitExpression, // Statements
  Statement, VariableDeclaration, UsingStatement, ShieldedStatement, FunctionDeclaration, ExpressionStatement, BlockStatement, ReturnStatement, YieldStatement, BreakStatement, ContinueStatement, IfStatement, WhileStatement, ForStatement, ForInStatement, ClassDeclaration, InterfaceDeclaration, EnumDeclaration, MixinDeclaration, TypeAliasDeclaration, Decorator, ImportDeclaration, ExportAllDeclaration, ExportFromDeclaration, DeclareFunction, SymbolDeclaration, isSymbolFieldDeclaration, // Patterns
  Pattern, BindingPattern, IdentifierPattern, RecordPattern, TuplePattern, ArrayPattern, RestPattern, AsPattern, ClassPattern, LogicalPattern, AssignmentPattern, AbsencePattern, LiteralPattern, // Type Annotations
  TypeAnnotation, NamedTypeAnnotation, UnionTypeAnnotation, NullableTypeAnnotation, FunctionTypeAnnotation, LiteralTypeAnnotation, RecordTypeAnnotation, TupleTypeAnnotation, InlineTypeAnnotation, ThisTypeAnnotation, // Direct Node variants
  TemplateElement, PropertyAssignment, SpreadElement, BindingProperty, LetPatternCondition, TypeParameter, Parameter, CaseClassParam, SealedVariant, FieldDefinition, MethodDefinition, AccessorDeclaration, SetterInfo, FieldInitializer, SuperInitializer, MethodSignature, AccessorSignature, CatchClause, PropertySignature, ImportSpecifier, SymbolPropertyName, ContractClause, ContractMode, contractKeyword, contractModifier,
} from 'compiler/ast';
import {
  Doc, text, concat, group, groupWithBreak, ifBreak, indent, line, softline, hardline, join, lineSuffix,
} from './doc.zena';
import { printDocToString, PrintOptions } from './doc-printer.zena';
import { CommentMap, attachComments } from 'compiler/comment-attachment';

var currentCommentMap = new CommentMap();
var currentSource = '';

// ============================================================================
// Blank-line and source-span helpers
// ============================================================================

/**
 * Whether `source` contains a newline (`\n`) in `[from, to)`.
 */
function hasNewlineBetween(source: String, from: i32, to: i32): boolean {
  var i = from;
  while (i < to && i < source.length) {
    if (source.getByteAt(i) == 10) {
      return true;
    }
    i += 1;
  }
  return false;
}

/**
 * Whether `source` contains a blank line (at least two newlines separated
 * only by horizontal whitespace) in `[from, to)`.
 */
function hasBlankLineBetween(source: String, from: i32, to: i32): boolean {
  var newlineCount = 0;
  var i = from;
  while (i < to && i < source.length) {
    let ch = source.getByteAt(i);
    if (ch == 10) {
      newlineCount += 1;
      if (newlineCount >= 2) { return true; }
    } else if (ch != 13 && ch != 32 && ch != 9) {
      newlineCount = 0;
    }
    i += 1;
  }
  return false;
}

function getNodeStart(node: Node): i32 {
  let loc = node.loc;
  return loc?.start ?? 0 - 1;
}

function getNodeEnd(node: Node): i32 {
  let loc = node.loc;
  return loc?.end ?? 0 - 1;
}

function getEffectiveNodeStart(node: Node) {
  let leading = currentCommentMap.getLeading(node);
  if (leading != null && leading.length > 0) {
    return leading[0].start;
  }
  return getNodeStart(node);
}

function getEffectiveNodeEnd(node: Node) {
  let trailing = currentCommentMap.getTrailing(node);
  if (trailing != null && trailing.length > 0) {
    return trailing[trailing.length - 1].end;
  }
  return getNodeEnd(node);
}

function hasBlankLineBetweenNodes(a: Node, b: Node): boolean {
  let endA = getEffectiveNodeEnd(a);
  let startB = getEffectiveNodeStart(b);
  if (endA < 0 || startB < 0) { return false; }
  return hasBlankLineBetween(currentSource, endA, startB);
}

// ============================================================================
// Array helpers
// ============================================================================

function docs2(a: Doc, b: Doc): Array<Doc> {
  let arr = growable<Doc>([a, b]);
  return arr;
}

function docs3(a: Doc, b: Doc, c: Doc): Array<Doc> {
  let arr = growable<Doc>([a, b, c]);
  return arr;
}

// ============================================================================
// Operator precedence
//
// The AST has no node for parentheses, so the printer is what decides where
// they go. These ranks mirror the descent in `parser.zena`, from
// `#parseAssignment` down to `#parseUnary`: a smaller rank binds looser. Only
// the order matters, not the values.
// ============================================================================

let PREC_LOOSEST: i32 = 1;      // assignment, arrow, throw, if, match, try
let PREC_PIPELINE: i32 = 2;     // |>
let PREC_OR: i32 = 3;           // || ??
let PREC_AND: i32 = 4;          // &&
let PREC_BIT_OR: i32 = 5;       // |
let PREC_BIT_XOR: i32 = 6;      // ^
let PREC_BIT_AND: i32 = 7;      // &
let PREC_EQUALITY: i32 = 8;     // == != === !==
let PREC_COMPARISON: i32 = 9;   // < <= > >=
let PREC_SHIFT: i32 = 10;       // << >> >>>
let PREC_RANGE: i32 = 11;       // ..
let PREC_AS: i32 = 12;          // as is
let PREC_TERM: i32 = 13;        // + -
let PREC_FACTOR: i32 = 14;      // * / %
let PREC_EXPONENT: i32 = 15;    // **
let PREC_UNARY: i32 = 16;       // prefix ! -, await
let PREC_PRIMARY: i32 = 17;     // a call, a member, a literal — never wrapped

/**
 * The precedence of a binary operator. Every operator `parser.zena` builds a
 * `BinaryExpression` from is named here.
 *
 * Exported for `precedence-agreement_test.zena`, which reads the order back out
 * of real parses and checks that the two still agree.
 */
export function binaryOperatorRank(op: String): i32 {
  if (op == '||' || op == '??') { return PREC_OR; }
  if (op == '&&') { return PREC_AND; }
  if (op == '|') { return PREC_BIT_OR; }
  if (op == '^') { return PREC_BIT_XOR; }
  if (op == '&') { return PREC_BIT_AND; }
  if (op == '==' || op == '!=' || op == '===' || op == '!==') { return PREC_EQUALITY; }
  if (op == '<' || op == '<=' || op == '>' || op == '>=') { return PREC_COMPARISON; }
  if (op == '<<' || op == '>>' || op == '>>>') { return PREC_SHIFT; }
  if (op == '+' || op == '-') { return PREC_TERM; }
  if (op == '*' || op == '/' || op == '%') { return PREC_FACTOR; }
  if (op == '**') { return PREC_EXPONENT; }
  // Unreachable for a parsed tree. Reporting the loosest rank means an
  // operand of an unknown operator keeps its parentheses.
  return PREC_LOOSEST;
}

/**
 * How tightly an expression's own top-level operator binds.
 *
 * Anything without one — a call, a member access, a literal, `new` — is
 * `PREC_PRIMARY`, so it is never parenthesized. `await` sits at unary
 * precedence because `#parseUnary` is where the parser reads it.
 */
function expressionRank(expr: Expression) {
  return match (expr) {
  case BinaryExpression {operator}: binaryOperatorRank(operator)
  case UnaryExpression {prefix}: if (prefix) PREC_UNARY else PREC_PRIMARY
  case AwaitExpression {}: PREC_UNARY
  case AsExpression {}: PREC_AS
  case IsExpression {}: PREC_AS
  case RangeExpression {}: PREC_RANGE
  case PipelineExpression {}: PREC_PIPELINE
  case AssignmentExpression {}: PREC_LOOSEST
  case FunctionExpression {}: PREC_LOOSEST
  case ThrowExpression {}: PREC_LOOSEST
  case IfExpression {}: PREC_LOOSEST
  case MatchExpression {}: PREC_LOOSEST
  case TryExpression {}: PREC_LOOSEST
  case _: PREC_PRIMARY
};
}

/**
 * An operand, parenthesized when it binds looser than its position allows.
 *
 * `minRank` is the precedence of the parser function that reads this
 * position: the operand of a `*` is read by `#parseExponentiation`, so it
 * must bind at least that tightly to survive a round trip.
 */
function printOperand(expr: Expression, minRank: i32) {
  if (expressionRank(expr) < minRank) {
    return concat(docs3(text('('), printExpression(expr), text(')')));
  }
  return printExpression(expr);
}

/**
 * Whether `expr` prints with a type annotation as its last token, as
 * `a as T` and `a << b as T` do. A cast the printer parenthesizes, as in
 * `a + (b as T)`, does not count.
 */
function endsWithType(expr: Expression): boolean {
  return match (expr) {
    case AsExpression {}: true
    case IsExpression {}: true
    case BinaryExpression {operator, right}: {
      let rank = binaryOperatorRank(operator);
      let rightMin = if (operator == '**') rank else rank + 1;
      expressionRank(right) >= rightMin && endsWithType(right)
    }
    case RangeExpression {end}: {
      end != null && expressionRank(end) >= PREC_AS && endsWithType(end)
    }
    case _: false
  };
}

/**
 * `printOperand`, but when `typeSensitive` (the operand is followed by `<` or
 * `|`) an operand that ends with a type is parenthesized too.
 */
function printOperandBefore(expr: Expression, minRank: i32, typeSensitive: boolean) {
  if (typeSensitive && endsWithType(expr)) {
    return concat(docs3(text('('), printExpression(expr), text(')')));
  }
  return printOperand(expr, minRank);
}

// ============================================================================
// Comment Printing Helpers
// ============================================================================

/**
 * Print a single comment as a Doc.
 */ 
function printComment(c: Comment) {
  if (c.isBlock) {
    return text(`/*${c.value}*/`);
  }
  return text('//' + c.value);
}

/**
 * Wrap a node's doc with its leading and trailing comments.
 * Leading comments appear before the doc (each on its own line).
 * Trailing comments appear after the doc on the same line (via lineSuffix).
 */
function withComments(node: Node, doc: Doc) {
  let leading = currentCommentMap.getLeading(node);
  let trailing = currentCommentMap.getTrailing(node);

  if (leading == null && trailing == null) {
    return doc;
  }

  let parts = new Array<Doc>();

  // Leading comments
  if (leading != null) {
    var i = 0;
    while (i < leading.length) {
      let c = leading[i];
      parts.push(printComment(c));
      parts.push(hardline);
      let nextStart = if (i + 1 < leading.length) {
        leading[i + 1].start
      } else {
        getNodeStart(node)
      };
      if (nextStart >= 0 && hasBlankLineBetween(currentSource, c.end, nextStart)) {
        parts.push(hardline);
      }
      i += 1;
    }
  }

  parts.push(doc);

  // Trailing comments: same-line comments use lineSuffix so they stick to
  // the end of the line; trailing comments on subsequent lines (after the
  // last node in a block or module) start on a new line.
  if (trailing != null) {
    var prevEnd = getNodeEnd(node);
    for (let c in trailing) {
      if (prevEnd >= 0 && hasNewlineBetween(currentSource, prevEnd, c.start)) {
        parts.push(hardline);
        if (hasBlankLineBetween(currentSource, prevEnd, c.start)) {
          parts.push(hardline);
        }
        parts.push(printComment(c));
      } else {
        parts.push(lineSuffix(concat(docs2(text(' '), printComment(c)))));
      }
      prevEnd = c.end;
    }
  }

  return concat(parts);
}

/**
 * Print braces with inner comments for an empty body.
 * Returns `{ <comment> }` if the node has inner comments, otherwise `{}`.
 * The `spaceBeforeOpen` flag prepends a space (for `class Foo {}` vs `{}`).
 */
function printEmptyBody(node: Node, spaceBeforeOpen: boolean) {
  let inner = currentCommentMap.getInner(node);
  if (inner == null) {
    if (spaceBeforeOpen) { return text(' {}'); }
    return text('{}');
  }
  let commentDocs = new Array<Doc>();
  var i = 0;
  while (i < inner.length) {
    commentDocs.push(printComment(inner[i]));
    if (i < inner.length - 1) {
      commentDocs.push(hardline);
      if (hasBlankLineBetween(currentSource, inner[i].end, inner[i + 1].start)) {
        commentDocs.push(hardline);
      }
    }
    i += 1;
  }
  let parts = new Array<Doc>();
  if (spaceBeforeOpen) { parts.push(text(' ')); }
  parts.push(text('{'));
  parts.push(indent(concat(docs2(hardline, concat(commentDocs)))));
  parts.push(hardline);
  parts.push(text('}'));
  return concat(parts);
}

// ============================================================================
// Main entry point
// ============================================================================

export function format(source: String): String {
  // The module-body rule is off. Where a statement may run is not a
  // question the formatter has to answer to lay it out, and a file the
  // compiler rejects is one a user may still want formatted.
  let module = parseAllowingStatements(source, '<input>');
  currentSource = source;
  currentCommentMap = attachComments(module);
  let doc = printModule(module);
  let options = new PrintOptions(80);
  return printDocToString(doc, options);
}

// ============================================================================
// Module
// ============================================================================

function printModule(module: Module): Doc {
  let parts = new Array<Doc>();

  // File-level leading comments (attached to Module by blank-line heuristic)
  let fileComments = currentCommentMap.getLeading(module);
  if (fileComments != null) {
    var fi = 0;
    while (fi < fileComments.length) {
      parts.push(printComment(fileComments[fi]));
      parts.push(hardline);
      if (fi + 1 < fileComments.length
          && hasBlankLineBetween(currentSource, fileComments[fi].end, fileComments[fi + 1].start)) {
        parts.push(hardline);
      }
      fi += 1;
    }
    if (module.body.length > 0) {
      parts.push(hardline);
    }
  }

  // Inner comments in empty modules
  if (module.body.length == 0) {
    let inner = currentCommentMap.getInner(module);
    if (inner != null) {
      var di = 0;
      while (di < inner.length) {
        parts.push(printComment(inner[di]));
        parts.push(hardline);
        if (di + 1 < inner.length
            && hasBlankLineBetween(currentSource, inner[di].end, inner[di + 1].start)) {
          parts.push(hardline);
        }
        di += 1;
      }
    }
  }

  var i = 0;
  while (i < module.body.length) {
    let stmt = module.body[i];
    parts.push(printStatement(stmt));
    if (i < module.body.length - 1) {
      parts.push(hardline);
      if (hasBlankLineBetweenNodes(stmt, module.body[i + 1])) {
        parts.push(hardline);
      }
    }
    i += 1;
  }
  if (module.body.length > 0 || parts.length == 0) {
    parts.push(hardline);
  }
  return concat(parts);
}

// ============================================================================
// Statements
// ============================================================================

function printStatement(stmt: Statement): Doc {
  let doc = printStatementInner(stmt);
  return withComments(stmt, doc);
}

function printStatementInner(stmt: Statement): Doc {
  return match (stmt) {
  case VariableDeclaration {}: printVariableDeclaration(stmt)
  case UsingStatement {}: printUsingStatement(stmt)
  case ShieldedStatement {body}: concat(docs2(text('shielded '), printBlockStatement(body)))
  case FunctionDeclaration {}: printFunctionDeclaration(stmt)
  case ExpressionStatement {expression}: concat(docs2(printExpression(expression), text(';')))
  case BlockStatement {}: printBlockStatement(stmt)
  case ReturnStatement {}: printReturnStatement(stmt)
  case YieldStatement {argument}: concat(docs3(text('yield '), printExpression(argument), text(';')))
  case BreakStatement {}: text('break;')
  case ContinueStatement {}: text('continue;')
  case IfStatement {}: printIfStatement(stmt)
  case WhileStatement {}: printWhileStatement(stmt)
  case ForStatement {}: printForStatement(stmt)
  case ForInStatement {}: printForInStatement(stmt)
  case ClassDeclaration {}: printClassDeclaration(stmt)
  case InterfaceDeclaration {}: printInterfaceDeclaration(stmt)
  case EnumDeclaration {}: printEnumDeclaration(stmt)
  case MixinDeclaration {}: printMixinDeclaration(stmt)
  case TypeAliasDeclaration {}: printTypeAliasDeclaration(stmt)
  case ImportDeclaration {}: printImportDeclaration(stmt)
  case ExportAllDeclaration {moduleSpecifier}: {
    concat(docs3(text('export * from '), printExpression(moduleSpecifier), text(';')))
  }
  case ExportFromDeclaration {}: printExportFromDeclaration(stmt)
  case DeclareFunction {}: printDeclareFunction(stmt)
  case SymbolDeclaration {name, exported}: {
    let parts = new Array<Doc>();
    if (exported) { parts.push(text('export ')); }
    parts.push(text('symbol '));
    parts.push(text(name.name));
    parts.push(text(';'));
    concat(parts)
  }
};
}

// ============================================================================
// Variable Declaration
// ============================================================================

/**
 * `let name: T = init`, without a terminating `;`. A C-style `for` header
 * supplies its own separators, so it prints the declaration this way.
 */
function printVariableDeclarator(decl: VariableDeclaration) {
  let parts = new Array<Doc>();
  if (decl.exported) { parts.push(text('export ')); }
  parts.push(text(decl.kind));
  parts.push(text(' '));
  parts.push(printPattern(decl.pattern));
  if (decl.typeAnnotation != null) {
    parts.push(text(': '));
    parts.push(printTypeAnnotation(decl.typeAnnotation as TypeAnnotation));
  }
  if (!(decl.init is NullLiteral && decl.init.loc == null)) {
    parts.push(text(' = '));
    parts.push(printExpression(decl.init));
  }
  return concat(parts);
}

function printVariableDeclaration(decl: VariableDeclaration): Doc {
  return group(concat(docs2(printVariableDeclarator(decl), text(';'))));
}

/** `using name: T = init;`, or the unbound `using init;`. */
function printUsingStatement(stmt: UsingStatement): Doc {
  let parts = growable<Doc>([text('using ')]);
  if (stmt.pattern != null) {
    parts.push(printPattern(stmt.pattern as Pattern));
    if (stmt.typeAnnotation != null) {
      parts.push(text(': '));
      parts.push(printTypeAnnotation(stmt.typeAnnotation as TypeAnnotation));
    }
    parts.push(text(' = '));
  }
  parts.push(printExpression(stmt.init));
  parts.push(text(';'));
  return group(concat(parts));
}

// ============================================================================
// Function Declaration
// ============================================================================

function printFunctionDeclaration(decl: FunctionDeclaration): Doc {
  let fn = decl.func;
  let parts = new Array<Doc>();
  if (decl.exported) { parts.push(text('export ')); }
  if (fn.isGenerator) { parts.push(text('gen ')); }
  if (fn.isAsync) { parts.push(text('async ')); }
  parts.push(text('function '));
  parts.push(text(decl.name.name));
  if (fn.typeParameters != null) {
    parts.push(printTypeParams(fn.typeParameters as GrowableArray<TypeParameter>));
  }
  parts.push(text('('));
  parts.push(printParams(fn.params));
  parts.push(text(')'));
  if (fn.returnType != null) {
    parts.push(text(': '));
    parts.push(printTypeAnnotation(fn.returnType as TypeAnnotation));
  }
  parts.push(printContractClauses(fn.contracts, true));
  // The parser guarantees a block body.
  parts.push(printBlockStatement(fn.body as BlockStatement));
  return group(concat(parts));
}

// ============================================================================
// Return Statement
// ============================================================================

function printReturnStatement(stmt: ReturnStatement): Doc {
  if (stmt.argument == null) { return text('return;'); }
  let parts = growable<Doc>([
    text(if (stmt.isTail) 'tail return ' else 'return '),
    printExpression(stmt.argument as Expression),
    text(';'),
  ]);
  return concat(parts);
}

// ============================================================================
// Block Statement
// ============================================================================

function printBlockStatement(block: BlockStatement): Doc {
  if (block.body.length == 0) { return printEmptyBody(block, false); }
  let stmts = new Array<Doc>();
  var i = 0;
  while (i < block.body.length) {
    let stmt = block.body[i];
    stmts.push(printStatement(stmt));
    if (i < block.body.length - 1) {
      stmts.push(hardline);
      if (hasBlankLineBetweenNodes(stmt, block.body[i + 1])) {
        stmts.push(hardline);
      }
    }
    i += 1;
  }
  let parts = growable<Doc>([
    text('{'),
    indent(concat(docs2(hardline, concat(stmts)))),
    hardline,
    text('}'),
  ]);
  return concat(parts);
}

// ============================================================================
// If Statement
// ============================================================================

function printIfStatement(stmt: IfStatement): Doc {
  let parts = growable<Doc>([
    text('if ('),
    printCondition(stmt.test),
    text(') '),
    printStatement(stmt.consequent),
  ]);
  if (stmt.alternate != null) {
    let alt = stmt.alternate as Statement;
    parts.push(text(' else '));
    if (alt is IfStatement) {
      parts.push(printIfStatement(alt));
    } else {
      parts.push(printStatement(alt));
    }
  }
  return concat(parts);
}

// ============================================================================
// While Statement
// ============================================================================

function printWhileStatement(stmt: WhileStatement): Doc {
  let parts = growable<Doc>([
    text('while ('),
    printCondition(stmt.test),
    text(')'),
    printContractClauses(stmt.invariants, true),
    printStatement(stmt.body),
  ]);
  return concat(parts);
}

// ============================================================================
// Contract Clauses
// ============================================================================

/**
 * The clauses that follow a signature or a loop header, with what
 * separates the header from its body when `beforeBody` is set. Clauses
 * that fit stay on the header's line:
 *
 *     function half(n: i32): i32 requires (n % 2 == 0) {
 *
 * Otherwise each takes a line of its own, and so does the body's `{` or
 * `=>`:
 *
 *     function withdraw(account: Account, amount: i32): Account
 *       requires (amount > 0)
 *       requires (account.balance >= amount)
 *     {
 */
function printContractClauses(clauses: GrowableArray<ContractClause> | null, beforeBody: boolean): Doc {
  if (clauses == null) {
    return text(if (beforeBody) ' ' else '');
  }
  let lines = new Array<Doc>();
  for (let clause in clauses) {
    lines.push(line);
    if (clause.mode != ContractMode.Checked) {
      lines.push(text(`${contractModifier(clause.mode)} `));
    }
    lines.push(text(`${contractKeyword(clause.kind)} (`));
    lines.push(printExpression(clause.condition));
    lines.push(text(')'));
  }
  let parts = growable<Doc>([indent(concat(lines))]);
  if (beforeBody) { parts.push(line); }
  return group(concat(parts));
}

// ============================================================================
// For Statement
// ============================================================================

function printForStatement(stmt: ForStatement): Doc {
  let parts = growable<Doc>([text('for (')]);
  // The header owns its `;` separators, and a space belongs after one only
  // when a clause follows it — `for (;;)` has three empty clauses.
  if (stmt.init != null) {
    let init = stmt.init as Node;
    parts.push(if (init is VariableDeclaration) {
      printVariableDeclarator(init)
    } else {
      printExpression(init as Expression)
    });
  }
  parts.push(text(';'));
  if (stmt.test != null) {
    parts.push(text(' '));
    parts.push(printExpression(stmt.test as Expression));
  }
  parts.push(text(';'));
  if (stmt.update != null) {
    parts.push(text(' '));
    parts.push(printExpression(stmt.update as Expression));
  }
  parts.push(text(')'));
  parts.push(printContractClauses(stmt.invariants, true));
  parts.push(printStatement(stmt.body));
  return concat(parts);
}

// ============================================================================
// For-In Statement
// ============================================================================

function printForInStatement(stmt: ForInStatement): Doc {
  let parts = growable<Doc>([
    text('for (let '),
    printPattern(stmt.pattern),
    text(' in '),
    printExpression(stmt.iterable),
    text(')'),
    printContractClauses(stmt.invariants, true),
    printStatement(stmt.body),
  ]);
  return concat(parts);
}

// ============================================================================
// Class Declaration
// ============================================================================

function printClassDeclaration(decl: ClassDeclaration): Doc {
  let parts = new Array<Doc>();
  if (decl.exported) { parts.push(text('export ')); }
  if (decl.isResource) { parts.push(text('resource ')); }
  if (decl.isAbstract) { parts.push(text('abstract ')); }
  if (decl.isFinal) { parts.push(text('final ')); }
  if (decl.isSealed) { parts.push(text('sealed ')); }
  if (decl.isExtension) { parts.push(text('extension ')); }
  parts.push(text('class '));
  parts.push(text(decl.name.name));

  if (decl.typeParameters != null) {
    parts.push(printTypeParams(decl.typeParameters as GrowableArray<TypeParameter>));
  }

  if (decl.caseParams != null) {
    parts.push(printCaseClassParamList(decl.caseParams as GrowableArray<CaseClassParam>));
  }

  // A `resource class` with no written superclass is parsed as extending
  // `Resource`, the root of every resource hierarchy. Printing that clause
  // back would turn the class into an ordinary one extending a resource,
  // which is an error rather than a different spelling of the same thing.
  var superClass = decl.superClass;
  if (decl.isResource && superClass != null) {
    if (let NamedTypeAnnotation {name} = superClass) {
      if (name == 'Resource') { superClass = null; }
    }
  }

  // The `on` clause comes first: an extension class may write both
  // (`extension class Sub on i32 extends Base`), and that is the order
  // the parser accepts.
  if (decl.onType != null) {
    parts.push(text(' on '));
    parts.push(printTypeAnnotation(decl.onType as TypeAnnotation));
  }

  if (superClass != null) {
    parts.push(text(' extends '));
    parts.push(printTypeAnnotation(superClass));
  }

  if (decl.mixins != null) {
    let mx = decl.mixins as GrowableArray<TypeAnnotation>;
    if (mx.length > 0) {
      parts.push(text(' with '));
      parts.push(join(text(', '), mapTypeAnnotations(mx)));
    }
  }

  if (decl.implementsList != null) {
    let impls = decl.implementsList as GrowableArray<TypeAnnotation>;
    if (impls.length > 0) {
      parts.push(text(' implements '));
      parts.push(join(text(', '), mapTypeAnnotations(impls)));
    }
  }

  let hasVariants = decl.sealedVariants != null
      && (decl.sealedVariants as GrowableArray<SealedVariant>).length > 0;
  if (!hasVariants && decl.body.length == 0) {
    if (decl.caseParams != null) {
      // Concise case class — no braces
    } else {
      parts.push(printEmptyBody(decl, true));
    }
  } else {
    parts.push(text(' {'));
    let itemNodes = new Array<Node>();
    if (hasVariants) {
      let variants = decl.sealedVariants as GrowableArray<SealedVariant>;
      var vi = 0;
      var bi = 0;
      while (vi < variants.length && bi < decl.body.length) {
        if (startsBefore(variants[vi], decl.body[bi])) {
          itemNodes.push(variants[vi]);
          vi += 1;
        } else {
          itemNodes.push(decl.body[bi]);
          bi += 1;
        }
      }
      while (vi < variants.length) {
        itemNodes.push(variants[vi]);
        vi += 1;
      }
      while (bi < decl.body.length) {
        itemNodes.push(decl.body[bi]);
        bi += 1;
      }
    } else {
      var bi = 0;
      while (bi < decl.body.length) {
        itemNodes.push(decl.body[bi]);
        bi += 1;
      }
    }
    let members = new Array<Doc>();
    var i = 0;
    while (i < itemNodes.length) {
      let cur = itemNodes[i];
      if (cur is SealedVariant) {
        members.push(withComments(cur, printSealedVariant(cur)));
      } else {
        members.push(printClassMember(cur));
      }
      if (i < itemNodes.length - 1) {
        members.push(hardline);
        if (hasBlankLineBetweenNodes(cur, itemNodes[i + 1])) {
          members.push(hardline);
        }
      }
      i += 1;
    }
    parts.push(indent(concat(docs2(hardline, concat(members)))));
    parts.push(hardline);
    parts.push(text('}'));
  }

  return concat(parts);
}

function printSealedVariant(v: SealedVariant): Doc {
  let parts = growable<Doc>([text('case '), text(v.name.name)]);
  if (v.params != null) {
    parts.push(printCaseClassParamList(v.params as GrowableArray<CaseClassParam>));
  }
  return concat(parts);
}

function printCaseClassParamInner(param: CaseClassParam) {
  let parts = new Array<Doc>();
  if (param.mutability != null) {
    parts.push(text(param.mutability as String));
    parts.push(text(' '));
  }
  parts.push(text(param.name.name));
  parts.push(text(': '));
  parts.push(printTypeAnnotation(param.typeAnnotation));
  if (param.defaultValue != null) {
    parts.push(text(' = '));
    parts.push(printExpression(param.defaultValue as Expression));
  }
  return concat(parts);
}

function printCaseClassParamList(ps: GrowableArray<CaseClassParam>): Doc {
  var hasParamComments = false;
  for (let p in ps) {
    if (currentCommentMap.getLeading(p) != null
        || currentCommentMap.getTrailing(p) != null) {
      hasParamComments = true;
    }
  }
  if (!hasParamComments) {
    let pDocs = new Array<Doc>();
    var i = 0;
    while (i < ps.length) {
      pDocs.push(printCaseClassParamInner(ps[i]));
      i += 1;
    }
    return concat(docs3(text('('), join(text(', '), pDocs), text(')')));
  }
  let pDocs = new Array<Doc>();
  var i = 0;
  while (i < ps.length) {
    let cur = ps[i];
    let inner = printCaseClassParamInner(cur);
    let withComma = if (i < ps.length - 1) concat(docs2(inner, text(','))) else inner;
    pDocs.push(withComments(cur, withComma));
    if (i < ps.length - 1) {
      pDocs.push(hardline);
      if (hasBlankLineBetweenNodes(cur, ps[i + 1])) {
        pDocs.push(hardline);
      }
    }
    i += 1;
  }
  return concat(docs3(
    text('('),
    indent(concat(docs2(hardline, concat(pDocs)))),
    concat(docs2(hardline, text(')')))));
}

function printClassMember(member: Node): Doc {
  let doc = match (member) {
    case FieldDefinition {}: printFieldDefinition(member)
    case MethodDefinition {}: printMethodDefinition(member)
    case AccessorDeclaration {}: printAccessorDeclaration(member)
    case _: text('/* unknown member */')
  };
  return withComments(member, doc);
}

function printFieldDefinition(field: FieldDefinition): Doc {
  // `static symbol sym;` — a declaration, not a field with a type.
  // Printing it as one spells `static sym: symbol;`, which does not
  // parse back.
  if (isSymbolFieldDeclaration(field)) {
    return concat(docs3(
      text('static symbol '), printNodeName(field.name), text(';')));
  }
  let parts = new Array<Doc>();
  printMemberDecorators(field.decorators, parts);
  if (field.isShared) { parts.push(text('shared ')); }
  if (field.isStatic) { parts.push(text('static ')); }
  if (field.isAbstract) { parts.push(text('abstract ')); }
  if (field.isFinal) { parts.push(text('final ')); }
  if (field.mutability != null) {
    parts.push(text(field.mutability as String));
    let setterName = field.setterName;
    if (setterName != null) {
      parts.push(text('('));
      parts.push(printNodeName(setterName));
      parts.push(text(')'));
    }
    parts.push(text(' '));
  }
  parts.push(printNodeName(field.name));
  if (field.typeAnnotation != null) {
    parts.push(text(': '));
    parts.push(printTypeAnnotation(field.typeAnnotation as TypeAnnotation));
  }
  if (field.value != null) {
    parts.push(text(' = '));
    parts.push(printExpression(field.value as Expression));
  }
  parts.push(text(';'));
  return concat(parts);
}

/**
 * How many leading initializer entries the parser synthesized for `this.`
 * parameters, and so how many the printer must leave out.
 *
 * Each `this.x` parameter becomes a plain parameter plus a `x = x` entry, and
 * those entries are prepended to any the source wrote. Printing them as well
 * as the `this.` on the parameter would give the constructor an initializer
 * list it never had.
 *
 * Only a leading run that actually looks synthesized — a field initialized
 * from an identifier of its own name, for a parameter marked `isThisParam` —
 * is counted, so an entry the source wrote is never dropped.
 */
function synthesizedInitializerCount(
    params: Array<Parameter>,
    inits: GrowableArray<Node>) {
  var thisParams = 0;
  for (let p in params) {
    if (p.isThisParam) { thisParams += 1; }
  }

  var counted = 0;
  while (counted < thisParams && counted < inits.length) {
    let looksSynthesized = if (let FieldInitializer {field, value} = inits[counted]) {
      if (let Identifier {name} = value) name == field.name else false
    } else {
      false
    };
    if (!looksSynthesized) { break; }
    counted += 1;
  }
  return counted;
}

function printMethodDefinition(method: MethodDefinition): Doc {
  let parts = new Array<Doc>();
  printMemberDecorators(method.decorators, parts);
  if (method.isShared) { parts.push(text('shared ')); }
  if (method.isStatic) { parts.push(text('static ')); }
  if (method.isAbstract) { parts.push(text('abstract ')); }
  if (method.isFinal) { parts.push(text('final ')); }
  if (method.isGenerator) { parts.push(text('gen ')); }
  if (method.isAsync) { parts.push(text('async ')); }

  if (method.isConstructor) {
    // `new(...)`, or a named constructor `new name(...)`.
    parts.push(text('new'));
    let isDefault = if (let Identifier {name} = method.name) {
      name == '<constructor>'
    } else {
      false
    };
    if (!isDefault) {
      parts.push(text(' '));
      parts.push(printNodeName(method.name));
    }
  } else {
    parts.push(printNodeName(method.name));
  }

  if (method.typeParameters != null) {
    parts.push(printTypeParams(method.typeParameters as GrowableArray<TypeParameter>));
  }

  parts.push(text('('));
  // A declared receiver leads the parameter list without being one of them.
  if (method.receiver != null) {
    parts.push(text('this: '));
    parts.push(printTypeAnnotation(method.receiver as TypeAnnotation));
    if (method.params.length > 0) { parts.push(text(', ')); }
  }
  parts.push(printParams(method.params));
  parts.push(text(')'));

  if (method.returnType != null) {
    parts.push(text(': '));
    parts.push(printTypeAnnotation(method.returnType as TypeAnnotation));
  }

  // A constructor's clauses come before its initializer list, which
  // stays on the last clause's line. A method's are printed with its body.
  let contractsBeforeBody = !method.isConstructor && method.body is BlockStatement;
  if (!contractsBeforeBody) {
    parts.push(printContractClauses(method.contracts, false));
  }

  // Initializer list, less the entries synthesized for `this.` parameters —
  // those are printed as part of the parameter.
  var printedInitializer = false;
  if (method.initializerList != null) {
    let inits = method.initializerList as GrowableArray<Node>;
    let skip = synthesizedInitializerCount(method.params, inits);
    if (inits.length > skip) {
      parts.push(text(' : '));
      let initDocs = new Array<Doc>();
      var i = skip;
      while (i < inits.length) {
        initDocs.push(printInitializerEntry(inits[i]));
        i += 1;
      }
      parts.push(join(text(', '), initDocs));
      printedInitializer = true;
    }
  }

  // Super initializer
  if (method.superInitializer != null) {
    if (let SuperInitializer {args} = method.superInitializer as Node) {
      if (printedInitializer) {
        parts.push(text(', '));
      } else {
        parts.push(text(' : '));
      }
      parts.push(text('super('));
      let argDocs = new Array<Doc>();
      var i = 0;
      while (i < args.length) {
        argDocs.push(printExpression(args[i]));
        i += 1;
      }
      parts.push(join(text(', '), argDocs));
      parts.push(text(')'));
    }
  }

  if (method.body != null) {
    let body = method.body as Node;
    if (body is BlockStatement) {
      parts.push(if (contractsBeforeBody) printContractClauses(method.contracts, true) else text(' '));
      parts.push(printBlockStatement(body));
    } else {
      parts.push(text(' '));
      parts.push(printNode(body));
    }
  } else {
    parts.push(text(';'));
  }

  return concat(parts);
}

function printInitializerEntry(entry: Node): Doc {
  return if (let FieldInitializer {field, value} = entry) {
    concat(docs3(text(field.name), text(' = '), printExpression(value)))
  } else {
    text('/* unknown initializer */')
  };
}

function printAccessorDeclaration(acc: AccessorDeclaration): Doc {
  let parts = new Array<Doc>();
  printMemberDecorators(acc.decorators, parts);
  if (acc.isStatic) { parts.push(text('static ')); }
  if (acc.isFinal) { parts.push(text('final ')); }
  parts.push(printNodeName(acc.name));
  parts.push(text(': '));
  parts.push(printTypeAnnotation(acc.typeAnnotation));
  // The accessor block: `name: T { get {...} set(v) {...} }`. Without
  // the enclosing braces the output does not parse back.
  parts.push(text(' {'));
  let accessors = new Array<Doc>();
  if (acc.getter != null) {
    accessors.push(concat(docs2(
        text('get '), printBlockStatement(acc.getter as BlockStatement))));
  }
  if (acc.setter != null) {
    if (let SetterInfo {param, body} = acc.setter as Node) {
      if (acc.getter != null) {
        accessors.push(hardline);
        if (hasBlankLineBetweenNodes(acc.getter as Node, acc.setter as Node)) {
          accessors.push(hardline);
        }
      }
      accessors.push(concat(docs2(
          text(`set(${param.name}) `), printBlockStatement(body))));
    }
  }
  parts.push(indent(concat(docs2(hardline, concat(accessors)))));
  parts.push(hardline);
  parts.push(text('}'));
  return concat(parts);
}

// ============================================================================
// Interface Declaration
// ============================================================================

function printInterfaceDeclaration(decl: InterfaceDeclaration): Doc {
  let parts = new Array<Doc>();
  if (decl.exported) { parts.push(text('export ')); }
  parts.push(text('interface '));
  parts.push(text(decl.name.name));
  if (decl.typeParameters != null) {
    parts.push(printTypeParams(decl.typeParameters as GrowableArray<TypeParameter>));
  }
  if (decl.extendsList != null) {
    let exts = decl.extendsList as GrowableArray<TypeAnnotation>;
    if (exts.length > 0) {
      parts.push(text(' extends '));
      parts.push(join(text(', '), mapTypeAnnotations(exts)));
    }
  }
  if (decl.body.length == 0) {
    parts.push(printEmptyBody(decl, true));
  } else {
    parts.push(text(' {'));
    let memberDocs = new Array<Doc>();
    var i = 0;
    while (i < decl.body.length) {
      let cur = decl.body[i];
      memberDocs.push(printInterfaceMember(cur));
      if (i < decl.body.length - 1) {
        memberDocs.push(hardline);
        if (hasBlankLineBetweenNodes(cur, decl.body[i + 1])) {
          memberDocs.push(hardline);
        }
      }
      i += 1;
    }
    parts.push(indent(concat(docs2(hardline, concat(memberDocs)))));
    parts.push(hardline);
    parts.push(text('}'));
  }
  return concat(parts);
}

function printInterfaceMember(member: Node): Doc {
  let doc = match (member) {
    // An interface constructor: the same node a class constructor is.
    case MethodDefinition {}: printMethodDefinition(member)
    case MethodSignature {name, typeParameters, params, returnType, contracts}: {
      let parts = new Array<Doc>();
      // Not always an Identifier: a symbol-keyed signature such as
      // `[Disposable.dispose](): void;` carries a SymbolPropertyName.
      parts.push(printNodeName(name));
      if (typeParameters != null) {
        parts.push(printTypeParams(typeParameters));
      }
      parts.push(text('('));
      parts.push(printParams(params));
      parts.push(text(')'));
      if (returnType != null) {
        parts.push(text(': '));
        parts.push(printTypeAnnotation(returnType));
      }
      parts.push(printContractClauses(contracts, false));
      parts.push(text(';'));
      concat(parts)
    }
    case AccessorSignature {name, typeAnnotation}: {
      let parts = growable<Doc>([
        text(name.name),
        text(': '),
        printTypeAnnotation(typeAnnotation),
        text(';'),
      ]);
      concat(parts)
    }
    case PropertySignature {name, typeAnnotation}: {
      let parts = growable<Doc>([
        text(name.name),
        text(': '),
        printTypeAnnotation(typeAnnotation),
        text(';'),
      ]);
      concat(parts)
    }
    // `static symbol sym;`. The statement printer spells a top-level
    // `symbol sym;`, which is a different declaration — printing one as
    // the other would drop the `static` and move the symbol out of the
    // type that owns it.
    case SymbolDeclaration {name}: {
      concat(docs3(text('static symbol '), text(name.name), text(';')))
    }
    case _: text('/* unknown interface member */')
  };
  return withComments(member, doc);
}

// ============================================================================
// Enum Declaration
// ============================================================================

function printEnumDeclaration(decl: EnumDeclaration): Doc {
  let parts = new Array<Doc>();
  if (decl.exported) { parts.push(text('export ')); }
  parts.push(text('enum '));
  parts.push(text(decl.name.name));
  if (decl.members.length == 0) {
    parts.push(printEmptyBody(decl, true));
    return concat(parts);
  }
  parts.push(text(' {'));
  let memberDocs = new Array<Doc>();
  var i = 0;
  while (i < decl.members.length) {
    let m = decl.members[i];
    let memberDoc = if (m.initializer != null) {
      concat(docs3(text(m.name.name), text(' = '), printExpression(m.initializer as Expression)));
    } else {
      text(m.name.name);
    };
    let withComma = if (i < decl.members.length - 1) {
      concat(docs2(memberDoc, text(',')))
    } else {
      memberDoc
    };
    memberDocs.push(withComments(m, withComma));
    if (i < decl.members.length - 1) {
      memberDocs.push(hardline);
      if (hasBlankLineBetweenNodes(m, decl.members[i + 1])) {
        memberDocs.push(hardline);
      }
    }
    i += 1;
  }
  parts.push(indent(concat(docs2(hardline, concat(memberDocs)))));
  parts.push(hardline);
  parts.push(text('}'));
  return concat(parts);
}

// ============================================================================
// Mixin Declaration
// ============================================================================

function printMixinDeclaration(decl: MixinDeclaration): Doc {
  let parts = new Array<Doc>();
  if (decl.exported) { parts.push(text('export ')); }
  let subject = decl.decoratorSubject;
  parts.push(text(if (subject != null) 'decorator ' else 'mixin '));
  parts.push(text(decl.name.name));
  if (decl.typeParameters != null) {
    parts.push(printTypeParams(decl.typeParameters as GrowableArray<TypeParameter>));
  }
  if (subject != null) {
    parts.push(text('('));
    if (subject.mutability != null) {
      parts.push(text(subject.mutability as String));
      parts.push(text(' '));
    }
    parts.push(printNodeName(subject.name));
    parts.push(text(': '));
    parts.push(printTypeAnnotation(subject.typeAnnotation as TypeAnnotation));
    parts.push(text(')'));
  }
  if (decl.on != null) {
    parts.push(text(' on '));
    parts.push(text((decl.on as Identifier).name));
  }
  if (decl.body.length == 0) {
    parts.push(printEmptyBody(decl, true));
  } else {
    parts.push(text(' {'));
    let memberDocs = new Array<Doc>();
    var i = 0;
    while (i < decl.body.length) {
      let cur = decl.body[i];
      memberDocs.push(printClassMember(cur));
      if (i < decl.body.length - 1) {
        memberDocs.push(hardline);
        if (hasBlankLineBetweenNodes(cur, decl.body[i + 1])) {
          memberDocs.push(hardline);
        }
      }
      i += 1;
    }
    parts.push(indent(concat(docs2(hardline, concat(memberDocs)))));
    parts.push(hardline);
    parts.push(text('}'));
  }
  return concat(parts);
}

// ============================================================================
// Type Alias Declaration
// ============================================================================

function printTypeAliasDeclaration(decl: TypeAliasDeclaration): Doc {
  let parts = new Array<Doc>();
  printDecorators(decl.decorators, parts);
  if (decl.exported) { parts.push(text('export ')); }
  // `opaque` implies `isDistinct`, so it has to win — printing both would
  // produce `distinct opaque type`, which does not parse.
  if (decl.isOpaque) {
    parts.push(text('opaque '));
  } else if (decl.isDistinct) {
    parts.push(text('distinct '));
  }
  let body = decl.typeAnnotation;
  if (body == null) {
    parts.push(text('declare '));
  }
  parts.push(text('type '));
  parts.push(text(decl.name.name));
  if (decl.typeParameters != null) {
    parts.push(printTypeParams(decl.typeParameters as GrowableArray<TypeParameter>));
  }
  if (body != null) {
    parts.push(text(' = '));
    parts.push(printTypeAnnotation(body));
  }
  parts.push(text(';'));
  return concat(parts);
}

// ============================================================================
// Import Declaration
// ============================================================================

function printImportSpecifier(spec: ImportSpecifier) {
  if (spec.imported.name == spec.local.name) {
    return text(spec.imported.name);
  }
  return concat(docs3(text(spec.imported.name), text(' as '), text(spec.local.name)));
}

function printSpecifierListDeclaration(
  prefix: String,
  decl: Node,
  specifiers: GrowableArray<ImportSpecifier>,
  moduleSpecifier: Expression
) {
  if (specifiers.length == 0) {
    return concat(growable<Doc>([
      text(prefix),
      printEmptyBody(decl, false),
      text(' from '),
      printExpression(moduleSpecifier),
      text(';'),
    ]));
  }
  var hasSpecComments = false;
  for (let spec in specifiers) {
    if (currentCommentMap.getLeading(spec) != null
        || currentCommentMap.getTrailing(spec) != null) {
      hasSpecComments = true;
    }
  }
  if (specifiers.length == 1 && !hasSpecComments) {
    return concat(growable<Doc>([
      text(prefix),
      text('{'),
      printImportSpecifier(specifiers[0]),
      text('} from '),
      printExpression(moduleSpecifier),
      text(';'),
    ]));
  }
  let specParts = new Array<Doc>();
  var i = 0;
  while (i < specifiers.length) {
    let cur = specifiers[i];
    let specDoc = printImportSpecifier(cur);
    let withComma = if (i < specifiers.length - 1) {
      concat(docs2(specDoc, text(',')))
    } else {
      concat(docs2(specDoc, ifBreak(text(','), text(''))))
    };
    specParts.push(withComments(cur, withComma));
    if (i < specifiers.length - 1) {
      let next = specifiers[i + 1];
      if (currentCommentMap.getLeading(next) != null
          && hasBlankLineBetweenNodes(cur, next)) {
        specParts.push(hardline);
        specParts.push(hardline);
      } else {
        specParts.push(line);
      }
    }
    i += 1;
  }
  let parts = growable<Doc>([
    text(prefix),
    text('{'),
    indent(concat(docs2(softline, concat(specParts)))),
    softline,
    text('} from '),
    printExpression(moduleSpecifier),
    text(';'),
  ]);
  return groupWithBreak(concat(parts), hasSpecComments);
}

function printImportDeclaration(decl: ImportDeclaration): Doc {
  if (decl.imports.length == 1 && decl.imports[0].imported.name == '*') {
    return concat(growable<Doc>([
      text('import * as '),
      text(decl.imports[0].local.name),
      text(' from '),
      printExpression(decl.moduleSpecifier),
      text(';'),
    ]));
  }
  return printSpecifierListDeclaration('import ', decl, decl.imports, decl.moduleSpecifier);
}

// ============================================================================
// Export From Declaration
// ============================================================================

function printExportFromDeclaration(decl: ExportFromDeclaration): Doc {
  return printSpecifierListDeclaration('export ', decl, decl.specifiers, decl.moduleSpecifier);
}

// ============================================================================
// Declare Function
// ============================================================================

function printDecorators(decorators: GrowableArray<Decorator>, parts: GrowableArray<Doc>): void {
  for (let dec in decorators) {
    printDecorator(dec, parts);
    parts.push(hardline);
  }
}

/** `@name` or `@a.b(args)`, with no trailing break. */
function printDecorator(dec: Decorator, parts: GrowableArray<Doc>): void {
  parts.push(text('@'));
  parts.push(text(dec.name));
  if (dec.args.length > 0) {
    parts.push(text('('));
    var first = true;
    for (let arg in dec.args) {
      if (!first) { parts.push(text(', ')); }
      first = false;
      parts.push(printExpression(arg));
    }
    parts.push(text(')'));
  }
}

/**
 * A class member's decorators, each followed by a space so they lead the
 * member on its own line: `@signal var count: i32 = 0;`.
 */
function printMemberDecorators(decorators: GrowableArray<Decorator>, parts: GrowableArray<Doc>): void {
  for (let dec in decorators) {
    printDecorator(dec, parts);
    parts.push(text(' '));
  }
}

function printDeclareFunction(decl: DeclareFunction): Doc {
  let parts = new Array<Doc>();
  printDecorators(decl.decorators, parts);
  if (decl.exported) { parts.push(text('export ')); }
  parts.push(text('declare '));
  parts.push(text(decl.name.name));
  if (decl.typeParameters != null) {
    parts.push(printTypeParams(decl.typeParameters as GrowableArray<TypeParameter>));
  }
  parts.push(text('('));
  parts.push(printParams(decl.params));
  parts.push(text('): '));
  parts.push(printTypeAnnotation(decl.returnType));
  parts.push(text(';'));
  return concat(parts);
}

// ============================================================================
// Expressions
// ============================================================================

function printExpression(expr: Expression): Doc {
  let doc = printExpressionInner(expr);
  return withComments(expr, doc);
}

function printExpressionInner(expr: Expression): Doc {
  return match (expr) {
  case Identifier {name}: text(name)
  case NumberLiteral {raw}: text(raw)
  case StringLiteral {}: printStringLiteral(expr)
  case BooleanLiteral {value}: if (value) { text('true') } else { text('false') }
  case NullLiteral {}: text('null')
  case ThisExpression {}: text('this')
  case SuperExpression {}: text('super')
  case PipePlaceholder {}: text('$')
  case BinaryExpression {}: printBinaryExpression(expr)
  case UnaryExpression {}: printUnaryExpression(expr)
  case AssignmentExpression {}: printAssignmentExpression(expr)
  case MemberExpression {}: printMemberExpression(expr)
  case IndexExpression {}: printIndexExpression(expr)
  case CallExpression {}: printCallExpression(expr)
  case NewExpression {}: printNewExpression(expr)
  case FunctionExpression {}: printFunctionExpression(expr)
  case ArrayLiteral {}: printArrayLiteral(expr)
  case RecordLiteral {}: printRecordLiteral(expr)
  case TupleLiteral {}: printTupleLiteral(expr)
  case MapLiteral {}: printMapLiteral(expr)
  case AsExpression {expression, typeAnnotation}: {
    concat(docs3(printOperand(expression, PREC_AS), text(' as '), printTypeAnnotation(typeAnnotation)))
  }
  case IsExpression {expression, typeAnnotation}: {
    concat(docs3(printOperand(expression, PREC_AS), text(' is '), printTypeAnnotation(typeAnnotation)))
  }
  case RangeExpression {}: printRangeExpression(expr)
  case PipelineExpression {}: printPipelineExpression(expr)
  case TemplateLiteral {}: printTemplateLiteral(expr)
  case TaggedTemplateExpression {tag, quasi}: {
    concat(docs2(printExpression(tag), printTemplateLiteral(quasi)))
  }
  case MatchExpression {}: printMatchExpression(expr)
  case IfExpression {}: printIfExpression(expr)
  case ThrowExpression {argument}: concat(docs2(text('throw '), printExpression(argument)))
  case AwaitExpression {argument}: concat(docs2(text('await '), printOperand(argument, PREC_UNARY)))
  case TryExpression {}: printTryExpression(expr)
};
}

// ============================================================================
// String Literals — normalize to single quotes with proper escaping
// ============================================================================

// Re-escape a decoded string value for single-quoted output.
// The value has already been unescaped by the lexer, so literal characters
// like ' and \ and control characters need to be escaped back.
function escapeForSingleQuote(value: String) {
  let len = value.length;
  // Fast path: if no characters need escaping, return as-is
  var needsEscape = false;
  var i = 0;
  while (i < len) {
    let b = value.getByteAt(i);
    // 39=', 92=\, 10=\n, 13=\r, 9=\t, 0=\0
    if (b == 39 || b == 92 || b == 10 || b == 13 || b == 9 || b == 0) {
      needsEscape = true;
      i = len; // break
    }
    i += 1;
  }
  if (!needsEscape) {
    return value;
  }

  let sb = new StringBuilder(len + 8);
  i = 0;
  while (i < len) {
    let b = value.getByteAt(i);
    if (b == 92) {
      // backslash → \\
      sb.appendByte(92);
      sb.appendByte(92);
    } else if (b == 39) {
      // single quote → \'
      sb.appendByte(92);
      sb.appendByte(39);
    } else if (b == 10) {
      // newline → \n
      sb.appendByte(92);
      sb.appendByte(110);
    } else if (b == 13) {
      // carriage return → \r
      sb.appendByte(92);
      sb.appendByte(114);
    } else if (b == 9) {
      // tab → \t
      sb.appendByte(92);
      sb.appendByte(116);
    } else if (b == 0) {
      // null → \0
      sb.appendByte(92);
      sb.appendByte(48);
    } else {
      sb.appendByte(b);
    }
    i += 1;
  }
  return sb.toString();
}

function printStringLiteral(lit: StringLiteral): Doc {
  let parts = growable<Doc>([
    text("'"),
    text(escapeForSingleQuote(lit.value)),
    text("'"),
  ]);
  return concat(parts);
}

// ============================================================================
// Binary Expression
// ============================================================================

/**
 * Check if two binary expressions have the same operator (for chain flattening).
 */
function isSameOpChain(expr: Expression, op: String): boolean {
  return if (let BinaryExpression {operator} = expr) operator == op else false;
}

/**
 * Flatten a left-associative chain of same-operator binary expressions.
 * ((a + b) + c) + d → [a, b, c, d] with operator "+"
 */
function flattenBinaryChain(expr: BinaryExpression): Array<Expression> {
  let parts = new Array<Expression>();
  let op = expr.operator;

  // Walk left spine collecting operands
  var current: Expression = expr;
  while (isSameOpChain(current, op)) {
    let bin = current as BinaryExpression;
    parts.push(bin.right);
    current = bin.left;
  }
  // current is the leftmost non-matching operand
  parts.push(current);

  // Reverse to get left-to-right order
  let result = new Array<Expression>(parts.length);
  var i = parts.length - 1;
  while (i >= 0) {
    result.push(parts[i]);
    i -= 1;
  }
  return result;
}

/**
 * `a + b + c`, breaking before each operator when the whole chain does not fit:
 *
 *     a
 *       + b
 *       + c
 *
 * Every chain gets that break opportunity, a two-operand one included. A
 * single operator used to print with no `line` in it, so the group had nothing
 * to break at, and a long condition broke in whatever group was nested inside
 * it — the argument list of a call, say — leaving the operator on one line.
 */
function printBinaryExpression(expr: BinaryExpression): Doc {
  let op = expr.operator;
  let rank = binaryOperatorRank(op);
  // `**` is the one right-associative binary operator. Flattening its left
  // spine would reassociate it: `(a ** b) ** c` is not `a ** b ** c`.
  let rightAssociative = op == '**';

  var operands = flattenBinaryChain(expr);
  if (rightAssociative) {
    // The walk above collects the left spine, which is the reassociation.
    // Take the two operands as written instead.
    let pair = growable<Expression>([expr.left, expr.right]);
    operands = pair;
  }

  // A left-associative operator accepts an operand of its own precedence on
  // the left but not on the right: `a - b - c` needs no parentheses, while
  // `a - (b - c)` does. A right-associative one is the mirror image.
  let leftMin = if (rightAssociative) rank + 1 else rank;
  let rightMin = if (rightAssociative) rank else rank + 1;

  // After `as T` or `is T` the parser reads `<` as the start of type
  // arguments and `|` as a union type, so an operand that would print with a
  // type last keeps its parentheses before those two.
  let typeSensitive = op == '<' || op == '|';
  let parts = growable<Doc>([printOperandBefore(operands[0], leftMin, typeSensitive && operands.length > 1)]);

  let rest = new Array<Doc>(operands.length * 3);
  var j = 1;
  while (j < operands.length) {
    rest.push(line);
    rest.push(text(op));
    rest.push(text(' '));
    rest.push(printOperandBefore(operands[j], rightMin, typeSensitive && j < operands.length - 1));
    j += 1;
  }
  parts.push(indent(concat(rest)));
  return group(concat(parts));
}

// ============================================================================
// Unary Expression
// ============================================================================

function printUnaryExpression(expr: UnaryExpression): Doc {
  if (expr.prefix) {
    // `#parseUnary` reads the operand, so anything looser needs parentheses:
    // without them `-(a + b)` prints as `-a + b`, which negates `a` alone.
    return concat(docs2(text(expr.operator), printOperand(expr.argument, PREC_UNARY)));
  }
  return concat(docs2(printOperand(expr.argument, PREC_UNARY), text(expr.operator)));
}

// ============================================================================
// Assignment Expression
// ============================================================================

function printAssignmentExpression(expr: AssignmentExpression): Doc {
  let parts = growable<Doc>([printExpression(expr.left)]);
  // `operator` holds `+` for `+=`, and is absent for a plain assignment.
  let operator = expr.operator ?? '';
  parts.push(text(` ${operator}= `));
  parts.push(printExpression(expr.value));
  return group(concat(parts));
}

// ============================================================================
// Member / Index Expression
// ============================================================================

/**
 * Check if an expression is the head of a method chain (2+ method calls).
 * e.g., foo.bar().baz() is a chain of length 2.
 */
function isMethodChain(expr: Expression): boolean {
  return if (let CallExpression {callee} = expr) {
    if (let MemberExpression {object} = callee) isChainLink(object) else false
  } else {
    false
  };
}

/**
 * Check if an expression is a call with a member callee (one link in a chain).
 */
function isChainLink(expr: Expression): boolean {
  return if (let CallExpression {callee} = expr) {
    callee is MemberExpression
  } else {
    false
  };
}

/**
 * Represents one segment of a method chain: .method(args)
 */
class ChainSegment {
  dot: Doc;
  property: Doc;
  args: Doc;
  new(this.dot, this.property, this.args);
}

/**
 * Print a method chain with grouped line-breaking.
 *
 * Flattens foo.bar(a).baz(b).qux(c) into:
 *   [head] [.bar(a), .baz(b), .qux(c)]
 *
 * When it fits: foo.bar(a).baz(b).qux(c)
 * When it breaks:
 *   foo
 *     .bar(a)
 *     .baz(b)
 *     .qux(c)
 */
function printMethodChain(expr: CallExpression) {
  // Collect chain segments in reverse order (innermost first)
  let segments = new Array<ChainSegment>();
  var current: Expression = expr;
  var collecting = true;

  while (collecting) {
    collecting = isChainLink(current);
    if (collecting) {
      let callExpr = current as CallExpression;
      let memberExpr = callExpr.callee as MemberExpression;

      let dot = if (memberExpr.optional) { text('?.') } else { text('.') };
      let prop = printMemberProperty(memberExpr);

      // Build args doc
      let argParts = new Array<Doc>();
      if (callExpr.optional) {
        argParts.push(text('?'));
      }
      if (callExpr.typeArguments != null) {
        let tas = callExpr.typeArguments as GrowableArray<TypeAnnotation>;
        if (tas.length > 0) {
          argParts.push(text('<'));
          argParts.push(join(text(', '), mapTypeAnnotations(tas)));
          argParts.push(text('>'));
        }
      }
      argParts.push(group(concat(printArgList(callExpr.args))));
      let argDoc = concat(argParts);

      segments.push(new ChainSegment(dot, prop, argDoc));
      current = memberExpr.object;
    }
  }

  // Print the head (non-chain part)
  let head = printPostfixOperand(current, true);

  // Reverse segments to get correct order (outermost first)
  let ordered = new Array<Doc>(segments.length);
  var i = segments.length - 1;
  while (i >= 0) {
    let seg = segments[i];
    ordered.push(concat(docs3(seg.dot, seg.property, seg.args)));
    i -= 1;
  }

  // Build: group(head, indent(softline, .a(), softline, .b(), ...))
  let chainParts = new Array<Doc>(ordered.length * 2);
  var j = 0;
  while (j < ordered.length) {
    chainParts.push(softline);
    chainParts.push(ordered[j]);
    j += 1;
  }

  return group(concat(docs2(head, indent(concat(chainParts)))));
}

/**
 * The object of a `.` or `[]` access, or the callee of a call, parenthesized
 * when it binds looser than the postfix operator being applied to it.
 *
 * The AST has no node for parentheses, so the printer is what decides where
 * they go. Without them `(value as Point).x` prints as `value as Point.x`,
 * where `.x` binds to the type instead of the cast, and the result does not
 * parse.
 */
function printPostfixOperand(expr: Expression, beforeDot: boolean): Doc {
  // `1.toString()` lexes `1.` as the start of a float, so a numeric literal
  // needs parentheses before a `.` despite binding as tightly as anything.
  // Before a `[` or a `(` it does not.
  let numberBeforeDot = beforeDot && expr is NumberLiteral;
  if (numberBeforeDot) {
    return concat(docs3(text('('), printExpression(expr), text(')')));
  }
  // A postfix operator reads a primary, so every operand with an operator of
  // its own needs parentheses here.
  return printOperand(expr, PREC_PRIMARY);
}

function printMemberProperty(expr: MemberExpression): Doc {
  let symbolPath = expr.symbolPath;
  if (expr.isSymbolAccess && symbolPath != null) {
    return concat(docs3(text('['), printExpression(symbolPath), text(']')));
  }
  return text(expr.property.name);
}

function printMemberExpression(expr: MemberExpression): Doc {
  let parts = growable<Doc>([printPostfixOperand(expr.object, true)]);
  if (expr.optional) { parts.push(text('?.')); } else { parts.push(text('.')); }
  parts.push(printMemberProperty(expr));
  return concat(parts);
}

function printIndexExpression(expr: IndexExpression): Doc {
  let parts = growable<Doc>([printPostfixOperand(expr.object, false)]);
  if (expr.optional) { parts.push(text('?[')); } else { parts.push(text('[')); }
  parts.push(printExpression(expr.index));
  parts.push(text(']'));
  return concat(parts);
}

// ============================================================================
// Call Expression
// ============================================================================

function printCallExpression(expr: CallExpression): Doc {
  // Check for method chain (2+ chained method calls)
  if (isMethodChain(expr)) {
    return printMethodChain(expr);
  }

  let parts = growable<Doc>([printPostfixOperand(expr.callee, false)]);
  if (expr.optional) {
    parts.push(text('?'));
  }
  if (expr.typeArguments != null) {
    let tas = expr.typeArguments as GrowableArray<TypeAnnotation>;
    if (tas.length > 0) {
      parts.push(text('<'));
      parts.push(join(text(', '), mapTypeAnnotations(tas)));
      parts.push(text('>'));
    }
  }
  parts.push(group(concat(printArgList(expr.args))));
  return concat(parts);
}

// ============================================================================
// New Expression
// ============================================================================

function printNewExpression(expr: NewExpression): Doc {
  let parts = growable<Doc>([text('new '), text(expr.callee.name)]);
  if (expr.typeArguments != null) {
    let tas = expr.typeArguments as GrowableArray<TypeAnnotation>;
    if (tas.length > 0) {
      parts.push(text('<'));
      parts.push(join(text(', '), mapTypeAnnotations(tas)));
      parts.push(text('>'));
    }
  }
  // `new C.name()`, `new C.#name()`, `new C.[sym]()`.
  let constructorName = expr.constructorName;
  if (constructorName != null) {
    parts.push(text('.'));
    parts.push(printNodeName(constructorName));
  }
  parts.push(group(concat(printArgList(expr.args))));
  return concat(parts);
}

function printArgList(args: Array<Expression>): Array<Doc> {
  let parts = new Array<Doc>();
  if (args.length == 0) {
    parts.push(text('('));
    parts.push(text(')'));
    return parts;
  }
  let argDocs = new Array<Doc>();
  var i = 0;
  while (i < args.length) {
    argDocs.push(printExpression(args[i]));
    i += 1;
  }
  parts.push(text('('));
  parts.push(indent(concat(docs2(softline, join(concat(docs2(text(','), line)), argDocs)))));
  parts.push(softline);
  parts.push(text(')'));
  return parts;
}

// ============================================================================
// Function Expression
// ============================================================================

function printFunctionExpression(fn: FunctionExpression): Doc {
  let parts = new Array<Doc>();

  if (fn.isGenerator) { parts.push(text('gen ')); }
  if (fn.isAsync) { parts.push(text('async ')); }

  if (fn.typeParameters != null) {
    parts.push(printTypeParams(fn.typeParameters as GrowableArray<TypeParameter>));
  }

  parts.push(text('('));
  parts.push(printParams(fn.params));
  parts.push(text(')'));

  if (fn.returnType != null) {
    parts.push(text(': '));
    parts.push(printTypeAnnotation(fn.returnType as TypeAnnotation));
  }

  parts.push(printContractClauses(fn.contracts, true));
  parts.push(text('=> '));

  if (fn.body is BlockStatement) {
    parts.push(printBlockStatement(fn.body as BlockStatement));
  } else {
    parts.push(printExpression(fn.body as Expression));
  }

  return concat(parts);
}

function printParams(params: Array<Parameter>): Doc {
  if (params.length == 0) { return text(''); }
  let paramDocs = new Array<Doc>();
  var i = 0;
  while (i < params.length) {
    paramDocs.push(printParam(params[i]));
    i += 1;
  }
  return join(text(', '), paramDocs);
}

function printParam(param: Parameter): Doc {
  let parts = new Array<Doc>();
  // A `this.x` parameter takes its type from the field, so it is written
  // without one. The parser records it as a plain parameter plus a synthesized
  // initializer entry; `printConstructorInitializers` leaves that entry out.
  if (param.isThisParam) { parts.push(text('this.')); }
  parts.push(text(param.name.name));
  if (param.typeAnnotation != null) {
    parts.push(text(': '));
    parts.push(printTypeAnnotation(param.typeAnnotation as TypeAnnotation));
  }
  if (param.defaultValue != null) {
    parts.push(text(' = '));
    parts.push(printExpression(param.defaultValue as Expression));
  }
  return concat(parts);
}

// ============================================================================
// Literals (Array, Record, Tuple, Map)
// ============================================================================

function printArrayLiteral(expr: ArrayLiteral): Doc {
  if (expr.elements.length == 0) { return text('[]'); }
  let elemDocs = new Array<Doc>();
  var i = 0;
  while (i < expr.elements.length) {
    elemDocs.push(printExpression(expr.elements[i]));
    i += 1;
  }
  let inner = growable<Doc>([
    text('['),
    indent(concat(docs2(softline, join(concat(docs2(text(','), line)), elemDocs)))),
    softline,
    text(']'),
  ]);
  return group(concat(inner));
}

function printRecordLiteral(expr: RecordLiteral): Doc {
  if (expr.properties.length == 0) { return text('{}'); }
  let propDocs = new Array<Doc>();
  for (let prop in expr.properties) {
    match (prop) {
      case PropertyAssignment {name, value}: {
        propDocs.push(concat(docs3(text(name.name), text(': '), printExpression(value))));
      }
      case SpreadElement {argument}: {
        propDocs.push(concat(docs2(text('...'), printExpression(argument))));
      }
      case _: {}
    }
  }
  let inner = growable<Doc>([
    text('{'),
    indent(concat(docs2(line, join(concat(docs2(text(','), line)), propDocs)))),
    line,
    text('}'),
  ]);
  return group(concat(inner));
}

function printTupleLiteral(expr: TupleLiteral): Doc {
  let elemDocs = new Array<Doc>();
  let spreadIndices = expr.spreadIndices;
  var i = 0;
  for (let element in expr.elements) {
    let elementDoc = printExpression(element);
    if (spreadIndices != null && spreadIndices.contains(i)) {
      elemDocs.push(concat(docs2(text('...'), elementDoc)));
    } else {
      elemDocs.push(elementDoc);
    }
    i += 1;
  }
  return concat(docs3(text('('), join(text(', '), elemDocs), text(')')));
}

/**
 * `{key => value, ...}`. The `#{key: value}` spelling this used to print was
 * replaced by `docs/design/syntax-overhaul.md` and no longer parses.
 *
 * A map literal with no entries cannot be written — `{}` is an empty record —
 * so the empty case is only a fallback.
 */
function printMapLiteral(expr: MapLiteral): Doc {
  if (expr.entries.length == 0) { return text('{}'); }
  let entryDocs = new Array<Doc>();
  for (let entry in expr.entries) {
    entryDocs.push(concat(docs3(printExpression(entry.key), text(' => '), printExpression(entry.value))));
  }
  let inner = growable<Doc>([
    text('{'),
    indent(concat(docs2(softline, join(concat(docs2(text(','), line)), entryDocs)))),
    softline,
    text('}'),
  ]);
  return group(concat(inner));
}

// ============================================================================
// Range / Pipeline
// ============================================================================

function printRangeExpression(expr: RangeExpression): Doc {
  let parts = new Array<Doc>();
  // Both ends are read by `#parseAs`, so `a + b..c` is already `(a + b)..(c)`
  // and only an operand looser than that needs parentheses.
  if (expr.start != null) { parts.push(printOperand(expr.start as Expression, PREC_AS)); }
  parts.push(text('..'));
  if (expr.end != null) { parts.push(printOperand(expr.end as Expression, PREC_AS)); }
  return concat(parts);
}

function printPipelineExpression(expr: PipelineExpression): Doc {
  let parts = new Array<Doc>();
  // `|>` is left-associative, so the left side may be another pipeline while
  // the right side is read by `#parseLogicalOr`.
  parts.push(printOperand(expr.left, PREC_PIPELINE));
  parts.push(indent(concat(docs3(line, text('|> '), printOperand(expr.right, PREC_PIPELINE + 1)))));
  return group(concat(parts));
}

// ============================================================================
// Template Literals
// ============================================================================

function printTemplateLiteral(expr: TemplateLiteral): Doc {
  let parts = growable<Doc>([text('`')]);
  var i = 0;
  while (i < expr.quasis.length) {
    parts.push(text(expr.quasis[i].raw));
    if (i < expr.expressions.length) {
      parts.push(text('${'));
      parts.push(printExpression(expr.expressions[i]));
      parts.push(text('}'));
    }
    i += 1;
  }
  parts.push(text('`'));
  return concat(parts);
}

// ============================================================================
// Match Expression
// ============================================================================

function printMatchExpression(expr: MatchExpression): Doc {
  let parts = growable<Doc>([
    text('match ('),
    printExpression(expr.discriminant),
    text(') {'),
  ]);
  let caseDocs = new Array<Doc>();
  var i = 0;
  while (i < expr.cases.length) {
    let c = expr.cases[i];
    let caseParts = growable<Doc>([text('case '), printNode(c.pattern)]);
    if (c.guard != null) {
      caseParts.push(text(' if '));
      caseParts.push(printExpression(c.guard as Expression));
    }
    caseParts.push(text(': '));
    caseParts.push(printNode(c.body));
    caseDocs.push(withComments(c, concat(caseParts)));
    if (i < expr.cases.length - 1) {
      caseDocs.push(hardline);
      if (hasBlankLineBetweenNodes(c, expr.cases[i + 1])) {
        caseDocs.push(hardline);
      }
    }
    i += 1;
  }
  if (caseDocs.length > 0) {
    parts.push(indent(concat(docs2(hardline, concat(caseDocs)))));
  }
  parts.push(hardline);
  parts.push(text('}'));
  return concat(parts);
}

// ============================================================================
// If Expression
// ============================================================================

function printIfExpression(expr: IfExpression): Doc {
  let parts = growable<Doc>([
    text('if ('),
    printCondition(expr.test),
    text(') '),
    printNode(expr.consequent),
  ]);
  if (expr.alternate != null) {
    parts.push(text(' else '));
    parts.push(printNode(expr.alternate));
  }
  return concat(parts);
}

// ============================================================================
// Try Expression
// ============================================================================

function printTryExpression(expr: TryExpression): Doc {
  let parts = growable<Doc>([text('try '), printBlockStatement(expr.body)]);
  if (expr.cancelBlock != null) {
    parts.push(text(' cancel '));
    parts.push(printBlockStatement(expr.cancelBlock as BlockStatement));
  }
  if (expr.handler != null) {
    let handler = expr.handler as CatchClause;
    parts.push(text(' catch'));
    if (handler.param != null) {
      parts.push(text(' ('));
      parts.push(text((handler.param as Identifier).name));
      parts.push(text(')'));
    }
    parts.push(text(' '));
    parts.push(printBlockStatement(handler.body));
  }
  if (expr.finalizer != null) {
    parts.push(text(' finally '));
    parts.push(printBlockStatement(expr.finalizer as BlockStatement));
  }
  return concat(parts);
}

// ============================================================================
// Patterns
// ============================================================================

function printPattern(pat: Pattern): Doc {
  return match (pat) {
  case BindingPattern {kind, pattern}: concat(docs3(text(kind), text(' '), printPattern(pattern)))
  case IdentifierPattern {name}: text(name)
  case RecordPattern {}: printRecordPattern(pat)
  case TuplePattern {}: printTuplePattern(pat)
  case ArrayPattern {}: printArrayPattern(pat)
  case RestPattern {pattern}: concat(docs2(text('...'), printNode(pattern)))
  case AsPattern {pattern, name}: {
    concat(docs3(printNode(pattern), text(' as '), text(name.name)))
  }
  case ClassPattern {name, typeArguments, properties}: {
    let parts = growable<Doc>([text(name.name)]);
    if (typeArguments != null) {
      parts.push(text('<'));
      parts.push(join(text(', '), mapTypeAnnotations(typeArguments)));
      parts.push(text('>'));
    }
    if (properties.length > 0) {
      parts.push(text(' {'));
      let propDocs = new Array<Doc>();
      var i = 0;
      while (i < properties.length) {
        propDocs.push(printBindingProperty(properties[i]));
        i += 1;
      }
      parts.push(join(text(', '), propDocs));
      parts.push(text('}'));
    }
    concat(parts)
  }
  case LogicalPattern {operator, left, right}: {
    concat(docs3(printNode(left), concat(docs2(text(' '), text(operator))), concat(docs2(text(' '), printNode(right)))))
  }
  case AssignmentPattern {left, right}: {
    concat(docs3(printNode(left), text(' = '), printExpression(right)))
  }
  case LiteralPattern {value}: printExpression(value)
  // Only reachable through printBindingProperty, which prints the
  // `!name` form; standalone the node is just its marker.
  case AbsencePattern {}: text('!')
};
}

function printRecordPattern(pattern: RecordPattern): Doc {
  let rest = pattern.rest;
  if (pattern.properties.length == 0 && rest == null) { return text('{}'); }
  let propDocs = new Array<Doc>();
  for (let prop in pattern.properties) {
    propDocs.push(printBindingProperty(prop));
  }
  if (rest != null) {
    propDocs.push(concat(docs2(text('...'), printNode(rest))));
  }
  return concat(docs3(text('{'), join(text(', '), propDocs), text('}')));
}

function printBindingProperty(bp: BindingProperty): Doc {
  match (bp.value) {
    case IdentifierPattern {name}: {
      if (name == bp.name.name) { return text(bp.name.name); }
      if (name != '_') {
        return concat(docs3(text(bp.name.name), text(' as '), text(name)));
      }
    }
    case AssignmentPattern {left, right}: {
      if (let IdentifierPattern {name} = left) {
        let lhs = if (name == bp.name.name) {
          text(bp.name.name)
        } else if (name != '_') {
          concat(docs3(text(bp.name.name), text(' as '), text(name)))
        } else {
          concat(docs3(text(bp.name.name), text(': '), text(name)))
        };
        return concat(docs3(lhs, text(' = '), printExpression(right)));
      }
    }
    case AbsencePattern {}: {
      return concat(docs2(text('!'), text(bp.name.name)));
    }
    case _: {}
  }
  return concat(docs3(text(bp.name.name), text(': '), printNode(bp.value)));
}

function printTuplePattern(pattern: TuplePattern): Doc {
  let elemDocs = new Array<Doc>();
  for (let elem in pattern.elements) {
    if (elem != null) {
      elemDocs.push(printNode(elem));
    } else {
      elemDocs.push(text('_'));
    }
  }
  return concat(docs3(text('('), join(text(', '), elemDocs), text(')')));
}

function printArrayPattern(pattern: ArrayPattern): Doc {
  let elemDocs = new Array<Doc>();
  for (let elem in pattern.elements) {
    if (elem != null) {
      elemDocs.push(printNode(elem));
    } else {
      elemDocs.push(text(''));
    }
  }
  return concat(docs3(text('['), join(text(', '), elemDocs), text(']')));
}

// ============================================================================
// Type Annotations
// ============================================================================

/** Whether `a` starts before `b` in the source; false when either has no location. */
function startsBefore(a: Node, b: Node) {
  let la = a.loc;
  let lb = b.loc;
  return la != null && lb != null && la.start < lb.start;
}

function printTypeAnnotation(ann: TypeAnnotation): Doc {
  let doc = printTypeAnnotationInner(ann);
  return withComments(ann, doc);
}

function printRecordTypeItem(item: Node): Doc {
  return if (let PropertySignature {name, typeAnnotation, optional} = item) {
    let nameDoc = if (optional) {
      concat(docs2(text(name.name), text('?')))
    } else {
      text(name.name)
    };
    concat(docs3(nameDoc, text(': '), printTypeAnnotation(typeAnnotation)))
  } else {
    concat(docs2(text('...'), printTypeAnnotationInner(item as TypeAnnotation)))
  };
}

/**
 * Whether `ann` prints with an unparenthesized `inline` or function return
 * type at its right edge, where `#parseTypeAnnotation` would absorb a
 * following `| U`.
 */
function typeCapturesUnion(ann: TypeAnnotation): boolean {
  return match (ann) {
    case InlineTypeAnnotation {}: true
    case FunctionTypeAnnotation {}: true
    case UnionTypeAnnotation {types}: {
      types.length > 0 && typeCapturesUnion(types[types.length - 1])
    }
    case _: false
  };
}

function printTypeAnnotationInner(ann: TypeAnnotation): Doc {
  return match (ann) {
  case NamedTypeAnnotation {name, typeArguments, elementsMutable}: {
    let parts = growable<Doc>([text(name)]);
    if (typeArguments != null) {
      if (typeArguments.length > 0) {
        parts.push(text('<'));
        if (elementsMutable) {
          parts.push(text('var '));
        }
        parts.push(join(text(', '), mapTypeAnnotations(typeArguments)));
        parts.push(text('>'));
      }
    }
    concat(parts)
  }
  case UnionTypeAnnotation {types}: {
    let typeDocs = new Array<Doc>();
    var i = 0;
    while (i < types.length) {
      // `inline` and function return types take every union member after
      // them, so one that stops short of the end was parenthesized.
      let member = types[i];
      let doc = printTypeAnnotation(member);
      if (i < types.length - 1 && typeCapturesUnion(member)) {
        typeDocs.push(concat(docs3(text('('), doc, text(')'))));
      } else {
        typeDocs.push(doc);
      }
      i += 1;
    }
    join(text(' | '), typeDocs)
  }
  case NullableTypeAnnotation {typeAnnotation}: {
    // `?` binds tighter than `|`, function arrows and `inline`, so those
    // need parens to survive a round-trip; so does a nested `?` (`??`
    // lexes as one token).
    match (typeAnnotation) {
      case UnionTypeAnnotation {}: concat(docs3(text('('), printTypeAnnotation(typeAnnotation), text(')?')))
      case InlineTypeAnnotation {}: concat(docs3(text('('), printTypeAnnotation(typeAnnotation), text(')?')))
      case FunctionTypeAnnotation {}: concat(docs3(text('('), printTypeAnnotation(typeAnnotation), text(')?')))
      case NullableTypeAnnotation {}: concat(docs3(text('('), printTypeAnnotation(typeAnnotation), text(')?')))
      case _: concat(docs2(printTypeAnnotation(typeAnnotation), text('?')))
    }
  }
  case FunctionTypeAnnotation {paramNames, params, returnType}: {
    let parts = growable<Doc>([text('(')]);
    let pDocs = new Array<Doc>();
    var i = 0;
    while (i < params.length) {
      // The parser requires the names: `(String) => T` does not parse.
      pDocs.push(concat(docs3(text(paramNames[i]), text(': '), printTypeAnnotation(params[i]))));
      i += 1;
    }
    parts.push(join(text(', '), pDocs));
    parts.push(text(') => '));
    parts.push(printTypeAnnotation(returnType));
    concat(parts)
  }
  case LiteralTypeAnnotation {value}: printNode(value)
  case RecordTypeAnnotation {properties, spreads, isExistential}: {
    let itemNodes = new Array<Node>();
    // Spreads print where they were written: merge the two lists by
    // source position.
    var si = 0;
    for (let p in properties) {
      if (spreads != null) {
        while (si < spreads.length && startsBefore(spreads[si], p)) {
          itemNodes.push(spreads[si]);
          si += 1;
        }
      }
      itemNodes.push(p);
    }
    if (spreads != null) {
      while (si < spreads.length) {
        itemNodes.push(spreads[si]);
        si += 1;
      }
    }
    if (itemNodes.length == 0 && !isExistential) {
      printEmptyBody(ann, false)
    } else {
      var hasItemComments = false;
      for (let item in itemNodes) {
        if (currentCommentMap.getLeading(item) != null
            || currentCommentMap.getTrailing(item) != null) {
          hasItemComments = true;
        }
      }
      if (!hasItemComments) {
        let propDocs = new Array<Doc>();
        for (let item in itemNodes) {
          propDocs.push(printRecordTypeItem(item));
        }
        if (isExistential) {
          propDocs.push(text('...'));
        }
        concat(docs3(text('{'), join(text(', '), propDocs), text('}')))
      } else {
        let totalItems = itemNodes.length + (if (isExistential) 1 else 0);
        let memberDocs = new Array<Doc>();
        var i = 0;
        while (i < itemNodes.length) {
          let cur = itemNodes[i];
          let itemDoc = printRecordTypeItem(cur);
          let withComma = if (i < totalItems - 1) {
            concat(docs2(itemDoc, text(',')))
          } else {
            itemDoc
          };
          memberDocs.push(withComments(cur, withComma));
          if (i < itemNodes.length - 1) {
            memberDocs.push(hardline);
            if (hasBlankLineBetweenNodes(cur, itemNodes[i + 1])) {
              memberDocs.push(hardline);
            }
          }
          i += 1;
        }
        if (isExistential) {
          if (itemNodes.length > 0) {
            memberDocs.push(hardline);
          }
          memberDocs.push(text('...'));
        }
        concat(docs3(
          text('{'),
          indent(concat(docs2(hardline, concat(memberDocs)))),
          concat(docs2(hardline, text('}')))))
      }
    }
  }
  case TupleTypeAnnotation {elementTypes, spreadIndices}: {
    let eDocs = new Array<Doc>();
    var i = 0;
    while (i < elementTypes.length) {
      if (spreadIndices != null && spreadIndices.contains(i)) {
        let spreadDoc = concat(docs2(text('...'), printTypeAnnotationInner(elementTypes[i])));
        eDocs.push(withComments(elementTypes[i], spreadDoc));
      } else {
        eDocs.push(printTypeAnnotation(elementTypes[i]));
      }
      i += 1;
    }
    concat(docs3(text('('), join(text(', '), eDocs), text(')')))
  }
  case InlineTypeAnnotation {typeAnnotation, ifPossible}:
    concat(docs2(text(if (ifPossible) 'inline? ' else 'inline '), printTypeAnnotation(typeAnnotation)))
  case ThisTypeAnnotation {}: text('this')
};
}

// ============================================================================
// Helpers
// ============================================================================

function printTypeParams(tps: Array<TypeParameter>): Doc {
  if (tps.length == 0) { return text(''); }
  let parts = growable<Doc>([text('<')]);
  let tpDocs = new Array<Doc>();
  for (let tp in tps) {
    let tpParts = new Array<Doc>();
    if (tp.isScoped) {
      tpParts.push(text('scoped '));
    }
    tpParts.push(text(tp.name));
    if (tp.constraint != null) {
      tpParts.push(text(' extends '));
      tpParts.push(printTypeAnnotation(tp.constraint as TypeAnnotation));
    }
    if (tp.defaultType != null) {
      tpParts.push(text(' = '));
      tpParts.push(printTypeAnnotation(tp.defaultType as TypeAnnotation));
    }
    tpDocs.push(concat(tpParts));
  }
  parts.push(join(text(', '), tpDocs));
  parts.push(text('>'));
  return concat(parts);
}

function mapTypeAnnotations(anns: Array<TypeAnnotation>): Array<Doc> {
  let docs = new Array<Doc>();
  var i = 0;
  while (i < anns.length) {
    docs.push(printTypeAnnotation(anns[i]));
    i += 1;
  }
  return docs;
}

/// Print a FieldDefinition or MethodDefinition name, which may be an
/// Identifier or SymbolPropertyName.
function printNodeName(name: Node): Doc {
  return match (name) {
  case Identifier {name}: text(name)
  case SymbolPropertyName {symbolRef}: {
    concat(docs3(text('['), printExpression(symbolRef), text(']')))
  }
  case _: text('/* unknown name */')
};
}

/// Print a condition — may be an Expression or LetPatternCondition.
function printCondition(node: Node): Doc {
  return if (let LetPatternCondition {pattern, init} = node) {
    concat(docs3(text('let '), printPattern(pattern), concat(docs2(text(' = '), printExpression(init)))))
  } else {
    printExpression(node as Expression)
  };
}

/// Generic Node printer — dispatches to the right sub-printer.
function printNode(node: Node): Doc {
  if (node is Module) { return printModule(node); }
  if (node is Expression) { return printExpression(node); }
  if (node is Statement) { return printStatement(node); }
  if (node is Pattern) { return printPattern(node); }
  if (node is TypeAnnotation) { return printTypeAnnotation(node); }
  if (let LetPatternCondition {pattern, init} = node) {
    return concat(docs3(text('let '), printPattern(pattern), concat(docs2(text(' = '), printExpression(init)))));
  }
  return text('/* unknown node */');
}
  • compiler compiler.zena-lang.pkg.zena-lang.dev 0.0.2-preview.1
VersionPublishedDependenciesApproved by
0.0.2-preview.1 2026-11-19
  • compiler compiler.zena-lang.pkg.zena-lang.dev 0.0.2-preview.1