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.

107.5 KiB Raw
/**
 * WIT AST to JSON Serializer
 * 
 * Test utility for serializing parsed WIT AST to the JSON format
 * used by the wit-parser test suite (matching wasm-tools output).
 */

import {JsonBuilder} from 'zena:json';
import { HashSet } from 'zena:collections';
import {Ast, AstItem, AstItemTag, PackageName, NestedPackage, Id, Use, UseName, UsePath, UsePathTag, Include, IncludeName, ToplevelUse} from './parser.zena';
import {InterfaceDef, InterfaceItem, InterfaceItemTag} from './parser.zena';
import {WorldDef, WorldItem, WorldItemTag, ExternKind, ExternKindTag, Import, Export} from './parser.zena';
import {TypeDef, TypeDefTag, Type, TypeTag, NamedFunc, Func, Param, Field} from './parser.zena';
import {Case, EnumCaseDef, FlagDef, ResourceFunc, ResourceFuncTag, Docs, Attribute, AttributeTag} from './parser.zena';
import {normalizeId, compareStrings, isPurelyNumeric, stringToInt, getPreIdentifiers, compareVersions, formatPackageName, comparePackageNames, comparePackageNameStrings, InterfaceNameRef, parseInterfaceName, PackageNameRef, parsePackageName} from './helpers.zena';
import {TypeRef, PrimitiveRef, IndexRef, TypeOwner, InterfaceOwner, WorldOwner, ScopeTypeElement, TypeDefElement, UseElement, RecordField, VariantCase, EnumCase, TypeEntry, TypeKind, TypeAlias, ListKind, FixedLengthListKind, OptionKind, ResultKind, RecordKind, TupleKind, FlagsKind, VariantKind, EnumKind, HandleKind, MapKind, FutureKind, StreamKind, UnknownKind, ResourceKind, PackageEntry, serializeStability} from './ast-json-types.zena';

function isExcluded(docs: Docs | null, pkgName: PackageName | null): boolean {
  if (docs == null || docs.attributes == null) {
    return false;
  }
  let attrs = docs.attributes as GrowableArray<Attribute>;
  var hasUnstable = false;
  var unstableActive = false;
  var hasSince = false;
  var sincePassed = false;
  var hasStability = false;
  
  for (let attr in attrs) {
    if (attr.tag == AttributeTag.Unstable) {
      hasStability = true;
      hasUnstable = true;
      let featureName = (attr.feature as Id).name;
      if (featureName == "active") {
        unstableActive = true;
      }
    } else if (attr.tag == AttributeTag.Since) {
      hasStability = true;
      hasSince = true;
      if (pkgName != null && pkgName.version != null) {
        let pkgVer = pkgName.version as String;
        let sinceVer = attr.version as String;
        if (compareVersions(pkgVer, sinceVer) >= 0) {
          sincePassed = true;
        }
      } else {
        sincePassed = true;
      }
    } else if (attr.tag == AttributeTag.Deprecated) {
      hasStability = true;
    }
  }
  
  if (hasUnstable && !unstableActive) {
    return true;
  }
  
  if (hasStability) {
    if (unstableActive) {
      return false;
    }
    if (hasSince) {
      return !sincePassed;
    }
    return true;
  }
  
  return false;
}

function filterInterfaceItems(iface: InterfaceDef, pkgName: PackageName | null) {
  let filtered = new GrowableArray<InterfaceItem>();
  for (let item in iface.items) {
    var keep = true;
    if (item.tag == InterfaceItemTag.TypeDef) {
      let td = item.typeDef as TypeDef;
      if (isExcluded(td.docs, pkgName)) {
        keep = false;
      }
    } else if (item.tag == InterfaceItemTag.Func) {
      let func = item.func as NamedFunc;
      if (isExcluded(func.docs, pkgName)) {
        keep = false;
      }
    } else if (item.tag == InterfaceItemTag.Use) {
      let u = item.use as Use;
      if (isExcluded(u.docs, pkgName)) {
        keep = false;
      }
    }
    if (keep) {
      filtered.push(item);
    }
  }
  iface.items = filtered;
}

function filterWorldItems(world: WorldDef, pkgName: PackageName | null) {
  let filtered = new GrowableArray<WorldItem>();
  for (let item in world.items) {
    var keep = true;
    if (item.tag == WorldItemTag.Import) {
      let imp = item.importItem as Import;
      if (isExcluded(imp.docs, pkgName)) {
        keep = false;
      }
    } else if (item.tag == WorldItemTag.Export) {
      let exp = item.exportItem as Export;
      if (isExcluded(exp.docs, pkgName)) {
        keep = false;
      }
    } else if (item.tag == WorldItemTag.Use) {
      let u = item.use as Use;
      if (isExcluded(u.docs, pkgName)) {
        keep = false;
      }
    } else if (item.tag == WorldItemTag.TypeDef) {
      let td = item.typeDef as TypeDef;
      if (isExcluded(td.docs, pkgName)) {
        keep = false;
      }
    } else if (item.tag == WorldItemTag.Include) {
      let inc = item.include as Include;
      if (isExcluded(inc.docs, pkgName)) {
        keep = false;
      }
    }
    if (keep) {
      filtered.push(item);
    }
  }
  world.items = filtered;
}

function filterGatedItems(ast: Ast) {
  let filteredItems = new GrowableArray<AstItem>();
  for (let item in ast.items) {
    var keep = true;
    if (item.tag == AstItemTag.Interface) {
      let iface = item.interfaceDef as InterfaceDef;
      if (isExcluded(iface.docs, ast.packageName)) {
        keep = false;
      } else {
        filterInterfaceItems(iface, ast.packageName);
      }
    } else if (item.tag == AstItemTag.World) {
      let world = item.worldDef as WorldDef;
      if (isExcluded(world.docs, ast.packageName)) {
        keep = false;
      } else {
        filterWorldItems(world, ast.packageName);
      }
    }
    if (keep) {
      filteredItems.push(item);
    }
  }
  ast.items = filteredItems;
  
  for (let np in ast.nestedPackages) {
    let npItems = new GrowableArray<AstItem>();
    for (let item in np.items) {
      var keep = true;
      if (item.tag == AstItemTag.Interface) {
        let iface = item.interfaceDef as InterfaceDef;
        if (isExcluded(iface.docs, np.name)) {
          keep = false;
        } else {
          filterInterfaceItems(iface, np.name);
        }
      } else if (item.tag == AstItemTag.World) {
        let world = item.worldDef as WorldDef;
        if (isExcluded(world.docs, np.name)) {
          keep = false;
        } else {
          filterWorldItems(world, np.name);
        }
      }
      if (keep) {
        npItems.push(item);
      }
    }
    np.items = npItems;
  }
}

// ============================================================================
// Helper Classes
// ============================================================================

/**
 * Context that tracks registered packages, interfaces, worlds, and types,
 * along with their resolved indices and aliases during JSON serialization.
 */
class SerializeContext {
  var interfaces = new GrowableArray<InterfaceDef>();
  var worlds = new GrowableArray<WorldDef>();
  types = new GrowableArray<TypeEntry>();
  packages = new GrowableArray<PackageEntry>();
  var interfaceIndices = new HashMap<String, i32>();
  var worldIndices = new HashMap<String, i32>();
  var typeIndices = new HashMap<String, i32>();
  // Maps to track borrow/own types by resource index
  var borrowTypeIndices = new HashMap<i32, i32>();
  var ownTypeIndices = new HashMap<i32, i32>();
  // Map to track complex anonymous types by canonical key
  var anonTypeIndices = new HashMap<String, i32>();
  // Track which type indices are resources (for bare resource name -> own<resource> conversion)
  var resourceTypeIndices = new HashMap<i32, i32>();
  // Map to track top-level use aliases by package key (pkgKey/aliasName -> resolvedName)
  var useAliases = new HashMap<String, String>();
  currentPackageIndex = 0;
  var currentInterfaceName: String | null = null;
  var currentWorldName: String | null = null;
  var currentInterfacePackageIndex = -1;
  var currentWorldPackageIndex = -1;

  resolveInterfaceAlias(pkgName: String, name: String): String {
    var cur = name;
    let visited = new HashSet<String>();
    while (true) {
      let key = `${pkgName}/${cur}`;
      if (!visited.add(key)) {
        throw new Error("Circular dependency in interface alias resolution: " + name);
      }
      if (let (true, resolved) = this.useAliases.get(key)) {
        cur = resolved;
      } else {
        break;
      }
    }
    return cur;
  }

  registerInterface(iface: InterfaceDef): i32 {
    let index = this.interfaces.length;
    this.interfaces.push(iface);
    this.interfaceIndices[iface.name.name] = index;
    return index;
  }

  registerWorld(world: WorldDef): i32 {
    let index = this.worlds.length;
    this.worlds.push(world);
    this.worldIndices[world.name.name] = index;
    return index;
  }

  registerType(entry: TypeEntry): i32 {
    let index = this.types.length;
    this.types.push(entry);
    if (entry.name != null) {
      this.typeIndices[entry.name as String] = index;
    }
    return index;
  }

  isResourceType(idx: i32): boolean {
    if (this.resourceTypeIndices.has(idx)) {
      return true;
    }
    if (idx >= 0 && idx < this.types.length) {
      let t = this.types[idx];
      if (t.kind is TypeAlias) {
        let alias = t.kind as TypeAlias;
        if (alias.inner.isIndex()) {
          return this.isResourceType(alias.inner.indexValue());
        }
      }
    }
    return false;
  }
  
  /** Get or create an anonymous type with the given key. */
  getOrCreateAnonType(key: String, kind: TypeKind): i32 {
    if (let (true, idx) = this.anonTypeIndices.get(key)) {
      return idx;
    }
    let entry = new TypeEntry(null, kind, none, null);
    let idx = this.registerType(entry);
    this.anonTypeIndices[key] = idx;
    return idx;
  }
  
  /** Get or create a borrow<resource> type for the given resource index. */
  getBorrowType(resourceIdx: i32): i32 {
    if (let (true, idx) = this.borrowTypeIndices.get(resourceIdx)) {
      return idx;
    }
    // Create new borrow type
    let kind = new HandleKind(resourceIdx, -1);
    
    let docs: Docs | null = if (resourceIdx >= 0 && resourceIdx < this.types.length) {
      this.types[resourceIdx].docs
    } else {
      null
    };
    
    let entry = new TypeEntry(null, kind, none, docs);
    let idx = this.registerType(entry);
    this.borrowTypeIndices[resourceIdx] = idx;
    return idx;
  }
  
  /** Get or create an own<resource> type for the given resource index. */
  getOwnType(resourceIdx: i32): i32 {
    if (let (true, idx) = this.ownTypeIndices.get(resourceIdx)) {
      return idx;
    }
    // Create new own type
    let kind = new HandleKind(-1, resourceIdx);
    let entry = new TypeEntry(null, kind, none, null);
    let idx = this.registerType(entry);
    this.ownTypeIndices[resourceIdx] = idx;
    return idx;
  }

  /** 
   * Get type reference for a function param or return type.
   * Handles bare resource names (converts them to own<resource>).
   */
  getParamTypeRef(t: Type): TypeRef {
    return this.getTypeRefEx(t, true);
  }

  /** Get a type reference: primitive as string, complex as index. */
  getTypeRef(t: Type): TypeRef {
    return this.getTypeRefEx(t, true);
  }

  getTypeRefEx(t: Type, resolveResourceAsOwn: boolean): TypeRef {
    return match (t.tag) {
      case TypeTag.U8: TypeRef.str("u8")
      case TypeTag.U16: TypeRef.str("u16")
      case TypeTag.U32: TypeRef.str("u32")
      case TypeTag.U64: TypeRef.str("u64")
      case TypeTag.S8: TypeRef.str("s8")
      case TypeTag.S16: TypeRef.str("s16")
      case TypeTag.S32: TypeRef.str("s32")
      case TypeTag.S64: TypeRef.str("s64")
      case TypeTag.F32: TypeRef.str("f32")
      case TypeTag.F64: TypeRef.str("f64")
      case TypeTag.Char: TypeRef.str("char")
      case TypeTag.Bool: TypeRef.str("bool")
      case TypeTag.String: TypeRef.str("string")
      case TypeTag.ErrorContext: TypeRef.str("error-context")
      case TypeTag.Name: {
        let id = t.name as Id;
        let name = normalizeId(id.name);
        
        var foundIdx = -1;
        if (this.currentInterfaceName != null) {
          let key = `interface:${this.currentInterfaceName as String}/${name}`;
          if (let (true, idx) = this.typeIndices.get(key)) {
            foundIdx = idx;
          }
        }
        if (foundIdx < 0 && this.currentWorldName != null) {
          let key = `world:${this.currentWorldName as String}/${name}`;
          if (let (true, idx) = this.typeIndices.get(key)) {
            foundIdx = idx;
          }
        }
        if (foundIdx < 0) {
          if (let (true, idx) = this.typeIndices.get(name)) {
            foundIdx = idx;
          }
        }
        
        // Check if it's a user-defined type
        if (foundIdx >= 0) {
          if (resolveResourceAsOwn && this.isResourceType(foundIdx)) {
            TypeRef.idx(this.getOwnType(foundIdx))
          } else {
            TypeRef.idx(foundIdx)
          }
        } else {
          TypeRef.str(name)
        }
      }
      case _: {
        // Complex type - register and return index
        let idx = this.registerAnonymousTypeEx(t, resolveResourceAsOwn);
        TypeRef.idx(idx)
      }
    };
  }
  
  /** Get canonical key for a TypeRef. */
  typeRefToKey(ref: TypeRef): String {
    if (ref.isIndex()) {
      return "#" + i32ToString(ref.indexValue());
    } else {
      return ref.strValue();
    }
  }

  /** Register an anonymous complex type and return its index. */
  registerAnonymousType(t: Type): i32 {
    return this.registerAnonymousTypeEx(t, true);
  }

