compiler 0.0.2-preview.1

The Zena self-hosted compiler

Readme Files Dependencies Versions

compiler#

The Zena compiler, written in Zena. It parses, type-checks, and compiles Zena source code to WebAssembly (Wasm GC) and WebAssembly Text (WAT).

Usage#

Parsing a Single File#

Use compiler/parser to parse Zena source text into an AST (Module):

import { parse } from 'compiler/parser';

let ast = parse('export let answer = 42;', 'example.zena');

Loading and Checking a Program#

Use compiler (createCompiler and checkCompilation) with a CompilerHost to resolve imports across a module graph and type-check a program:

import {
  createCompiler, checkCompilation, buildStdlibConfig
} from 'compiler';
import { FsCompilerHost } from 'compiler/fs-host';

let stdlibRoot = '/stdlib';
let host = new FsCompilerHost(stdlibRoot);
let packages = buildStdlibConfig(stdlibRoot, 'host');
let compiler = createCompiler(host, {
  stdlibRoot,
  packages,
});

let result = await compiler.compile({
  entry: '/workspace/main.zena',
  target: 'host',
});
let checked = checkCompilation(result);

Compiling a File to WebAssembly#

Use compiler/compile-file to compile an entry file on disk to a .wasm or .wat output file:

import { compileFile } from 'compiler/compile-file';

let ok = await compileFile({
  entry: 'src/main.zena',
  outPath: 'out/main.wasm',
  stdlibRoot: '/stdlib',
});

Libraries#

  • compiler / compiler/compiler — compiler entry point (Compiler, createCompiler, checkCompilation, ProgramCheckResult)
  • compiler/compile-file — end-to-end file compilation (compileFile, CompileFileOptions)
  • compiler/tokenizer — lexer and token definitions (tokenize, Token, TokenType)
  • compiler/parser — recursive-descent parser (parse, Parser)
  • compiler/ast — AST node definitions (Node, Module, Statement, Expression, TypeAnnotation)
  • compiler/visitor — AST traversal helpers (walk, Visitor)
  • compiler/scope — lexical scope and symbol resolution (ScopeBuilder, ScopeResult, Symbol)
  • compiler/checker — static type checker (checkModule, CheckResult)
  • compiler/semantic-model — semantic queries over a checked module (SemanticModel)
  • compiler/types — compiler type representations (Type, ClassType, FunctionType, typeToString)
  • compiler/diagnostics — compiler diagnostics and source spans (Diagnostic, DiagnosticCode, DiagnosticSeverity, SourceSpan)
  • compiler/package-manifest — zena-package.json manifest and workspace loader (loadWorkspace, loadPackageMap)
  • compiler/module-resolver — package and relative module specifier resolution (ModuleResolver, PackageConfig)
  • compiler/library-loader — module graph loader (LibraryLoader, CompilerHost, SourceFile)
  • compiler/codegen/binary-generator — WebAssembly GC binary emitter (BinaryGenerator)
  • compiler/codegen/wat-generator — WebAssembly Text (WAT) emitter (WatGenerator)

License#

MIT

37.7 KiB Raw
/**
 * AST to JSON conversion utilities
 * Converts Zena AST nodes to JsonObject/JsonArray for serialization
 */

import { JsonObject, JsonArray, stringify } from 'zena:json';
import {
  Node, Module, Statement, Expression, TypeAnnotation, VariableDeclaration, UsingStatement, ShieldedStatement, FunctionDeclaration, ExpressionStatement, BlockStatement, IfStatement, WhileStatement, ForStatement, ForInStatement, LetPatternCondition, ReturnStatement, YieldStatement, BreakStatement, ContinueStatement, Identifier, BindingPattern, IdentifierPattern, NumberLiteral, StringLiteral, BooleanLiteral, NullLiteral, TemplateElement, TemplateLiteral, TaggedTemplateExpression, BinaryExpression, UnaryExpression, AssignmentExpression, AsExpression, IsExpression, RangeExpression, PipelineExpression, PipePlaceholder, FunctionExpression, Parameter, CallExpression, TypeParameter, MemberExpression, IndexExpression, ThisExpression, NewExpression, ArrayLiteral, RecordLiteral, TupleLiteral, PropertyAssignment, SpreadElement, MapLiteral, MapEntry, RecordPattern, TuplePattern, ArrayPattern, RestPattern, BindingProperty, AsPattern, ClassPattern, LogicalPattern, AssignmentPattern, AbsencePattern, LiteralPattern, MatchExpression, MatchCase, IfExpression, ThrowExpression, TryExpression, AwaitExpression, CatchClause, NamedTypeAnnotation, UnionTypeAnnotation, NullableTypeAnnotation, FunctionTypeAnnotation, LiteralTypeAnnotation, RecordTypeAnnotation, TupleTypeAnnotation, InlineTypeAnnotation, ThisTypeAnnotation, PropertySignature, TypeAliasDeclaration, CaseClassParam, SealedVariant, ClassDeclaration, FieldDefinition, MethodDefinition, AccessorDeclaration, SetterInfo, SuperExpression, FieldInitializer, SuperInitializer, InterfaceDeclaration, MixinDeclaration, MethodSignature, AccessorSignature, EnumDeclaration, EnumMember, ImportDeclaration, ImportSpecifier, ExportAllDeclaration, ExportFromDeclaration, Decorator, ContractClause, ContractMode, contractKeyword, contractModifier, DeclareFunction, SymbolDeclaration, SymbolPropertyName,
} from './ast.zena';

// ============================================================================
// Core Conversion Functions
// ============================================================================

/**
 * Get the type name string for an AST node.
 */
