wit-parser 0.0.1-preview.1
A WIT (WebAssembly Interface Types) parser, resolver and component encoder
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)andjoinWitDocument(files): concatenates.witfiles in canonical name order and records where each file starts.WitDocument.locate(offset): maps a byte offset back to aWitLocation(file, 1-basedline, 1-basedcolumn).witDiagnostic(doc, error): formats aLexError,ParseError, orResolveErrorwith 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)andworldNames(ast): expands worldincludes and transitiveusedependencies.
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.
import {JsonBuilder} from 'zena:json';
import {Docs, TypeDef, UsePath, UseName, Id, Attribute, AttributeTag} from './parser.zena';
import {normalizeId} from './helpers.zena';
// ============================================================================
// Helper Types for JSON Output (Flat Schema matching wasm-tools)
// ============================================================================
export sealed class TypeRef {
case PrimitiveRef, IndexRef
static str(s: String): TypeRef {
return new PrimitiveRef(s);
}
static idx(i: i32): TypeRef {
return new IndexRef(i);
}
serialize(b: JsonBuilder): void {
match (this) {
case let PrimitiveRef {name}: { b.string(name); }
case let IndexRef {value}: { b.i32(value); }
}
}
isIndex(): boolean {
return !(this is PrimitiveRef);
}
indexValue(): i32 {
return match (this) {
case PrimitiveRef: -1
case let IndexRef {value}: value
};
}
strValue(): String {
return if (let PrimitiveRef {name} = this) name else "";
}
}
export final class PrimitiveRef(name: String) extends TypeRef
export final class IndexRef(value: i32) extends TypeRef
export sealed class TypeOwner {
case InterfaceOwner, WorldOwner
static fromInterface(index: i32): TypeOwner {
return new InterfaceOwner(index);
}
static fromWorld(index: i32): TypeOwner {
return new WorldOwner(index);
}
serialize(b: JsonBuilder): void {
b.beginObject();
match (this) {
case let InterfaceOwner {index}: { b.key("interface").i32(index); }
case let WorldOwner {index}: { b.key("world").i32(index); }
}
b.endObject();
}
isWorld(): boolean {
return !(this is InterfaceOwner);
}
}
export final class InterfaceOwner(index: i32) extends TypeOwner
export final class WorldOwner(index: i32) extends TypeOwner
export sealed class ScopeTypeElement {
case TypeDefElement, UseElement
static fromTd(td: TypeDef): ScopeTypeElement {
return new TypeDefElement(td);
}
static fromUse(path: UsePath, name: UseName, docs: Docs | null): ScopeTypeElement {
return new UseElement(path, name, docs);
}
isTypeDef(): boolean {
return this is TypeDefElement;
}
typeDef(): TypeDef | null {
return if (let TypeDefElement {def} = this) def else null;
}
usePath(): UsePath | null {
return match (this) {
case TypeDefElement: null
case let UseElement {path}: path
};
}
useName(): UseName | null {
return match (this) {
case TypeDefElement: null
case let UseElement {name}: name
};
}
docs(): Docs | null {
return match (this) {
case let TypeDefElement {def}: def.docs
case let UseElement {docs}: docs
};
}
}
export final class TypeDefElement(def: TypeDef) extends ScopeTypeElement
export final class UseElement(path: UsePath, name: UseName, docs: Docs | null) extends ScopeTypeElement
export class RecordField {
var name: String;
var typeRef: TypeRef;
new(name: String, typeRef: TypeRef) : name = name, typeRef = typeRef;
serialize(b: JsonBuilder): void {
b.beginObject();
b.key("name").string(this.name);
b.key("type");
this.typeRef.serialize(b);
b.endObject();
}
}
export class VariantCase {
var name: String;
var typeRef: TypeRef | null;
new(name: String, typeRef: TypeRef | null) : name = name, typeRef = typeRef;
serialize(b: JsonBuilder): void {
b.beginObject();
b.key("name").string(this.name);
b.key("type");
if (this.typeRef != null) {
(this.typeRef as TypeRef).serialize(b);
} else {
b.nullValue();
}
b.endObject();
}
}
export class EnumCase {
var name: String;
var docs: Docs | null;
new(name: String, docs: Docs | null) : name = name, docs = docs;
serialize(b: JsonBuilder): void {
b.beginObject();
b.key("name").string(this.name);
if (this.docs != null) {
let d = this.docs as Docs;
if (d.contents != null) {
b.key("docs").beginObject();
b.key("contents").string(d.contents as String);
b.endObject();
}
}
b.endObject();
}
}
export sealed class TypeKind {
case TypeAlias, ListKind, FixedLengthListKind, OptionKind, ResultKind
case RecordKind, TupleKind, FlagsKind, VariantKind, EnumKind, HandleKind
case MapKind, FutureKind, StreamKind, UnknownKind, ResourceKind
tag(): String {
return match (this) {
case TypeAlias: "type"
case ListKind: "list"
case FixedLengthListKind: "fixed-length-list"
case OptionKind: "option"
case ResultKind: "result"
case RecordKind: "record"
case TupleKind: "tuple"
case FlagsKind: "flags"
case VariantKind: "variant"
case EnumKind: "enum"
case HandleKind: "handle"
case MapKind: "map"
case FutureKind: "future"
case StreamKind: "stream"
case UnknownKind: "unknown"
case ResourceKind: "resource"
};
}
serialize(b: JsonBuilder): void {
match (this) {
case ResourceKind: {
b.string("resource");
}
case let TypeAlias {inner}: {
b.beginObject();
b.key("type");
inner.serialize(b);
b.endObject();
}
case let ListKind {inner}: {
b.beginObject();
b.key("list");
inner.serialize(b);
b.endObject();
}
case let FixedLengthListKind {inner, len}: {
b.beginObject();
b.key("fixed-length-list").beginArray();
inner.serialize(b);
b.i32(len);
b.endArray();
b.endObject();
}
case let OptionKind {inner}: {
b.beginObject();
b.key("option");
inner.serialize(b);
b.endObject();
}
case let ResultKind {ok, err}: {
b.beginObject();
b.key("result").beginObject();
b.key("ok");
if (ok != null) { ok.serialize(b); } else { b.nullValue(); }
b.key("err");
if (err != null) { err.serialize(b); } else { b.nullValue(); }
b.endObject();
b.endObject();
}
case let RecordKind {fields}: {
b.beginObject();
b.key("record").beginObject();
b.key("fields").beginArray();
for (let f in fields) {
f.serialize(b);
}
b.endArray();
b.endObject();
b.endObject();
}
case let TupleKind {types}: {
b.beginObject();
b.key("tuple").beginObject();
b.key("types").beginArray();
for (let t in types) {
t.serialize(b);
}
b.endArray();
b.endObject();
b.endObject();
}
case let FlagsKind {flags}: {
b.beginObject();
b.key("flags").beginObject();
b.key("flags").beginArray();
for (let f in flags) {
b.beginObject();
b.key("name").string(f);
b.endObject();
}
b.endArray();
b.endObject();
b.endObject();
}
case let VariantKind {cases}: {
b.beginObject();
b.key("variant").beginObject();
b.key("cases").beginArray();
for (let c in cases) {
c.serialize(b);
}
b.endArray();
b.endObject();
b.endObject();
}
case let EnumKind {cases}: {
b.beginObject();
b.key("enum").beginObject();
b.key("cases").beginArray();
for (let c in cases) {
c.serialize(b);
}
b.endArray();
b.endObject();
b.endObject();
}
case let HandleKind {borrowIndex, ownIndex}: {
b.beginObject();
b.key("handle").beginObject();
if (borrowIndex >= 0) {
b.key("borrow").i32(borrowIndex);
} else if (ownIndex >= 0) {
b.key("own").i32(ownIndex);
}
b.endObject();
b.endObject();
}
case let MapKind {key, value}: {
b.beginObject();
b.key("map").beginArray();
key.serialize(b);
value.serialize(b);
b.endArray();
b.endObject();
}
case let FutureKind {inner}: {
b.beginObject();
b.key("future");
if (inner != null) { inner.serialize(b); } else { b.nullValue(); }
b.endObject();
}
case let StreamKind {inner}: {
b.beginObject();
b.key("stream");
if (inner != null) { inner.serialize(b); } else { b.nullValue(); }
b.endObject();
}
case UnknownKind: {
b.beginObject();
b.key("unknown").beginObject().endObject();
b.endObject();
}
}
}
}
export final class TypeAlias(inner: TypeRef) extends TypeKind
export final class ListKind(inner: TypeRef) extends TypeKind
export final class FixedLengthListKind(inner: TypeRef, len: i32) extends TypeKind
export final class OptionKind(inner: TypeRef) extends TypeKind
export final class ResultKind(ok: TypeRef | null, err: TypeRef | null) extends TypeKind
export final class RecordKind(fields: Array<RecordField>) extends TypeKind
export final class TupleKind(types: Array<TypeRef>) extends TypeKind
export final class FlagsKind(flags: Array<String>) extends TypeKind
export final class VariantKind(cases: Array<VariantCase>) extends TypeKind
export final class EnumKind(cases: Array<EnumCase>) extends TypeKind
export final class HandleKind(borrowIndex: i32, ownIndex: i32) extends TypeKind
export final class MapKind(key: TypeRef, value: TypeRef) extends TypeKind
export final class FutureKind(inner: TypeRef | null) extends TypeKind
export final class StreamKind(inner: TypeRef | null) extends TypeKind
export final class UnknownKind extends TypeKind {}
export final class ResourceKind extends TypeKind {}
export function serializeStability(b: JsonBuilder, docs: Docs | null): void {
if (docs == null || docs.attributes == null) {
return;
}
let attrs = docs.attributes as GrowableArray<Attribute>;
var hasSince = false;
var sinceVer: String | null = null;
var hasDeprecated = false;
var depVer: String | null = null;
var hasUnstable = false;
var unstFeature: String | null = null;
for (let attr in attrs) {
if (attr.tag == AttributeTag.Since) {
hasSince = true;
sinceVer = attr.version;
} else if (attr.tag == AttributeTag.Deprecated) {
hasDeprecated = true;
depVer = attr.version;
} else if (attr.tag == AttributeTag.Unstable) {
hasUnstable = true;
unstFeature = (attr.feature as Id).name;
}
}
if (hasUnstable) {
b.key("stability").beginObject();
b.key("unstable").beginObject();
b.key("feature").string(unstFeature as String);
b.endObject();
b.endObject();
} else if (hasSince || hasDeprecated) {
b.key("stability").beginObject();
b.key("stable").beginObject();
if (hasSince) {
b.key("since").string(sinceVer as String);
}
if (hasDeprecated) {
b.key("deprecated").string(depVer as String);
}
b.endObject();
b.endObject();
}
}
export class TypeEntry {
var name: String | null;
var kind: TypeKind;
var owner: Option<TypeOwner>;
var docs: Docs | null;
new(name: String | null, kind: TypeKind, owner: Option<TypeOwner>, docs: Docs | null)
: name = name, kind = kind, owner = owner, docs = docs;
serialize(b: JsonBuilder): void {
b.beginObject();
if (this.name != null) {
b.key("name").string(this.name as String);
} else {
b.key("name").nullValue();
}
b.key("kind");
this.kind.serialize(b);
if (this.owner is Some<TypeOwner>) {
let o = (this.owner as Some<TypeOwner>).value;
b.key("owner");
o.serialize(b);
} else {
b.key("owner").nullValue();
}
if (this.docs != null) {
let d = this.docs as Docs;
if (d.contents != null) {
b.key("docs").beginObject();
b.key("contents").string(d.contents as String);
b.endObject();
}
}
serializeStability(b, this.docs);
b.endObject();
}
}
export class PackageEntry {
var name: String;
interfaces = new HashMap<String, i32>();
worlds = new HashMap<String, i32>();
new(name: String) : name = name;
serialize(b: JsonBuilder): void {
b.beginObject();
b.key("name").string(this.name);
b.key("interfaces").beginObject();
this.interfaces.forEach((name, idx) => {
b.key(name).i32(idx);
});
b.endObject();
b.key("worlds").beginObject();
this.worlds.forEach((name, idx) => {
b.key(name).i32(idx);
});
b.endObject();
b.endObject();
}
}
| Version | Published | Dependencies | Approved by |
|---|---|---|---|
| 0.0.1-preview.1 | 2026-11-19 | none |
|