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.1 KiB Raw
/**
 * Abstract Syntax Tree types for the Zena language
 */


/**
 * Distinct type for Node identity keys.
 * Prevents accidental use of source offsets or other i32 values as Node IDs.
 */
export distinct type NodeId = i32;

/**
 * A monotonic ID counter, generic over the ID type it mints.
 *
 * The forging cast is not in here — it arrives as `mint`, a closure written
 * beside the type it produces. That keeps one counter implementation while
 * putting each `i32 -> Id` conversion in the file that declares that Id, which
 * is where it would have to be if any of these became `opaque`. It also means
 * this body contains no cast at all, so it does not need the type-parameter
 * exemption that `return id as T` would (and could not get — see
 * docs/design/opaque-types.md).
 *
 * `mint` is private, so a generator hands out IDs but never the conversion
 * that made them.
 */
export final class IdGenerator<T> {
  #mint: (id: i32) => T;
  var #nextId: i32;
  new(mint: (id: i32) => T, nextId: i32 = 1)
    : #mint = mint,
      #nextId = nextId;
  next(): T {
    let id = this.#nextId;
    this.#nextId += 1;
    return this.#mint(id);
  }

  /** The raw value the next `next()` will mint, without minting it. */
  peek(): i32 {
    return this.#nextId;
  }
}

/**
 * The only way to get NodeIds. There is deliberately no `makeNodeId(i32)`:
 * what matters about these is that they are unique within a compilation, and
 * a public conversion hands that away to every caller.
 */
export function makeNodeIdGenerator(nextId: i32 = 1): IdGenerator<NodeId> {
  return new IdGenerator<NodeId>((id: i32) => id as NodeId, nextId);
}

/**
 * Where a node came from: a byte range in a file. There is one per
 * node, so it is kept to three fields — 32 bytes in wasmtime's GC heap,
 * where five was 48. The line and column a diagnostic prints are
 * derived from `start` on demand (`line-index.zena`), since nothing
 * reads them until something is reported.
 */
export final class SourceLocation(
  /** 0-based start index (inclusive) */
  start: i32,
  /** 0-based end index (exclusive) */
  end: i32,
  /**
   * Path of the source file this location belongs to. Lets diagnostics
   * report the correct file when an error is raised against a node from
   * another module than the one being checked, and is the key the line
   * index answers for.
   */
  path: String | null)

/**
 * A source comment collected during tokenization.
 */
export final class Comment(
  /** The comment text without delimiters. */
  value: String,
  /** True for block comments, false for line comments. */
  isBlock: boolean,
  /** 0-based start byte offset (inclusive, includes delimiter). */
  start: i32,
  /** 0-based end byte offset (exclusive, includes delimiter). */
  end: i32,
  /** 1-based line number where the comment starts. */
  line: i32,
  /** 1-based column where the comment starts. */
  column: i32)

export sealed class Node {
  // Sub-hierarchies
  case Expression, Statement, Pattern, TypeAnnotation

  // Direct case classes
  case Module
  case TemplateElement, PropertyAssignment, SpreadElement, MapEntry
  case BindingProperty, MatchCase, LetPatternCondition
  case TypeParameter, Parameter
  case CaseClassParam, SealedVariant
  case FieldDefinition, MethodDefinition, AccessorDeclaration, SetterInfo
  case FieldInitializer, SuperInitializer
  case MethodSignature, AccessorSignature
  case EnumMember, CatchClause
  case PropertySignature
  case ImportSpecifier
  case Decorator
  case ContractClause
  case SymbolPropertyName

  abstract loc: SourceLocation | null;

  /**
   * Unique ID assigned to this node instance.
   * Useful for mapping nodes to semantic information without relying on
   * object identity (which is tricky for case classes) or source location.
   */
  var id: NodeId = 0 as NodeId;
}

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

export final class Module(
  body: GrowableArray<Statement>,
  path: String,
  source: String,
  comments: GrowableArray<Comment>,
  loc: SourceLocation | null) extends Node {
  /**
   * The last node id the parser assigned under this module. Ids are
   * minted in one pre-order walk, so every node parsed as part of this
   * module has an id in `[id, lastNodeId]`, contiguous and starting at
   * the module's own — which is what lets a per-node side table be a
   * dense array (`DenseNodeMap`) and the node-to-module index a range
   * lookup (`ModelIndex`). A node minted later, by the scope builder or
   * the checker, falls outside every module's range and those
   * structures keep a hash map for it.
   */
  var lastNodeId: NodeId = 0 as NodeId;
}

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