function nodeTypeName(node: Node) {
  let name = match (node) {
    // Patterns
    case BindingPattern {}: 'BindingPattern'
    case IdentifierPattern {}: 'Identifier'
    case RecordPattern {}: 'RecordPattern'
    case TuplePattern {}: 'TuplePattern'
    case ArrayPattern {}: 'ArrayPattern'
    case RestPattern {}: 'RestPattern'
    case AsPattern {}: 'AsPattern'
    case ClassPattern {}: 'ClassPattern'
    case LogicalPattern {}: 'LogicalPattern'
    case LiteralPattern {}: 'LiteralPattern'
    // Literals
    case NumberLiteral {}: 'NumberLiteral'
    case StringLiteral {}: 'StringLiteral'
    case BooleanLiteral {}: 'BooleanLiteral'
    case NullLiteral {}: 'NullLiteral'
    case Identifier {}: 'Identifier'
    // Templates
    case TemplateLiteral {}: 'TemplateLiteral'
    case TaggedTemplateExpression {}: 'TaggedTemplateExpression'
    case TemplateElement {}: 'TemplateElement'
    // Operators
    case BinaryExpression {}: 'BinaryExpression'
    case UnaryExpression {}: 'UnaryExpression'
    case AssignmentExpression {}: 'AssignmentExpression'
    case AsExpression {}: 'AsExpression'
    case IsExpression {}: 'IsExpression'
    case RangeExpression {}: 'RangeExpression'
    case PipelineExpression {}: 'PipelineExpression'
    case PipePlaceholder {}: 'PipePlaceholder'
    // Functions & Calls
    case FunctionExpression {}: 'FunctionExpression'
    case CallExpression {}: 'CallExpression'
    // Member Access
    case MemberExpression {}: 'MemberExpression'
    case IndexExpression {}: 'IndexExpression'
    case ThisExpression {}: 'ThisExpression'
    case SuperExpression {}: 'SuperExpression'
    case NewExpression {}: 'NewExpression'
    // Collections
    case ArrayLiteral {}: 'ArrayLiteral'
    case RecordLiteral {}: 'RecordLiteral'
    case MapLiteral {}: 'MapLiteral'
    case TupleLiteral {}: 'TupleLiteral'
    case PropertyAssignment {}: 'PropertyAssignment'
    case SpreadElement {}: 'SpreadElement'
    case MapEntry {}: 'MapEntry'
    case BindingProperty {}: 'BindingProperty'
    case AssignmentPattern {}: 'AssignmentPattern'
    case AbsencePattern {}: 'AbsencePattern'
    // Statements
    case VariableDeclaration {}: 'VariableDeclaration'
    case UsingStatement {}: 'UsingStatement'
    case ShieldedStatement {}: 'ShieldedStatement'
    case FunctionDeclaration {}: 'FunctionDeclaration'
    case ExpressionStatement {}: 'ExpressionStatement'
    case BlockStatement {}: 'BlockStatement'
    case ReturnStatement {}: 'ReturnStatement'
    case YieldStatement {}: 'YieldStatement'
    case BreakStatement {}: 'BreakStatement'
    case ContinueStatement {}: 'ContinueStatement'
    case IfStatement {}: 'IfStatement'
    case WhileStatement {}: 'WhileStatement'
    case ForStatement {}: 'ForStatement'
    case ForInStatement {}: 'ForInStatement'
    // Expressions
    case MatchExpression {}: 'MatchExpression'
    case MatchCase {}: 'MatchCase'
    case IfExpression {}: 'IfExpression'
    case ThrowExpression {}: 'ThrowExpression'
    case TryExpression {}: 'TryExpression'
    case AwaitExpression {}: 'AwaitExpression'
    case CatchClause {}: 'CatchClause'
    case LetPatternCondition {}: 'LetPatternCondition'
    // Parameters
    case Parameter {}: 'Parameter'
    case TypeParameter {}: 'TypeParameter'
    // Type Annotations
    case NamedTypeAnnotation {}: 'TypeAnnotation'
    case UnionTypeAnnotation {}: 'UnionTypeAnnotation'
    case NullableTypeAnnotation {}: 'NullableTypeAnnotation'
    case FunctionTypeAnnotation {}: 'FunctionTypeAnnotation'
    case LiteralTypeAnnotation {}: 'LiteralTypeAnnotation'
    case RecordTypeAnnotation {}: 'RecordTypeAnnotation'
    case TupleTypeAnnotation {}: 'TupleTypeAnnotation'
    case InlineTypeAnnotation {}: 'InlineTypeAnnotation'
    case ThisTypeAnnotation {}: 'ThisTypeAnnotation'
    // Module
    case Module {}: 'Module'
    // Declarations
    case ClassDeclaration {}: 'ClassDeclaration'
    case InterfaceDeclaration {}: 'InterfaceDeclaration'
    case EnumDeclaration {}: 'EnumDeclaration'
    case MixinDeclaration {}: 'MixinDeclaration'
    case TypeAliasDeclaration {}: 'TypeAliasDeclaration'
    // Class Members
    case FieldDefinition {}: 'FieldDefinition'
    case MethodDefinition {}: 'MethodDefinition'
    case AccessorDeclaration {}: 'AccessorDeclaration'
    case MethodSignature {}: 'MethodSignature'
    case AccessorSignature {}: 'AccessorSignature'
    // Helpers
    case CaseClassParam {}: 'CaseClassParam'
    case SealedVariant {}: 'SealedVariant'
    case FieldInitializer {}: 'FieldInitializer'
    case SuperInitializer {}: 'SuperInitializer'
    case EnumMember {}: 'EnumMember'
    case PropertySignature {}: 'PropertySignature'
    case SetterInfo {}: 'AccessorDeclaration'
    case ImportDeclaration {}: 'ImportDeclaration'
    case ImportSpecifier {}: 'ImportSpecifier'
    case ExportAllDeclaration {}: 'ExportAllDeclaration'
    case ExportFromDeclaration {}: 'ExportFromDeclaration'
    case Decorator {}: 'Decorator'
    case ContractClause {}: 'ContractClause'
    case DeclareFunction {}: 'DeclareFunction'
    case SymbolDeclaration {}: 'SymbolDeclaration'
    case SymbolPropertyName {}: 'SymbolPropertyName'
  };
  return name;
}