  registerAnonymousTypeEx(t: Type, resolveResourceAsOwn: boolean): i32 {
    return match (t.tag) {
      case TypeTag.Tuple: {
        let types = t.types as GrowableArray<Type>;
        let refs = new GrowableArray<TypeRef>();
        var keyParts = "tuple:";
        for (var idx = 0; idx < types.length; idx += 1) {
          let ref = this.getTypeRefEx(types[idx], resolveResourceAsOwn);
          refs.push(ref);
          if (idx > 0) { keyParts = keyParts + ","; }
          keyParts = keyParts + this.typeRefToKey(ref);
        }
        let kind = new TupleKind(refs);
        this.getOrCreateAnonType(keyParts, kind)
      }
      case TypeTag.Option: {
        let innerRef = this.getTypeRefEx(t.inner as Type, resolveResourceAsOwn);
        let key = "option:" + this.typeRefToKey(innerRef);
        let kind = new OptionKind(innerRef);
        this.getOrCreateAnonType(key, kind)
      }
      case TypeTag.Result: {
        var key = "result:";
        let ok = if (t.okType != null) {
          let okRef = this.getTypeRefEx(t.okType as Type, resolveResourceAsOwn);
          key = key + this.typeRefToKey(okRef);
          okRef
        } else {
          null
        };
        key = key + ",";
        let err = if (t.errType != null) {
          let errRef = this.getTypeRefEx(t.errType as Type, resolveResourceAsOwn);
          key = key + this.typeRefToKey(errRef);
          errRef
        } else {
          null
        };
        let kind = new ResultKind(ok, err);
        this.getOrCreateAnonType(key, kind)
      }
      case TypeTag.List: {
        let innerRef = this.getTypeRefEx(t.inner as Type, resolveResourceAsOwn);
        if (t.fixedLength >= 0) {
          let key = `fixed-length-list:${this.typeRefToKey(innerRef)}:${i32ToString(t.fixedLength)}`;
          let kind = new FixedLengthListKind(innerRef, t.fixedLength);
          this.getOrCreateAnonType(key, kind)
        } else {
          let key = "list:" + this.typeRefToKey(innerRef);
          let kind = new ListKind(innerRef);
          this.getOrCreateAnonType(key, kind)
        }
      }
      case TypeTag.Future: {
        var key = "future:";
        let inner = if (t.inner != null) {
          let innerRef = this.getTypeRefEx(t.inner as Type, resolveResourceAsOwn);
          key = key + this.typeRefToKey(innerRef);
          innerRef
        } else {
          null
        };
        let kind = new FutureKind(inner);
        this.getOrCreateAnonType(key, kind)
      }
      case TypeTag.Stream: {
        var key = "stream:";
        let inner = if (t.inner != null) {
          let innerRef = this.getTypeRefEx(t.inner as Type, resolveResourceAsOwn);
          key = key + this.typeRefToKey(innerRef);
          innerRef
        } else {
          null
        };
        let kind = new StreamKind(inner);
        this.getOrCreateAnonType(key, kind)
      }
      case TypeTag.Own: {
        // Get the inner type index
        let innerRef = this.getTypeRefEx(t.inner as Type, false);
        var resourceIdx = -1;
        if (innerRef.isIndex()) {
          resourceIdx = innerRef.indexValue();
        } else {
          // Named resource - look up in typeIndices
          if (let (true, idx) = this.typeIndices.get(innerRef.strValue())) {
            resourceIdx = idx;
          }
        }
        if (resourceIdx >= 0) {
          // Use getOwnType to avoid duplicates
          this.getOwnType(resourceIdx)
        } else {
          // Fallback if resource not found
          let kind = new HandleKind(-1, resourceIdx);
          let entry = new TypeEntry(null, kind, none, null);
          this.registerType(entry)
        }
      }
      case TypeTag.Borrow: {
        // Get the inner type index
        let innerRef = this.getTypeRefEx(t.inner as Type, false);
        var resourceIdx = -1;
        if (innerRef.isIndex()) {
          resourceIdx = innerRef.indexValue();
        } else {
          // Named resource - look up in typeIndices
          if (let (true, idx) = this.typeIndices.get(innerRef.strValue())) {
            resourceIdx = idx;
          }
        }
        if (resourceIdx >= 0) {
          // Use getBorrowType to avoid duplicates
          this.getBorrowType(resourceIdx)
        } else {
          // Fallback if resource not found
          let kind = new HandleKind(resourceIdx, -1);
          let entry = new TypeEntry(null, kind, none, null);
          this.registerType(entry)
        }
      }
      case TypeTag.Map: {
        let keyRef = this.getTypeRefEx(t.keyType as Type, resolveResourceAsOwn);
        let valRef = this.getTypeRefEx(t.valueType as Type, resolveResourceAsOwn);
        let key = `map:${this.typeRefToKey(keyRef)}:${this.typeRefToKey(valRef)}`;
        let kind = new MapKind(keyRef, valRef);
        this.getOrCreateAnonType(key, kind)
      }
      case _: {
        // Unknown type - should not reach here
        let kind = new UnknownKind();
        let entry = new TypeEntry(null, kind, none, null);
        this.registerType(entry)
      }
    };
  }
}

// ============================================================================
// Helper Functions (defined before use)
// ============================================================================

function getUsePathInterfaceName(path: UsePath) {
  if (path.tag == UsePathTag.Id) {
    return normalizeId((path.id as Id).name);
  }
  let pkg = path.packageId as PackageName;
  let name = (path.name as Id).name;
  var pkgName = `${normalizeId(pkg.namespace.name)}:${normalizeId(pkg.name.name)}`;
  if (pkg.version != null) {
    pkgName = `${pkgName}@${pkg.version as String}`;
  }
  return `${pkgName}/${normalizeId(name)}`;
}



function isStabilityEqual(d1: Docs | null, d2: Docs | null): boolean {
  if (d1 == null && d2 == null) return true;
  if (d1 == null || d2 == null) return false;
  if (d1.attributes == null && d2.attributes == null) return true;
  if (d1.attributes == null || d2.attributes == null) return false;
  let attrs1 = d1.attributes as GrowableArray<Attribute>;
  let attrs2 = d2.attributes as GrowableArray<Attribute>;
  if (attrs1.length != attrs2.length) return false;
  
  for (var i = 0; i < attrs1.length; i += 1) {
    let a1 = attrs1[i];
    let a2 = attrs2[i];
    if (a1.tag != a2.tag) return false;
    
    // Only omit since/stable attributes
    if (a1.tag != AttributeTag.Since) return false;
    
    if (a1.version != a2.version) return false;
  }
  return true;
}

function resolveInterfaceIndex(ctx: SerializeContext, name: String): i32 {
  if (let (true, sIdx) = ctx.interfaceIndices.get(name)) {
    return sIdx;
  }
  
  let parsed = parseInterfaceName(name);
  if (parsed == null) {
    return -1;
  }
  
  // If the lookup name already has a version, we don't try to resolve it to an unversioned match
  if (parsed.version != null) {
    return -1;
  }
  
  for (let pkg in ctx.packages) {
    let pkgRef = parsePackageName(pkg.name);
    if (pkgRef.packageName == parsed.packageName) {
      let lookupKey = `${pkg.name}/${parsed.interfaceName}`;
      if (let (true, sIdx) = ctx.interfaceIndices.get(lookupKey)) {
        return sIdx;
      }
    }
  }
  
  return -1;
}

function resolveInterfaceName(ctx: SerializeContext, pkgName: String, path: UsePath) {
  let name = getUsePathInterfaceName(path);
  if (path.tag == UsePathTag.Id) {
    return ctx.resolveInterfaceAlias(pkgName, name);
  }
  return name;
}

function resolveInterfaceNameAndIndex(ctx: SerializeContext, itemPkgName: String, path: UsePath) {
  let resolved = resolveInterfaceName(ctx, itemPkgName, path);
  if (resolved.contains("/")) {
    return resolveInterfaceIndex(ctx, resolved);
  }
  return resolveInterfaceIndex(ctx, `${itemPkgName}/${resolved}`);
}

function findWorldItemDocs(ctx: SerializeContext, world: WorldDef, ifaceIdx: i32, isImport: boolean, items: Array<WorldItem>): Docs | null {
  let pkgName = ctx.packages[world.packageIndex].name;
  
  var combinedDocs: Docs | null = null;
  var hasMatch = false;
  var hasExplicitDocs = false;
  
  // Compute if the interface is purely included (only imported via includes with no direct references)
  var isPurelyIncluded = true;
  for (let item in items) {
    let itemPkgName = if (item.packageIndex >= 0) ctx.packages[item.packageIndex].name else pkgName;
    if (item.tag == WorldItemTag.Import || item.tag == WorldItemTag.Use) {
      var curIdx = -1;
      if (item.tag == WorldItemTag.Import) {
        let imp = item.importItem as Import;
        if (imp.kind.tag == ExternKindTag.Interface) {
          let name = normalizeId((imp.kind.name as Id).name);
          let inlineName = "[import]" + name;
          if (itemPkgName.length > 0) {
            let lookupKey = `${itemPkgName}/inline/${inlineName}`;
            curIdx = resolveInterfaceIndex(ctx, lookupKey);
          }
          if (curIdx < 0) {
            curIdx = resolveInterfaceIndex(ctx, inlineName);
          }
          if (curIdx < 0 && itemPkgName.length > 0) {
            let lookupKey = `${itemPkgName}/${name}`;
            curIdx = resolveInterfaceIndex(ctx, lookupKey);
          }
          if (curIdx < 0) {
            curIdx = resolveInterfaceIndex(ctx, name);
          }
        } else if (imp.kind.tag == ExternKindTag.Path) {
          curIdx = resolveInterfaceNameAndIndex(ctx, itemPkgName, imp.kind.path as UsePath);
        }
      } else {
        let u = item.use as Use;
        curIdx = resolveInterfaceNameAndIndex(ctx, itemPkgName, u.from);
      }
      
      if (curIdx == ifaceIdx && !item.isIncluded) {
        isPurelyIncluded = false;
      }
    }
  }
  
  // Pass 1: Direct imports / exports, and included Use statements (which act as implicit interface imports)
  for (let item in items) {
    let itemPkgName = if (item.packageIndex >= 0) ctx.packages[item.packageIndex].name else pkgName;
    if (isImport && (item.tag == WorldItemTag.Import || (item.tag == WorldItemTag.Use && item.isIncluded))) {
      var curIdx = -1;
      var docs: Docs | null = null;
      if (item.tag == WorldItemTag.Import) {
        let imp = item.importItem as Import;
        docs = imp.docs;
        if (imp.kind.tag == ExternKindTag.Interface) {
          let name = normalizeId((imp.kind.name as Id).name);
          let inlineName = "[import]" + name;
          if (itemPkgName.length > 0) {
            let lookupKey = `${itemPkgName}/inline/${inlineName}`;
            curIdx = resolveInterfaceIndex(ctx, lookupKey);
          }
          if (curIdx < 0) {
            curIdx = resolveInterfaceIndex(ctx, inlineName);
          }
          if (curIdx < 0 && itemPkgName.length > 0) {
            let lookupKey = `${itemPkgName}/${name}`;
            curIdx = resolveInterfaceIndex(ctx, lookupKey);
          }
          if (curIdx < 0) {
            curIdx = resolveInterfaceIndex(ctx, name);
          }
        } else if (imp.kind.tag == ExternKindTag.Path) {
          curIdx = resolveInterfaceNameAndIndex(ctx, itemPkgName, imp.kind.path as UsePath);
        }
      } else {
        let u = item.use as Use;
        docs = item.inheritedDocs;
        curIdx = resolveInterfaceNameAndIndex(ctx, itemPkgName, u.from);
      }
      
      if (curIdx == ifaceIdx) {
        hasMatch = true;
        combinedDocs = mergeDocs(combinedDocs, docs);
        if (item.isExplicit) {
          hasExplicitDocs = true;
        }
      }
    } else if (!isImport && item.tag == WorldItemTag.Export) {
      let exp = item.exportItem as Export;
      var curIdx = -1;
      let docs: Docs | null = exp.docs;
      if (exp.kind.tag == ExternKindTag.Interface) {
        let name = normalizeId((exp.kind.name as Id).name);
        let inlineName = "[export]" + name;
        if (itemPkgName.length > 0) {
          let lookupKey = `${itemPkgName}/inline/${inlineName}`;
          curIdx = resolveInterfaceIndex(ctx, lookupKey);
        }
        if (curIdx < 0) {
          curIdx = resolveInterfaceIndex(ctx, inlineName);
        }
        if (curIdx < 0 && itemPkgName.length > 0) {
          let lookupKey = `${itemPkgName}/${name}`;
          curIdx = resolveInterfaceIndex(ctx, lookupKey);
        }
        if (curIdx < 0) {
          curIdx = resolveInterfaceIndex(ctx, name);
        }
      } else if (exp.kind.tag == ExternKindTag.Path) {
        curIdx = resolveInterfaceNameAndIndex(ctx, itemPkgName, exp.kind.path as UsePath);
      }
      
      if (curIdx == ifaceIdx) {
        hasMatch = true;
        combinedDocs = mergeDocs(combinedDocs, docs);
        if (item.isExplicit) {
          hasExplicitDocs = true;
        }
      }
    }
  }
  
  if (hasMatch) {
    let iface = ctx.interfaces[ifaceIdx];
    let isForeign = iface.packageIndex != world.packageIndex;
    
    if (!hasExplicitDocs || isForeign) {
      let ifaceDocs = iface.docs;
      if (ifaceDocs != null && isStabilityEqual(combinedDocs, ifaceDocs)) {
        return null;
      }
      
      let worldDocs = world.docs;
      if (worldDocs != null && isStabilityEqual(combinedDocs, worldDocs)) {
        return null;
      }
    }
    
    if (!hasExplicitDocs) {
      var isUnstable = false;
      if (combinedDocs != null && combinedDocs.attributes != null) {
        let attrs = combinedDocs.attributes as GrowableArray<Attribute>;
        for (let attr in attrs) {
          if (attr.tag == AttributeTag.Unstable) {
            isUnstable = true;
          }
        }
      }
      
      if (!isUnstable) {
        return null;
      }
    }
    return combinedDocs;
  }
  
  // Pass 2: Local type imports (direct/explicit Use statements) that act as implicit interface imports
  if (isImport) {
    for (let item in items) {
      let itemPkgName = if (item.packageIndex >= 0) ctx.packages[item.packageIndex].name else pkgName;
      if (item.tag == WorldItemTag.Use) {
        let u = item.use as Use;
        let name = getUsePathInterfaceName(u.from);
        var curIdx = -1;
        if (itemPkgName.length > 0) {
          let lookupKey = `${itemPkgName}/${name}`;
          if (let (true, sIdx) = ctx.interfaceIndices.get(lookupKey)) { curIdx = sIdx; }
        }
        if (curIdx < 0) {
          if (let (true, sIdx) = ctx.interfaceIndices.get(name)) { curIdx = sIdx; }
        }
        if (curIdx == ifaceIdx) {
          let worldDocs = world.docs;
          if (worldDocs != null && isStabilityEqual(u.docs, worldDocs)) {
            return null;
          }
          
          if (item.isExplicit) {
            return u.docs;
          }
          
          let iface = ctx.interfaces[ifaceIdx];
          let ifaceDocs = iface.docs;
          if (ifaceDocs != null && isStabilityEqual(u.docs, ifaceDocs)) {
            return null;
          }
          
          var isUnstable = false;
          let uDocs = u.docs;
          if (uDocs != null && uDocs.attributes != null) {
            let attrs = uDocs.attributes as GrowableArray<Attribute>;
            for (let attr in attrs) {
              if (attr.tag == AttributeTag.Unstable) {
                isUnstable = true;
              }
            }
          }
          
          if (!isUnstable) {
            return null;
          }
          return u.docs;
        }
      }
    }
  }
  
  return null;
}