export sealed class Expression extends Node {
  // Identifiers & Literals
  case Identifier(name: String, loc: SourceLocation | null)
  case NumberLiteral(raw: String, loc: SourceLocation | null)
  case StringLiteral(value: String, loc: SourceLocation | null)
  case BooleanLiteral(value: boolean, loc: SourceLocation | null)
  case NullLiteral(loc: SourceLocation | null)

  // Templates
  case TemplateLiteral(
    quasis: GrowableArray<TemplateElement>,
    expressions: GrowableArray<Expression>,
    loc: SourceLocation | null)
  case TaggedTemplateExpression(
    tag: Expression,
    quasi: TemplateLiteral,
    loc: SourceLocation | null)

  // Operators
  case BinaryExpression(
    operator: String,
    left: Expression,
    right: Expression,
    loc: SourceLocation | null)
  case UnaryExpression(
    operator: String,
    argument: Expression,
    prefix: boolean,
    loc: SourceLocation | null)
  case AssignmentExpression(
    left: Expression,
    value: Expression,
    operator: String | null,
    loc: SourceLocation | null)
  case AsExpression(
    expression: Expression,
    typeAnnotation: TypeAnnotation,
    loc: SourceLocation | null)
  case IsExpression(
    expression: Expression,
    typeAnnotation: TypeAnnotation,
    loc: SourceLocation | null)
  case RangeExpression(
    start: Expression | null,
    end: Expression | null,
    loc: SourceLocation | null)
  case PipelineExpression(
    left: Expression,
    right: Expression,
    loc: SourceLocation | null)
  case PipePlaceholder(loc: SourceLocation | null)

  // Functions & Calls
  case FunctionExpression(
    typeParameters: GrowableArray<TypeParameter> | null,
    params: GrowableArray<Parameter>,
    returnType: TypeAnnotation | null,
    body: BlockStatement | Expression,
    isGenerator: boolean,
    isAsync: boolean,
    /** The `requires` and `ensures` clauses, in source order; null when there are none. */
    contracts: GrowableArray<ContractClause> | null,
    loc: SourceLocation | null)
  case AwaitExpression(argument: Expression, loc: SourceLocation | null)
  case CallExpression(
    callee: Expression,
    args: GrowableArray<Expression>,
    typeArguments: GrowableArray<TypeAnnotation> | null,
    optional: boolean,
    loc: SourceLocation | null)

  // Member Access
  case MemberExpression(
    object: Expression,
    property: Identifier,
    optional: boolean,
    isSymbolAccess: boolean,
    symbolPath: Expression | null,
    loc: SourceLocation | null)
  case IndexExpression(
    object: Expression,
    index: Expression,
    optional: boolean,
    loc: SourceLocation | null)
  case ThisExpression(loc: SourceLocation | null)
  case SuperExpression(loc: SourceLocation | null)
  case NewExpression(
    callee: Identifier,
    typeArguments: GrowableArray<TypeAnnotation> | null,
    args: GrowableArray<Expression>,
    constructorName: Node | null,
    loc: SourceLocation | null)

  // Collection Literals
  case ArrayLiteral(elements: GrowableArray<Expression>, loc: SourceLocation | null)
  case RecordLiteral(properties: GrowableArray<Node>, loc: SourceLocation | null)
  case MapLiteral(entries: GrowableArray<MapEntry>, loc: SourceLocation | null)
  /**
   * `spreadIndices` are the positions in `elements` written `...t`, whose
   * tuple's elements splice in there; null when there are none.
   */
  case TupleLiteral(elements: GrowableArray<Expression>, spreadIndices: GrowableArray<i32> | null, loc: SourceLocation | null)

  // Control Flow Expressions
  case MatchExpression(
    discriminant: Expression,
    cases: GrowableArray<MatchCase>,
    loc: SourceLocation | null)
  case IfExpression(
    test: Node,
    consequent: Node,
    alternate: Node | null,
    loc: SourceLocation | null)