/**
 * Convert any AST node to a JsonObject.
 */
export function nodeToJson(node: Node): JsonObject {
  let obj = new JsonObject();
  obj['type'] = nodeTypeName(node);
  
  match (node) {
    // Patterns
    case BindingPattern as bp: {
      obj['kind'] = bp.kind;
      obj['pattern'] = nodeToJson(bp.pattern);
    }
    case IdentifierPattern { name }: {
      obj['name'] = name;
    }
    case RecordPattern { properties, rest }: {
      obj['properties'] = bindingPropertiesToJson(properties);
      if (rest != null) {
        obj['rest'] = nodeToJson(rest);
      }
    }
    case TuplePattern { elements }: {
      obj['elements'] = patternsToJson(elements);
    }
    case ArrayPattern { elements }: {
      obj['elements'] = patternsToJson(elements);
    }
    case RestPattern { pattern }: {
      obj['pattern'] = nodeToJson(pattern);
    }
    case AsPattern { pattern, name }: {
      obj['pattern'] = nodeToJson(pattern);
      obj['name'] = nodeToJson(name);
    }
    case ClassPattern { name, typeArguments, properties }: {
      obj['name'] = nodeToJson(name);
      if (typeArguments != null) {
        obj['typeArguments'] = typeAnnotationsToJson(typeArguments);
      }
      obj['properties'] = bindingPropertiesToJson(properties);
    }
    case LogicalPattern { operator, left, right }: {
      obj['operator'] = operator;
      obj['left'] = nodeToJson(left);
      obj['right'] = nodeToJson(right);
    }
    case AssignmentPattern { left, right }: {
      obj['left'] = nodeToJson(left);
      obj['right'] = nodeToJson(right);
    }
    case LiteralPattern { value }: {
      obj['value'] = nodeToJson(value);
    }
    
    // Literals
    case NumberLiteral { raw }: {
      obj['raw'] = raw;
    }
    case StringLiteral { value }: {
      obj['value'] = value;
    }
    case BooleanLiteral { value }: {
      obj['value'] = new Box<boolean>(value);
    }
    case NullLiteral {}: {
      // No additional fields
    }
    case TemplateElement { cooked, raw, tail }: {
      let valueObj = new JsonObject();
      valueObj['cooked'] = cooked;
      valueObj['raw'] = raw;
      obj['value'] = valueObj;
      obj['tail'] = new Box<boolean>(tail);
    }
    case TemplateLiteral { quasis, expressions }: {
      obj['quasis'] = templateElementsToJson(quasis);
      obj['expressions'] = expressionsToJson(expressions);
    }
    case TaggedTemplateExpression { tag, quasi }: {
      obj['tag'] = nodeToJson(tag);
      obj['quasi'] = nodeToJson(quasi);
    }
    case Identifier { name }: {
      obj['name'] = name;
    }
    
    // Expressions
    case BinaryExpression { operator, left, right }: {
      obj['operator'] = operator;
      obj['left'] = nodeToJson(left);
      obj['right'] = nodeToJson(right);
    }
    case UnaryExpression { operator, argument, prefix }: {
      obj['operator'] = operator;
      obj['argument'] = nodeToJson(argument);
      obj['prefix'] = new Box<boolean>(prefix);
    }
    case AssignmentExpression { left, value, operator }: {
      obj['left'] = nodeToJson(left);
      if (operator != null) {
        obj['operator'] = operator;
      }
      obj['value'] = nodeToJson(value);
    }
    case AsExpression { expression, typeAnnotation }: {
      obj['expression'] = nodeToJson(expression);
      obj['typeAnnotation'] = nodeToJson(typeAnnotation);
    }
    case IsExpression { expression, typeAnnotation }: {
      obj['expression'] = nodeToJson(expression);
      obj['typeAnnotation'] = nodeToJson(typeAnnotation);
    }
    case RangeExpression { start, end }: {
      if (start != null) {
        obj['start'] = nodeToJson(start as Node);
      } else {
        obj['start'] = null;
      };
      if (end != null) {
        obj['end'] = nodeToJson(end as Node);
      } else {
        obj['end'] = null;
      };
    }
    case PipelineExpression { left, right }: {
      obj['left'] = nodeToJson(left);
      obj['right'] = nodeToJson(right);
    }
    case PipePlaceholder {}: {
      // No fields to serialize
    }
    case CallExpression { callee, args, typeArguments, optional }: {
      obj['callee'] = nodeToJson(callee);
      if (optional) {
        obj['optional'] = new Box<boolean>(true);
      }
      obj['arguments'] = expressionsToJson(args);
      if (typeArguments != null) {
        obj['typeArguments'] = typeAnnotationsToJson(typeArguments);
      }
    }
    case MemberExpression { object, property, optional, isSymbolAccess, symbolPath }: {
      obj['object'] = nodeToJson(object);
      obj['property'] = nodeToJson(property);
      if (optional) {
        obj['optional'] = new Box<boolean>(true);
      }
      if (isSymbolAccess) {
        obj['isSymbolAccess'] = new Box<boolean>(true);
      }
      if (symbolPath != null) {
        obj['symbolPath'] = nodeToJson(symbolPath);
      }
    }
    case IndexExpression { object, index, optional }: {
      obj['object'] = nodeToJson(object);
      obj['index'] = nodeToJson(index);
      if (optional) {
        obj['optional'] = new Box<boolean>(true);
      }
    }
    case ThisExpression {}: {
      // No additional fields
    }
    case NewExpression { callee, typeArguments, args, constructorName }: {
      obj['callee'] = nodeToJson(callee);
      if (typeArguments != null) {
        obj['typeArguments'] = typeAnnotationsToJson(typeArguments);
      }
      if (constructorName != null) {
        obj['constructorName'] = nodeToJson(constructorName);
      }
      obj['arguments'] = expressionsToJson(args);
    }
    case FunctionExpression { typeParameters, params, returnType, body, isGenerator, isAsync, contracts }: {
      if (typeParameters != null) {
        obj['typeParameters'] = typeParametersToJson(typeParameters);
      }
      obj['params'] = parametersToJson(params);
      if (returnType != null) {
        obj['returnType'] = nodeToJson(returnType as Node);
      }
      if (contracts != null) {
        obj['contracts'] = contractsToJson(contracts);
      }
      obj['body'] = nodeToJson(body);
      // Only emitted when set: bootstrap snapshots predate generators.
      if (isGenerator) {
        obj['isGenerator'] = new Box<boolean>(true);
      }
      if (isAsync) {
        obj['isAsync'] = new Box<boolean>(true);
      }
    }
    
    // Arrays, Records, Tuples
    case ArrayLiteral { elements }: {
      obj['elements'] = expressionsToJson(elements);
    }
    case RecordLiteral { properties }: {
      obj['properties'] = propertyAssignmentsToJson(properties);
    }
    case MapLiteral { entries }: {
      obj['entries'] = mapEntriesToJson(entries);
    }
    case MapEntry { key, value }: {
      obj['key'] = nodeToJson(key);
      obj['value'] = nodeToJson(value);
    }
    case TupleLiteral { elements, spreadIndices }: {
      obj['elements'] = expressionsToJson(elements);
      if (spreadIndices != null) {
        let arr = new JsonArray();
        for (let index in spreadIndices) {
          arr.push(new Box<f64>(index as f64));
        }
        obj['spreadIndices'] = arr;
      }
    }
    case PropertyAssignment { name, value }: {
      obj['name'] = nodeToJson(name);
      obj['value'] = nodeToJson(value);
    }
    case SpreadElement { argument }: {
      obj['argument'] = nodeToJson(argument);
    }
    case BindingProperty { name, value }: {
      obj['name'] = nodeToJson(name);
      obj['value'] = nodeToJson(value);
    }
    
    // Statements
    case VariableDeclaration { kind, pattern, typeAnnotation, init, exported }: {
      obj['kind'] = kind;
      obj['pattern'] = nodeToJson(pattern);
      if (typeAnnotation != null) {
        obj['typeAnnotation'] = nodeToJson(typeAnnotation as Node);
      }
      obj['init'] = nodeToJson(init);
      obj['exported'] = new Box<boolean>(exported);
    }
    case UsingStatement { pattern, typeAnnotation, init }: {
      if (pattern != null) {
        obj['pattern'] = nodeToJson(pattern as Node);
      }
      if (typeAnnotation != null) {
        obj['typeAnnotation'] = nodeToJson(typeAnnotation as Node);
      }
      obj['init'] = nodeToJson(init);
    }
    case FunctionDeclaration { name, func, exported }: {
      obj['name'] = nodeToJson(name);
      obj['func'] = nodeToJson(func);
      obj['exported'] = new Box<boolean>(exported);
    }
    case ShieldedStatement { body }: {
      obj['body'] = nodeToJson(body);
    }
    case ExpressionStatement { expression }: {
      obj['expression'] = nodeToJson(expression);
    }
    case BlockStatement { body }: {
      obj['body'] = statementsToJson(body);
    }
    case ReturnStatement { argument, isTail }: {
      if (argument != null) {
        obj['argument'] = nodeToJson(argument);
      }
      if (isTail) {
        obj['isTail'] = new Box<boolean>(true);
      }
    }
    case YieldStatement { argument }: {
      obj['argument'] = nodeToJson(argument);
    }
    case BreakStatement {}: {
      // No additional fields
    }
    case ContinueStatement {}: {
      // No additional fields
    }
    case IfStatement { test, consequent, alternate }: {
      obj['test'] = nodeToJson(test);
      obj['consequent'] = nodeToJson(consequent);
      if (alternate != null) {
        obj['alternate'] = nodeToJson(alternate);
      }
    }
    case MatchExpression { discriminant, cases }: {
      obj['discriminant'] = nodeToJson(discriminant);
      obj['cases'] = matchCasesToJson(cases);
    }
    case MatchCase { pattern, guard, body }: {
      obj['pattern'] = nodeToJson(pattern);
      if (guard != null) {
        obj['guard'] = nodeToJson(guard);
      }
      obj['body'] = nodeToJson(body);
    }
    case IfExpression { test, consequent, alternate }: {
      obj['test'] = nodeToJson(test);
      obj['consequent'] = nodeToJson(consequent);
      if (alternate != null) {
        obj['alternate'] = nodeToJson(alternate);
      } else {
        obj['alternate'] = null;
      }
    }
    case ThrowExpression { argument }: {
      obj['argument'] = nodeToJson(argument);
    }
    case AwaitExpression { argument }: {
      obj['argument'] = nodeToJson(argument);
    }
    case TryExpression { body, handler, cancelBlock, finalizer }: {
      obj['body'] = nodeToJson(body);
      if (handler != null) {
        obj['handler'] = nodeToJson(handler);
      } else {
        obj['handler'] = null;
      };
      if (cancelBlock != null) {
        obj['cancelBlock'] = nodeToJson(cancelBlock);
      } else {
        obj['cancelBlock'] = null;
      };
      if (finalizer != null) {
        obj['finalizer'] = nodeToJson(finalizer);
      } else {
        obj['finalizer'] = null;
      };
    }
    case CatchClause { param, body }: {
      if (param != null) {
        obj['param'] = nodeToJson(param);
      } else {
        obj['param'] = null;
      };
      obj['body'] = nodeToJson(body);
    }
    case WhileStatement { test, body, invariants }: {
      obj['test'] = nodeToJson(test);
      if (invariants != null) {
        obj['invariants'] = contractsToJson(invariants);
      }
      obj['body'] = nodeToJson(body);
    }
    case ForStatement { init, test, update, body, invariants }: {
      if (init != null) {
        obj['init'] = nodeToJson(init);
      }
      if (test != null) {
        obj['test'] = nodeToJson(test);
      }
      if (update != null) {
        obj['update'] = nodeToJson(update);
      }
      if (invariants != null) {
        obj['invariants'] = contractsToJson(invariants);
      }
      obj['body'] = nodeToJson(body);
    }
    case ForInStatement { pattern, iterable, body, invariants }: {
      obj['pattern'] = nodeToJson(pattern);
      obj['iterable'] = nodeToJson(iterable);
      if (invariants != null) {
        obj['invariants'] = contractsToJson(invariants);
      }
      obj['body'] = nodeToJson(body);
    }
    case LetPatternCondition { pattern, init }: {
      obj['pattern'] = nodeToJson(pattern);
      obj['init'] = nodeToJson(init);
    }
    
    // Parameters
    case Parameter { name, pattern, typeAnnotation, optional, defaultValue, isThisParam }: {
      obj['name'] = nodeToJson(name);
      if (pattern != null) {
        obj['pattern'] = nodeToJson(pattern as Node);
      }
      if (typeAnnotation != null) {
        obj['typeAnnotation'] = nodeToJson(typeAnnotation as Node);
      }
      obj['optional'] = new Box<boolean>(optional);
      if (defaultValue != null) {
        obj['initializer'] = nodeToJson(defaultValue);
      }
      if (isThisParam) {
        obj['isThisParam'] = new Box<boolean>(true);
      }
    }
    
    // Type Parameters
    case TypeParameter { name, constraint, defaultType, isScoped }: {
      obj['name'] = name;
      if (constraint != null) {
        obj['constraint'] = nodeToJson(constraint as Node);
      }
      if (defaultType != null) {
        obj['default'] = nodeToJson(defaultType as Node);
      }
      // Written only when set, so snapshots without the modifier are
      // unchanged.
      if (isScoped) {
        obj['scoped'] = new Box<boolean>(true);
      }
    }
    
    // Type Annotations
    case NamedTypeAnnotation { name, typeArguments, elementsMutable }: {
      obj['name'] = name;
      if (typeArguments != null) {
        obj['typeArguments'] = typeAnnotationsToJson(typeArguments);
      }
      // Written only when set, so snapshots without the modifier are
      // unchanged.
      if (elementsMutable) {
        obj['elementsMutable'] = new Box<boolean>(true);
      }
    }
    case UnionTypeAnnotation { types }: {
      obj['types'] = typeAnnotationsToJson(types);
    }
    case NullableTypeAnnotation { typeAnnotation }: {
      obj['typeAnnotation'] = nodeToJson(typeAnnotation as Node);
    }
    case FunctionTypeAnnotation { paramNames, params, returnType }: {
      let namesArr = new JsonArray();
      for (let paramName in paramNames) {
        namesArr.push(paramName);
      }
      obj['paramNames'] = namesArr;
      obj['params'] = typeAnnotationsToJson(params);
      obj['returnType'] = nodeToJson(returnType as Node);
    }
    case LiteralTypeAnnotation { value }: {
      match (value) {
        case StringLiteral { value }: {
          obj['value'] = value;
        }
        case NumberLiteral { raw }: {
          obj['value'] = new Box<f64>(parseF64(raw));
        }
        case BooleanLiteral { value }: {
          obj['value'] = new Box<boolean>(value);
        }
        case _: {}
      }
    }
    case RecordTypeAnnotation { properties, spreads, isExistential }: {
      let arr = new JsonArray();
      var i = 0;
      while (i < properties.length) {
        arr.push(nodeToJson(properties[i] as Node));
        i += 1;
      }
      obj['properties'] = arr;
      if (isExistential) {
        obj['isExistential'] = new Box<boolean>(true);
      }
      if (spreads != null) {
        obj['spreads'] = typeAnnotationsToJson(spreads);
      }
    }
    case TupleTypeAnnotation { elementTypes, spreadIndices }: {
      obj['elementTypes'] = typeAnnotationsToJson(elementTypes);
      if (spreadIndices != null) {
        let arr = new JsonArray();
        for (let index in spreadIndices) {
          arr.push(new Box<f64>(index as f64));
        }
        obj['spreadIndices'] = arr;
      }
    }
    case InlineTypeAnnotation { typeAnnotation, ifPossible }: {
      obj['typeAnnotation'] = nodeToJson(typeAnnotation as Node);
      if (ifPossible) {
        obj['ifPossible'] = new Box<boolean>(true);
      }
    }
    case ThisTypeAnnotation {}: {
      // No additional fields
    }
    case PropertySignature { name, typeAnnotation, optional }: {
      obj['name'] = nodeToJson(name as Node);
      obj['typeAnnotation'] = nodeToJson(typeAnnotation as Node);
      if (optional) {
        obj['optional'] = new Box<boolean>(true);
      }
    }
    
    // Module
    case Module {body, source}: {
      obj['body'] = statementsToJson(body);
    }
    
    // Imports / Exports
    case ImportDeclaration { moduleSpecifier, imports }: {
      obj['moduleSpecifier'] = nodeToJson(moduleSpecifier);
      obj['imports'] = importSpecifiersToJson(imports);
    }
    case ImportSpecifier { imported, local }: {
      obj['imported'] = nodeToJson(imported);
      obj['local'] = nodeToJson(local);
    }
    case ExportAllDeclaration { moduleSpecifier }: {
      obj['moduleSpecifier'] = nodeToJson(moduleSpecifier);
    }
    case ExportFromDeclaration { specifiers, moduleSpecifier }: {
      obj['specifiers'] = importSpecifiersToJson(specifiers);
      obj['moduleSpecifier'] = nodeToJson(moduleSpecifier);
    }
    case Decorator { name, args }: {
      obj['name'] = name;
      obj['args'] = decoratorArgsToJson(args);
    }
    case ContractClause { kind, condition, mode }: {
      obj['kind'] = contractKeyword(kind);
      if (mode != ContractMode.Checked) {
        obj['mode'] = contractModifier(mode);
      }
      obj['condition'] = nodeToJson(condition);
    }
    case DeclareFunction { name, typeParameters, params, returnType, externalModule, externalName, exported, decorators }: {
      obj['name'] = nodeToJson(name);
      if (typeParameters != null) {
        obj['typeParameters'] = typeParametersToJson(typeParameters);
      } else { };
      obj['params'] = parametersToJson(params);
      obj['returnType'] = nodeToJson(returnType as Node);
      if (externalModule != null) {
        obj['externalModule'] = externalModule;
      } else { };
      if (externalName != null) {
        obj['externalName'] = externalName;
      } else { };
      obj['exported'] = new Box<boolean>(exported);
      if (decorators.length > 0) {
        obj['decorators'] = decoratorsToJson(decorators);
      } else { };
    }
    
    // Class Declarations
    case ClassDeclaration { name, typeParameters, caseParams, superClass, mixins, implementsList, body, exported, isFinal, isAbstract, isExtension, isSealed, sealedVariants, onType, isResource }: {
      obj['name'] = nodeToJson(name);
      if (typeParameters != null) {
        obj['typeParameters'] = typeParametersToJson(typeParameters);
      }
      if (caseParams != null) {
        obj['caseParams'] = caseClassParamsToJson(caseParams);
      }
      if (superClass != null) {
        obj['superClass'] = nodeToJson(superClass as Node);
      }
      if (mixins != null) {
        obj['mixins'] = typeAnnotationsToJson(mixins);
      }
      if (implementsList != null) {
        obj['implements'] = typeAnnotationsToJson(implementsList);
      }
      obj['body'] = nodesToJson(body);
      obj['exported'] = new Box<boolean>(exported);
      obj['isFinal'] = new Box<boolean>(isFinal);
      obj['isAbstract'] = new Box<boolean>(isAbstract);
      obj['isExtension'] = new Box<boolean>(isExtension);
      obj['isSealed'] = new Box<boolean>(isSealed);
      if (isResource) { obj['isResource'] = new Box<boolean>(isResource); }
      if (sealedVariants != null) {
        obj['sealedVariants'] = sealedVariantsToJson(sealedVariants);
      }
      if (onType != null) {
        obj['onType'] = nodeToJson(onType as Node);
      }
    }
    case SealedVariant { name, params }: {
      obj['name'] = nodeToJson(name);
      if (params != null) {
        obj['params'] = caseClassParamsToJson(params);
      }
    }
    case CaseClassParam { name, typeAnnotation, mutability, defaultValue }: {
      obj['name'] = nodeToJson(name);
      obj['typeAnnotation'] = nodeToJson(typeAnnotation as Node);
      if (mutability != null) {
        obj['mutability'] = mutability;
      }
      if (defaultValue != null) {
        obj['initializer'] = nodeToJson(defaultValue);
      }
    }
    case FieldDefinition { name, typeAnnotation, value, isFinal, isAbstract, isStatic, isDeclare, mutability, decorators, setterName, isShared }: {
      if (isShared) {
        obj['isShared'] = new Box<boolean>(true);
      }
      obj['name'] = nodeToJson(name);
      if (typeAnnotation != null) {
        obj['typeAnnotation'] = nodeToJson(typeAnnotation as Node);
      }
      if (value != null) {
        obj['value'] = nodeToJson(value as Node);
      }
      obj['isFinal'] = new Box<boolean>(isFinal);
      obj['isAbstract'] = new Box<boolean>(isAbstract);
      obj['isStatic'] = new Box<boolean>(isStatic);
      obj['isDeclare'] = new Box<boolean>(isDeclare);
      obj['decorators'] = decoratorsToJson(decorators);
      if (mutability != null) {
        obj['mutability'] = mutability;
      }
      if (setterName != null) {
        obj['setterName'] = nodeToJson(setterName);
      }
    }
    case MethodDefinition { name, typeParameters, receiver, params, returnType, body, initializerList, superInitializer, isFinal, isAbstract, isStatic, isDeclare, isGenerator, isAsync, decorators, isConstructor, isShared, contracts }: {
      if (isShared) {
        obj['isShared'] = new Box<boolean>(true);
      }
      if (contracts != null) {
        obj['contracts'] = contractsToJson(contracts);
      }
      obj['name'] = nodeToJson(name);
      if (typeParameters != null) {
        obj['typeParameters'] = typeParametersToJson(typeParameters);
      }
      // Only emitted when declared: bootstrap snapshots predate receivers.
      if (receiver != null) {
        obj['receiver'] = nodeToJson(receiver as Node);
      }
      obj['params'] = parametersToJson(params);
      if (returnType != null) {
        obj['returnType'] = nodeToJson(returnType as Node);
      }
      if (body != null) {
        obj['body'] = nodeToJson(body);
      }
      if (initializerList != null) {
        obj['initializerList'] = nodesToJson(initializerList);
      }
      if (superInitializer != null) {
        obj['superInitializer'] = nodeToJson(superInitializer);
      }
      obj['isFinal'] = new Box<boolean>(isFinal);
      obj['isAbstract'] = new Box<boolean>(isAbstract);
      obj['isStatic'] = new Box<boolean>(isStatic);
      obj['isDeclare'] = new Box<boolean>(isDeclare);
      // Only emitted when set: bootstrap snapshots predate generators.
      if (isGenerator) {
        obj['isGenerator'] = new Box<boolean>(true);
      }
      if (isAsync) {
        obj['isAsync'] = new Box<boolean>(true);
      }
      if (isConstructor) {
        let isDefaultCtor = if (let Identifier { name } = name) {
          name == "<constructor>"
        } else {
          false
        };
        if (!isDefaultCtor) {
          obj['isConstructor'] = new Box<boolean>(true);
        }
      }
      obj['decorators'] = decoratorsToJson(decorators);
    }
    case AccessorDeclaration { name, typeAnnotation, getter, setter, isFinal, isStatic, decorators }: {
      obj['name'] = nodeToJson(name);
      obj['typeAnnotation'] = nodeToJson(typeAnnotation as Node);
      if (getter != null) {
        obj['getter'] = nodeToJson(getter as Node);
      }
      if (setter != null) {
        let setterInfo = setter as SetterInfo;
        let setterObj = new JsonObject();
        setterObj['param'] = nodeToJson(setterInfo.param);
        setterObj['body'] = nodeToJson(setterInfo.body);
        obj['setter'] = setterObj;
      }
      obj['isFinal'] = new Box<boolean>(isFinal);
      obj['isStatic'] = new Box<boolean>(isStatic);
      obj['decorators'] = decoratorsToJson(decorators);
    }
    case SuperExpression {}: {
      // No additional fields
    }
    case FieldInitializer { field, value }: {
      obj['field'] = nodeToJson(field);
      obj['value'] = nodeToJson(value);
    }
    case SuperInitializer { args, constructorName }: {
      obj['arguments'] = expressionsToJson(args);
      if (constructorName != null) {
        obj['constructorName'] = nodeToJson(constructorName);
      }
    }
    
    // Interface Declarations
    case InterfaceDeclaration { name, typeParameters, extendsList, body, exported }: {
      obj['name'] = nodeToJson(name);
      if (typeParameters != null) {
        obj['typeParameters'] = typeParametersToJson(typeParameters);
      }
      if (extendsList != null) {
        obj['extends'] = typeAnnotationsToJson(extendsList);
      }
      obj['body'] = nodesToJson(body);
      obj['exported'] = new Box<boolean>(exported);
    }
    case MethodSignature { name, typeParameters, params, returnType, contracts }: {
      obj['name'] = nodeToJson(name);
      if (typeParameters != null) {
        obj['typeParameters'] = typeParametersToJson(typeParameters);
      }
      obj['params'] = parametersToJson(params);
      if (returnType != null) {
        obj['returnType'] = nodeToJson(returnType as Node);
      }
      if (contracts != null) {
        obj['contracts'] = contractsToJson(contracts);
      }
    }
    case AccessorSignature { name, typeAnnotation, hasGetter, hasSetter }: {
      obj['name'] = nodeToJson(name);
      obj['typeAnnotation'] = nodeToJson(typeAnnotation as Node);
      obj['hasGetter'] = new Box<boolean>(hasGetter);
      obj['hasSetter'] = new Box<boolean>(hasSetter);
    }
    
    // Mixin Declarations
    case MixinDeclaration { name, typeParameters, on, mixins, body, exported, decoratorSubject }: {
      obj['name'] = nodeToJson(name);
      if (typeParameters != null) {
        obj['typeParameters'] = typeParametersToJson(typeParameters);
      }
      if (decoratorSubject != null) {
        obj['decoratorSubject'] = nodeToJson(decoratorSubject);
      }
      if (on != null) {
        obj['on'] = nodeToJson(on as Node);
      }
      if (mixins != null) {
        obj['mixins'] = typeAnnotationsToJson(mixins);
      }
      obj['body'] = nodesToJson(body);
      obj['exported'] = new Box<boolean>(exported);
    }
    
    // Enum Declarations
    case EnumDeclaration { name, members, exported }: {
      obj['name'] = nodeToJson(name);
      obj['members'] = enumMembersToJson(members);
      obj['exported'] = new Box<boolean>(exported);
    }
    case TypeAliasDeclaration { name, typeParameters, typeAnnotation, exported, isDistinct, isOpaque, decorators }: {
      obj['name'] = nodeToJson(name);
      if (typeParameters != null) {
        obj['typeParameters'] = typeParametersToJson(typeParameters);
      }
      if (typeAnnotation != null) {
        obj['typeAnnotation'] = nodeToJson(typeAnnotation as Node);
      } else { };
      obj['exported'] = new Box<boolean>(exported);
      obj['isDistinct'] = new Box<boolean>(isDistinct);
      obj['isOpaque'] = new Box<boolean>(isOpaque);
      if (decorators.length > 0) {
        obj['decorators'] = decoratorsToJson(decorators);
      } else { };
    }
    case EnumMember { name, initializer }: {
      obj['name'] = nodeToJson(name);
      if (initializer != null) {
        obj['initializer'] = nodeToJson(initializer);
      }
    }
    
    // Symbol Declarations
    case SymbolDeclaration { name, exported }: {
      obj['name'] = nodeToJson(name);
      obj['exported'] = new Box<boolean>(exported);
    }
    case SymbolPropertyName { symbolRef }: {
      obj['symbol'] = nodeToJson(symbolRef);
    }
    
    // Default: type field is already set
    case _: {}
  }
  
  return obj;
}

