wit-parser 0.0.1-preview.1

A WIT (WebAssembly Interface Types) parser, resolver and component encoder

Readme Files Dependencies Versions

wit-parser#

A WebAssembly Interface Types (WIT) parser, semantic resolver, .wit.json serializer, and component type encoder for Zena.

Installation#

zena pkg add zena-lang:wit-parser

Example#

import { parse } from 'zena-lang:wit-parser';
import { AstItemTag } from 'zena-lang:wit-parser/parser';

let source = `
package example:greeter@1.0.0;

interface greet {
  record greeting { text: string, formal: bool }
  hello: func(name: string) -> greeting;
}

interface farewell {
  use greet.{greeting};
  goodbye: func(name: string) -> greeting;
}

world greeter {
  export greet;
  export farewell;
}
`;

// Parses syntax and resolves names and cross-interface `use` references.
// Throws `ParseError` or `ResolveError` if the document is invalid.
let doc = parse(source);

var interfaces = 0;
var worlds = 0;
for (let item in doc.items) {
  if (item.tag == AstItemTag.Interface) {
    interfaces += 1;
  } else if (item.tag == AstItemTag.World) {
    worlds += 1;
  }
}

Libraries#

zena-lang:wit-parser#

The primary entry point for parsing, resolving, and serializing WIT source text.

Function Description
parse(source) Parses and resolves source into a validated Ast. Throws ParseError or ResolveError.
parseSyntax(source) Parses source without resolving names, for single-file syntax tooling such as formatters.
resolve(ast) Resolves names and validates an Ast in place.
toJson(ast, packageOrder?) Serializes a resolved Ast to the .wit.json format emitted by wasm-tools component wit --json.

zena-lang:wit-parser also re-exports Ast, ParseError, and ResolveError. Both error types carry a Span with byte offsets into the source text.

zena-lang:wit-parser/parser#

The AST node declarations (Ast, AstItem, AstItemTag, InterfaceDef, WorldDef, TypeDef, Type, NamedFunc, ResourceFunc, Use, Include, Docs, Attribute, PackageName, NestedPackage, and related types) and Parser.

zena-lang:wit-parser/document#

Utilities for assembling multi-file WIT directories into a single source document while tracking file boundaries for error reporting:

  • WitFile(name, source) and joinWitDocument(files): concatenates .wit files in canonical name order and records where each file starts.
  • WitDocument.locate(offset): maps a byte offset back to a WitLocation (file, 1-based line, 1-based column).
  • witDiagnostic(doc, error): formats a LexError, ParseError, or ResolveError with its filename, line, column, source line, and caret underline.
  • findInterface(ast, namespace, interfacePath): looks up an interface (pkg/iface) in a parsed document.

zena-lang:wit-parser/component-encoder#

Encodes a resolved WIT world into WebAssembly Component Model binary type and import sections:

  • encodeTypesOnlyComponent(ast, worldName): encodes the named world as a standalone types-only component binary.
  • ComponentTypeEncoder: emits component type, alias, import, and export sections and canonical ABI metadata (WitFuncMeta, WitFlatMeta).
  • expandedWorldItems(ast, world) and worldNames(ast): expands world includes and transitive use dependencies.

zena-lang:wit-parser/lexer and zena-lang:wit-parser/token#

Low-level tokenization: Lexer, LexError, Token, TokenType, and Span.

zena-lang:wit-parser/resolver#

Semantic validation and name resolution: Resolver and ResolveError.

13.7 KiB Raw
/**
 * AST types for the WIT parser.
 *
 * These types represent the resolved WIT document structure that matches
 * the JSON output format used by wasm-tools. The parser produces these
 * types after name resolution.
 *
 * Since Zena doesn't have sum types with payloads, we use a class-based
 * approach with discriminator patterns.
 */

import {Span} from './token.zena';

// ============================================================================
// Type References
// ============================================================================

/**
 * Primitive type names (matches JSON output format).
 */
export enum PrimitiveType {
  U8 = "u8",
  U16 = "u16",
  U32 = "u32",
  U64 = "u64",
  S8 = "s8",
  S16 = "s16",
  S32 = "s32",
  S64 = "s64",
  F32 = "f32",
  F64 = "f64",
  Char = "char",
  Bool = "bool",
  String = "string",
  ErrorContext = "error-context",
}