function collectTypeDeps(t: Type, deps: GrowableArray<String>): void {
  if (t.tag == TypeTag.Name) {
    let id = t.name as Id;
    deps.push(normalizeId(id.name));
  } else if (t.tag == TypeTag.Tuple) {
    let types = t.types as GrowableArray<Type>;
    for (let subtype in types) {
      collectTypeDeps(subtype, deps);
    }
  } else if (t.tag == TypeTag.Result) {
    if (t.okType != null) {
      collectTypeDeps(t.okType as Type, deps);
    }
    if (t.errType != null) {
      collectTypeDeps(t.errType as Type, deps);
    }
  } else if (t.tag == TypeTag.Option || t.tag == TypeTag.List ||
             t.tag == TypeTag.Future || t.tag == TypeTag.Stream ||
             t.tag == TypeTag.Own || t.tag == TypeTag.Borrow) {
    if (t.inner != null) {
      collectTypeDeps(t.inner as Type, deps);
    }
  } else if (t.tag == TypeTag.Map) {
    if (t.keyType != null) {
      collectTypeDeps(t.keyType as Type, deps);
    }
    if (t.valueType != null) {
      collectTypeDeps(t.valueType as Type, deps);
    }
  }
}

function collectTypeDefDeps(td: TypeDef, deps: GrowableArray<String>) {
  if (td.tag == TypeDefTag.Record) {
    let fields = td.fields as GrowableArray<Field>;
    for (let f in fields) {
      collectTypeDeps(f.type, deps);
    }
  } else if (td.tag == TypeDefTag.Alias) {
    collectTypeDeps(td.aliasType as Type, deps);
  } else if (td.tag == TypeDefTag.Variant) {
    let cases = td.cases as GrowableArray<Case>;
    for (let c in cases) {
      if (c.type != null) {
        collectTypeDeps(c.type as Type, deps);
      }
    }
  }
}

function collectInterfaceDeps(ctx: SerializeContext, iface: InterfaceDef, deps: GrowableArray<String>) {
  let pkgName = ctx.packages[iface.packageIndex].name;
  for (let item in iface.items) {
    if (item.tag == InterfaceItemTag.Use) {
      let u = item.use as Use;
      deps.push(resolveInterfaceName(ctx, pkgName, u.from));
    }
  }
}

function sortInterfaces(ctx: SerializeContext, interfaces: Array<InterfaceDef>): Array<InterfaceDef> {
  let sorted = new GrowableArray<InterfaceDef>();
  let visited = new HashMap<String, i32>();
  
  let ifaceMap = new HashMap<String, InterfaceDef>();
  for (let iface in interfaces) {
    let key = if (iface.isInline) {
      `${i32ToString(iface.packageIndex)}/inline/${normalizeId(iface.name.name)}`;
    } else {
      `${i32ToString(iface.packageIndex)}/${normalizeId(iface.name.name)}`;
    };
    ifaceMap[key] = iface;
  }
  
  let visit = (key: String): void => {
    if (let (true, status) = visited.get(key)) {
      if (status == 1 || status == 2) {
        return;
      }
    }
    
    if (let (true, ifaceObj) = ifaceMap.get(key)) {
      let iface = ifaceObj;
      visited[key] = 1;
      
      let deps = new GrowableArray<String>();
      collectInterfaceDeps(ctx, iface, deps);
      
      for (let dep in deps) {
        
        var hasSlash = false;
        var slashIdx = -1;
        for (var sIdx = 0; sIdx < dep.length; sIdx += 1) {
          if (dep.getByteAt(sIdx) == 47) { // '/'
            hasSlash = true;
            slashIdx = sIdx;
            break;
          }
          }
        
        var depKey = dep;
        if (!hasSlash) {
          depKey = `${i32ToString(iface.packageIndex)}/${dep}`;
        } else {
          let pkgNamePart = dep.sliceBytes(0, slashIdx);
          let ifaceNamePart = dep.sliceBytes(slashIdx + 1, dep.length);
          var foundPkgIdx = -1;
          for (var p = 0; p < ctx.packages.length; p += 1) {
            if (ctx.packages[p].name == pkgNamePart) {
              foundPkgIdx = p;
              break;
            }
            }
          if (foundPkgIdx >= 0) {
            depKey = `${i32ToString(foundPkgIdx)}/${ifaceNamePart}`;
          }
        }
        
        if (ifaceMap.has(depKey)) {
          visit(depKey);
        }
      }
      
      visited[key] = 2;
      sorted.push(iface);
    }
  };
  
  for (let iface in interfaces) {
    let key = if (iface.isInline) {
      `${i32ToString(iface.packageIndex)}/inline/${normalizeId(iface.name.name)}`;
    } else {
      `${i32ToString(iface.packageIndex)}/${normalizeId(iface.name.name)}`;
    };
    visit(key);
  }
  
  return sorted;
}

function collectWorldDeps(world: WorldDef, deps: GrowableArray<String>) {
  for (let item in world.items) {
    if (item.tag == WorldItemTag.Include) {
      let inc = item.include as Include;
      if (inc.from.tag == UsePathTag.Id) {
        deps.push(normalizeId((inc.from.id as Id).name));
      }
    }
  }
}

function sortWorlds(worlds: Array<WorldDef>): Array<WorldDef> {
  let sorted = new GrowableArray<WorldDef>();
  let visited = new HashMap<String, i32>();
  
  let worldMap = new HashMap<String, WorldDef>();
  for (let world in worlds) {
    let key = `${i32ToString(world.packageIndex)}/${normalizeId(world.name.name)}`;
    worldMap[key] = world;
  }
  
  let visit = (key: String): void => {
    if (let (true, status) = visited.get(key)) {
      if (status == 1 || status == 2) {
        return;
      }
    }
    
    if (let (true, worldObj) = worldMap.get(key)) {
      let world = worldObj;
      visited[key] = 1;
      
      let deps = new GrowableArray<String>();
      collectWorldDeps(world, deps);
      
      for (let dep in deps) {
        let depKey = `${i32ToString(world.packageIndex)}/${dep}`;
        if (worldMap.has(depKey)) {
          visit(depKey);
        }
      }
      
      visited[key] = 2;
      sorted.push(world);
    }
  };
  
  for (let world in worlds) {
    let key = `${i32ToString(world.packageIndex)}/${normalizeId(world.name.name)}`;
    visit(key);
  }
  
  return sorted;
}

function registerInterfaceTypes(ctx: SerializeContext, iface: InterfaceDef, ifaceIdx: i32) {
  let siblingTypes = new HashMap<String, ScopeTypeElement>();
  let ifaceName = normalizeId(iface.name.name);
  
  for (let item in iface.items) {
    if (item.tag == InterfaceItemTag.TypeDef) {
      let td = item.typeDef as TypeDef;
      siblingTypes[normalizeId(td.name.name)] = ScopeTypeElement.fromTd(td);
    } else if (item.tag == InterfaceItemTag.Use) {
      let u = item.use as Use;
      for (let un in u.names) {
        let localName = normalizeId(if (un.asName != null) (un.asName as Id).name else un.name.name);
        siblingTypes[localName] = ScopeTypeElement.fromUse(u.from, un, u.docs);
        }
    }
  }

  let visited = new HashMap<String, i32>();
  let registeredIndices = new HashMap<String, i32>();

  let ensureRegistered = (name: String): i32 => {
    let normName = normalizeId(name);
    if (let (true, status) = visited.get(normName)) {
      if (status == 2) {
        if (let (true, registeredIdx) = registeredIndices.get(normName)) {
          return registeredIdx;
        }
        return -1;
      }
      if (status == 1) {
        return -1;
      }
    }

    if (let (true, elemObj) = siblingTypes.get(normName)) {
      visited[normName] = 1;
      let elem = elemObj;
      
      var typeIdx = -1;
      if (elem.isTypeDef()) {
        let td = elem.typeDef() as TypeDef;
        let deps = new GrowableArray<String>();
        collectTypeDefDeps(td, deps);

        for (let dep in deps) {
          if (siblingTypes.has(dep)) {
            ensureRegistered(dep);
          }
        }

        typeIdx = registerTypeDef(ctx, td, TypeOwner.fromInterface(ifaceIdx));
      } else {
        let pkgName = ctx.packages[iface.packageIndex].name;
        let srcIfaceName = resolveInterfaceName(ctx, pkgName, elem.usePath() as UsePath);
        let srcTypeName = normalizeId((elem.useName() as UseName).name.name);
        
        var srcIdx = -1;
        let lookupKey = `interface:${srcIfaceName}/${srcTypeName}`;
        if (let (true, sIdx) = ctx.typeIndices.get(lookupKey)) {
          srcIdx = sIdx;
        } else if (let (true, sIdx) = ctx.typeIndices.get(srcTypeName)) {
          srcIdx = sIdx;
        }
        
        if (srcIdx >= 0) {
          let kind = new TypeAlias(TypeRef.idx(srcIdx));
          
          let entry = new TypeEntry(normName, kind, some(TypeOwner.fromInterface(ifaceIdx)), elem.docs());
          typeIdx = ctx.registerType(entry);
        }
      }

      if (typeIdx >= 0) {
        registeredIndices[normName] = typeIdx;
        ctx.typeIndices[`interface:${ifaceName}/${normName}`] = typeIdx;
        let pkgName = ctx.packages[iface.packageIndex].name;
        if (pkgName.length > 0) {
          ctx.typeIndices[`interface:${pkgName}/${ifaceName}/${normName}`] = typeIdx;
        }
      }
      
      visited[normName] = 2;
      return typeIdx;
    }

    return -1;
  };

  for (let item in iface.items) {
    if (item.tag == InterfaceItemTag.TypeDef) {
      let td = item.typeDef as TypeDef;
      ensureRegistered(normalizeId(td.name.name));
    } else if (item.tag == InterfaceItemTag.Use) {
      let u = item.use as Use;
      for (let un in u.names) {
        let localName = normalizeId(if (un.asName != null) (un.asName as Id).name else un.name.name);
        ensureRegistered(localName);
        }
    }
  }
}

function findWorldByUsePath(ctx: SerializeContext, path: UsePath): WorldDef | null {
  if (path.tag == UsePathTag.Id) {
    let name = (path.id as Id).name;
    let currentPkg = ctx.packages[ctx.currentWorldPackageIndex];
    if (let (true, wIdx) = currentPkg.worlds.get(normalizeId(name))) {
      return ctx.worlds[wIdx];
    }
    for (var p = 0; p < ctx.packages.length; p += 1) {
      if (let (true, wIdx) = ctx.packages[p].worlds.get(normalizeId(name))) {
        return ctx.worlds[wIdx];
      }
    }
  } else if (path.tag == UsePathTag.Package) {
    let name = (path.name as Id).name;
    let pkg = path.packageId as PackageName;
    let pkgNameStr = formatPackageName(pkg);
    for (var p = 0; p < ctx.packages.length; p += 1) {
      if (ctx.packages[p].name == pkgNameStr) {
        if (let (true, wIdx) = ctx.packages[p].worlds.get(normalizeId(name))) {
          return ctx.worlds[wIdx];
        }
      }
    }
  }
  return null;
}

function applyRename(name: String, renames: Array<IncludeName>) {
  for (let r in renames) {
    if (r.name.name == name) {
      return r.asName.name;
    }
  }
  return name;
}

function renameType(t: Type, renames: Array<IncludeName>): Type {
  if (t.tag == TypeTag.Name) {
    let originalName = (t.name as Id).name;
    let newName = applyRename(originalName, renames);
    if (newName != originalName) {
      return Type.named(new Id(newName, (t.name as Id).span), t.span);
    }
    return t;
  }
  
  if (t.tag == TypeTag.List || t.tag == TypeTag.Option || t.tag == TypeTag.Future || t.tag == TypeTag.Stream || t.tag == TypeTag.Own || t.tag == TypeTag.Borrow) {
    if (t.inner != null) {
      let renamedInner = renameType(t.inner as Type, renames);
      if (renamedInner != t.inner) {
        let tClone = match (t.tag) {
          case TypeTag.List: Type.list(renamedInner, t.span)
          case TypeTag.Option: Type.option(renamedInner, t.span)
          case TypeTag.Future: Type.future(renamedInner, t.span)
          case TypeTag.Stream: Type.stream(renamedInner, t.span)
          case TypeTag.Own: Type.own(renamedInner, t.span)
          case TypeTag.Borrow: Type.borrow(renamedInner, t.span)
          case _: Type.primitive(t.tag, t.span)
        };
        tClone.fixedLength = t.fixedLength;
        return tClone;
      }
    }
    return t;
  }
  
  if (t.tag == TypeTag.Result) {
    let newOk = if (t.okType != null) renameType(t.okType as Type, renames) else null;
    let newErr = if (t.errType != null) renameType(t.errType as Type, renames) else null;
    if (newOk != t.okType || newErr != t.errType) {
      return Type.result(newOk, newErr, t.span);
    }
    return t;
  }
  
  if (t.tag == TypeTag.Tuple) {
    var changed = false;
    let newTypes = new GrowableArray<Type>();
    for (let originalType in (t.types as GrowableArray<Type>)) {
      let renamedType = renameType(originalType, renames);
      if (renamedType != originalType) {
        changed = true;
      }
      newTypes.push(renamedType);
    }
    if (changed) {
      return Type.tuple(newTypes, t.span);
    }
    return t;
  }
  
  if (t.tag == TypeTag.Map) {
    let newKey = renameType(t.keyType as Type, renames);
    let newVal = renameType(t.valueType as Type, renames);
    if (newKey != t.keyType || newVal != t.valueType) {
      return Type.map(newKey, newVal, t.span);
    }
    return t;
  }
  
  return t;
}

function renameParam(p: Param, renames: Array<IncludeName>) {
  let renamedType = renameType(p.type, renames);
  if (renamedType != p.type) {
    return new Param(p.name, renamedType);
  }
  return p;
}

function renameFunc(f: Func, renames: Array<IncludeName>) {
  var changed = false;
  let newParams = new GrowableArray<Param>();
  for (let p in f.params) {
    let renamedParam = renameParam(p, renames);
    if (renamedParam != p) {
      changed = true;
    }
    newParams.push(renamedParam);
  }
  let newResult = if (f.result != null) renameType(f.result as Type, renames) else null;
  if (newResult != f.result) {
    changed = true;
  }
  if (changed) {
    let fClone = new Func(f.span);
    fClone.isAsync = f.isAsync;
    fClone.params = newParams;
    fClone.result = newResult;
    return fClone;
  }
  return f;
}

function renameNamedFunc(nf: NamedFunc, renames: Array<IncludeName>) {
  let renamedFunc = renameFunc(nf.func, renames);
  if (renamedFunc != nf.func) {
    return new NamedFunc(nf.docs, nf.name, renamedFunc);
  }
  return nf;
}