// ============================================================================
// Array Conversion Helpers
// ============================================================================

function statementsToJson(stmts: GrowableArray<Statement>): JsonArray {
  let arr = new JsonArray();
  for (let statement in stmts) {
    arr.push(nodeToJson(statement));
  }
  return arr;
}

function importSpecifiersToJson(specs: GrowableArray<ImportSpecifier>): JsonArray {
  let arr = new JsonArray();
  for (let spec in specs) {
    arr.push(nodeToJson(spec));
  }
  return arr;
}

function expressionsToJson(exprs: GrowableArray<Expression>): JsonArray {
  let arr = new JsonArray();
  for (let expr in exprs) {
    arr.push(nodeToJson(expr));
  }
  return arr;
}

function templateElementsToJson(elems: GrowableArray<TemplateElement>): JsonArray {
  let arr = new JsonArray();
  for (let elem in elems) {
    arr.push(nodeToJson(elem));
  }
  return arr;
}

function enumMembersToJson(members: GrowableArray<EnumMember>): JsonArray {
  let arr = new JsonArray();
  for (let member in members) {
    arr.push(nodeToJson(member));
  }
  return arr;
}

function parametersToJson(params: GrowableArray<Parameter>): JsonArray {
  let arr = new JsonArray();
  for (let param in params) {
    arr.push(nodeToJson(param));
  }
  return arr;
}