/**
 * A reference to a type - either a primitive type or an index into
 * the types array. Uses a nullable i32 where:
 * - null means "no type" (e.g., void result)
 * - negative values are impossible (indices are always >= 0)
 * - primitives are represented by their PrimitiveType enum
 *
 * We use two separate fields: one for primitive and one for index.
 */
export class TypeRef {
  // If primitive is not null, this is a primitive type
  var primitive: PrimitiveType | null = null;
  // If index >= 0 and primitive is null, this is a type index
  var index = -1;

  /**
   * Create a TypeRef for a primitive type.
   */
  static fromPrimitive(p: PrimitiveType): TypeRef {
    let ref = new TypeRef();
    ref.primitive = p;
    return ref;
  }

  /**
   * Create a TypeRef for a type index.
   */
  static fromIndex(i: i32): TypeRef {
    let ref = new TypeRef();
    ref.index = i;
    return ref;
  }

  /**
   * Check if this is a primitive type.
   */
  isPrimitive(): boolean {
    return this.primitive != null;
  }

  /**
   * Check if this is a type index reference.
   */
  isIndex(): boolean {
    return this.primitive == null && this.index >= 0;
  }
}

// ============================================================================
// Type Definitions
// ============================================================================

/**
 * A field in a record type.
 */
export class RecordField {
  name: String;
  type: TypeRef;
  var docs: String | null = null;

  new(name: String, type: TypeRef) : name = name, type = type;
}

/**
 * A case in a variant type.
 */
export class VariantCase {
  name: String;
  type: TypeRef | null;  // null if no payload
  var docs: String | null = null;

  new(name: String, type: TypeRef | null) : name = name, type = type;
}

/**
 * A flag in a flags type.
 */
export class Flag {
  name: String;
  var docs: String | null = null;

  new(name: String) : name = name;
}

/**
 * A case in an enum type.
 */
export class EnumCase {
  name: String;
  var docs: String | null = null;

  new(name: String) : name = name;
}

/**
 * Type kind discriminator.
 */
export enum TypeKindTag {
  Type,      // Alias to another type
  List,      // List of elements
  Option,    // Optional value
  Result,    // Result with ok/err
  Record,    // Record with fields
  Tuple,     // Tuple of types
  Flags,     // Bitset flags
  Variant,   // Variant with cases
  Enum,      // Enum (variant without payloads)
  Resource,  // Resource type
  Own,       // Own handle
  Borrow,    // Borrow handle
  Future,    // Future (async)
  Stream,    // Stream (async)
}

/**
 * The kind of a type definition.
 *
 * Uses a tagged class approach since Zena doesn't have sum types.
 */
export class TypeKind {
  tag: TypeKindTag;

  // For Type, List, Option, Future, Stream
  var innerType: TypeRef | null = null;

  // For Result
  var okType: TypeRef | null = null;
  var errType: TypeRef | null = null;

  // For Record
  var fields: Array<RecordField> | null = null;

  // For Tuple
  var types: Array<TypeRef> | null = null;

  // For Flags
  var flags: Array<Flag> | null = null;

  // For Variant
  var cases: Array<VariantCase> | null = null;

  // For Enum
  var enumCases: Array<EnumCase> | null = null;

  // For Own, Borrow
  var resourceIndex = -1;

  new(tag: TypeKindTag) : tag = tag;

  /**
   * Create a type alias kind.
   */
  static typeAlias(t: TypeRef): TypeKind {
    let k = new TypeKind(TypeKindTag.Type);
    k.innerType = t;
    return k;
  }

  /**
   * Create a list kind.
   */
  static list(element: TypeRef): TypeKind {
    let k = new TypeKind(TypeKindTag.List);
    k.innerType = element;
    return k;
  }

  /**
   * Create an option kind.
   */
  static option(inner: TypeRef): TypeKind {
    let k = new TypeKind(TypeKindTag.Option);
    k.innerType = inner;
    return k;
  }

  /**
   * Create a result kind.
   */
  static result(ok: TypeRef | null, err: TypeRef | null): TypeKind {
    let k = new TypeKind(TypeKindTag.Result);
    k.okType = ok;
    k.errType = err;
    return k;
  }

  /**
   * Create a record kind.
   */
  static record(fields: Array<RecordField>): TypeKind {
    let k = new TypeKind(TypeKindTag.Record);
    k.fields = fields;
    return k;
  }

  /**
   * Create a tuple kind.
   */
  static tuple(types: Array<TypeRef>): TypeKind {
    let k = new TypeKind(TypeKindTag.Tuple);
    k.types = types;
    return k;
  }