function renameResourceFunc(rf: ResourceFunc, renames: Array<IncludeName>) {
  let renamedFunc = renameNamedFunc(rf.func, renames);
  if (renamedFunc != rf.func) {
    return new ResourceFunc(rf.tag, renamedFunc);
  }
  return rf;
}

function renameTypeDef(td: TypeDef, renames: Array<IncludeName>) {
  let newName = applyRename(td.name.name, renames);
  var changed = (newName != td.name.name);
  
  var newAlias = td.aliasType;
  if (td.tag == TypeDefTag.Alias && td.aliasType != null) {
    newAlias = renameType(td.aliasType as Type, renames);
    if (newAlias != td.aliasType) {
      changed = true;
    }
  }
  
  var newFields = td.fields;
  if (td.tag == TypeDefTag.Record && td.fields != null) {
    let oldFields = td.fields as GrowableArray<Field>;
    let fields = new GrowableArray<Field>();
    for (let f in oldFields) {
      let renamedType = renameType(f.type, renames);
      if (renamedType != f.type) {
        changed = true;
        fields.push(new Field(f.docs, f.name, renamedType));
      } else {
        fields.push(f);
      }
    }
    newFields = fields;
  }
  
  var newCases = td.cases;
  if (td.tag == TypeDefTag.Variant && td.cases != null) {
    let oldCases = td.cases as GrowableArray<Case>;
    let cases = new GrowableArray<Case>();
    for (let c in oldCases) {
      var renamedType = c.type;
      if (c.type != null) {
        renamedType = renameType(c.type as Type, renames);
        if (renamedType != c.type) {
          changed = true;
        }
      }
      if (renamedType != c.type) {
        let cClone = new Case(c.docs, c.name);
        cClone.type = renamedType;
        cases.push(cClone);
      } else {
        cases.push(c);
      }
    }
    newCases = cases;
  }
  
  var newResourceFuncs = td.resourceFuncs;
  if (td.tag == TypeDefTag.Resource && td.resourceFuncs != null) {
    let oldFuncs = td.resourceFuncs as GrowableArray<ResourceFunc>;
    let funcs = new GrowableArray<ResourceFunc>();
    for (let rf in oldFuncs) {
      let renamedRf = renameResourceFunc(rf, renames);
      if (renamedRf != rf) {
        changed = true;
      }
      funcs.push(renamedRf);
    }
    newResourceFuncs = funcs;
  }
  
  if (changed) {
    let tdClone = match (td.tag) {
      case TypeDefTag.Alias: TypeDef.alias(td.docs, new Id(newName, td.name.span), newAlias as Type)
      case TypeDefTag.Record: TypeDef.record(td.docs, new Id(newName, td.name.span), newFields as GrowableArray<Field>)
      case TypeDefTag.Flags: TypeDef.flagsDef(td.docs, new Id(newName, td.name.span), td.flags as GrowableArray<FlagDef>)
      case TypeDefTag.Variant: TypeDef.variant(td.docs, new Id(newName, td.name.span), newCases as GrowableArray<Case>)
      case TypeDefTag.Enum: TypeDef.enumDef(td.docs, new Id(newName, td.name.span), td.enumCases as GrowableArray<EnumCaseDef>)
      case TypeDefTag.Resource: TypeDef.resource(td.docs, new Id(newName, td.name.span), newResourceFuncs as GrowableArray<ResourceFunc>)
    };
    return tdClone;
  }
  
  return td;
}

function renameImport(imp: Import, renames: Array<IncludeName>) {
  let kind = imp.kind;
  var changed = false;
  var newName = kind.name;
  if (kind.name != null) {
    let originalName = (kind.name as Id).name;
    let nameStr = applyRename(originalName, renames);
    if (nameStr != originalName) {
      changed = true;
      newName = new Id(nameStr, (kind.name as Id).span);
    }
  }
  
  var newFuncDef = kind.funcDef;
  if (kind.tag == ExternKindTag.Func && kind.funcDef != null) {
    newFuncDef = renameFunc(kind.funcDef as Func, renames);
    if (newFuncDef != kind.funcDef) {
      changed = true;
    }
  }
  
  if (changed) {
    let kindClone = match (kind.tag) {
      case ExternKindTag.Interface: ExternKind.iface(newName as Id, kind.items as GrowableArray<InterfaceItem>)
      case ExternKindTag.Path: ExternKind.fromPath(kind.path as UsePath)
      case ExternKindTag.Func: ExternKind.makeFunc(newName as Id, newFuncDef as Func)
    };
    return new Import(imp.docs, kindClone);
  }
  return imp;
}

function renameExport(exp: Export, renames: Array<IncludeName>) {
  let kind = exp.kind;
  var changed = false;
  var newName = kind.name;
  if (kind.name != null) {
    let originalName = (kind.name as Id).name;
    let nameStr = applyRename(originalName, renames);
    if (nameStr != originalName) {
      changed = true;
      newName = new Id(nameStr, (kind.name as Id).span);
    }
  }
  
  var newFuncDef = kind.funcDef;
  if (kind.tag == ExternKindTag.Func && kind.funcDef != null) {
    newFuncDef = renameFunc(kind.funcDef as Func, renames);
    if (newFuncDef != kind.funcDef) {
      changed = true;
    }
  }
  
  if (changed) {
    let kindClone = match (kind.tag) {
      case ExternKindTag.Interface: ExternKind.iface(newName as Id, kind.items as GrowableArray<InterfaceItem>)
      case ExternKindTag.Path: ExternKind.fromPath(kind.path as UsePath)
      case ExternKindTag.Func: ExternKind.makeFunc(newName as Id, newFuncDef as Func)
    };
    return new Export(exp.docs, kindClone);
  }
  return exp;
}

function renameUse(u: Use, renames: Array<IncludeName>) {
  var changed = false;
  let newNames = new GrowableArray<UseName>();
  for (let un in u.names) {
    let originalName = if (un.asName != null) (un.asName as Id).name else un.name.name;
    let newName = applyRename(originalName, renames);
    if (newName != originalName) {
      changed = true;
      let unClone = new UseName(un.name);
      unClone.asName = new Id(newName, un.name.span);
      newNames.push(unClone);
    } else {
      newNames.push(un);
    }
  }
  if (changed) {
    return new Use(u.docs, u.from, newNames);
  }
  return u;
}

function renameWorldItem(item: WorldItem, renames: Array<IncludeName>) {
  if (renames.length == 0) {
    return item;
  }
  if (item.tag == WorldItemTag.TypeDef) {
    let td = item.typeDef as TypeDef;
    let renamedTd = renameTypeDef(td, renames);
    if (renamedTd != td) {
      return WorldItem.fromTypeDef(renamedTd);
    }
  } else if (item.tag == WorldItemTag.Import) {
    let imp = item.importItem as Import;
    let renamedImp = renameImport(imp, renames);
    if (renamedImp != imp) {
      return WorldItem.fromImport(renamedImp);
    }
  } else if (item.tag == WorldItemTag.Export) {
    let exp = item.exportItem as Export;
    let renamedExp = renameExport(exp, renames);
    if (renamedExp != exp) {
      return WorldItem.fromExport(renamedExp);
    }
  } else if (item.tag == WorldItemTag.Use) {
    let u = item.use as Use;
    let renamedUse = renameUse(u, renames);
    if (renamedUse != u) {
      return WorldItem.fromUse(renamedUse);
    }
  }
  return item;
}



function combineDocs(parent: Docs | null, child: Docs | null): Docs | null {
  if (parent == null) return child;
  if (child == null) return parent;
  if (parent.attributes == null) return child;
  if (child.attributes == null) return parent;
  
  let pattrs = parent.attributes as GrowableArray<Attribute>;
  let cattrs = child.attributes as GrowableArray<Attribute>;
  
  let newAttrs = new GrowableArray<Attribute>();
  
  var parentUnstable: Attribute | null = null;
  var childUnstable: Attribute | null = null;
  var parentSince: Attribute | null = null;
  var childSince: Attribute | null = null;
  var parentDeprecated: Attribute | null = null;
  var childDeprecated: Attribute | null = null;
  
  for (let a in pattrs) {
    if (a.tag == AttributeTag.Unstable) parentUnstable = a;
    else if (a.tag == AttributeTag.Since) parentSince = a;
    else if (a.tag == AttributeTag.Deprecated) parentDeprecated = a;
  }
  
  for (let a in cattrs) {
    if (a.tag == AttributeTag.Unstable) childUnstable = a;
    else if (a.tag == AttributeTag.Since) childSince = a;
    else if (a.tag == AttributeTag.Deprecated) childDeprecated = a;
  }
  
  let hasSinceAttr = parentSince != null || childSince != null;
  if (!hasSinceAttr) {
    if (parentUnstable != null) newAttrs.push(parentUnstable);
    else if (childUnstable != null) newAttrs.push(childUnstable);
  }
  
  if (parentSince != null && childSince != null) {
    let pv = parentSince.version as String;
    let cv = childSince.version as String;
    if (compareVersions(pv, cv) > 0) newAttrs.push(parentSince);
    else newAttrs.push(childSince);
  } else if (parentSince != null) {
    newAttrs.push(parentSince);
  } else if (childSince != null) {
    newAttrs.push(childSince);
  }
  
  if (parentDeprecated != null && childDeprecated != null) {
    let pv = parentDeprecated.version as String;
    let cv = childDeprecated.version as String;
    if (compareVersions(pv, cv) < 0) newAttrs.push(parentDeprecated);
    else newAttrs.push(childDeprecated);
  } else if (parentDeprecated != null) {
    newAttrs.push(parentDeprecated);
  } else if (childDeprecated != null) {
    newAttrs.push(childDeprecated);
  }
  
  let d = new Docs(parent.span);
  d.attributes = newAttrs;
  return d;
}

function mergeDocs(parent: Docs | null, child: Docs | null): Docs | null {
  if (parent == null) return child;
  if (child == null) return parent;
  if (parent.attributes == null) return child;
  if (child.attributes == null) return parent;
  
  let pattrs = parent.attributes as GrowableArray<Attribute>;
  let cattrs = child.attributes as GrowableArray<Attribute>;
  
  let newAttrs = new GrowableArray<Attribute>();
  
  var parentUnstable: Attribute | null = null;
  var childUnstable: Attribute | null = null;
  var parentSince: Attribute | null = null;
  var childSince: Attribute | null = null;
  var parentDeprecated: Attribute | null = null;
  var childDeprecated: Attribute | null = null;
  
  for (let a in pattrs) {
    if (a.tag == AttributeTag.Unstable) parentUnstable = a;
    else if (a.tag == AttributeTag.Since) parentSince = a;
    else if (a.tag == AttributeTag.Deprecated) parentDeprecated = a;
  }
  
  for (let a in cattrs) {
    if (a.tag == AttributeTag.Unstable) childUnstable = a;
    else if (a.tag == AttributeTag.Since) childSince = a;
    else if (a.tag == AttributeTag.Deprecated) childDeprecated = a;
  }
  
  if (parentUnstable != null) {
    newAttrs.push(parentUnstable);
  } else if (childUnstable != null) {
    newAttrs.push(childUnstable);
  } else if (parentSince != null && childSince != null) {
    let pv = parentSince.version as String;
    let cv = childSince.version as String;
    if (compareVersions(pv, cv) > 0) newAttrs.push(parentSince);
    else newAttrs.push(childSince);
  } else if (parentSince != null) {
    newAttrs.push(parentSince);
  } else if (childSince != null) {
    newAttrs.push(childSince);
  }
  
  if (parentDeprecated != null && childDeprecated != null) {
    let pv = parentDeprecated.version as String;
    let cv = childDeprecated.version as String;
    if (compareVersions(pv, cv) < 0) newAttrs.push(parentDeprecated);
    else newAttrs.push(childDeprecated);
  } else if (parentDeprecated != null) {
    newAttrs.push(parentDeprecated);
  } else if (childDeprecated != null) {
    newAttrs.push(childDeprecated);
  }
  
  let d = new Docs(parent.span);
  d.attributes = newAttrs;
  return d;
}

function filterUnstableOnly(docs: Docs | null): Docs | null {
  if (docs == null || docs.attributes == null) return null;
  let attrs = docs.attributes as GrowableArray<Attribute>;
  let newAttrs = new GrowableArray<Attribute>();
  for (let attr in attrs) {
    if (attr.tag == AttributeTag.Unstable) {
      newAttrs.push(attr);
    }
  }
  if (newAttrs.length == 0) return null;
  let d = new Docs(docs.span);
  d.attributes = newAttrs;
  return d;
}

function filterStableOnly(docs: Docs | null): Docs | null {
  if (docs == null || docs.attributes == null) return null;
  let attrs = docs.attributes as GrowableArray<Attribute>;
  let newAttrs = new GrowableArray<Attribute>();
  for (let attr in attrs) {
    if (attr.tag == AttributeTag.Since || attr.tag == AttributeTag.Deprecated) {
      newAttrs.push(attr);
    }
  }
  if (newAttrs.length == 0) return null;
  let d = new Docs(docs.span);
  d.attributes = newAttrs;
  return d;
}

function expandWorldItems(ctx: SerializeContext, world: WorldDef): Array<WorldItem> {
  let result = new GrowableArray<WorldItem>();
  let visited = new HashMap<String, boolean>();
  
  let rec = (w: WorldDef, renames: Array<IncludeName>, inheritedDocs: Docs | null): void => {
    let key = `${i32ToString(w.packageIndex)}/${normalizeId(w.name.name)}`;
    if (visited.has(key)) {
      return;
    }
    visited[key] = true;
    
    let worldUnstableDocs = if (visited.size > 1) filterUnstableOnly(w.docs) else null;
    let currentInheritedDocs = combineDocs(inheritedDocs, worldUnstableDocs);
    
    for (let item in w.items) {
      if (item.tag == WorldItemTag.Include) {
        let inc = item.include as Include;
        let incWorld = findWorldByUsePath(ctx, inc.from);
        if (incWorld != null) {
          let nestedRenames = new GrowableArray<IncludeName>();
          for (let n in inc.names) {
            let renamedAs = applyRename(n.asName.name, renames);
            nestedRenames.push(new IncludeName(n.name, new Id(renamedAs, n.asName.span)));
            }
          for (let pr in renames) {
            var found = false;
            for (var j = 0; j < nestedRenames.length; j += 1) {
              if (nestedRenames[j].name.name == pr.name.name) {
                found = true;
              }
              }
            if (!found) {
              nestedRenames.push(pr);
            }
            }
          
          let includeInheritedDocs = if (visited.size == 1) combineDocs(currentInheritedDocs, filterStableOnly(inc.docs)) else currentInheritedDocs;
          rec(incWorld, nestedRenames, includeInheritedDocs);
        }
      } else {
        let renamedItem = renameWorldItem(item, renames);
        let combineWith = if (visited.size > 1) currentInheritedDocs else null;
        
        let cloned = match (item.tag) {
          case WorldItemTag.Import: {
            let imp = renamedItem.importItem as Import;
            let clonedImport = new Import(combineDocs(combineWith, imp.docs) as Docs, imp.kind);
            let c = WorldItem.fromImport(clonedImport);
            c.isExplicit = imp.docs != null;
            c
          }
          case WorldItemTag.Export: {
            let exp = renamedItem.exportItem as Export;
            let clonedExport = new Export(combineDocs(combineWith, exp.docs) as Docs, exp.kind);
            let c = WorldItem.fromExport(clonedExport);
            c.isExplicit = exp.docs != null;
            c
          }
          case WorldItemTag.Use: {
            let u = renamedItem.use as Use;
            let clonedUse = new Use(combineDocs(combineWith, u.docs) as Docs, u.from, u.names);
            let c = WorldItem.fromUse(clonedUse);
            c.isExplicit = u.docs != null;
            c
          }
          case WorldItemTag.TypeDef: {
            let c = WorldItem.fromTypeDef(renamedItem.typeDef as TypeDef);
            c.isExplicit = true;
            c
          }
          case WorldItemTag.Include: {
            let c = WorldItem.fromInclude(renamedItem.include as Include);
            c.isExplicit = true;
            c
          }
        };

        cloned.packageIndex = w.packageIndex;
        if (renames.length > 0 || visited.size > 1) {
          cloned.isIncluded = true;
        }
        cloned.inheritedDocs = combineWith;
        
        result.push(cloned);
      }
    }
  };
  
  let prevWorldPackageIndex = ctx.currentWorldPackageIndex;
  ctx.currentWorldPackageIndex = world.packageIndex;
  rec(world, new GrowableArray<IncludeName>(), null);
  ctx.currentWorldPackageIndex = prevWorldPackageIndex;
  return result;
}