  // Error Handling Expressions
  case ThrowExpression(argument: Expression, loc: SourceLocation | null)
  case TryExpression(
    body: BlockStatement,
    handler: CatchClause | null,
    cancelBlock: BlockStatement | null,
    finalizer: BlockStatement | null,
    loc: SourceLocation | null)
}

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

export sealed class Statement extends Node {
  case VariableDeclaration(
    kind: String,
    pattern: Pattern,
    typeAnnotation: TypeAnnotation | null,
    init: Expression,
    exported: boolean,
    loc: SourceLocation | null)
  /**
   * A top-level `function` declaration.
   *
   * `name` is an `IdentifierPattern`, not an `Identifier`, so the binding
   * site has the same shape as `let f = () => ...`: the scope builder
   * records the symbol on the pattern, and everything downstream that
   * reads `Symbol.declaration` (documented to be an `IdentifierPattern`
   * for function bindings) keeps working unchanged.
   *
   * `func` holds the signature and body, and is the same
   * `FunctionExpression` an arrow produces, so the checker, reachability
   * and lowering paths are shared. What differs is a static guarantee:
   * a `function` never closes over anything, so it needs no context
   * struct and no closure wrapper. See language-reference.md §4.
   */
  case FunctionDeclaration(
    name: IdentifierPattern,
    func: FunctionExpression,
    exported: boolean,
    loc: SourceLocation | null)
  /**
   * A `using` statement: `using let file = open(path);`, or the unbound
   * `using acquire(lock);` when there is nothing worth naming.
   *
   * One node covers both forms because they differ only in whether the
   * value is named: `pattern` is null for the unbound form, and `init` is
   * the disposable either way. The value is released on every path leaving
   * the enclosing block — normal exit, `return`, `break`/`continue`, and
   * exception unwind — in reverse declaration order. See
   * docs/design/ownership.md §`using`.
   */
  case UsingStatement(
    pattern: Pattern | null,
    typeAnnotation: TypeAnnotation | null,
    init: Expression,
    loc: SourceLocation | null)
  /**
   * `shielded { ... }` — a region where cancellation checkpoints do
   * not deliver, for cleanup that must await after cancellation has
   * arrived. Level-triggering resumes at the closing brace. Legal only
   * in async bodies. See docs/design/cancellation.md §Shields.
   */
  case ShieldedStatement(body: BlockStatement, loc: SourceLocation | null)
  case ExpressionStatement(expression: Expression, loc: SourceLocation | null)
  case BlockStatement(body: GrowableArray<Statement>, loc: SourceLocation | null)
  /**
   * `return e;`, or `tail return e;` when `isTail` is set. A tail
   * return compiles the operand call to `return_call`, discarding this
   * frame before the callee runs. See docs/design/tail-calls.md.
   */
  case ReturnStatement(
    argument: Expression | null,
    isTail: boolean,
    loc: SourceLocation | null)
  case YieldStatement(argument: Expression, loc: SourceLocation | null)
  case BreakStatement(loc: SourceLocation | null)
  case ContinueStatement(loc: SourceLocation | null)
  case IfStatement(
    test: Node,
    consequent: Statement,
    alternate: Statement | null,
    loc: SourceLocation | null)
  /**
   * `invariants`, here and on the two `for` loops, are the loop's
   * `invariant` clauses in source order; null when there are none.
   */
  case WhileStatement(
    test: Node,
    body: Statement,
    invariants: GrowableArray<ContractClause> | null,
    loc: SourceLocation | null)
  case ForStatement(
    init: Node | null,
    test: Expression | null,
    update: Expression | null,
    body: Statement,
    invariants: GrowableArray<ContractClause> | null,
    loc: SourceLocation | null)
  case ForInStatement(
    pattern: Pattern,
    iterable: Expression,
    body: Statement,
    isAwait: boolean,
    invariants: GrowableArray<ContractClause> | null,
    loc: SourceLocation | null)
  case ClassDeclaration(
    name: Identifier,
    typeParameters: GrowableArray<TypeParameter> | null,
    caseParams: GrowableArray<CaseClassParam> | null,
    superClass: TypeAnnotation | null,
    mixins: GrowableArray<TypeAnnotation> | null,
    implementsList: GrowableArray<TypeAnnotation> | null,
    body: GrowableArray<Node>,
    exported: boolean,
    isFinal: boolean,
    isAbstract: boolean,
    isExtension: boolean,
    isSealed: boolean,
    sealedVariants: GrowableArray<SealedVariant> | null,
    onType: TypeAnnotation | null,
    /**
     * `resource class C` — the class has no unwrapped form. Every mention of
     * `C` in a type position must be `Own<C>`, `Borrow<C>` or `Unmanaged<C>`.
     * See docs/design/ownership.md §"Resource-ness and affineness are
     * different properties": this declares resource-ness, not affineness —
     * affineness comes from the `Own<T>` wrapper.
     */
    isResource: boolean,
    loc: SourceLocation | null)
  case InterfaceDeclaration(
    name: Identifier,
    typeParameters: GrowableArray<TypeParameter> | null,
    extendsList: GrowableArray<TypeAnnotation> | null,
    body: GrowableArray<Node>,
    exported: boolean,
    loc: SourceLocation | null)
  case EnumDeclaration(
    name: Identifier,
    members: GrowableArray<EnumMember>,
    exported: boolean,
    loc: SourceLocation | null)
  /**
   * A `mixin` declaration, or a `decorator` declaration, which is a mixin
   * applied to one field at a time (docs/design/decorators.md).
   *
   * `decoratorSubject` is null for a mixin. For a decorator it is the
   * placeholder field written in the header — `decorator signal<T>(var
   * value: T)` — whose name the body's one public member must carry and
   * whose mutability and type the decorated field must match.
   */
  case MixinDeclaration(
    name: Identifier,
    typeParameters: GrowableArray<TypeParameter> | null,
    on: TypeAnnotation | null,
    mixins: GrowableArray<TypeAnnotation> | null,
    body: GrowableArray<Node>,
    exported: boolean,
    decoratorSubject: FieldDefinition | null,
    loc: SourceLocation | null)
  // `isOpaque` implies `isDistinct`: an opaque alias is a distinct type that
  // additionally restricts casts *to* it to the file that declares it. Every
  // pass that only cares about nominal identity keeps reading `isDistinct`.
  case TypeAliasDeclaration(
    name: Identifier,
    typeParameters: GrowableArray<TypeParameter> | null,
    /** Null for `declare type` — the bodyless form a builtin type
     * operator uses, where no body could be honest. */
    typeAnnotation: TypeAnnotation | null,
    exported: boolean,
    isDistinct: boolean,
    isOpaque: boolean,
    decorators: GrowableArray<Decorator>,
    loc: SourceLocation | null)
  case ImportDeclaration(
    moduleSpecifier: StringLiteral,
    imports: GrowableArray<ImportSpecifier>,
    loc: SourceLocation | null)
  case ExportAllDeclaration(
    moduleSpecifier: StringLiteral,
    loc: SourceLocation | null)
  case ExportFromDeclaration(
    specifiers: GrowableArray<ImportSpecifier>,
    moduleSpecifier: StringLiteral,
    loc: SourceLocation | null)
  case DeclareFunction(
    name: Identifier,
    typeParameters: GrowableArray<TypeParameter> | null,
    params: GrowableArray<Parameter>,
    returnType: TypeAnnotation,
    externalModule: String | null,
    externalName: String | null,
    exported: boolean,
    decorators: GrowableArray<Decorator>,
    loc: SourceLocation | null)
  case SymbolDeclaration(
    name: Identifier,
    exported: boolean,
    loc: SourceLocation | null)
}

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