function typeParametersToJson(params: GrowableArray<TypeParameter>): JsonArray {
  let arr = new JsonArray();
  for (let param in params) {
    arr.push(nodeToJson(param));
  }
  return arr;
}

function propertyAssignmentsToJson(props: GrowableArray<Node>): JsonArray {
  let arr = new JsonArray();
  for (let prop in props) {
    arr.push(nodeToJson(prop));
  }
  return arr;
}

function mapEntriesToJson(entries: GrowableArray<MapEntry>): JsonArray {
  let arr = new JsonArray();
  for (let entry in entries) {
    arr.push(nodeToJson(entry));
  }
  return arr;
}

function bindingPropertiesToJson(props: GrowableArray<BindingProperty>): JsonArray {
  let arr = new JsonArray();
  for (let prop in props) {
    arr.push(nodeToJson(prop));
  }
  return arr;
}

function matchCasesToJson(cases: GrowableArray<MatchCase>): JsonArray {
  let arr = new JsonArray();
  for (let matchCase in cases) {
    arr.push(nodeToJson(matchCase));
  }
  return arr;
}

function patternsToJson(patterns: GrowableArray<Node | null>): JsonArray {
  let arr = new JsonArray();
  for (let p in patterns) {
    if (p != null) {
      arr.push(nodeToJson(p));
    } else {
      arr.push(null);
    }
  }
  return arr;
}