function registerWorldTypes(ctx: SerializeContext, world: WorldDef, worldIdx: i32, items: Array<WorldItem>) {
  let siblingTypes = new HashMap<String, ScopeTypeElement>();
  let worldName = normalizeId(world.name.name);
  
  for (let item in items) {
    if (item.tag == WorldItemTag.TypeDef) {
      let td = item.typeDef as TypeDef;
      siblingTypes[normalizeId(td.name.name)] = ScopeTypeElement.fromTd(td);
    } else if (item.tag == WorldItemTag.Use) {
      let u = item.use as Use;
      for (let un in u.names) {
        let localName = normalizeId(if (un.asName != null) (un.asName as Id).name else un.name.name);
        siblingTypes[localName] = ScopeTypeElement.fromUse(u.from, un, u.docs);
        }
    }
  }

  let visited = new HashMap<String, i32>();
  let registeredIndices = new HashMap<String, i32>();

  let ensureRegistered = (name: String): i32 => {
    let normName = normalizeId(name);
    if (let (true, status) = visited.get(normName)) {
      if (status == 2) {
        if (let (true, registeredIdx) = registeredIndices.get(normName)) {
          return registeredIdx;
        }
        return -1;
      }
      if (status == 1) {
        return -1;
      }
    }

    if (let (true, elemObj) = siblingTypes.get(normName)) {
      visited[normName] = 1;
      let elem = elemObj;
      
      var typeIdx = -1;
      if (elem.isTypeDef()) {
        let td = elem.typeDef() as TypeDef;
        let deps = new GrowableArray<String>();
        collectTypeDefDeps(td, deps);

        for (let dep in deps) {
          if (siblingTypes.has(dep)) {
            ensureRegistered(dep);
          }
        }

        typeIdx = registerTypeDef(ctx, td, TypeOwner.fromWorld(worldIdx));
      } else {
        let pkgName = ctx.packages[world.packageIndex].name;
        let srcIfaceName = resolveInterfaceName(ctx, pkgName, elem.usePath() as UsePath);
        let srcTypeName = normalizeId((elem.useName() as UseName).name.name);
        
        var srcIdx = -1;
        let lookupKey = `interface:${srcIfaceName}/${srcTypeName}`;
        if (let (true, sIdx) = ctx.typeIndices.get(lookupKey)) {
          srcIdx = sIdx;
        } else if (let (true, sIdx) = ctx.typeIndices.get(srcTypeName)) {
          srcIdx = sIdx;
        }
        
        if (srcIdx >= 0) {
          let kind = new TypeAlias(TypeRef.idx(srcIdx));
          
          let entry = new TypeEntry(normName, kind, some(TypeOwner.fromWorld(worldIdx)), elem.docs());
          typeIdx = ctx.registerType(entry);
        }
      }

      if (typeIdx >= 0) {
        registeredIndices[normName] = typeIdx;
        ctx.typeIndices[`world:${worldName}/${normName}`] = typeIdx;
      }
      
      visited[normName] = 2;
      return typeIdx;
    }

    return -1;
  };

  for (let item in items) {
    if (item.tag == WorldItemTag.TypeDef) {
      let td = item.typeDef as TypeDef;
      ensureRegistered(normalizeId(td.name.name));
    } else if (item.tag == WorldItemTag.Use) {
      let u = item.use as Use;
      for (let un in u.names) {
        let localName = normalizeId(if (un.asName != null) (un.asName as Id).name else un.name.name);
        ensureRegistered(localName);
        }
    }
  }
}

function registerAllTypes(ctx: SerializeContext) {
  for (var iIdx = 0; iIdx < ctx.interfaces.length; iIdx += 1) {
    ctx.currentInterfaceName = normalizeId(ctx.interfaces[iIdx].name.name);
    ctx.currentWorldName = null;
    registerInterfaceTypes(ctx, ctx.interfaces[iIdx], iIdx);
  }

  for (var wIdx = 0; wIdx < ctx.worlds.length; wIdx += 1) {
    ctx.currentInterfaceName = null;
    ctx.currentWorldName = normalizeId(ctx.worlds[wIdx].name.name);
    let expandedItems = expandWorldItems(ctx, ctx.worlds[wIdx]);
    registerWorldTypes(ctx, ctx.worlds[wIdx], wIdx, expandedItems);
  }
  
  ctx.currentInterfaceName = null;
  ctx.currentWorldName = null;
}

function typeContainsBorrowFor(t: Type, resourceName: String): boolean {
  if (t.tag == TypeTag.Borrow) {
    let inner = t.inner as Type;
    if (inner.tag == TypeTag.Name) {
      let id = inner.name as Id;
      return normalizeId(id.name) == resourceName;
    }
  }
  if (t.tag == TypeTag.Tuple) {
    let types = t.types as GrowableArray<Type>;
    for (var idx = 0; idx < types.length; idx += 1) {
      if (typeContainsBorrowFor(types[idx], resourceName)) {
        return true;
      }
    }
  } else if (t.tag == TypeTag.Result) {
    if (t.okType != null && typeContainsBorrowFor(t.okType as Type, resourceName)) {
      return true;
    }
    if (t.errType != null && typeContainsBorrowFor(t.errType as Type, resourceName)) {
      return true;
    }
  } else if (t.tag == TypeTag.Option || t.tag == TypeTag.List ||
             t.tag == TypeTag.Future || t.tag == TypeTag.Stream) {
    if (t.inner != null) {
      return typeContainsBorrowFor(t.inner as Type, resourceName);
    }
  }
  return false;
}

function isNakedOwnOrResource(ctx: SerializeContext, t: Type): boolean {
  if (t.tag == TypeTag.Own) {
    return true;
  }
  if (t.tag == TypeTag.Name) {
    let id = t.name as Id;
    let name = normalizeId(id.name);
    var foundIdx = -1;
    if (ctx.currentInterfaceName != null) {
      let key = `interface:${ctx.currentInterfaceName as String}/${name}`;
      if (let (true, idx) = ctx.typeIndices.get(key)) {
        foundIdx = idx;
      }
    }
    if (foundIdx < 0 && ctx.currentWorldName != null) {
      let key = `world:${ctx.currentWorldName as String}/${name}`;
      if (let (true, idx) = ctx.typeIndices.get(key)) {
        foundIdx = idx;
      }
    }
    if (foundIdx < 0) {
      if (let (true, idx) = ctx.typeIndices.get(name)) {
        foundIdx = idx;
      }
    }
    if (foundIdx >= 0 && ctx.isResourceType(foundIdx)) {
      return true;
    }
  }
  return false;
}

function registerInterfaceAllScopeTypes(ctx: SerializeContext, iface: InterfaceDef, ifaceIdx: i32) {
  ctx.currentInterfaceName = normalizeId(iface.name.name);
  ctx.currentWorldName = null;
  
  // Stage 1: Register all defined TypeDefs
  registerInterfaceTypes(ctx, iface, ifaceIdx);
  
  // Identify all local resources
  let resources = new GrowableArray<TypeDef>();
  for (let item in iface.items) {
    if (item.tag == InterfaceItemTag.TypeDef) {
      let td = item.typeDef as TypeDef;
      if (td.tag == TypeDefTag.Resource) {
        resources.push(td);
      }
    }
  }
  
  // Stage 3a: Process resource functions' explicit types FIRST
  for (let item in iface.items) {
    if (item.tag == InterfaceItemTag.TypeDef) {
      let td = item.typeDef as TypeDef;
      if (td.tag == TypeDefTag.Resource && td.resourceFuncs != null) {
        let funcs = td.resourceFuncs as GrowableArray<ResourceFunc>;
        for (let rf in funcs) {
          
          // Prepend implicit self parameter (borrow<resource>) if it is a method
          if (rf.tag == ResourceFuncTag.Method) {
            let rName = normalizeId(td.name.name);
            var resourceTypeIdx = -1;
            let lookupKey = `interface:${ctx.currentInterfaceName as String}/${rName}`;
            if (let (true, sIdx) = ctx.typeIndices.get(lookupKey)) {
              resourceTypeIdx = sIdx;
            }
            if (resourceTypeIdx >= 0) {
              ctx.getBorrowType(resourceTypeIdx);
            }
          }
          
          for (var pIdx = 0; pIdx < rf.func.func.params.length; pIdx += 1) {
            let paramType = rf.func.func.params[pIdx].type;
            if (!isNakedOwnOrResource(ctx, paramType)) {
              ctx.getParamTypeRef(paramType);
            }
            }
          if (rf.func.func.result != null) {
            let resultType = rf.func.func.result as Type;
            if (!isNakedOwnOrResource(ctx, resultType)) {
              ctx.getParamTypeRef(resultType);
            }
          }
          }
      }
    }
  }
  
  // Stage 3b: Process freestanding functions' explicit types SECOND
  for (let item in iface.items) {
    if (item.tag == InterfaceItemTag.Func) {
      let func = item.func as NamedFunc;
      for (var pIdx = 0; pIdx < func.func.params.length; pIdx += 1) {
        let paramType = func.func.params[pIdx].type;
        if (!isNakedOwnOrResource(ctx, paramType)) {
          ctx.getParamTypeRef(paramType);
        }
        }
      if (func.func.result != null) {
        let resultType = func.func.result as Type;
        if (!isNakedOwnOrResource(ctx, resultType)) {
          ctx.getParamTypeRef(resultType);
        }
      }
    }
  }
  
  ctx.currentInterfaceName = null;
  ctx.currentWorldName = null;
}

function registerWorldAllScopeTypes(ctx: SerializeContext, world: WorldDef, worldIdx: i32) {
  ctx.currentInterfaceName = null;
  ctx.currentWorldName = normalizeId(world.name.name);
  
  let expandedItems = expandWorldItems(ctx, world);
  
  // Stage 1: Register all defined TypeDefs
  registerWorldTypes(ctx, world, worldIdx, expandedItems);
  
  // Identify all local/included resources
  let resources = new GrowableArray<WorldItem>();
  for (let item in expandedItems) {
    if (item.tag == WorldItemTag.TypeDef) {
      let td = item.typeDef as TypeDef;
      if (td.tag == TypeDefTag.Resource) {
        resources.push(item);
      }
    }
  }
  
  // Stage 3a: Process world resource functions' explicit types FIRST (only local resources)
  for (let item in resources) {
    if (!item.isIncluded) {
      let r = item.typeDef as TypeDef;
      if (r.resourceFuncs != null) {
        let funcs = r.resourceFuncs as GrowableArray<ResourceFunc>;
        for (let rf in funcs) {
          
          // Prepend implicit self parameter (borrow<resource>) if it is a method
          if (rf.tag == ResourceFuncTag.Method) {
            let rName = normalizeId(r.name.name);
            var resourceTypeIdx = -1;
            let lookupKey = `world:${ctx.currentWorldName as String}/${rName}`;
            if (let (true, sIdx) = ctx.typeIndices.get(lookupKey)) {
              resourceTypeIdx = sIdx;
            }
            if (resourceTypeIdx >= 0) {
              ctx.getBorrowType(resourceTypeIdx);
            }
          }
          
          for (var pIdx = 0; pIdx < rf.func.func.params.length; pIdx += 1) {
            let paramType = rf.func.func.params[pIdx].type;
            if (!isNakedOwnOrResource(ctx, paramType)) {
              ctx.getParamTypeRef(paramType);
            }
            }
          if (rf.func.func.result != null) {
            let resultType = rf.func.func.result as Type;
            if (!isNakedOwnOrResource(ctx, resultType)) {
              ctx.getParamTypeRef(resultType);
            }
          }
          }
      }
    }
  }
  
  // Stage 3b: Process world import/export function explicit types SECOND
  for (let item in expandedItems) {
    if (item.tag == WorldItemTag.Import) {
      let imp = item.importItem as Import;
      if (imp.kind.tag == ExternKindTag.Func) {
        let func = imp.kind.funcDef as Func;
        for (var pIdx = 0; pIdx < func.params.length; pIdx += 1) {
          let paramType = func.params[pIdx].type;
          if (!isNakedOwnOrResource(ctx, paramType)) {
            ctx.getParamTypeRef(paramType);
          }
          }
        if (func.result != null) {
          let resultType = func.result as Type;
          if (!isNakedOwnOrResource(ctx, resultType)) {
            ctx.getParamTypeRef(resultType);
          }
        }
      }
    } else if (item.tag == WorldItemTag.Export) {
      let exp = item.exportItem as Export;
      if (exp.kind.tag == ExternKindTag.Func) {
        let func = exp.kind.funcDef as Func;
        for (var pIdx = 0; pIdx < func.params.length; pIdx += 1) {
          let paramType = func.params[pIdx].type;
          if (!isNakedOwnOrResource(ctx, paramType)) {
            ctx.getParamTypeRef(paramType);
          }
          }
        if (func.result != null) {
          let resultType = func.result as Type;
          if (!isNakedOwnOrResource(ctx, resultType)) {
            ctx.getParamTypeRef(resultType);
          }
        }
      }
    }
  }
  
  // Stage 3c: Process world resource functions' explicit types THIRD (only included resources)
  for (let item in resources) {
    if (item.isIncluded) {
      let r = item.typeDef as TypeDef;
      if (r.resourceFuncs != null) {
        let funcs = r.resourceFuncs as GrowableArray<ResourceFunc>;
        for (let rf in funcs) {
          
          // Prepend implicit self parameter (borrow<resource>) if it is a method
          if (rf.tag == ResourceFuncTag.Method) {
            let rName = normalizeId(r.name.name);
            var resourceTypeIdx = -1;
            let lookupKey = `world:${ctx.currentWorldName as String}/${rName}`;
            if (let (true, sIdx) = ctx.typeIndices.get(lookupKey)) {
              resourceTypeIdx = sIdx;
            }
            if (resourceTypeIdx >= 0) {
              ctx.getBorrowType(resourceTypeIdx);
            }
          }
          
          for (var pIdx = 0; pIdx < rf.func.func.params.length; pIdx += 1) {
            let paramType = rf.func.func.params[pIdx].type;
            if (!isNakedOwnOrResource(ctx, paramType)) {
              ctx.getParamTypeRef(paramType);
            }
            }
          if (rf.func.func.result != null) {
            let resultType = rf.func.func.result as Type;
            if (!isNakedOwnOrResource(ctx, resultType)) {
              ctx.getParamTypeRef(resultType);
            }
          }
          }
      }
    }
  }
  
  ctx.currentInterfaceName = null;
  ctx.currentWorldName = null;
}