  /**
   * Create a flags kind.
   */
  static makeFlags(flagsArr: Array<Flag>): TypeKind {
    let k = new TypeKind(TypeKindTag.Flags);
    k.flags = flagsArr;
    return k;
  }

  /**
   * Create a variant kind.
   */
  static variant(cases: Array<VariantCase>): TypeKind {
    let k = new TypeKind(TypeKindTag.Variant);
    k.cases = cases;
    return k;
  }

  /**
   * Create an enum kind.
   */
  static enumKind(cases: Array<EnumCase>): TypeKind {
    let k = new TypeKind(TypeKindTag.Enum);
    k.enumCases = cases;
    return k;
  }

  /**
   * Create a resource kind.
   */
  static resource(): TypeKind {
    return new TypeKind(TypeKindTag.Resource);
  }

  /**
   * Create an own handle kind.
   */
  static own(resourceIdx: i32): TypeKind {
    let k = new TypeKind(TypeKindTag.Own);
    k.resourceIndex = resourceIdx;
    return k;
  }

  /**
   * Create a borrow handle kind.
   */
  static borrow(resourceIdx: i32): TypeKind {
    let k = new TypeKind(TypeKindTag.Borrow);
    k.resourceIndex = resourceIdx;
    return k;
  }

  /**
   * Create a future kind.
   */
  static future(inner: TypeRef | null): TypeKind {
    let k = new TypeKind(TypeKindTag.Future);
    k.innerType = inner;
    return k;
  }

  /**
   * Create a stream kind.
   */
  static stream(inner: TypeRef | null): TypeKind {
    let k = new TypeKind(TypeKindTag.Stream);
    k.innerType = inner;
    return k;
  }
}

/**
 * Type owner tag.
 */
export enum TypeOwnerTag {
  Interface,
  World,
  None,
}

/**
 * Owner of a type - either an interface or a world.
 */
export class TypeOwner {
  tag: TypeOwnerTag;
  var index = -1;  // Valid when tag is Interface or World

  new(tag: TypeOwnerTag) : tag = tag;

  static iface(idx: i32): TypeOwner {
    let o = new TypeOwner(TypeOwnerTag.Interface);
    o.index = idx;
    return o;
  }

  static world(idx: i32): TypeOwner {
    let o = new TypeOwner(TypeOwnerTag.World);
    o.index = idx;
    return o;
  }

  static none(): TypeOwner {
    return new TypeOwner(TypeOwnerTag.None);
  }
}

/**
 * Stability tag.
 */
export enum StabilityTag {
  Stable,
  Unstable,
}

/**
 * Stability annotation for gated features.
 */
export class Stability {
  tag: StabilityTag;
  // For Stable: version string
  var version: String | null = null;
  // For both: feature name (optional for stable)
  var feature: String | null = null;

  new(tag: StabilityTag) : tag = tag;

  static stable(version: String, feature: String | null): Stability {
    let s = new Stability(StabilityTag.Stable);
    s.version = version;
    s.feature = feature;
    return s;
  }

  static unstable(feature: String): Stability {
    let s = new Stability(StabilityTag.Unstable);
    s.feature = feature;
    return s;
  }
}

/**
 * A type definition in the resolved WIT document.
 */
export class TypeDef {
  var name: String | null;  // null for anonymous types
  var kind: TypeKind;
  var owner: TypeOwner;
  var docs: String | null = null;
  var stability: Stability | null = null;

  new(name: String | null, kind: TypeKind, owner: TypeOwner) : name = name, kind = kind, owner = owner;
}

// ============================================================================
// Functions
// ============================================================================

/**
 * A function parameter.
 */
export class Param {
  name: String;
  type: TypeRef;

  new(name: String, type: TypeRef) : name = name, type = type;
}

/**
 * Function kind tag.
 */
export enum FunctionKindTag {
  Freestanding,
  Method,
  Static,
  Constructor,
}

/**
 * The kind of function.
 */
export class FunctionKind {
  tag: FunctionKindTag;
  var resourceIndex = -1;  // Valid for Method, Static, Constructor

  new(tag: FunctionKindTag) : tag = tag;

  static freestanding(): FunctionKind {
    return new FunctionKind(FunctionKindTag.Freestanding);
  }

  static method(resourceIdx: i32): FunctionKind {
    let k = new FunctionKind(FunctionKindTag.Method);
    k.resourceIndex = resourceIdx;
    return k;
  }