export sealed class Pattern extends Node {
  case BindingPattern(
    kind: String,
    pattern: Pattern,
    loc: SourceLocation | null)
  case IdentifierPattern(name: String, loc: SourceLocation | null)
  /**
   * `rest` is the pattern after a trailing `...` (`{x, ...rest}`), which
   * binds the fields `properties` does not name; null when there is none.
   */
  case RecordPattern(properties: GrowableArray<BindingProperty>, rest: Node | null, loc: SourceLocation | null)
  case TuplePattern(elements: GrowableArray<Node | null>, loc: SourceLocation | null)
  case ArrayPattern(elements: GrowableArray<Node | null>, loc: SourceLocation | null)
  case RestPattern(pattern: Node, loc: SourceLocation | null)
  case AsPattern(pattern: Node, name: Identifier, loc: SourceLocation | null)
  /**
   * `Name {fields}`, or `Name<Args> {fields}` naming an instantiation of
   * a generic class. With type arguments the field list may be left out
   * (`case Box<f64>:`); then `properties` is empty. Null `typeArguments`
   * means none were written, and the checker takes them from the matched
   * value's type.
   */
  case ClassPattern(
    name: Identifier,
    typeArguments: GrowableArray<TypeAnnotation> | null,
    properties: GrowableArray<BindingProperty>,
    loc: SourceLocation | null)
  case LogicalPattern(
    operator: String,
    left: Node,
    right: Node,
    loc: SourceLocation | null)
  case AssignmentPattern(
    left: Node,
    right: Expression,
    loc: SourceLocation | null)
  case LiteralPattern(value: Expression, loc: SourceLocation | null)
  // `{!field}` — asserts an optional record field is absent. Binds
  // nothing; only valid as a record-pattern property value.
  case AbsencePattern(loc: SourceLocation | null)
}

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