function registerAllTypesAndScopeSignatures(ctx: SerializeContext) {
  // First, process all interfaces Block-by-Block (one at a time)
  for (var iIdx = 0; iIdx < ctx.interfaces.length; iIdx += 1) {
    registerInterfaceAllScopeTypes(ctx, ctx.interfaces[iIdx], iIdx);
  }
  
  // Second, process all worlds Block-by-Block (one at a time)
  for (var wIdx = 0; wIdx < ctx.worlds.length; wIdx += 1) {
    registerWorldAllScopeTypes(ctx, ctx.worlds[wIdx], wIdx);
  }
}



function typeDefTagToString(tag: TypeDefTag) {
  if (tag == TypeDefTag.Record) { return "record"; }
  if (tag == TypeDefTag.Flags) { return "flags"; }
  if (tag == TypeDefTag.Variant) { return "variant"; }
  if (tag == TypeDefTag.Enum) { return "enum"; }
  if (tag == TypeDefTag.Resource) { return "resource"; }
  return "type";
}

/** Check if a type is a primitive (outputs as string) vs complex (outputs as index). */
function isPrimitiveType(t: Type): boolean {
  if (t.tag == TypeTag.U8) { return true; }
  if (t.tag == TypeTag.U16) { return true; }
  if (t.tag == TypeTag.U32) { return true; }
  if (t.tag == TypeTag.U64) { return true; }
  if (t.tag == TypeTag.S8) { return true; }
  if (t.tag == TypeTag.S16) { return true; }
  if (t.tag == TypeTag.S32) { return true; }
  if (t.tag == TypeTag.S64) { return true; }
  if (t.tag == TypeTag.F32) { return true; }
  if (t.tag == TypeTag.F64) { return true; }
  if (t.tag == TypeTag.Char) { return true; }
  if (t.tag == TypeTag.Bool) { return true; }
  if (t.tag == TypeTag.String) { return true; }
  if (t.tag == TypeTag.ErrorContext) { return true; }
  return t.tag == TypeTag.Name;
}

/** Get primitive type as string. Only valid for primitive types. */
function primitiveTypeToString(t: Type) {
  if (t.tag == TypeTag.U8) { return "u8"; }
  if (t.tag == TypeTag.U16) { return "u16"; }
  if (t.tag == TypeTag.U32) { return "u32"; }
  if (t.tag == TypeTag.U64) { return "u64"; }
  if (t.tag == TypeTag.S8) { return "s8"; }
  if (t.tag == TypeTag.S16) { return "s16"; }
  if (t.tag == TypeTag.S32) { return "s32"; }
  if (t.tag == TypeTag.S64) { return "s64"; }
  if (t.tag == TypeTag.F32) { return "f32"; }
  if (t.tag == TypeTag.F64) { return "f64"; }
  if (t.tag == TypeTag.Char) { return "char"; }
  if (t.tag == TypeTag.Bool) { return "bool"; }
  if (t.tag == TypeTag.String) { return "string"; }
  if (t.tag == TypeTag.ErrorContext) { return "error-context"; }
  if (t.tag == TypeTag.Name) {
    let id = t.name as Id;
    return id.name;
  }
  return "unknown";
}



/** Build a TypeKind from a Type for use in type definitions (embeds complex types directly). */
function buildTypeKind(ctx: SerializeContext, t: Type, resolveResourceAsOwn: boolean): TypeKind {
  if (t.tag == TypeTag.Stream) {
    let innerRef = if (t.inner != null) ctx.getTypeRef(t.inner as Type) else null;
    return new StreamKind(innerRef);
  } else if (t.tag == TypeTag.Future) {
    let innerRef = if (t.inner != null) ctx.getTypeRef(t.inner as Type) else null;
    return new FutureKind(innerRef);
  } else if (t.tag == TypeTag.Option) {
    return new OptionKind(ctx.getTypeRef(t.inner as Type));
  } else if (t.tag == TypeTag.List) {
    if (t.fixedLength >= 0) {
      return new FixedLengthListKind(ctx.getTypeRef(t.inner as Type), t.fixedLength);
    } else {
      return new ListKind(ctx.getTypeRef(t.inner as Type));
    }
  } else if (t.tag == TypeTag.Result) {
    let ok = if (t.okType != null) ctx.getTypeRef(t.okType as Type) else null;
    let err = if (t.errType != null) ctx.getTypeRef(t.errType as Type) else null;
    return new ResultKind(ok, err);
  } else if (t.tag == TypeTag.Tuple) {
    let types = t.types as GrowableArray<Type>;
    let refs = new GrowableArray<TypeRef>();
    for (var idx = 0; idx < types.length; idx += 1) {
      refs.push(ctx.getTypeRef(types[idx]));
    }
    return new TupleKind(refs);
  } else if (t.tag == TypeTag.Own) {
    let innerRef = ctx.getTypeRefEx(t.inner as Type, false);
    let ownIndex = if (innerRef.isIndex()) innerRef.indexValue() else -1;
    return new HandleKind(-1, ownIndex);
  } else if (t.tag == TypeTag.Borrow) {
    let innerRef = ctx.getTypeRefEx(t.inner as Type, false);
    let borrowIndex = if (innerRef.isIndex()) innerRef.indexValue() else -1;
    return new HandleKind(borrowIndex, -1);
  } else if (t.tag == TypeTag.Map) {
    let key = ctx.getTypeRefEx(t.keyType as Type, resolveResourceAsOwn);
    let value = ctx.getTypeRefEx(t.valueType as Type, resolveResourceAsOwn);
    return new MapKind(key, value);
  } else {
    // Primitive or name reference - wrap it as "type"
    return new TypeAlias(ctx.getTypeRefEx(t, resolveResourceAsOwn));
  }
}

function registerTypeDef(ctx: SerializeContext, td: TypeDef, owner: TypeOwner): i32 {
  let kind = if (td.tag == TypeDefTag.Record) {
    let fieldsArr = new GrowableArray<RecordField>();
    let fields = td.fields as GrowableArray<Field>;
    for (let field in fields) {
      let typeRef = ctx.getTypeRef(field.type);
      fieldsArr.push(new RecordField(normalizeId(field.name.name), typeRef));
    }
    new RecordKind(fieldsArr)
  } else if (td.tag == TypeDefTag.Alias) {
    buildTypeKind(ctx, td.aliasType as Type, false)
  } else if (td.tag == TypeDefTag.Enum) {
    let casesArr = new GrowableArray<EnumCase>();
    let cases = td.enumCases as GrowableArray<EnumCaseDef>;
    for (let ec in cases) {
      let docs: Docs | null = if (ec.docs.contents != null) ec.docs else null;
      casesArr.push(new EnumCase(normalizeId(ec.name.name), docs));
    }
    new EnumKind(casesArr)
  } else if (td.tag == TypeDefTag.Flags) {
    let flagsArr = new GrowableArray<String>();
    let flags = td.flags as GrowableArray<FlagDef>;
    for (var idx = 0; idx < flags.length; idx += 1) {
      flagsArr.push(normalizeId(flags[idx].name.name));
    }
    new FlagsKind(flagsArr)
  } else if (td.tag == TypeDefTag.Variant) {
    let casesArr = new GrowableArray<VariantCase>();
    let cases = td.cases as GrowableArray<Case>;
    for (let c in cases) {
      let typeRef: TypeRef | null = if (c.type != null) {
        ctx.getTypeRef(c.type as Type)
      } else {
        null
      };
      casesArr.push(new VariantCase(normalizeId(c.name.name), typeRef));
    }
    new VariantKind(casesArr)
  } else if (td.tag == TypeDefTag.Resource) {
    new ResourceKind()
  } else {
    new UnknownKind()
  };

  let entry = new TypeEntry(normalizeId(td.name.name), kind, some(owner), td.docs);
  let typeIdx = ctx.registerType(entry);
  
  // Track resources for bare name -> own<resource> conversion
  if (td.tag == TypeDefTag.Resource) {
    ctx.resourceTypeIndices[typeIdx] = 1;
  }
  
  return typeIdx;
}

function serializeResourceFunc(b: JsonBuilder, ctx: SerializeContext, rf: ResourceFunc, resourceName: String, ifaceIndex: i32) {
  b.beginObject();
    // Get the resource type index using current interface/world scope first
  var resourceTypeIdx = -1;
  if (ctx.currentInterfaceName != null) {
    let key = `interface:${ctx.currentInterfaceName as String}/${resourceName}`;
    if (let (true, idx) = ctx.typeIndices.get(key)) {
      resourceTypeIdx = idx;
    }
  }
  if (resourceTypeIdx < 0 && ctx.currentWorldName != null) {
    let key = `world:${ctx.currentWorldName as String}/${resourceName}`;
    if (let (true, idx) = ctx.typeIndices.get(key)) {
      resourceTypeIdx = idx;
    }
  }
  if (resourceTypeIdx < 0) {
    if (let (true, idx) = ctx.typeIndices.get(resourceName)) {
      resourceTypeIdx = idx;
    }
  }
  if (resourceTypeIdx < 0) {
    resourceTypeIdx = 0;
  }
  
  // name includes prefix (e.g., "[method]resource.method")
  if (rf.tag == ResourceFuncTag.Method) {
    b.key("name").string(`[method]${resourceName}.${normalizeId(rf.func.name.name)}`);
    b.key("kind").beginObject();
    if (rf.func.func.isAsync) {
      b.key("async-method").i32(resourceTypeIdx);
    } else {
      b.key("method").i32(resourceTypeIdx);
    }
    b.endObject();
  } else if (rf.tag == ResourceFuncTag.Static) {
    b.key("name").string(`[static]${resourceName}.${normalizeId(rf.func.name.name)}`);
    b.key("kind").beginObject();
    if (rf.func.func.isAsync) {
      b.key("async-static").i32(resourceTypeIdx);
    } else {
      b.key("static").i32(resourceTypeIdx);
    }
    b.endObject();
  } else if (rf.tag == ResourceFuncTag.Constructor) {
    b.key("name").string("[constructor]" + resourceName);
    b.key("kind").beginObject();
    b.key("constructor").i32(resourceTypeIdx);
    b.endObject();
  }
  
  // Serialize params
  b.key("params").beginArray();
  
  // For methods, prepend implicit "self" parameter (borrow<resource>)
  if (rf.tag == ResourceFuncTag.Method) {
    // Use existing borrow type or create if needed
    let borrowIdx = ctx.getBorrowType(resourceTypeIdx);
    
    b.beginObject();
    b.key("name").string("self");
    b.key("type").i32(borrowIdx);
    b.endObject();
  }
  
  let nf = rf.func;
  for (let param in nf.func.params) {
    b.beginObject();
    b.key("name").string(normalizeId(param.name.name));
    b.key("type");
    let typeRef = ctx.getParamTypeRef(param.type);
    typeRef.serialize(b);
    b.endObject();
  }
  b.endArray();
  
  // Result
  // Constructors have an implicit own<resource> result
  if (rf.tag == ResourceFuncTag.Constructor) {
    // Check if there's an explicit result
    if (nf.func.result != null) {
      b.key("result");
      let resultRef = ctx.getParamTypeRef(nf.func.result as Type);
      resultRef.serialize(b);
    } else {
      // Use existing own type or create if needed
      let ownIdx = ctx.getOwnType(resourceTypeIdx);
      b.key("result").i32(ownIdx);
    }
  } else if (nf.func.result != null) {
    b.key("result");
    let resultRef = ctx.getParamTypeRef(nf.func.result as Type);
    resultRef.serialize(b);
  }
  
  serializeStability(b, rf.func.docs);
  b.endObject();
}

function serializeFunction(b: JsonBuilder, ctx: SerializeContext, nf: NamedFunc) {
  b.beginObject();
  b.key("name").string(normalizeId(nf.name.name));
  if (nf.func.isAsync) {
    b.key("kind").string("async-freestanding");
  } else {
    b.key("kind").string("freestanding");
  }
  
  b.key("params").beginArray();
  for (let param in nf.func.params) {
    b.beginObject();
    b.key("name").string(normalizeId(param.name.name));
    b.key("type");
    let typeRef = ctx.getParamTypeRef(param.type);
    typeRef.serialize(b);
    b.endObject();
  }
  b.endArray();
  
  if (nf.func.result != null) {
    b.key("result");
    let resultRef = ctx.getParamTypeRef(nf.func.result as Type);
    resultRef.serialize(b);
  }
  
  // Serialize docs if present
  if (nf.docs.contents != null) {
    b.key("docs").beginObject();
    b.key("contents").string(nf.docs.contents as String);
    b.endObject();
  }
  
  serializeStability(b, nf.docs);
  b.endObject();
}



/** Serialize a world function (for import/export). */
function serializeWorldFunction(b: JsonBuilder, ctx: SerializeContext, name: String, func: Func, docs: Docs | null) {
  b.beginObject();
  b.key("name").string(name);
  
  // Determine kind
  if (func.isAsync) {
    b.key("kind").string("async-freestanding");
  } else {
    b.key("kind").string("freestanding");
  }
  
  // Params
  b.key("params").beginArray();
  for (let param in func.params) {
    b.beginObject();
    b.key("name").string(normalizeId(param.name.name));
    b.key("type");
    let typeRef = ctx.getParamTypeRef(param.type);
    typeRef.serialize(b);
    b.endObject();
  }
  b.endArray();
  
  // Result
  if (func.result != null) {
    let resultType = func.result as Type;
    b.key("result");
    let resultRef = ctx.getParamTypeRef(resultType);
    resultRef.serialize(b);
  }
  
  serializeStability(b, docs);
  b.endObject();
}