  static staticFn(resourceIdx: i32): FunctionKind {
    let k = new FunctionKind(FunctionKindTag.Static);
    k.resourceIndex = resourceIdx;
    return k;
  }

  static ctor(resourceIdx: i32): FunctionKind {
    let k = new FunctionKind(FunctionKindTag.Constructor);
    k.resourceIndex = resourceIdx;
    return k;
  }
}

/**
 * A function definition.
 */
export class Function {
  name: String;
  kind: FunctionKind;
  params: Array<Param>;
  var result: TypeRef | null = null;  // null for no return value
  var docs: String | null = null;
  var stability: Stability | null = null;

  new(name: String, kind: FunctionKind, params: Array<Param>) : name = name, kind = kind, params = params;
}

// ============================================================================
// Interfaces
// ============================================================================

/**
 * An interface definition.
 */
export class Interface {
  name: String | null;  // null for inline/anonymous interfaces
  types = new HashMap<String, i32>();  // name -> type index
  functions = new HashMap<String, Function>();
  var package = -1;  // package index, -1 if not in a package
  var docs: String | null = null;
  var stability: Stability | null = null;

  new(name: String | null) : name = name;
}

// ============================================================================
// Worlds
// ============================================================================

/**
 * World item tag.
 */
export enum WorldItemTag {
  Interface,  // Import/export an interface
  Function,   // Import/export a function
  Type,       // Import/export a type
}

/**
 * An item that can be imported or exported in a world.
 */
export class WorldItem {
  tag: WorldItemTag;
  var interfaceId = -1;      // For Interface tag
  var func: Function | null = null;   // For Function tag
  var typeIndex = -1;        // For Type tag

  new(tag: WorldItemTag) : tag = tag;

  static iface(id: i32): WorldItem {
    let item = new WorldItem(WorldItemTag.Interface);
    item.interfaceId = id;
    return item;
  }

  static fn(f: Function): WorldItem {
    let item = new WorldItem(WorldItemTag.Function);
    item.func = f;
    return item;
  }

  static typeItem(idx: i32): WorldItem {
    let item = new WorldItem(WorldItemTag.Type);
    item.typeIndex = idx;
    return item;
  }
}

/**
 * A world definition.
 */
export class World {
  name: String;
  imports = new HashMap<String, WorldItem>();
  exports = new HashMap<String, WorldItem>();
  var package = -1;  // package index, -1 if not in a package
  var docs: String | null = null;
  var stability: Stability | null = null;

  new(name: String) : name = name;
}

// ============================================================================
// Packages
// ============================================================================

/**
 * A package identifier (namespace:name@version).
 */
export class PackageId {
  namespace: String;
  name: String;
  var version: String | null = null;

  new(namespace: String, name: String) : namespace = namespace, name = name;
}

/**
 * A package definition.
 */
export class Package {
  id: PackageId;
  interfaces = new HashMap<String, i32>();  // name -> interface index
  worlds = new HashMap<String, i32>();      // name -> world index
  var docs: String | null = null;

  new(id: PackageId) : id = id;
}

// ============================================================================
// Resolved Document
// ============================================================================

/**
 * A fully resolved WIT document.
 *
 * This is the output of parsing and resolution. It contains all types,
 * interfaces, worlds, and packages with all references resolved to indices.
 */
export class Resolve {
  types = new GrowableArray<TypeDef>();
  interfaces = new GrowableArray<Interface>();
  worlds = new GrowableArray<World>();
  packages = new GrowableArray<Package>();

  /**
   * Add a type and return its index.
   */
  addType(typeDef: TypeDef): i32 {
    let index = this.types.length;
    this.types.push(typeDef);
    return index;
  }

  /**
   * Add an interface and return its index.
   */
  addInterface(iface: Interface): i32 {
    let index = this.interfaces.length;
    this.interfaces.push(iface);
    return index;
  }

  /**
   * Add a world and return its index.
   */
  addWorld(world: World): i32 {
    let index = this.worlds.length;
    this.worlds.push(world);
    return index;
  }

  /**
   * Add a package and return its index.
   */
  addPackage(pkg: Package): i32 {
    let index = this.packages.length;
    this.packages.push(pkg);
    return index;
  }
}

// Note: All classes and enums above should have 'export' keyword added
// to make them accessible from other modules.
none
VersionPublishedDependenciesApproved by
0.0.1-preview.1 2026-11-19 none