export sealed class TypeAnnotation extends Node {
  // `elementsMutable` records a written `var` element modifier —
  // `array<var T>`. It is part of the grammar of the builtin array type
  // constructor, not a general type-argument modifier; the checker
  // rejects it on any other name. See docs/design/array-mutability.md.
  case NamedTypeAnnotation(
    name: String,
    typeArguments: GrowableArray<TypeAnnotation> | null,
    elementsMutable: boolean,
    loc: SourceLocation | null)
  case UnionTypeAnnotation(
    types: GrowableArray<TypeAnnotation>,
    loc: SourceLocation | null)
  case NullableTypeAnnotation(
    typeAnnotation: TypeAnnotation,
    loc: SourceLocation | null)
  case FunctionTypeAnnotation(
    paramNames: GrowableArray<String>,
    params: GrowableArray<TypeAnnotation>,
    returnType: TypeAnnotation,
    loc: SourceLocation | null)
  case LiteralTypeAnnotation(
    value: Node,
    loc: SourceLocation | null)
  case RecordTypeAnnotation(
    properties: GrowableArray<PropertySignature>,
    /**
     * The `...T` entries, in source order: a record type to merge in, or
     * a type parameter bounded by `record` (docs/design/row-types.md
     * §3.1). Null when there are none. Their positions among the
     * properties are in their locations; the order means nothing to the
     * type.
     */
    spreads: GrowableArray<TypeAnnotation> | null,
    /**
     * A trailing bare `...` (`{x: i32, ...}`): an existential record type,
     * whose values have the named fields and others the type does not
     * name (docs/design/row-types.md, Decisions).
     */
    isExistential: boolean,
    loc: SourceLocation | null)
  case TupleTypeAnnotation(
    elementTypes: GrowableArray<TypeAnnotation>,
    /**
     * The positions in `elementTypes` written `...T`: a tuple type to
     * splice in, or a type parameter bounded by `tuple`
     * (docs/design/row-types.md §3.3). Null when there are none.
     */
    spreadIndices: GrowableArray<i32> | null,
    loc: SourceLocation | null)
  /**
   * `inline T`: a value type held unboxed, in return position. The
   * modifier takes the whole union to its right (`inline A | B` is
   * `inline (A | B)`), and the checker decides whether `T` is something
   * that can be unboxed (docs/design/multi-return-values.md).
   * `ifPossible` is `inline? T`, on a type parameter: unboxed when the
   * argument can be, and the argument as it is otherwise.
   */
  case InlineTypeAnnotation(
    typeAnnotation: TypeAnnotation,
    ifPossible: boolean,
    loc: SourceLocation | null)
  case ThisTypeAnnotation(
    loc: SourceLocation | null)
}

// ============================================================================
// Import/Export Helpers
// ============================================================================