/** Serialize an extern kind (import/export item content). */
function serializeExternKind(b: JsonBuilder, ctx: SerializeContext, kind: ExternKind, docs: Docs | null) {
  b.beginObject();
  if (kind.tag == ExternKindTag.Func) {
    b.key("function");
    let name = normalizeId((kind.name as Id).name);
    let func = kind.funcDef as Func;
    serializeWorldFunction(b, ctx, name, func, docs);
  } else if (kind.tag == ExternKindTag.Path) {
    // Interface reference - TODO: Resolve interface by path
    b.key("interface").beginObject();
    b.key("id").i32(0); // placeholder
    b.endObject();
  } else if (kind.tag == ExternKindTag.Interface) {
    // Inline interface - TODO: Create anonymous interface in interfaces array
    b.key("interface").beginObject();
    b.key("id").i32(0); // placeholder
    b.endObject();
  }
  b.endObject();
}

function collectWorldImports(ctx: SerializeContext, world: WorldDef, items: Array<WorldItem>) {
  let imports = new HashMap<i32, boolean>();
  let visited = new HashMap<i32, boolean>();

  // Worker to recursively traverse used interfaces
  let visit = (ifaceIdx: i32, isDirectExport: boolean): void => {
    if (visited.has(ifaceIdx)) return;
    visited[ifaceIdx] = true;
    
    // Any transitive dependency of an imported or exported interface is imported!
    if (!isDirectExport) {
      imports[ifaceIdx] = true;
    }
    
    // Now, find what this interface uses
    let iface = ctx.interfaces[ifaceIdx];
    for (let item in iface.items) {
      if (item.tag == InterfaceItemTag.Use) {
        let u = item.use as Use;
        let usePkgName = ctx.packages[iface.packageIndex].name;
        let depIdx = resolveInterfaceNameAndIndex(ctx, usePkgName, u.from);
        if (depIdx >= 0) {
          visit(depIdx, false);
        }
      }
    }
  };

  // Now, seed the recursive traversal with direct imports/exports
  let pkgName = ctx.packages[world.packageIndex].name;
  for (let item in items) {
    let itemPkgName = if (item.packageIndex >= 0) ctx.packages[item.packageIndex].name else pkgName;
    if (item.tag == WorldItemTag.Import) {
      let imp = item.importItem as Import;
      if (imp.kind.tag == ExternKindTag.Interface) {
        let name = "[import]" + normalizeId((imp.kind.name as Id).name);
        var ifaceIdx = -1;
        if (itemPkgName.length > 0) {
          let lookupKey = `${itemPkgName}/inline/${name}`;
          if (let (true, sIdx) = ctx.interfaceIndices.get(lookupKey)) {
            ifaceIdx = sIdx;
          }
        }
        if (ifaceIdx < 0) {
          if (let (true, sIdx) = ctx.interfaceIndices.get(name)) {
            ifaceIdx = sIdx;
          }
        }
        if (ifaceIdx >= 0) {
          visit(ifaceIdx, false);
        }
      } else if (imp.kind.tag == ExternKindTag.Path) {
        let ifaceIdx = resolveInterfaceNameAndIndex(ctx, itemPkgName, imp.kind.path as UsePath);
        if (ifaceIdx >= 0) {
          visit(ifaceIdx, false);
        }
      }
    } else if (item.tag == WorldItemTag.Export) {
      let exp = item.exportItem as Export;
      if (exp.kind.tag == ExternKindTag.Interface) {
        let name = "[export]" + normalizeId((exp.kind.name as Id).name);
        var ifaceIdx = -1;
        if (itemPkgName.length > 0) {
          let lookupKey = `${itemPkgName}/inline/${name}`;
          if (let (true, sIdx) = ctx.interfaceIndices.get(lookupKey)) {
            ifaceIdx = sIdx;
          }
        }
        if (ifaceIdx < 0) {
          if (let (true, sIdx) = ctx.interfaceIndices.get(name)) {
            ifaceIdx = sIdx;
          }
        }
        if (ifaceIdx >= 0) {
          visit(ifaceIdx, true);
        }
      } else if (exp.kind.tag == ExternKindTag.Path) {
        let ifaceIdx = resolveInterfaceNameAndIndex(ctx, itemPkgName, exp.kind.path as UsePath);
        if (ifaceIdx >= 0) {
          visit(ifaceIdx, true);
        }
      }
    } else if (item.tag == WorldItemTag.Use) {
      let u = item.use as Use;
      let ifaceIdx = resolveInterfaceNameAndIndex(ctx, itemPkgName, u.from);
      if (ifaceIdx >= 0) {
        visit(ifaceIdx, false);
      }
    }
  }

  return imports;
}

function serializeWorld(b: JsonBuilder, ctx: SerializeContext, world: WorldDef, index: i32) {
  let worldName = normalizeId(world.name.name);
  ctx.currentInterfaceName = null;
  ctx.currentWorldName = worldName;
  ctx.currentInterfacePackageIndex = -1;
  ctx.currentWorldPackageIndex = world.packageIndex;
  
  let expandedItems = expandWorldItems(ctx, world);
  
  b.beginObject();
  b.key("name").string(worldName);
  
  // Serialize imports
  b.key("imports").beginObject();
  
  // 1. Serialize any world TypeDefs (like resources/types defined on the world)
  let pkgName = ctx.packages[world.packageIndex].name;
  for (let item in expandedItems) {
    let itemPkgName = if (item.packageIndex >= 0) ctx.packages[item.packageIndex].name else pkgName;
    if (item.tag == WorldItemTag.TypeDef) {
      let td = item.typeDef as TypeDef;
      let tdName = normalizeId(td.name.name);
      b.key(tdName).beginObject();
      
      var typeIdx = -1;
      if (itemPkgName.length > 0) {
        let key = `world:${itemPkgName}/${worldName}/${tdName}`;
        if (let (true, sIdx) = ctx.typeIndices.get(key)) {
          typeIdx = sIdx;
        }
      }
      if (typeIdx < 0) {
        let key = `world:${worldName}/${tdName}`;
        if (let (true, sIdx) = ctx.typeIndices.get(key)) {
          typeIdx = sIdx;
        }
      }
      b.key("type").i32(typeIdx);
      b.endObject();
    } else if (item.tag == WorldItemTag.Use) {
      let u = item.use as Use;
      for (let un in u.names) {
        let name = normalizeId(if (un.asName != null) (un.asName as Id).name else un.name.name);
        b.key(name).beginObject();
        
        var typeIdx = -1;
        let key = `world:${worldName}/${name}`;
        if (let (true, sIdx) = ctx.typeIndices.get(key)) {
          typeIdx = sIdx;
        }
        b.key("type").i32(typeIdx);
        b.endObject();
        }
    }
  }
  
  // 2. Serialize world resource functions as imports
  for (let item in expandedItems) {
    if (item.tag == WorldItemTag.TypeDef) {
      let td = item.typeDef as TypeDef;
      if (td.tag == TypeDefTag.Resource && td.resourceFuncs != null) {
        let resourceName = normalizeId(td.name.name);
        let funcs = td.resourceFuncs as GrowableArray<ResourceFunc>;
        for (let rf in funcs) {
          if (rf.tag == ResourceFuncTag.Method) {
            b.key(`[method]${resourceName}.${normalizeId(rf.func.name.name)}`).beginObject();
            b.key("function");
            serializeResourceFunc(b, ctx, rf, resourceName, index);
            b.endObject();
          } else if (rf.tag == ResourceFuncTag.Static) {
            b.key(`[static]${resourceName}.${normalizeId(rf.func.name.name)}`).beginObject();
            b.key("function");
            serializeResourceFunc(b, ctx, rf, resourceName, index);
            b.endObject();
          } else if (rf.tag == ResourceFuncTag.Constructor) {
            b.key("[constructor]" + resourceName).beginObject();
            b.key("function");
            serializeResourceFunc(b, ctx, rf, resourceName, index);
            b.endObject();
          }
          }
      }
    }
  }
  
  // 3. Serialize interface imports (both explicit inline, direct path, and transitives)
  let worldImports = collectWorldImports(ctx, world, expandedItems);
  let inlineImports = new HashMap<i32, String>();
  
  for (let item in expandedItems) {
    let itemPkgName = if (item.packageIndex >= 0) ctx.packages[item.packageIndex].name else pkgName;
    if (item.tag == WorldItemTag.Import) {
      let imp = item.importItem as Import;
      if (imp.kind.tag == ExternKindTag.Interface) {
        let name = normalizeId((imp.kind.name as Id).name);
        let inlineName = "[import]" + name;
        var ifaceIdx = -1;
        if (itemPkgName.length > 0) {
          let lookupKey = `${itemPkgName}/inline/${inlineName}`;
          if (let (true, sIdx) = ctx.interfaceIndices.get(lookupKey)) {
            ifaceIdx = sIdx;
          }
        }
        if (ifaceIdx < 0) {
          if (let (true, sIdx) = ctx.interfaceIndices.get(inlineName)) {
            ifaceIdx = sIdx;
          }
        }
        if (ifaceIdx >= 0) {
          inlineImports[ifaceIdx] = name;
        }
      }
    }
  }
  
  worldImports.forEach((ifaceIdx, val) => {
    if (let (true, inlineName) = inlineImports.get(ifaceIdx)) {
      b.key(inlineName).beginObject();
      b.key("interface").beginObject();
      b.key("id").i32(ifaceIdx);
      serializeStability(b, findWorldItemDocs(ctx, world, ifaceIdx, true, expandedItems));
      b.endObject();
      b.endObject();
    } else {
      b.key("interface-" + i32ToString(ifaceIdx)).beginObject();
      b.key("interface").beginObject();
      b.key("id").i32(ifaceIdx);
      serializeStability(b, findWorldItemDocs(ctx, world, ifaceIdx, true, expandedItems));
      b.endObject();
      b.endObject();
    }
  });
  
  // 4. Serialize regular freestanding function imports
  for (let item in expandedItems) {
    if (item.tag == WorldItemTag.Import) {
      let imp = item.importItem as Import;
      if (imp.kind.tag == ExternKindTag.Func) {
        let name = normalizeId((imp.kind.name as Id).name);
        b.key(name);
        serializeExternKind(b, ctx, imp.kind, imp.docs);
      }
    }
  }
  b.endObject();
  
  // Serialize exports
  b.key("exports").beginObject();
  for (var idx = 0; idx < expandedItems.length; idx += 1) {
    let item = expandedItems[idx];
    let itemPkgName = if (item.packageIndex >= 0) ctx.packages[item.packageIndex].name else pkgName;
    if (item.tag == WorldItemTag.Export) {
      let exp = item.exportItem as Export;
      if (exp.kind.tag == ExternKindTag.Interface) {
        let name = normalizeId((exp.kind.name as Id).name);
        let inlineName = "[export]" + name;
        b.key(name).beginObject();
        b.key("interface").beginObject();
        var inlineIdx = -1;
        if (itemPkgName.length > 0) {
          let lookupKey = `${itemPkgName}/inline/${inlineName}`;
          if (let (true, idxVal) = ctx.interfaceIndices.get(lookupKey)) {
            inlineIdx = idxVal;
          }
        }
        if (inlineIdx < 0) {
          if (let (true, idxVal) = ctx.interfaceIndices.get(inlineName)) {
            inlineIdx = idxVal;
          }
        }
        b.key("id").i32(inlineIdx);
        serializeStability(b, findWorldItemDocs(ctx, world, inlineIdx, false, expandedItems));
        b.endObject();
        b.endObject();
      } else if (exp.kind.tag == ExternKindTag.Path) {
        let path = exp.kind.path as UsePath;
        let pkgName = ctx.packages[world.packageIndex].name;
        let ifaceIdx = resolveInterfaceNameAndIndex(ctx, pkgName, path);
        if (ifaceIdx >= 0) {
          b.key("interface-" + i32ToString(ifaceIdx)).beginObject();
          b.key("interface").beginObject();
          b.key("id").i32(ifaceIdx);
          serializeStability(b, findWorldItemDocs(ctx, world, ifaceIdx, false, expandedItems));
          b.endObject();
          b.endObject();
        }
      } else if (exp.kind.tag == ExternKindTag.Func) {
        let name = normalizeId((exp.kind.name as Id).name);
        b.key(name);
        serializeExternKind(b, ctx, exp.kind, exp.docs);
      }
    }
  }
  b.endObject();
  if (world.docs != null) {
    let d = world.docs;
    if (d.contents != null) {
      b.key("docs").beginObject();
      b.key("contents").string(d.contents as String);
      b.endObject();
    }
  }
  serializeStability(b, world.docs);
  b.key("package").i32(world.packageIndex);
  b.endObject();
}



function serializeInterface(b: JsonBuilder, ctx: SerializeContext, iface: InterfaceDef, index: i32) {
  let ifaceName = normalizeId(iface.name.name);
  ctx.currentInterfaceName = ifaceName;
  ctx.currentWorldName = null;
  ctx.currentInterfacePackageIndex = iface.packageIndex;
  ctx.currentWorldPackageIndex = -1;
  
  b.beginObject();
  if (iface.isInline) {
    b.key("name").nullValue();
  } else {
    b.key("name").string(ifaceName);
  }
  
  b.key("types").beginObject();
  let pkgName = ctx.packages[iface.packageIndex].name;
  for (let item in iface.items) {
    if (item.tag == InterfaceItemTag.TypeDef) {
      let td = item.typeDef as TypeDef;
      let name = normalizeId(td.name.name);
      
      var foundIdx = -1;
      if (pkgName.length > 0) {
        let key = `interface:${pkgName}/${ifaceName}/${name}`;
        if (let (true, typeIdx) = ctx.typeIndices.get(key)) {
          foundIdx = typeIdx;
        }
      }
      if (foundIdx < 0) {
        let key = `interface:${ifaceName}/${name}`;
        if (let (true, typeIdx) = ctx.typeIndices.get(key)) {
          foundIdx = typeIdx;
        }
      }
      if (foundIdx >= 0) {
        b.key(name).i32(foundIdx);
      }
    } else if (item.tag == InterfaceItemTag.Use) {
      let u = item.use as Use;
      for (let un in u.names) {
        let name = normalizeId(if (un.asName != null) (un.asName as Id).name else un.name.name);
        
        var foundIdx = -1;
        if (pkgName.length > 0) {
          let key = `interface:${pkgName}/${ifaceName}/${name}`;
          if (let (true, typeIdx) = ctx.typeIndices.get(key)) {
            foundIdx = typeIdx;
          }
        }
        if (foundIdx < 0) {
          let key = `interface:${ifaceName}/${name}`;
          if (let (true, typeIdx) = ctx.typeIndices.get(key)) {
            foundIdx = typeIdx;
          }
        }
        if (foundIdx >= 0) {
          b.key(name).i32(foundIdx);
        }
        }
    }
  }
  b.endObject();
  
  b.key("functions").beginObject();
  // First serialize resource methods (wasm-tools order: resource methods create types first)
  for (let item in iface.items) {
    if (item.tag == InterfaceItemTag.TypeDef) {
      let td = item.typeDef as TypeDef;
      if (td.tag == TypeDefTag.Resource && td.resourceFuncs != null) {
        let resourceName = normalizeId(td.name.name);
        let funcs = td.resourceFuncs as GrowableArray<ResourceFunc>;
        for (let rf in funcs) {
          if (rf.tag == ResourceFuncTag.Method) {
            b.key(`[method]${resourceName}.${normalizeId(rf.func.name.name)}`);
            serializeResourceFunc(b, ctx, rf, resourceName, index);
          } else if (rf.tag == ResourceFuncTag.Static) {
            b.key(`[static]${resourceName}.${normalizeId(rf.func.name.name)}`);
            serializeResourceFunc(b, ctx, rf, resourceName, index);
          } else if (rf.tag == ResourceFuncTag.Constructor) {
            b.key("[constructor]" + resourceName);
            serializeResourceFunc(b, ctx, rf, resourceName, index);
          }
          }
      }
    }
  }
  // Then serialize regular interface functions
  for (let item in iface.items) {
    if (item.tag == InterfaceItemTag.Func) {
      let func = item.func as NamedFunc;
      b.key(normalizeId(func.name.name));
      serializeFunction(b, ctx, func);
    }
  }
  b.endObject();
  
  if (iface.docs.contents != null) {
    b.key("docs").beginObject();
    b.key("contents").string(iface.docs.contents as String);
    b.endObject();
  }
  
  serializeStability(b, iface.docs);
  
  b.key("package").i32(iface.packageIndex);
  b.endObject();
}