function typeAnnotationsToJson(types: GrowableArray<TypeAnnotation>): JsonArray {
  let arr = new JsonArray();
  for (let type in types) {
    arr.push(nodeToJson(type));
  }
  return arr;
}

function caseClassParamsToJson(params: GrowableArray<CaseClassParam>): JsonArray {
  let arr = new JsonArray();
  for (let param in params) {
    arr.push(nodeToJson(param));
  }
  return arr;
}

function sealedVariantsToJson(variants: GrowableArray<SealedVariant>): JsonArray {
  let arr = new JsonArray();
  for (let variant in variants) {
    arr.push(nodeToJson(variant));
  }
  return arr;
}

function nodesToJson(nodes: GrowableArray<Node>): JsonArray {
  let arr = new JsonArray();
  for (let node in nodes) {
    arr.push(nodeToJson(node));
  }
  return arr;
}

function decoratorsToJson(decorators: GrowableArray<Decorator>): JsonArray {
  let arr = new JsonArray();
  for (let decorator in decorators) {
    arr.push(nodeToJson(decorator));
  }
  return arr;
}

function contractsToJson(contracts: GrowableArray<ContractClause>): JsonArray {
  let arr = new JsonArray();
  for (let contract in contracts) {
    arr.push(nodeToJson(contract));
  }
  return arr;
}

function decoratorArgsToJson(args: GrowableArray<Expression>): JsonArray {
  let arr = new JsonArray();
  for (let arg in args) {
    arr.push(nodeToJson(arg));
  }
  return arr;
}

// ============================================================================
// Public API
// ============================================================================

/**
 * Convert an AST node to a JSON string.
 */
export function astToJsonString(node: Node): String {
  let json = nodeToJson(node);
  return stringify(json);
}
VersionPublishedDependenciesApproved by
0.0.2-preview.1 2026-11-19