export final class ImportSpecifier(
  imported: Identifier,
  local: Identifier,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Template Elements
// ============================================================================

export final class TemplateElement(
  cooked: String,
  raw: String,
  tail: boolean,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Record & Map Entries
// ============================================================================

export final class PropertyAssignment(
  name: Identifier,
  value: Expression,
  loc: SourceLocation | null) extends Node

export final class SpreadElement(
  argument: Expression,
  loc: SourceLocation | null) extends Node

export final class MapEntry(
  key: Expression,
  value: Expression,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Pattern Helpers
// ============================================================================

export final class BindingProperty(
  name: Identifier,
  value: Node,
  loc: SourceLocation | null) extends Node

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

export final class MatchCase(
  pattern: Node,
  guard: Expression | null,
  body: Node,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Control Flow Helpers
// ============================================================================

export final class LetPatternCondition(
  pattern: Pattern,
  init: Expression,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Type Parameters
// ============================================================================

export final class TypeParameter(
  name: String,
  constraint: TypeAnnotation | null,
  defaultType: TypeAnnotation | null,
  isScoped: boolean,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Parameters
// ============================================================================

export final class Parameter(
  name: Identifier,
  pattern: Pattern | null,
  typeAnnotation: TypeAnnotation | null,
  optional: boolean,
  defaultValue: Expression | null,
  isThisParam: boolean,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Case Class & Sealed Variant Helpers
// ============================================================================

export final class CaseClassParam(
  name: Identifier,
  typeAnnotation: TypeAnnotation,
  mutability: String | null,
  defaultValue: Expression | null,
  loc: SourceLocation | null) extends Node

export final class SealedVariant(
  name: Identifier,
  params: GrowableArray<CaseClassParam> | null,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Class Members
// ============================================================================

export final class FieldDefinition(
  name: Node,
  typeAnnotation: TypeAnnotation | null,
  value: Expression | null,
  isFinal: boolean,
  isAbstract: boolean,
  isStatic: boolean,
  isDeclare: boolean,
  mutability: String | null,
  decorators: GrowableArray<Decorator>,
  setterName: Node | null,
  /**
   * `shared`: in a decorator body, one copy per host class rather than
   * one per decorated field (docs/design/decorators.md).
   */
  isShared: boolean,
  loc: SourceLocation | null) extends Node

export final class MethodDefinition(
  name: Node,
  typeParameters: GrowableArray<TypeParameter> | null,
  /**
   * An explicitly declared receiver — the `this: Own<this>` of a method that
   * consumes what it is called on. Null when the method takes the default
   * borrowing receiver, which is nearly every method.
   *
   * Kept out of `params` because it is not one: every method already has a
   * receiver, and putting it there would shift each argument's position for
   * codegen and for every arity check. See docs/design/ownership.md
   * §"Release consumes its receiver".
   */
  receiver: TypeAnnotation | null,
  params: GrowableArray<Parameter>,
  returnType: TypeAnnotation | null,
  body: Node | null,
  initializerList: GrowableArray<Node> | null,
  superInitializer: Node | null,
  isFinal: boolean,
  isAbstract: boolean,
  isStatic: boolean,
  isDeclare: boolean,
  isGenerator: boolean,
  isAsync: boolean,
  decorators: GrowableArray<Decorator>,
  isConstructor: boolean,
  /** `shared`: see FieldDefinition.isShared. */
  isShared: boolean,
  /** The `requires` and `ensures` clauses, in source order; null when there are none. */
  contracts: GrowableArray<ContractClause> | null,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Accessors
// ============================================================================

export final class AccessorDeclaration(
  name: Node,
  typeAnnotation: TypeAnnotation,
  getter: BlockStatement | null,
  setter: Node | null,
  isFinal: boolean,
  isStatic: boolean,
  decorators: GrowableArray<Decorator>,
  loc: SourceLocation | null) extends Node

export final class SetterInfo(
  param: Identifier,
  body: BlockStatement,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Initializer List Entries
// ============================================================================

export final class FieldInitializer(
  field: Identifier,
  value: Expression,
  loc: SourceLocation | null) extends Node

export final class SuperInitializer(
  args: GrowableArray<Expression>,
  constructorName: Node | null,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Interface Members
// ============================================================================

export final class MethodSignature(
  name: Node,
  typeParameters: GrowableArray<TypeParameter> | null,
  params: GrowableArray<Parameter>,
  returnType: TypeAnnotation | null,
  /** The `requires` and `ensures` clauses, in source order; null when there are none. */
  contracts: GrowableArray<ContractClause> | null,
  loc: SourceLocation | null) extends Node

export final class AccessorSignature(
  name: Identifier,
  typeAnnotation: TypeAnnotation,
  hasGetter: boolean,
  hasSetter: boolean,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Enum Members
// ============================================================================

export final class EnumMember(
  name: Identifier,
  initializer: Expression | null,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Error Handling Helpers
// ============================================================================

export final class CatchClause(
  param: Identifier | null,
  body: BlockStatement,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Property Signatures (for Record Type Annotations)
// ============================================================================

export final class PropertySignature(
  name: Identifier,
  typeAnnotation: TypeAnnotation,
  optional: boolean,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Decorators
// ============================================================================

/**
 * A decorator application: `@name`, `@a.b`, or `@name(args)`.
 *
 * `path` is the dotted name as written, one identifier per segment, and
 * `name` is the same path joined with dots — what the builtin checks
 * (`@intrinsic`, `@external`) compare against. `args` are the call's
 * arguments when the decorator is written as a call, else empty.
 */
export final class Decorator(
  name: String,
  path: GrowableArray<Identifier>,
  args: GrowableArray<Expression>,
  loc: SourceLocation | null) extends Node

// ============================================================================
// Contracts
// ============================================================================

export enum ContractKind {
  /** `requires (c)`: holds when the function is entered. */
  Requires,
  /** `ensures (c)`: holds when the function returns; `result` names the returned value. */
  Ensures,
  /** `invariant (c)`: holds each time a loop is about to test its condition. */
  Invariant,
}

/** The keyword a clause of `kind` is written with. */
export function contractKeyword(kind: ContractKind): String {
  return match (kind) {
    case ContractKind.Requires: 'requires'
    case ContractKind.Ensures: 'ensures'
    case ContractKind.Invariant: 'invariant'
  };
}

/**
 * Whether `callee` is the name `old`. Directly in an `ensures`
 * condition, `old(e)` is the value `e` had when the function was
 * entered, and not a call; the scope builder and the checker decide
 * where that is.
 */
export function isOldCallee(callee: Expression): boolean {
  return if (let Identifier {name} = callee) name == 'old' else false;
}

/**
 * One contract clause: `requires (c)` or `ensures (c)` between a
 * function's signature and its body, or `invariant (c)` between a loop's
 * header and its body. The keywords are contextual. See
 * docs/design/contracts.md.
 */
/** When a contract clause's condition is checked at run time. */
export enum ContractMode {
  /** An unmarked clause: checked on every call, in every build. */
  Checked,
  /**
   * `debug requires (c)`: checked in test and debug builds and left out
   * of the others, for a condition that costs more than the code it
   * guards.
   */
  Debug,
  /**
   * `static requires (c)`: never checked at run time. A specification
   * the compiler type-checks and a verifier can prove.
   */
  Static,
}

/** The modifier a clause of `mode` is written with, or '' for an unmarked one. */
export function contractModifier(mode: ContractMode): String {
  return match (mode) {
    case ContractMode.Checked: ''
    case ContractMode.Debug: 'debug'
    case ContractMode.Static: 'static'
  };
}

export final class ContractClause(
  kind: ContractKind,
  condition: Expression,
  mode: ContractMode,
  /** The clause as written, `requires (n > 0)`, for the failure's message. */
  text: String,
  loc: SourceLocation | null) extends Node

/** Whether `contracts` holds an `ensures` clause. */
export function hasEnsuresClause(contracts: GrowableArray<ContractClause> | null): boolean {
  if (contracts == null) { return false; }
  for (let clause in contracts) {
    if (clause.kind == ContractKind.Ensures) { return true; }
  }
  return false;
}

/**
 * The message of the error thrown when `clause` does not hold.
 * Reachability registers it as a string constant and lowering reads that
 * constant back, so both ask here.
 */
export function contractFailureMessage(clause: ContractClause): String {
  return `${clause.text} does not hold`;
}

/**
 * The decorator names the compiler itself defines. They are not names in
 * any scope, so the scope builder does not try to resolve them, and a
 * `decorator` declaration cannot take one of them over.
 */
export function isBuiltinDecoratorName(name: String): boolean {
  return name == 'intrinsic' || name == 'external' || name == 'pure';
}

/**
 * The string value of a decorator's `i`th argument, or null when there is
 * no such argument or it is not a string literal.
 */
export function decoratorStringArg(dec: Decorator, i: i32): String | null {
  if (i >= dec.args.length) {
    return null;
  }
  return if (let StringLiteral {value} = dec.args[i]) value else null;
}

// ============================================================================
// Symbol Property Names
// ============================================================================

export final class SymbolPropertyName(
  symbolRef: Expression,
  loc: SourceLocation | null) extends Node

export function getMemberPropertyName(isSymbolAccess: boolean, name: String): String {
  return if (isSymbolAccess) ":" + name else name;
}

/**
 * The key a member's name node spells, before any symbol is resolved.
 *
 * Correct for a name-keyed member, and a stand-in for a symbol-keyed one
 * whose symbol did not resolve — that failure is reported at the
 * declaration, so the value only has to be something consistent. The
 * real key for a symbol-keyed member carries the symbol's identity and
 * comes from `SemanticModel.memberKey`.
 */
export function syntacticMemberName(node: Node): String {
  return match (node) {
    case Identifier {name}: name
    case SymbolPropertyName {symbolRef}: ":" + match (symbolRef) {
      case Identifier {name}: name
      case MemberExpression {property}: property.name
      case _: "<symbol>"
    }
    case _: "<unknown>"
  };
}

/**
 * Whether a static field is really a `static symbol` declaration.
 *
 * An interface spells one as a `SymbolDeclaration`, but a class or mixin
 * body parses the same words into a static field annotated with the bare
 * name `symbol`. There is no `symbol` type to annotate a field with
 * otherwise, so the name is unambiguous.
 *
 * A symbol exists only at compile time, so such a field declares no member
 * and needs no cell: the checker registers it on the type's static
 * symbols, and everything that walks a body's fields skips it.
 */
export function isSymbolFieldDeclaration(field: FieldDefinition): boolean {
  if (!field.isStatic) { return false; }
  let ann = field.typeAnnotation;
  // `if (let ...)` against a null value traps rather than not matching
  // (#663), so null is ruled out first.
  if (ann == null) { return false; }
  if (let NamedTypeAnnotation {name, typeArguments} = ann as TypeAnnotation) {
    return name == "symbol" && typeArguments == null;
  }
  return false;
}

/**
 * Whether `inner` is an unparenthesized postfix receiver or callee of
 * `outer` in the same `#parseCall` chain. Every postfix node in an
 * unparenthesized chain starts at `callStart.start`, whereas `(a?.b).c`
 * starts the outer node at `(` and `a?.b` at `a`.
 */
export function samePostfixChain(outer: Expression, inner: Expression): boolean {
  let outerLoc = outer.loc;
  let innerLoc = inner.loc;
  return outerLoc != null && innerLoc != null && outerLoc.start == innerLoc.start;
}

/**
 * Whether `expr` is a method-call step `recv.m(args)` or `recv?.m(args)`
 * (as opposed to `(recv?.m)(args)` or `recv.cb?(args)`).
 */
export function isMethodCallStep(expr: CallExpression): boolean {
  return !expr.optional && expr.callee is MemberExpression &&
      samePostfixChain(expr, expr.callee);
}

/**
 * The immediate target expression one postfix step inward from `expr`, or
 * null when `expr` is not a postfix access or call.
 */
export function postfixStepTarget(expr: Expression): Expression | null {
  if (expr is MemberExpression) {
    return expr.object;
  }
  if (expr is IndexExpression) {
    return expr.object;
  }
  if (expr is CallExpression) {
    if (isMethodCallStep(expr)) {
      return (expr.callee as MemberExpression).object;
    }
    return expr.callee;
  }
  return null;
}

/** Whether the single postfix step at `expr` uses `?.`, `?[`, or `?(`. */
export function isOptionalPostfixStep(expr: Expression): boolean {
  if (expr is MemberExpression) {
    return expr.optional;
  }
  if (expr is IndexExpression) {
    return expr.optional;
  }
  if (expr is CallExpression) {
    if (isMethodCallStep(expr)) {
      return (expr.callee as MemberExpression).optional;
    }
    return expr.optional;
  }
  return false;
}

/**
 * Whether `expr`'s unparenthesized postfix chain contains at least one
 * optional step (`?.`, `?[`, `?(`).
 */
export function hasOptionalChainStep(expr: Expression): boolean {
  var cur = expr;
  while (true) {
    if (isOptionalPostfixStep(cur)) {
      return true;
    }
    let next = postfixStepTarget(cur);
    if (next == null || !samePostfixChain(cur, next)) {
      return false;
    }
    cur = next;
  }
}
VersionPublishedDependenciesApproved by
0.0.2-preview.1 2026-11-19