function collectPackageDepFromUsePath(aliases: HashMap<String, String>, pkgName: String, path: UsePath, deps: GrowableArray<String>) {
  if (path.tag == UsePathTag.Package) {
    let pkg = path.packageId as PackageName;
    deps.push(formatPackageName(pkg));
  } else {
    let key = `${pkgName}/${normalizeId((path.id as Id).name)}`;
    var aliasTarget = (path.id as Id).name;
    if (let (true, resolved) = aliases.get(key)) {
      aliasTarget = resolved;
    }
    // Check if aliasTarget has a package prefix (contains a '/')
    var slashIdx = -1;
    for (var i = 0; i < aliasTarget.length; i += 1) {
      if (aliasTarget.getByteAt(i) == 47) { // '/'
        slashIdx = i;
        break;
      }
    }
    if (slashIdx >= 0) {
      deps.push(aliasTarget.sliceBytes(0, slashIdx));
    }
  }
}

function collectInterfaceDepsOnly(aliases: HashMap<String, String>, pkgName: String, items: Array<InterfaceItem>, deps: GrowableArray<String>) {
  for (let ifaceItem in items) {
    if (ifaceItem.tag == InterfaceItemTag.Use) {
      let u = ifaceItem.use as Use;
      collectPackageDepFromUsePath(aliases, pkgName, u.from, deps);
    }
  }
}

function collectPackageDeps(aliases: HashMap<String, String>, pkgName: String, items: Array<AstItem>, deps: GrowableArray<String>) {
  for (let item in items) {
    if (item.tag == AstItemTag.Interface) {
      let iface = item.interfaceDef as InterfaceDef;
      collectInterfaceDepsOnly(aliases, pkgName, iface.items, deps);
    } else if (item.tag == AstItemTag.World) {
      let world = item.worldDef as WorldDef;
      for (let worldItem in world.items) {
        if (worldItem.tag == WorldItemTag.Import) {
          let imp = worldItem.importItem as Import;
          if (imp.kind.tag == ExternKindTag.Path) {
            collectPackageDepFromUsePath(aliases, pkgName, imp.kind.path as UsePath, deps);
          } else if (imp.kind.tag == ExternKindTag.Interface) {
            let inlineItems = imp.kind.items as GrowableArray<InterfaceItem>;
            collectInterfaceDepsOnly(aliases, pkgName, inlineItems, deps);
          }
        } else if (worldItem.tag == WorldItemTag.Export) {
          let exp = worldItem.exportItem as Export;
          if (exp.kind.tag == ExternKindTag.Path) {
            collectPackageDepFromUsePath(aliases, pkgName, exp.kind.path as UsePath, deps);
          } else if (exp.kind.tag == ExternKindTag.Interface) {
            let inlineItems = exp.kind.items as GrowableArray<InterfaceItem>;
            collectInterfaceDepsOnly(aliases, pkgName, inlineItems, deps);
          }
        } else if (worldItem.tag == WorldItemTag.Use) {
          let u = worldItem.use as Use;
          collectPackageDepFromUsePath(aliases, pkgName, u.from, deps);
        } else if (worldItem.tag == WorldItemTag.Include) {
          let inc = worldItem.include as Include;
          collectPackageDepFromUsePath(aliases, pkgName, inc.from, deps);
        }
        }
    }
  }
}

function sortPackages(pkgSources: GrowableArray<{name: PackageName | null, items: GrowableArray<AstItem>}>, pkgDeps: HashMap<String, GrowableArray<String>>, pkgOrder: GrowableArray<String>) {
  let sorted = new GrowableArray<{name: PackageName | null, items: GrowableArray<AstItem>}>();
  if (pkgSources.length == 0) {
    return sorted;
  }
  
  // First, map package names to their pkgSources elements
  let pkgMap = new HashMap<String, {name: PackageName | null, items: GrowableArray<AstItem>}>();
  let keys = new GrowableArray<String>();
  
  for (let src in pkgSources) {
    let key = formatPackageName(src.name);
    pkgMap[key] = src;
    keys.push(key);
  }
  
  // Sort the keys alphabetically/semver to ensure deterministic start order
  for (var i = 0; i < keys.length; i += 1) {
    for (var j = i + 1; j < keys.length; j += 1) {
      if (comparePackageNameStrings(pkgOrder, keys[i], keys[j]) > 0) {
        let temp = keys[i];
        keys[i] = keys[j];
        keys[j] = temp;
      }
      }
  }
  
  // Now do a topological sort using DFS.
  // visited maps key -> status (0 = unvisited, 1 = visiting, 2 = visited)
  let visited = new HashMap<String, i32>();
  
  let visit = (key: String): void => {
    if (let (true, status) = visited.get(key)) {
      if (status == 1 || status == 2) {
        return;
      }
    }
    
    visited[key] = 1;
    
    // Visit dependencies
    if (let (true, depsList) = pkgDeps.get(key)) {
      let deps = depsList;
      
      // Sort dependencies alphabetically/semver for deterministic visit order
      for (var dI = 0; dI < deps.length; dI += 1) {
        for (var dJ = dI + 1; dJ < deps.length; dJ += 1) {
          if (comparePackageNameStrings(pkgOrder, deps[dI], deps[dJ]) > 0) {
            let temp = deps[dI];
            deps[dI] = deps[dJ];
            deps[dJ] = temp;
          }
          }
      }
      
      for (let depKey in deps) {
        if (pkgMap.has(depKey)) {
          visit(depKey);
        }
      }
    }
    
    visited[key] = 2;
    if (let (true, srcObj) = pkgMap.get(key)) {
      sorted.push(srcObj);
    }
  };
  
  // Visit all keys in alphabetical order
  for (var idx = 0; idx < keys.length; idx += 1) {
    visit(keys[idx]);
  }
  
  return sorted;
}

function collectFromAst(ctx: SerializeContext, ast: Ast, pkgDeps: HashMap<String, GrowableArray<String>>, pkgOrder: GrowableArray<String>) {
  let pkgSources = new GrowableArray<{name: PackageName | null, items: GrowableArray<AstItem>}>();
  pkgSources.push({name: ast.packageName, items: ast.items});
  
  for (let np in ast.nestedPackages) {
    pkgSources.push({name: np.name, items: np.items});
  }

  let finalPkgSources = sortPackages(pkgSources, pkgDeps, pkgOrder);
  
  let globalInterfaces = new GrowableArray<InterfaceDef>();
  let globalWorlds = new GrowableArray<WorldDef>();
  
  for (var pIdxVar = 0; pIdxVar < finalPkgSources.length; pIdxVar += 1) {
    let src = finalPkgSources[pIdxVar];
    let pkgName = formatPackageName(src.name);
    let pkg = new PackageEntry(pkgName);
    ctx.packages.push(pkg);
    
    let rawInterfaces = new GrowableArray<InterfaceDef>();
    let rawWorlds = new GrowableArray<WorldDef>();
    
    for (let item in src.items) {
      if (item.tag == AstItemTag.Interface) {
        let iface = item.interfaceDef as InterfaceDef;
        iface.packageIndex = pIdxVar;
        rawInterfaces.push(iface);
      } else if (item.tag == AstItemTag.World) {
        let world = item.worldDef as WorldDef;
        world.packageIndex = pIdxVar;
        rawWorlds.push(world);
      }
      }
    
    // Collect inline interfaces defined within the worlds of this package
    for (let world in rawWorlds) {
      for (let item in world.items) {
        if (item.tag == WorldItemTag.Import) {
          let imp = item.importItem as Import;
          if (imp.kind.tag == ExternKindTag.Interface) {
            let kind = imp.kind;
            let name = kind.name as Id;
            let nameId = new Id("[import]" + name.name, name.span);
            let inlineIface = new InterfaceDef(imp.docs, nameId);
            inlineIface.items = kind.items as GrowableArray<InterfaceItem>;
            inlineIface.isInline = true;
            inlineIface.packageIndex = pIdxVar;
            rawInterfaces.push(inlineIface);
          }
        } else if (item.tag == WorldItemTag.Export) {
          let exp = item.exportItem as Export;
          if (exp.kind.tag == ExternKindTag.Interface) {
            let kind = exp.kind;
            let name = kind.name as Id;
            let nameId = new Id("[export]" + name.name, name.span);
            let inlineIface = new InterfaceDef(exp.docs, nameId);
            inlineIface.items = kind.items as GrowableArray<InterfaceItem>;
            inlineIface.isInline = true;
            inlineIface.packageIndex = pIdxVar;
            rawInterfaces.push(inlineIface);
          }
        }
        }
      }
    
    // Append package items to global list
    for (var rI = 0; rI < rawInterfaces.length; rI += 1) {
      globalInterfaces.push(rawInterfaces[rI]);
      }
    
    for (var rW = 0; rW < rawWorlds.length; rW += 1) {
      globalWorlds.push(rawWorlds[rW]);
      }
    
  }
  
  let sortedInterfaces = sortInterfaces(ctx, globalInterfaces);
  let sortedWorlds = sortWorlds(globalWorlds);
  
  for (let iface in sortedInterfaces) {
    let ifaceIdx = ctx.registerInterface(iface);
    let pkg = ctx.packages[iface.packageIndex];
    if (pkg.name.length > 0) {
      if (iface.isInline) {
        ctx.interfaceIndices[`${pkg.name}/inline/${normalizeId(iface.name.name)}`] = ifaceIdx;
      } else {
        ctx.interfaceIndices[`${pkg.name}/${normalizeId(iface.name.name)}`] = ifaceIdx;
      }
    }
    if (!iface.isInline) {
      pkg.interfaces[normalizeId(iface.name.name)] = ifaceIdx;
    }
  }
  
  for (let world in sortedWorlds) {
    let worldIdx = ctx.registerWorld(world);
    let pkg = ctx.packages[world.packageIndex];
    pkg.worlds[normalizeId(world.name.name)] = worldIdx;
  }
}

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

/**
 * Serialize a parsed AST to JSON format matching wasm-tools output.
 */
export function serializeAstToJson(ast: Ast, pkgOrderStr: String | null = null): String {
  let aliases = new HashMap<String, String>();
  
  let pkgSources = new GrowableArray<{name: PackageName | null, items: GrowableArray<AstItem>}>();
  pkgSources.push({name: ast.packageName, items: ast.items});
  for (let np in ast.nestedPackages) {
    pkgSources.push({name: np.name, items: np.items});
  }
  
  for (let src in pkgSources) {
    let pkgName = formatPackageName(src.name);
    for (let item in src.items) {
      if (item.tag == AstItemTag.Use) {
        let u = item.use as ToplevelUse;
        let alias = if (u.asName != null) (u.asName as Id).name else getUsePathInterfaceName(u.item);
        let target = getUsePathInterfaceName(u.item);
        
        let resolvedTarget = if (u.item.tag == UsePathTag.Id) {
          `${pkgName}/${target}`;
        } else {
          target;
        };
        
        aliases[`${pkgName}/${normalizeId(alias)}`] = resolvedTarget;
      }
      }
  }

  let pkgDeps = new HashMap<String, GrowableArray<String>>();
  
  let mainKey = formatPackageName(ast.packageName);
  let mainDeps = new GrowableArray<String>();
  collectPackageDeps(aliases, mainKey, ast.items, mainDeps);
  pkgDeps[mainKey] = mainDeps;
  
  for (let np in ast.nestedPackages) {
    let key = formatPackageName(np.name);
    let deps = new GrowableArray<String>();
    collectPackageDeps(aliases, key, np.items, deps);
    pkgDeps[key] = deps;
  }

  let pkgOrder = new GrowableArray<String>();
  if (pkgOrderStr != null) {
    let str = pkgOrderStr;
    var start = 0;
    for (var i = 0; i < str.length; i += 1) {
      if (str.getByteAt(i) == 44) { // ','
        if (i > start) {
          pkgOrder.push(str.sliceBytes(start, i));
        }
        start = i + 1;
      }
    }
    if (str.length > start) {
      pkgOrder.push(str.sliceBytes(start, str.length));
    }
  }

  filterGatedItems(ast);
  let ctx = new SerializeContext();
  ctx.useAliases = aliases;
  collectFromAst(ctx, ast, pkgDeps, pkgOrder);
  registerAllTypesAndScopeSignatures(ctx);
  
  let b = new JsonBuilder();
  b.beginObject();
  
  b.key("interfaces").beginArray();
  for (var iIdx = 0; iIdx < ctx.interfaces.length; iIdx += 1) {
    serializeInterface(b, ctx, ctx.interfaces[iIdx], iIdx);
  }
  b.endArray();
  
  b.key("worlds").beginArray();
  for (var wIdx = 0; wIdx < ctx.worlds.length; wIdx += 1) {
    serializeWorld(b, ctx, ctx.worlds[wIdx], wIdx);
  }
  b.endArray();
  
  b.key("types").beginArray();
  for (var tIdx = 0; tIdx < ctx.types.length; tIdx += 1) {
    ctx.types[tIdx].serialize(b);
  }
  b.endArray();
  
  b.key("packages").beginArray();
  for (var pIdx = 0; pIdx < ctx.packages.length; pIdx += 1) {
    ctx.packages[pIdx].serialize(b);
  }
  b.endArray();
  
  b.endObject();
  return b.toString();
}
none
VersionPublishedDependenciesApproved by
0.0.1-preview.1 2026-11-19 none