/** * WIT Resolver * * Performs semantic validation on the parsed AST. Detects errors like: * - Duplicate definitions (types, interfaces, worlds) * - Undefined type references * - Cyclic type dependencies * - Invalid use statements * - Empty enums/variants * - Invalid borrow in return position * - Invalid map key types * - Feature gate violations (@since/@unstable) * - Cross-package reference validation * * Based on the canonical implementation in wasm-tools: * https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-parser/src/ast/resolve.rs */ import {StringBuilder} from 'zena:core'; import {Span} from './token.zena'; import { Ast, AstItem, AstItemTag, InterfaceDef, WorldDef, TypeDef, TypeDefTag, InterfaceItem, InterfaceItemTag, WorldItem, WorldItemTag, Use, UsePath, UsePathTag, Type, TypeTag, Field, Case, EnumCaseDef, FlagDef, NamedFunc, Func, Param, ResourceFunc, ResourceFuncTag, Id, PackageName, ToplevelUse, NestedPackage, Export, Import, ExternKind, ExternKindTag, Include, IncludeName, UseName, Docs, Attribute, AttributeTag } from './parser.zena'; // ============================================================================ // Resolution Error // ============================================================================ /** * Error produced during resolution/semantic validation. */ export class ResolveError extends Error { span: Span; new(message: String, span: Span) : span = span, super(message); } // ============================================================================ // Symbol Table Entry // ============================================================================ /** Tag for symbol kinds. */ export enum SymbolKind { Type, Resource, Interface, World, Func, } /** An entry in the symbol table. */ export class SymbolEntry { name: String; kind: SymbolKind; span: Span; /** Whether this symbol is feature-gated (has @unstable annotation). */ var isGated = false; /** The source of this symbol (e.g., world name for include tracking). */ var source: String | null = null; /** Whether this is a path import (vs inline interface). Path imports can be deduplicated. */ var isPathImport = false; new(name: String, kind: SymbolKind, span: Span) : name = name, kind = kind, span = span; static gated(name: String, kind: SymbolKind, span: Span): SymbolEntry { let s = new SymbolEntry(name, kind, span); s.isGated = true; return s; } static withSource(name: String, kind: SymbolKind, span: Span, source: String): SymbolEntry { let s = new SymbolEntry(name, kind, span); s.source = source; return s; } static pathImport(name: String, kind: SymbolKind, span: Span, source: String): SymbolEntry { let s = new SymbolEntry(name, kind, span); s.source = source; s.isPathImport = true; return s; } } // ============================================================================ // Package Registry // ============================================================================ /** Convert a PackageName to a lookup key (namespace:name@version if version present). */ function packageNameToKey(name: PackageName) { var key = `${name.namespace.name}:${name.name.name}`; if (name.version != null) { key = `${key}@${name.version as String}`; } return key; } /** * Contents of a package - its interfaces and worlds. */ class PackageContent { /** Interfaces defined in this package, keyed by name. */ interfaces = new HashMap(); /** Worlds defined in this package, keyed by name. */ worlds = new HashMap(); /** The package name for error messages. */ name: PackageName; new(name: PackageName) : name = name; } /** * Registry of all packages in the AST, for cross-package reference resolution. */ class PackageRegistry { /** Map from package key (namespace:name) to package content. */ #packages = new HashMap(); /** List of all package keys for error messages. */ #knownPackages = new GrowableArray(); /** Build a registry from an AST. */ static build(ast: Ast): PackageRegistry { let registry = new PackageRegistry(); // Register main package if (ast.packageName != null) { let name = ast.packageName as PackageName; registry.#registerPackage(name, ast.items); } // Register nested packages for (let pkg in ast.nestedPackages) { registry.#registerPackage(pkg.name, pkg.items); } return registry; } /** Register a package with its items. */ #registerPackage(name: PackageName, items: Array): void { let key = packageNameToKey(name); // Check for duplicate package if (this.#packages.has(key)) { // Later we can make this an error, for now just merge } let content = new PackageContent(name); // Collect interfaces and worlds for (let item in items) { if (item.tag == AstItemTag.Interface) { let iface = item.interfaceDef as InterfaceDef; content.interfaces[iface.name.name] = iface; } else if (item.tag == AstItemTag.World) { let world = item.worldDef as WorldDef; content.worlds[world.name.name] = world; } } this.#packages[key] = content; this.#knownPackages.push(key); } /** Look up a package by full key (including version if present). */ getPackageByName(pkgName: PackageName): PackageContent | null { let key = packageNameToKey(pkgName); if (let (true, content) = this.#packages.get(key)) { return content; } return null; } /** Look up a package by namespace:name (legacy, without version). */ getPackage(namespace: String, name: String): PackageContent | null { let key = `${namespace}:${name}`; if (let (true, content) = this.#packages.get(key)) { return content; } return null; } /** Look up an interface by PackageName and interface name. */ getInterfaceByPkg(pkgName: PackageName, ifaceName: String): InterfaceDef | null { let pkg = this.getPackageByName(pkgName); if (pkg == null) { return null; } let p = pkg; if (let (true, iface) = p.interfaces.get(ifaceName)) { return iface; } return null; } /** Look up an interface by full path (namespace:name/interface). Legacy without version. */ getInterface(namespace: String, pkgName: String, ifaceName: String): InterfaceDef | null { let pkg = this.getPackage(namespace, pkgName); if (pkg == null) { return null; } let p = pkg; if (let (true, iface) = p.interfaces.get(ifaceName)) { return iface; } return null; } /** Look up a world by PackageName and world name. */ getWorldByPkg(pkgName: PackageName, worldName: String): WorldDef | null { let pkg = this.getPackageByName(pkgName); if (pkg == null) { return null; } let p = pkg; if (let (true, world) = p.worlds.get(worldName)) { return world; } return null; } /** Look up a world by full path (namespace:name/world). Legacy without version. */ getWorld(namespace: String, pkgName: String, worldName: String): WorldDef | null { let pkg = this.getPackage(namespace, pkgName); if (pkg == null) { return null; } let p = pkg; if (let (true, world) = p.worlds.get(worldName)) { return world; } return null; } /** Check if a package exists by PackageName (with version). */ hasPackageByName(pkgName: PackageName): boolean { let key = packageNameToKey(pkgName); return this.#packages.has(key); } /** Check if a package exists (legacy, without version). */ hasPackage(namespace: String, name: String): boolean { let key = `${namespace}:${name}`; return this.#packages.has(key); } /** Get list of known package names for error messages. */ getKnownPackages(): Array { return this.#knownPackages; } } // ============================================================================ // Helper Functions // ============================================================================ /** Convert a string to lowercase (simple ASCII version). */ function toLower(s: String) { let sb = new StringBuilder(s.length); for (var i = 0; i < s.length; i += 1) { let b = s.getByteAt(i); // A-Z (65-90) -> a-z (97-122) if (b >= 65 && b <= 90) { sb.appendByte(b + 32); } else { sb.appendByte(b); } } return sb.toString(); } /** Find a symbol in a list by name (case-insensitive). */ function findSymbolInList(symbols: Array, name: String): SymbolEntry | null { let lower = toLower(name); for (let sym in symbols) { if (toLower(sym.name) == lower) { return sym; } } return null; } /** Check if a type is a valid map key type. */ function isValidMapKeyType(t: Type) { return t.tag == TypeTag.Bool || t.tag == TypeTag.U8 || t.tag == TypeTag.U16 || t.tag == TypeTag.U32 || t.tag == TypeTag.U64 || t.tag == TypeTag.S8 || t.tag == TypeTag.S16 || t.tag == TypeTag.S32 || t.tag == TypeTag.S64 || t.tag == TypeTag.Char || t.tag == TypeTag.String; } /** Check if a Docs has an @unstable attribute (feature gated). */ function isGated(docs: Docs): boolean { if (docs.attributes == null) { return false; } let attrs = docs.attributes as GrowableArray; for (var i = 0; i < attrs.length; i += 1) { if (attrs[i].tag == AttributeTag.Unstable) { return true; } } return false; } /** Get the full path string from a UsePath. */ function getFullPath(path: UsePath) { if (path.tag == UsePathTag.Id) { return (path.id as Id).name; } // Package style: namespace:name/interface let pkg = path.packageId as PackageName; let name = (path.name as Id).name; return `${pkg.namespace.name}:${pkg.name.name}/${name}`; } // ============================================================================ // Scope // ============================================================================ /** * A scope for name resolution. Contains symbols defined at this level. */ class Scope { symbols = new GrowableArray(); /** Types defined in this scope (for cycle detection). */ types = new GrowableArray(); /** Worlds defined in this scope (for include cycle detection). */ worlds = new GrowableArray(); /** Interfaces defined in this scope (for use validation). */ interfaces = new GrowableArray(); /** Find a symbol by name (case-insensitive for kebab-case). */ find(name: String): SymbolEntry | null { let lower = toLower(name); for (let sym in this.symbols) { if (toLower(sym.name) == lower) { return sym; } } return null; } /** Add a symbol, returning error if duplicate. */ add(name: String, kind: SymbolKind, span: Span, gated: boolean): ResolveError | null { let existing = this.find(name); if (existing != null) { let e = existing; // Case-insensitive check for kebab-case identifiers if (toLower(name) == toLower(e.name) && !(name == e.name)) { return new ResolveError( `name \`${name}\` conflicts with \`${e.name}\` (kebab-case identifiers are case-insensitive)`, span ); } return new ResolveError(`name \`${name}\` is defined more than once`, span); } let sym = if (gated) SymbolEntry.gated(name, kind, span) else new SymbolEntry(name, kind, span); this.symbols.push(sym); return null; } /** Find a type by name. */ findType(name: String): TypeDef | null { for (let td in this.types) { if (td.name.name == name) { return td; } } return null; } /** Find a world by name. */ findWorld(name: String): WorldDef | null { for (let wd in this.worlds) { if (wd.name.name == name) { return wd; } } return null; } /** Find an interface by name. */ findInterface(name: String): InterfaceDef | null { for (let iface in this.interfaces) { if (iface.name.name == name) { return iface; } } return null; } } // ============================================================================ // Resolver // ============================================================================ /** * Resolves an AST, performing semantic validation. */ export class Resolver { /** Stack of scopes for nested name resolution. */ #scopes = new GrowableArray(); /** Current package name (for error messages). */ var #packageName: PackageName | null = null; /** Current package being resolved (for cross-package cycle detection). */ var #currentResolvePackage: PackageName | null = null; /** Types being resolved (for cycle detection). */ #resolving = new GrowableArray(); /** Interfaces being resolved (for use cycle detection). Uses qualified names: "pkg:name/iface". */ #resolvingInterfaces = new GrowableArray(); /** Worlds being included (for include cycle detection). */ #includingWorlds = new GrowableArray(); /** Whether we're currently inside a gated context (@unstable). */ var #inGatedContext = false; /** Registry of all packages for cross-package resolution. */ var #registry: PackageRegistry | null = null; /** Current interface being resolved (for imported type lookup). */ var #currentInterface: InterfaceDef | null = null; /** * Resolve an AST. Throws ResolveError on validation failure. */ static resolve(ast: Ast): void { let resolver = new Resolver(); // Build registry of all packages first resolver.#registry = PackageRegistry.build(ast); resolver.#resolveAst(ast); } // -------------------------------------------------------------------------- // Scope Management // -------------------------------------------------------------------------- #pushScope(): void { this.#scopes.push(new Scope()); } #popScope(): void { if (this.#scopes.length > 0) { this.#scopes.pop(); } } #currentScope(): Scope { if (this.#scopes.length == 0) { // Create a root scope if none exists this.#pushScope(); } return this.#scopes[this.#scopes.length - 1]; } /** Find a symbol in any scope (innermost first). */ #findSymbol(name: String): SymbolEntry | null { for (var i = this.#scopes.length - 1; i >= 0; i -= 1) { let sym = this.#scopes[i].find(name); if (sym != null) { return sym; } } return null; } /** Define a symbol in current scope. */ #define(name: String, kind: SymbolKind, span: Span): void { this.#defineWithGating(name, kind, span, false); } /** Define a symbol in current scope with explicit gating. */ #defineWithGating(name: String, kind: SymbolKind, span: Span, gated: boolean): void { let err = this.#currentScope().add(name, kind, span, gated); if (err != null) { throw err; } } /** Check if referencing a gated symbol from non-gated context. */ #checkGatedReference(sym: SymbolEntry, refSpan: Span, itemKind: String): void { if (sym.isGated && !this.#inGatedContext) { throw new ResolveError( `found a reference to a ${itemKind} which is excluded due to its feature not being activated`, refSpan ); } } // -------------------------------------------------------------------------- // AST Resolution // -------------------------------------------------------------------------- #resolveAst(ast: Ast): void { // Check that a package declaration exists: // - Empty files need a package declaration (no items, no nested packages) // - Files with top-level items need a package declaration // - Files with only nested packages don't need a top-level package declaration if (ast.packageName == null && (ast.nestedPackages.length == 0 || ast.items.length > 0)) { throw new ResolveError( "no `package` header was found in any WIT file for this package", new Span(0, 0) ); } this.#packageName = ast.packageName; this.#currentResolvePackage = ast.packageName; this.#pushScope(); // First pass: collect interfaces and worlds (they take priority over use aliases) for (let item in ast.items) { if (item.tag == AstItemTag.Interface) { let iface = item.interfaceDef as InterfaceDef; let gated = isGated(iface.docs); this.#defineWithGating(iface.name.name, SymbolKind.Interface, iface.name.span, gated); // Store interface definition for use validation this.#currentScope().interfaces.push(iface); } else if (item.tag == AstItemTag.World) { let world = item.worldDef as WorldDef; let gated = isGated(world.docs); this.#defineWithGating(world.name.name, SymbolKind.World, world.name.span, gated); // Store the world definition for include cycle detection this.#currentScope().worlds.push(world); } } // Second mini-pass: collect top-level use aliases // Check for conflicts where a use alias appears BEFORE an interface/world in source order // but only if they're in the same "file" (no package declaration between them) let packageDeclPos = if (ast.packageName != null) (ast.packageName as PackageName).span.start else 0; for (let item in ast.items) { if (item.tag == AstItemTag.Use) { let use = item.use as ToplevelUse; let name = if (use.asName != null) (use.asName as Id).name else use.item.getName().name; let span = if (use.asName != null) (use.asName as Id).span else use.item.getName().span; let existing = this.#findSymbol(name); if (existing != null) { // Name already defined. Check if this use alias came BEFORE the definition. let e = existing; if (span.start < e.span.start) { // Use alias defined first, interface/world defined after. // But if the package declaration is BETWEEN them, they're in different files. let useBeforePkg = span.start < packageDeclPos; let defAfterPkg = e.span.start > packageDeclPos; if (useBeforePkg && defAfterPkg) { // Different files - silently shadow the use alias } else { // Same file - error throw new ResolveError( `duplicate name \`${name}\` in this file`, e.span ); } } // Otherwise, use alias is after the definition - silently shadow } else { this.#define(name, SymbolKind.Interface, span); } } } // Second pass: resolve each item for (let item in ast.items) { this.#resolveAstItem(item); } // Check for duplicate nested package names this.#checkDuplicateNestedPackages(ast.nestedPackages); // Resolve nested packages - each gets its own scope for (let pkg in ast.nestedPackages) { this.#resolveNestedPackage(pkg); } this.#popScope(); } /** Check for duplicate nested package names. */ #checkDuplicateNestedPackages(packages: Array): void { for (var i = 0; i < packages.length; i += 1) { let pkg1 = packages[i]; let name1 = this.#packageNameToString(pkg1.name); for (var j = i + 1; j < packages.length; j += 1) { let pkg2 = packages[j]; let name2 = this.#packageNameToString(pkg2.name); if (name1 == name2) { throw new ResolveError( `package ${name1} is defined in two different locations`, pkg2.name.span ); } } } } /** Convert a PackageName to a string for comparison. */ #packageNameToString(pkg: PackageName): String { let base = `${pkg.namespace.name}:${pkg.name.name}`; if (pkg.version != null) { return `${base}@${pkg.version as String}`; } return base; } /** Build qualified interface name for cycle detection: "pkg:name/iface". */ #getQualifiedInterfaceName(ifaceName: String): String { if (this.#currentResolvePackage != null) { let pkg = this.#currentResolvePackage as PackageName; return `${this.#packageNameToString(pkg)}/${ifaceName}`; } return ifaceName; } /** Build qualified interface name from package and interface name. */ #buildQualifiedName(pkg: PackageName, ifaceName: String): String { return `${this.#packageNameToString(pkg)}/${ifaceName}`; } #resolveAstItem(item: AstItem): void { if (item.tag == AstItemTag.Interface) { this.#resolveInterface(item.interfaceDef as InterfaceDef); } else if (item.tag == AstItemTag.World) { this.#resolveWorld(item.worldDef as WorldDef); } else if (item.tag == AstItemTag.Use) { this.#resolveToplevelUse(item.use as ToplevelUse); } } // -------------------------------------------------------------------------- // Nested Package Resolution // -------------------------------------------------------------------------- #resolveNestedPackage(pkg: NestedPackage): void { // Track which package we're resolving for cycle detection let prevPackage = this.#currentResolvePackage; this.#currentResolvePackage = pkg.name; // Each nested package gets its own scope this.#pushScope(); // First pass: collect all names in this package (interfaces, worlds, and top-level use aliases) for (let item in pkg.items) { if (item.tag == AstItemTag.Interface) { let iface = item.interfaceDef as InterfaceDef; this.#define(iface.name.name, SymbolKind.Interface, iface.name.span); // Store interface definition for use validation this.#currentScope().interfaces.push(iface); } else if (item.tag == AstItemTag.World) { let world = item.worldDef as WorldDef; this.#define(world.name.name, SymbolKind.World, world.name.span); // Store world definition for include resolution (needed for #findWorldDef) this.#currentScope().worlds.push(world); } else if (item.tag == AstItemTag.Use) { // Top-level use creates an alias - handle like in resolve() let use = item.use as ToplevelUse; let name = if (use.asName != null) (use.asName as Id).name else use.item.getName().name; let span = if (use.asName != null) (use.asName as Id).span else use.item.getName().span; let existing = this.#findSymbol(name); if (existing == null) { this.#define(name, SymbolKind.Interface, span); } // else: silently shadow - will resolve in second pass } } // Second pass: resolve each item for (var i = 0; i < pkg.items.length; i += 1) { this.#resolveAstItem(pkg.items[i]); } this.#popScope(); this.#currentResolvePackage = prevPackage; } // -------------------------------------------------------------------------- // Interface Resolution // -------------------------------------------------------------------------- #resolveInterface(iface: InterfaceDef): void { let ifaceGated = isGated(iface.docs); let prevGatedContext = this.#inGatedContext; let prevInterface = this.#currentInterface; // Track this interface for use cycle detection using qualified name let qualifiedName = this.#getQualifiedInterfaceName(iface.name.name); this.#resolvingInterfaces.push(qualifiedName); // Track current interface for imported type lookup this.#currentInterface = iface; // If interface is gated, we're now in a gated context if (ifaceGated) { this.#inGatedContext = true; } this.#pushScope(); // First pass: collect all type names and functions with gating info for (let item in iface.items) { if (item.tag == InterfaceItemTag.TypeDef) { let td = item.typeDef as TypeDef; let itemGated = isGated(td.docs); // Resources get their own symbol kind let kind = if (td.tag == TypeDefTag.Resource) SymbolKind.Resource else SymbolKind.Type; // If interface is gated, items must also be gated (bad-gate3) if (ifaceGated && !itemGated) { throw new ResolveError( "this type is not gated by a feature but its interface is gated by a feature: found a reference to a interface which is excluded due to its feature not being activated", td.name.span ); } this.#defineWithGating(td.name.name, kind, td.name.span, itemGated); this.#currentScope().types.push(td); } else if (item.tag == InterfaceItemTag.Func) { let f = item.func as NamedFunc; let itemGated = isGated(f.docs); this.#defineWithGating(f.name.name, SymbolKind.Func, f.name.span, itemGated); } } // Second pass: resolve types and validate for (let item in iface.items) { this.#resolveInterfaceItem(item); } this.#popScope(); this.#inGatedContext = prevGatedContext; this.#currentInterface = prevInterface; this.#resolvingInterfaces.pop(); } #resolveInterfaceItem(item: InterfaceItem): void { if (item.tag == InterfaceItemTag.TypeDef) { let td = item.typeDef as TypeDef; // Set gated context for resolving this type let prevGatedContext = this.#inGatedContext; if (isGated(td.docs)) { this.#inGatedContext = true; } this.#resolveTypeDef(td); this.#inGatedContext = prevGatedContext; } else if (item.tag == InterfaceItemTag.Func) { let f = item.func as NamedFunc; // Set gated context for resolving this function let prevGatedContext = this.#inGatedContext; if (isGated(f.docs)) { this.#inGatedContext = true; } this.#resolveNamedFunc(f); this.#inGatedContext = prevGatedContext; } else if (item.tag == InterfaceItemTag.Use) { let u = item.use as Use; let prevGatedContext = this.#inGatedContext; if (isGated(u.docs)) { this.#inGatedContext = true; } this.#resolveUse(u); this.#inGatedContext = prevGatedContext; } } // -------------------------------------------------------------------------- // World Resolution // -------------------------------------------------------------------------- #resolveWorld(world: WorldDef): void { // Track this world for include cycle detection this.#includingWorlds.push(world.name.name); this.#pushScope(); // Track import/export names separately for conflict detection let imports = new GrowableArray(); let exports = new GrowableArray(); // First pass: collect names from type definitions for (let item in world.items) { if (item.tag == WorldItemTag.TypeDef) { let td = item.typeDef as TypeDef; this.#define(td.name.name, SymbolKind.Type, td.name.span); this.#currentScope().types.push(td); } } // Second pass: resolve items and check import/export conflicts for (let item in world.items) { this.#resolveWorldItem(item, imports, exports, world.name.name); } // Third pass: check for transitive dependency conflicts this.#checkTransitiveDependencyConflicts(world); this.#popScope(); this.#includingWorlds.pop(); } #resolveWorldItem(item: WorldItem, imports: GrowableArray, exports: GrowableArray, worldName: String): void { if (item.tag == WorldItemTag.Import) { let imp = item.importItem as Import; // Set gated context based on the import's docs let prevGatedContext = this.#inGatedContext; if (isGated(imp.docs)) { this.#inGatedContext = true; } this.#resolveExternKind(imp.kind, true, imports, worldName); this.#inGatedContext = prevGatedContext; } else if (item.tag == WorldItemTag.Export) { let exp = item.exportItem as Export; // Set gated context based on the export's docs let prevGatedContext = this.#inGatedContext; if (isGated(exp.docs)) { this.#inGatedContext = true; } this.#resolveExternKind(exp.kind, false, exports, worldName); this.#inGatedContext = prevGatedContext; } else if (item.tag == WorldItemTag.Use) { let u = item.use as Use; let prevGatedContext = this.#inGatedContext; if (isGated(u.docs)) { this.#inGatedContext = true; } this.#resolveUse(u); this.#inGatedContext = prevGatedContext; } else if (item.tag == WorldItemTag.TypeDef) { let td = item.typeDef as TypeDef; let prevGatedContext = this.#inGatedContext; if (isGated(td.docs)) { this.#inGatedContext = true; } this.#resolveTypeDef(td); this.#inGatedContext = prevGatedContext; } else if (item.tag == WorldItemTag.Include) { let inc = item.include as Include; // Set gated context based on the include's docs let prevGatedContext = this.#inGatedContext; if (isGated(inc.docs)) { this.#inGatedContext = true; } // Check include for shadowing before resolving this.#checkIncludeShadowing(inc, imports, exports); this.#resolveInclude(inc); this.#inGatedContext = prevGatedContext; } } /** Check if an include statement would shadow existing imports/exports. */ #checkIncludeShadowing(include: Include, imports: GrowableArray, exports: GrowableArray): void { // Only check for local world references if (include.from.tag != UsePathTag.Id) { return; } let id = include.from.id as Id; let worldDef = this.#findWorldDef(id.name); if (worldDef == null) { return; } let w = worldDef; let worldName = id.name; // Check each item in the included world for (var i = 0; i < w.items.length; i += 1) { let item = w.items[i]; if (item.tag == WorldItemTag.Import) { let imp = item.importItem as Import; // Skip gated imports - they don't really exist in the active feature set if (isGated(imp.docs)) { i += 1; continue; } let impName = this.#getExternKindName(imp.kind); let isPath = imp.kind.tag == ExternKindTag.Path; if (impName != null) { let name = impName; // Apply rename if exists let finalName = this.#applyIncludeRename(name, include.names); // Check if this would shadow an existing NON-GATED import let existing = findSymbolInList(imports, finalName); if (existing != null) { let e = existing; // Only error if the existing item is NOT gated AND from a different source // Duplicate includes of the same world are allowed (deduped) if (!e.isGated) { if (e.source != null && (e.source as String) == worldName) { // Same source - this is a duplicate include, skip without error i += 1; continue; } // Path imports of the same interface from different worlds can be deduplicated if (isPath && e.isPathImport) { // Both are path imports to the same interface - deduplicate i += 1; continue; } throw new ResolveError( `import of \`${finalName}\` shadows previously imported items`, id.span ); } } // Add to imports for future shadowing checks, with source tracking if (isPath) { imports.push(SymbolEntry.pathImport(finalName, SymbolKind.Func, id.span, worldName)); } else { imports.push(SymbolEntry.withSource(finalName, SymbolKind.Func, id.span, worldName)); } } } else if (item.tag == WorldItemTag.Export) { let exp = item.exportItem as Export; // Skip gated exports if (isGated(exp.docs)) { i += 1; continue; } let expName = this.#getExternKindName(exp.kind); let isPath = exp.kind.tag == ExternKindTag.Path; if (expName != null) { let name = expName; let finalName = this.#applyIncludeRename(name, include.names); let existing = findSymbolInList(exports, finalName); if (existing != null) { let e = existing; if (!e.isGated) { if (e.source != null && (e.source as String) == worldName) { // Same source - duplicate include, skip without error i += 1; continue; } // Path exports of the same interface from different worlds can be deduplicated if (isPath && e.isPathImport) { // Both are path exports to the same interface - deduplicate i += 1; continue; } throw new ResolveError( `export of \`${finalName}\` shadows previously exported items`, id.span ); } } if (isPath) { exports.push(SymbolEntry.pathImport(finalName, SymbolKind.Func, id.span, worldName)); } else { exports.push(SymbolEntry.withSource(finalName, SymbolKind.Func, id.span, worldName)); } } } } } /** Get the name from an extern kind, if applicable. */ #getExternKindName(kind: ExternKind): String | null { if (kind.tag == ExternKindTag.Func) { return (kind.name as Id).name; } if (kind.tag == ExternKindTag.Interface) { return (kind.name as Id).name; } if (kind.tag == ExternKindTag.Path) { return (kind.path as UsePath).getName().name; } return null; } /** Apply a rename from include names if the name matches. */ #applyIncludeRename(name: String, names: Array): String { for (let n in names) { if (n.name.name == name) { return n.asName.name; } } return name; } #resolveExternKind(kind: ExternKind, isImport: boolean, symbols: GrowableArray, worldName: String): void { if (kind.tag == ExternKindTag.Func) { let funcName = kind.name as Id; // Check for duplicates in this category (imports or exports) let existing = findSymbolInList(symbols, funcName.name); if (existing != null) { let e = existing; // Skip conflict check if both are gated if (!(e.isGated && this.#inGatedContext)) { let direction = if (isImport) "import" else "export"; throw new ResolveError( `${direction} \`${funcName.name}\` conflicts with prior func of same name`, funcName.span ); } } // Check for conflicts with type definitions in the world let typeSym = this.#findSymbol(funcName.name); if (typeSym != null) { let ts = typeSym; if (ts.kind == SymbolKind.Type) { let direction = if (isImport) "import" else "export"; throw new ResolveError( `${direction} \`${funcName.name}\` conflicts with prior type of same name`, funcName.span ); } } // Mark as gated if in gated context if (this.#inGatedContext) { symbols.push(SymbolEntry.gated(funcName.name, SymbolKind.Func, funcName.span)); } else { symbols.push(new SymbolEntry(funcName.name, SymbolKind.Func, funcName.span)); } // Resolve the function type this.#resolveFunc(kind.funcDef as Func); } else if (kind.tag == ExternKindTag.Interface) { let ifaceName = kind.name as Id; // Check for duplicates let existing = findSymbolInList(symbols, ifaceName.name); if (existing != null) { let e = existing; // Skip conflict check if both are gated if (!(e.isGated && this.#inGatedContext)) { let direction = if (isImport) "import" else "export"; throw new ResolveError( `${direction} \`${ifaceName.name}\` conflicts with prior interface of same name`, ifaceName.span ); } } // Mark as gated if in gated context if (this.#inGatedContext) { symbols.push(SymbolEntry.gated(ifaceName.name, SymbolKind.Interface, ifaceName.span)); } else { symbols.push(new SymbolEntry(ifaceName.name, SymbolKind.Interface, ifaceName.span)); } // Resolve interface items in their own scope (inline interfaces have their own namespace) this.#pushScope(); let items = kind.items as GrowableArray; for (var j = 0; j < items.length; j += 1) { this.#resolveInterfaceItem(items[j]); } this.#popScope(); } else if (kind.tag == ExternKindTag.Path) { let path = kind.path as UsePath; // For path imports, use the full path as the unique identifier let fullPath = getFullPath(path); let pathName = path.getName(); // Check for duplicates using the full path let existing = findSymbolInList(symbols, fullPath); if (existing != null) { let e = existing; // Skip conflict check if both are gated if (!(e.isGated && this.#inGatedContext)) { let direction = if (isImport) "import" else "export"; throw new ResolveError( `${direction} \`${fullPath}\` conflicts with prior ${direction} of same name`, pathName.span ); } } // Mark as gated if in gated context if (this.#inGatedContext) { symbols.push(SymbolEntry.gated(fullPath, SymbolKind.Interface, pathName.span)); // Skip validation for gated items (the target may not exist or may be a world) } else { symbols.push(new SymbolEntry(fullPath, SymbolKind.Interface, pathName.span)); // Validate path references exist (use statements reference interfaces) this.#resolveUsePath(path, false); // Validate path references an interface, not a world (invalid-world-import) this.#validatePathIsInterface(path, isImport); } } } /** Validate that a UsePath references an interface, not a world. */ #validatePathIsInterface(path: UsePath, isImport: boolean): void { if (path.tag == UsePathTag.Id) { let id = path.id as Id; let sym = this.#findSymbol(id.name); if (sym != null) { let s = sym; if (s.kind == SymbolKind.World) { let direction = if (isImport) "import" else "export"; throw new ResolveError( `cannot ${direction} world \`${id.name}\` into a world`, id.span ); } } } // Package paths are validated at link time } // -------------------------------------------------------------------------- // Type Definition Resolution // -------------------------------------------------------------------------- #resolveTypeDef(td: TypeDef): void { // Check for empty enum if (td.tag == TypeDefTag.Enum) { let cases = td.enumCases as GrowableArray; if (cases.length == 0) { throw new ResolveError("empty enum", td.name.span); } // Check for duplicate case names this.#checkDuplicateCaseNames(cases); } // Check for empty variant if (td.tag == TypeDefTag.Variant) { let cases = td.cases as GrowableArray; if (cases.length == 0) { throw new ResolveError("empty variant", td.name.span); } // Check for duplicate case names this.#checkDuplicateVariantCases(cases); // Resolve case types for (let c in cases) { if (c.type != null) { this.#resolveType(c.type as Type, false); } } } // Resolve alias type if (td.tag == TypeDefTag.Alias) { let aliasType = td.aliasType as Type; // Check for cycles this.#resolving.push(td.name.name); this.#resolveType(aliasType, false); this.#resolving.pop(); } // Resolve record fields if (td.tag == TypeDefTag.Record) { let fields = td.fields as GrowableArray; this.#checkDuplicateFieldNames(fields, td.name.span); for (var i = 0; i < fields.length; i += 1) { this.#resolveType(fields[i].type, false); } } // Resolve resource methods if (td.tag == TypeDefTag.Resource) { let funcs = td.resourceFuncs as GrowableArray; // Check for duplicate constructors and method names this.#checkDuplicateResourceFuncs(funcs); // If the resource is gated, check that non-gated members are invalid // because they implicitly reference the gated resource type (bad-gate4, bad-gate5) let resourceGated = isGated(td.docs); for (let rf in funcs) { let funcGated = isGated(rf.func.docs); // If resource is gated and method is not, it's an error if (resourceGated && !funcGated) { throw new ResolveError( "found a reference to a type which is excluded due to its feature not being activated", rf.func.name.span ); } // Validate constructor return type if (rf.tag == ResourceFuncTag.Constructor) { this.#validateConstructorReturn(rf.func, td.name.name); } // Resolve the function with proper gating context let prevGatedContext = this.#inGatedContext; if (funcGated) { this.#inGatedContext = true; } this.#resolveNamedFunc(rf.func); this.#inGatedContext = prevGatedContext; } } // Check for duplicate flags if (td.tag == TypeDefTag.Flags) { let flags = td.flags as GrowableArray; this.#checkDuplicateFlagNames(flags); } } #validateConstructorReturn(f: NamedFunc, resourceName: String): void { let func = f.func; if (func.result == null) { // No return type - that's fine return; } let result = func.result as Type; // Constructor return must be a result type if (result.tag != TypeTag.Result) { throw new ResolveError( "if a constructor return type is declared it must be a `result`", result.span ); } // The ok type must be the resource being constructed (wildcard _ is not allowed) if (result.okType == null) { // Wildcard _ is not allowed throw new ResolveError( "the `ok` type must be the resource being constructed", result.span ); } let okType = result.okType as Type; // ok type must be a Name pointing to this resource if (okType.tag != TypeTag.Name) { throw new ResolveError( "the `ok` type must be the resource being constructed", result.span ); } let okName = (okType.name as Id).name; if (okName != resourceName) { throw new ResolveError( "the `ok` type must be the resource being constructed", okType.span ); } } #checkDuplicateResourceFuncs(funcs: Array): void { var constructorCount = 0; var constructorSpan: Span | null = null; let methodNames = new GrowableArray(); for (let rf in funcs) { if (rf.tag == ResourceFuncTag.Constructor) { constructorCount += 1; if (constructorCount == 1) { constructorSpan = rf.func.name.span; } else { throw new ResolveError("duplicate constructors", rf.func.name.span); } } else { // Method or static - check for duplicate names let name = rf.func.name.name; let existing = findSymbolInList(methodNames, name); if (existing != null) { throw new ResolveError(`duplicate function name \`${name}\``, rf.func.name.span); } methodNames.push(new SymbolEntry(name, SymbolKind.Func, rf.func.name.span)); } } } #checkDuplicateCaseNames(cases: Array): void { for (var i = 0; i < cases.length; i += 1) { for (var j = i + 1; j < cases.length; j += 1) { if (cases[i].name.name == cases[j].name.name) { throw new ResolveError( `duplicate enum case \`${cases[j].name.name}\``, cases[j].name.span ); } } } } #checkDuplicateVariantCases(cases: Array): void { for (var i = 0; i < cases.length; i += 1) { for (var j = i + 1; j < cases.length; j += 1) { if (cases[i].name.name == cases[j].name.name) { throw new ResolveError( `duplicate variant case \`${cases[j].name.name}\``, cases[j].name.span ); } } } } #checkDuplicateFieldNames(fields: Array, typeSpan: Span): void { for (var i = 0; i < fields.length; i += 1) { for (var j = i + 1; j < fields.length; j += 1) { if (fields[i].name.name == fields[j].name.name) { throw new ResolveError( `duplicate field \`${fields[j].name.name}\``, fields[j].name.span ); } } } } #checkDuplicateFlagNames(flags: Array): void { for (var i = 0; i < flags.length; i += 1) { for (var j = i + 1; j < flags.length; j += 1) { if (flags[i].name.name == flags[j].name.name) { throw new ResolveError( `duplicate flag \`${flags[j].name.name}\``, flags[j].name.span ); } } } } // -------------------------------------------------------------------------- // Type Resolution // -------------------------------------------------------------------------- #resolveType(t: Type, inReturnPosition: boolean): void { // Check for borrow in return position if (t.tag == TypeTag.Borrow && inReturnPosition) { throw new ResolveError( "function returns a type which contains a `borrow` which is not supported", t.span ); } // Handle types (borrow and own) must reference a resource if (t.tag == TypeTag.Borrow || t.tag == TypeTag.Own) { let inner = t.inner as Type; // Inner type should always be a Name (enforced by parser) if (inner.tag == TypeTag.Name) { let rawName = (inner.name as Id).name; let name = rawName; let sym = this.#findSymbol(name); if (sym == null) { throw new ResolveError(`type \`${rawName}\` does not exist`, inner.span); } // Check if the type is a resource let s = sym; if (s.kind == SymbolKind.Resource) { // Good - it's a resource return; } if (s.kind == SymbolKind.Type) { // Check if there's a TypeDef that's a resource let td = this.#findTypeDef(name); if (td != null) { if (!this.#isResourceType(td)) { throw new ResolveError(`type \`${rawName}\` used in a handle must be a resource`, inner.span); } // TypeDef is a resource (or alias to one) return; } // No type definition found - imported from another interface via `use` // Since it's registered as Type (not Resource), it's not a valid handle target throw new ResolveError(`type \`${rawName}\` used in a handle must be a resource`, inner.span); } // Symbol is not a Type or Resource (e.g., it's an Interface, World, or Func) throw new ResolveError(`type \`${rawName}\` does not exist`, inner.span); } return; } // Check for named type references if (t.tag == TypeTag.Name) { let rawName = (t.name as Id).name; let name = rawName; // Check for cycle if (this.#isResolving(name)) { throw new ResolveError( `type \`${rawName}\` depends on itself`, t.span ); } // Check if type exists let sym = this.#findSymbol(name); if (sym == null) { throw new ResolveError(`type \`${rawName}\` does not exist`, t.span); } // Check feature gate (bad-gate1): can't reference gated type from non-gated context let s = sym; this.#checkGatedReference(s, t.span, "type"); // Check that the symbol is a type, not a function (invalid-type-reference2) if (s.kind == SymbolKind.Func) { throw new ResolveError( `cannot use function \`${rawName}\` as a type`, t.span ); } // Follow type aliases to detect transitive cycles let td = this.#findTypeDef(name); if (td != null) { let typeDef = td; if (typeDef.tag == TypeDefTag.Alias) { // Add this type to the resolving stack and resolve its alias this.#resolving.push(name); this.#resolveType(typeDef.aliasType as Type, inReturnPosition); this.#resolving.pop(); } else if (typeDef.tag == TypeDefTag.Record) { // Check record fields for cycles and borrow usage this.#resolving.push(name); let fields = typeDef.fields as GrowableArray; for (var i = 0; i < fields.length; i += 1) { // Propagate inReturnPosition to catch borrow in record fields this.#resolveType(fields[i].type, inReturnPosition); } this.#resolving.pop(); } } else if (inReturnPosition) { // Imported type (no local TypeDef) - check if it contains borrows if (this.#importedTypeContainsBorrow(name, t.span)) { throw new ResolveError( "function returns a type which contains a `borrow` which is not supported", t.span ); } } } // Check map key types if (t.tag == TypeTag.Map) { let keyType = t.keyType as Type; if (!isValidMapKeyType(keyType)) { throw new ResolveError( "invalid map key type: map keys must be bool, u8, u16, u32, u64, s8, s16, s32, s64, char, or string", t.span ); } this.#resolveType(keyType, false); this.#resolveType(t.valueType as Type, false); } // Recurse into composite types if (t.tag == TypeTag.List || t.tag == TypeTag.Option || t.tag == TypeTag.Future || t.tag == TypeTag.Stream) { if (t.inner != null) { this.#resolveType(t.inner as Type, inReturnPosition); } } if (t.tag == TypeTag.Result) { if (t.okType != null) { this.#resolveType(t.okType as Type, inReturnPosition); } if (t.errType != null) { this.#resolveType(t.errType as Type, inReturnPosition); } } if (t.tag == TypeTag.Tuple) { let types = t.types as GrowableArray; for (var i = 0; i < types.length; i += 1) { this.#resolveType(types[i], inReturnPosition); } } } #isResolving(name: String): boolean { for (var i = 0; i < this.#resolving.length; i += 1) { if (this.#resolving[i] == name) { return true; } } return false; } /** Find a type definition by name in any scope. */ #findTypeDef(name: String): TypeDef | null { for (var i = this.#scopes.length - 1; i >= 0; i -= 1) { let td = this.#scopes[i].findType(name); if (td != null) { return td; } } return null; } /** Find a world definition by name in any scope. */ #findWorldDef(name: String): WorldDef | null { for (var i = this.#scopes.length - 1; i >= 0; i -= 1) { let wd = this.#scopes[i].findWorld(name); if (wd != null) { return wd; } } return null; } /** Check if a type definition is or refers to a resource. */ #isResourceType(td: TypeDef): boolean { // Direct resource if (td.tag == TypeDefTag.Resource) { return true; } // Not an alias - not a resource if (td.tag != TypeDefTag.Alias) { return false; } // Check what the alias points to let aliasType = td.aliasType as Type; // If it's own or borrow, the inner type must be a resource if (aliasType.tag == TypeTag.Own || aliasType.tag == TypeTag.Borrow) { // Already validated by handle type checking return false; // But the alias itself is not a resource } // If it aliases another name, check if that's a resource if (aliasType.tag == TypeTag.Name) { let name = (aliasType.name as Id).name; let sym = this.#findSymbol(name); if (sym != null) { let s = sym; if (s.kind == SymbolKind.Resource) { return true; } // If it's a Type, check if there's a local TypeDef or if it was imported if (s.kind == SymbolKind.Type) { let innerTd = this.#findTypeDef(name); if (innerTd != null) { return this.#isResourceType(innerTd); } // No TypeDef found - imported type, and it's not marked as Resource // so it's not a resource return false; } } } return false; } /** Check if an imported type (no local TypeDef) contains a borrow. */ #importedTypeContainsBorrow(typeName: String, span: Span): boolean { // Find the Use statement that imported this type let iface = this.#currentInterface; if (iface == null) { return false; } let ifaceDef = iface; // Search for a use statement that imports this type for (let item in ifaceDef.items) { if (item.tag == InterfaceItemTag.Use) { let u = item.use as Use; // Check if this use imports our type for (let useName in u.names) { let importedAs = if (useName.asName != null) (useName.asName as Id).name else useName.name.name; if (importedAs == typeName) { // Found it - look up the type in the source interface let originalName = useName.name.name; // Use original name for lookup return this.#typeDefContainsBorrowFromUse(u, originalName); } } } } return false; } /** Check if a type from a use statement contains a borrow. */ #typeDefContainsBorrowFromUse(use: Use, typeName: String): boolean { let sourceIface = this.#getInterfaceFromUsePath(use.from); if (sourceIface == null) { return false; } let ifaceDef = sourceIface; // Find the TypeDef in the source interface for (let item in ifaceDef.items) { if (item.tag == InterfaceItemTag.TypeDef) { let td = item.typeDef as TypeDef; if (td.name.name == typeName) { return this.#typeDefContainsBorrow(td, ifaceDef); } } } return false; } /** Check if a TypeDef contains a borrow type. */ #typeDefContainsBorrow(td: TypeDef, sourceIface: InterfaceDef): boolean { if (td.tag == TypeDefTag.Record) { let fields = td.fields as GrowableArray; for (var i = 0; i < fields.length; i += 1) { if (this.#typeContainsBorrow(fields[i].type, sourceIface)) { return true; } } } else if (td.tag == TypeDefTag.Variant) { let cases = td.cases as GrowableArray; for (var i = 0; i < cases.length; i += 1) { if (cases[i].type != null) { if (this.#typeContainsBorrow(cases[i].type as Type, sourceIface)) { return true; } } } } else if (td.tag == TypeDefTag.Alias) { return this.#typeContainsBorrow(td.aliasType as Type, sourceIface); } return false; } /** Check if a Type contains a borrow. */ #typeContainsBorrow(t: Type, sourceIface: InterfaceDef): boolean { if (t.tag == TypeTag.Borrow) { return true; } if (t.tag == TypeTag.Tuple) { let types = t.types as GrowableArray; for (var i = 0; i < types.length; i += 1) { if (this.#typeContainsBorrow(types[i], sourceIface)) { return true; } } } if (t.tag == TypeTag.List || t.tag == TypeTag.Option || t.tag == TypeTag.Future || t.tag == TypeTag.Stream) { if (t.inner != null) { return this.#typeContainsBorrow(t.inner as Type, sourceIface); } } if (t.tag == TypeTag.Result) { if (t.okType != null && this.#typeContainsBorrow(t.okType as Type, sourceIface)) { return true; } if (t.errType != null && this.#typeContainsBorrow(t.errType as Type, sourceIface)) { return true; } } if (t.tag == TypeTag.Name) { // Check if this named type is a record/variant that contains borrows let name = (t.name as Id).name; // Look up in the source interface for (let item in sourceIface.items) { if (item.tag == InterfaceItemTag.TypeDef) { let innerTd = item.typeDef as TypeDef; if (innerTd.name.name == name) { return this.#typeDefContainsBorrow(innerTd, sourceIface); } } } } return false; } /** Get interface definition from a use path. */ #getInterfaceFromUsePath(path: UsePath): InterfaceDef | null { if (path.tag == UsePathTag.Id) { let id = path.id as Id; return this.#findInterface(id.name); } else if (path.tag == UsePathTag.Package) { let pkgId = path.packageId as PackageName; let itemName = path.name as Id; let registry = this.#registry as PackageRegistry; return registry.getInterfaceByPkg(pkgId, itemName.name); } return null; } // -------------------------------------------------------------------------- // Function Resolution // -------------------------------------------------------------------------- #resolveNamedFunc(f: NamedFunc): void { this.#resolveFunc(f.func); } #resolveFunc(f: Func): void { // Check for duplicate parameter names this.#checkDuplicateParamNames(f.params); // Resolve parameter types for (var i = 0; i < f.params.length; i += 1) { this.#resolveType(f.params[i].type, false); } // Resolve return type if (f.result != null) { this.#resolveType(f.result as Type, true); } } #checkDuplicateParamNames(params: Array): void { for (var i = 0; i < params.length; i += 1) { for (var j = i + 1; j < params.length; j += 1) { if (params[i].name.name == params[j].name.name) { throw new ResolveError( `duplicate parameter \`${params[j].name.name}\``, params[j].name.span ); } } } } // -------------------------------------------------------------------------- // Use Statement Resolution // -------------------------------------------------------------------------- /** Check if an interface is currently being resolved (for cycle detection). */ #isResolvingInterface(name: String): boolean { for (var i = 0; i < this.#resolvingInterfaces.length; i += 1) { if (this.#resolvingInterfaces[i] == name) { return true; } } return false; } #resolveUse(use: Use): void { // Validate the path references an existing interface this.#resolveUsePath(use.from, false); // Check that we're not using a world (only interfaces can be used) if (use.from.tag == UsePathTag.Id) { let id = use.from.id as Id; let sym = this.#findSymbol(id.name); if (sym != null) { let s = sym; if (s.kind == SymbolKind.World) { throw new ResolveError( `name \`${id.name}\` is defined as a world, not an interface`, id.span ); } } // Check for use cycle using qualified name let qualifiedName = this.#getQualifiedInterfaceName(id.name); if (this.#isResolvingInterface(qualifiedName)) { throw new ResolveError( `interface or world \`${id.name}\` depends on itself`, id.span ); } // Recursively resolve the target interface to detect transitive cycles let iface = this.#findInterfaceInCurrentPackage(id.name); if (iface != null) { let ifaceDef = iface; // Only resolve if not already resolved (to avoid infinite recursion // in valid cases where an interface is used multiple times) let targetQualified = this.#getQualifiedInterfaceName(ifaceDef.name.name); if (!this.#isResolvingInterface(targetQualified)) { this.#resolveInterface(ifaceDef); } } } else if (use.from.tag == UsePathTag.Package) { // Cross-package reference: check for cycles let pkgId = use.from.packageId as PackageName; let itemName = use.from.name as Id; let qualifiedName = this.#buildQualifiedName(pkgId, itemName.name); // Check if this interface is currently being resolved (cycle) if (this.#isResolvingInterface(qualifiedName)) { throw new ResolveError( `interface \`${qualifiedName}\` depends on itself`, itemName.span ); } // Recursively resolve the target interface to detect transitive cycles let registry = this.#registry as PackageRegistry; let iface = registry.getInterfaceByPkg(pkgId, itemName.name); if (iface != null) { let ifaceDef = iface; // Temporarily switch to the target package context for resolution let prevPackage = this.#currentResolvePackage; this.#currentResolvePackage = pkgId; // Only resolve if not already resolved if (!this.#isResolvingInterface(qualifiedName)) { this.#resolveInterface(ifaceDef); } this.#currentResolvePackage = prevPackage; } } // Validate that imported names exist in the target interface this.#validateUseNames(use); // Add imported names to current scope with their correct kinds // (Resource vs Type) to support proper handle validation for (let useName in use.names) { let name = if (useName.asName != null) (useName.asName as Id).name else useName.name.name; let kind = this.#getUseNameKind(use, useName.name.name, this.#currentResolvePackage); this.#define(name, kind, useName.name.span); } } /** * Get the SymbolKind for a name being imported via a use statement. * * `ownerPkg` is the package owning the interface that holds `use` — the scope * an unqualified path in it resolves against. Threading it through is what * stops this and `#findItemInInterface` from recursing forever between two * packages that declare same-named interfaces. */ #getUseNameKind(use: Use, lookupName: String, ownerPkg: PackageName | null): SymbolKind { if (use.from.tag == UsePathTag.Id) { let id = use.from.id as Id; let iface = this.#findInterfaceInPackage(ownerPkg, id.name); if (iface != null) { // An unqualified path stays inside the owning package. let entry = this.#findItemInInterface(iface, lookupName, ownerPkg); if (entry != null) { return entry.kind; } } } else if (use.from.tag == UsePathTag.Package) { let pkgId = use.from.packageId as PackageName; let itemName = use.from.name as Id; let registry = this.#registry as PackageRegistry; let iface = registry.getInterfaceByPkg(pkgId, itemName.name); if (iface != null) { let entry = this.#findItemInInterface(iface, lookupName, pkgId); if (entry != null) { return entry.kind; } } } return SymbolKind.Type; // Default to Type if lookup fails } /** Validate that names in a use statement exist in the target interface. */ #validateUseNames(use: Use): void { if (use.from.tag == UsePathTag.Id) { // Local interface reference let id = use.from.id as Id; let iface = this.#findInterfaceInCurrentPackage(id.name); if (iface == null) { // Interface not found - already reported by #resolveUsePath return; } let ifaceDef = iface; this.#validateUseNamesInInterface(use, ifaceDef, this.#currentResolvePackage); } else if (use.from.tag == UsePathTag.Package) { // Cross-package reference let pkgId = use.from.packageId as PackageName; let itemName = use.from.name as Id; let registry = this.#registry as PackageRegistry; let iface = registry.getInterfaceByPkg(pkgId, itemName.name); if (iface == null) { // Interface not found - already reported by #resolveUsePath return; } this.#validateUseNamesInInterface(use, iface, pkgId); } } /** Helper to validate use names against an interface definition. */ #validateUseNamesInInterface(use: Use, ifaceDef: InterfaceDef, ownerPkg: PackageName | null): void { // Check each imported name for (let useName in use.names) { let lookupName = useName.name.name; let found = this.#findItemInInterface(ifaceDef, lookupName, ownerPkg); if (found == null) { throw new ResolveError( `name \`${lookupName}\` is not defined`, useName.name.span ); } // Check it's a type, not a function let foundEntry = found; if (foundEntry.kind == SymbolKind.Func) { throw new ResolveError( `cannot import function \`${lookupName}\``, useName.name.span ); } } } /** * Find an item in an interface by name. `ownerPkg` is the package `iface` * belongs to, so that a `use` inside it resolves unqualified names there. */ #findItemInInterface(iface: InterfaceDef, name: String, ownerPkg: PackageName | null): SymbolEntry | null { for (let item in iface.items) { if (item.tag == InterfaceItemTag.TypeDef) { let td = item.typeDef as TypeDef; if (td.name.name == name) { let kind = if (td.tag == TypeDefTag.Resource) SymbolKind.Resource else SymbolKind.Type; return new SymbolEntry(name, kind, td.name.span); } } else if (item.tag == InterfaceItemTag.Func) { let f = item.func as NamedFunc; if (f.name.name == name) { return new SymbolEntry(name, SymbolKind.Func, f.name.span); } } else if (item.tag == InterfaceItemTag.Use) { // Check names brought in by use statements let u = item.use as Use; for (let useName in u.names) { let importedName = if (useName.asName != null) (useName.asName as Id).name else useName.name.name; if (importedName == name) { // Recursively look up the original type to get its kind let originalKind = this.#getUseNameKind(u, useName.name.name, ownerPkg); return new SymbolEntry(name, originalKind, useName.name.span); } } } } return null; } /** * Find an interface by name within `pkg`, falling back to the scope walk. * * An unqualified interface name means "in this package", so the owning * package has to be consulted first. The scope walk alone returns whichever * same-named interface sits nearest on the stack, which is the wrong one once * resolution has followed a `use` into another package — WASI p3 declares an * `interface types` in both `wasi:clocks` and `wasi:sockets`. */ #findInterfaceInPackage(pkg: PackageName | null, name: String): InterfaceDef | null { if (pkg != null && this.#registry != null) { let registry = this.#registry as PackageRegistry; let owned = registry.getInterfaceByPkg(pkg, name); if (owned != null) { return owned; } } return this.#findInterface(name); } /** As above, for the package currently being resolved. */ #findInterfaceInCurrentPackage(name: String): InterfaceDef | null { return this.#findInterfaceInPackage(this.#currentResolvePackage, name); } /** Find an interface definition by name in any scope. */ #findInterface(name: String): InterfaceDef | null { for (var i = this.#scopes.length - 1; i >= 0; i -= 1) { let iface = this.#scopes[i].findInterface(name); if (iface != null) { return iface; } } return null; } #resolveUsePath(path: UsePath, expectWorld: boolean): void { if (path.tag == UsePathTag.Id) { // Local reference let id = path.id as Id; if (expectWorld) { // For include statements, look for world definitions specifically // (to avoid shadowing by local record/type definitions) let worldDef = this.#findWorldDef(id.name); if (worldDef == null) { throw new ResolveError( `world \`${id.name}\` not found in package`, id.span ); } } else { // For use statements, look for interface definitions specifically, // for the same reason worlds do above: a plain symbol lookup walks // every enclosing scope, so a *type* of the same name shadows the // interface. `wasi:sockets` relies on the distinction — `interface // network` declares `resource network`, so an earlier `use // network.{network}` in the enclosing interface binds that type // before a later `use` recurses back into the interface. let iface = this.#findInterface(id.name); if (iface == null) { // Not a declared interface, but it may still be an interface // *alias* (`use foo as bar;`), which lives only in the symbol // table, so fall back to it rather than reporting a failure. let sym = this.#findSymbol(id.name); if (sym == null) { throw new ResolveError( `interface \`${id.name}\` not found in package`, id.span ); } let s = sym; if (s.kind != SymbolKind.Interface) { throw new ResolveError( `\`${id.name}\` is not an interface`, id.span ); } } } } else if (path.tag == UsePathTag.Package) { // Cross-package reference: namespace:name/interface let pkgId = path.packageId as PackageName; let itemName = path.name as Id; let registry = this.#registry as PackageRegistry; // Check if the package exists (using full PackageName with version) if (!registry.hasPackageByName(pkgId)) { let knownPkgs = registry.getKnownPackages(); let knownStr = this.#formatKnownPackages(knownPkgs); var pkgStr = `${pkgId.namespace.name}:${pkgId.name.name}`; if (pkgId.version != null) { pkgStr = `${pkgStr}@${pkgId.version as String}`; } throw new ResolveError( `package '${pkgStr}' not found. known packages:\n${knownStr}`, pkgId.span ); } // Check if the interface or world exists in that package based on expectWorld if (expectWorld) { let world = registry.getWorldByPkg(pkgId, itemName.name); if (world == null) { // Check if it's an interface (for better error message) let iface = registry.getInterfaceByPkg(pkgId, itemName.name); if (iface != null) { throw new ResolveError( `\`${itemName.name}\` is an interface, not a world`, itemName.span ); } var pkgStr2 = `${pkgId.namespace.name}:${pkgId.name.name}`; if (pkgId.version != null) { pkgStr2 = `${pkgStr2}@${pkgId.version as String}`; } throw new ResolveError( `world \`${itemName.name}\` not found in package \`${pkgStr2}\``, itemName.span ); } } else { let iface = registry.getInterfaceByPkg(pkgId, itemName.name); if (iface == null) { // Check if it's a world (for better error message) let world = registry.getWorldByPkg(pkgId, itemName.name); if (world != null) { throw new ResolveError( `\`${itemName.name}\` is a world, not an interface`, itemName.span ); } var pkgStr3 = `${pkgId.namespace.name}:${pkgId.name.name}`; if (pkgId.version != null) { pkgStr3 = `${pkgStr3}@${pkgId.version as String}`; } throw new ResolveError( `interface \`${itemName.name}\` not found in package \`${pkgStr3}\``, itemName.span ); } } } } /** Format known packages for error messages. */ #formatKnownPackages(known: Array): String { let sb = new StringBuilder(64); for (var i = 0; i < known.length; i += 1) { sb.append(" "); sb.append(known[i]); if (i < known.length - 1) { sb.appendByte(10); // newline } } return sb.toString(); } #resolveToplevelUse(use: ToplevelUse): void { // Top-level use brings an interface into scope. // The name is already defined in the first pass, so we just validate the path here. this.#resolveUsePath(use.item, false); } /** Check if a name is a kebab-case name (contains hyphens). */ #isKebabName(name: String): boolean { for (var i = 0; i < name.length; i += 1) { if (name.getByteAt(i) == 45) { // 45 is '-' return true; } } return false; } #resolveInclude(include: Include): void { // Validate the path (includes reference worlds) this.#resolveUsePath(include.from, true); // Validate include renames (only for local world references) if (include.from.tag == UsePathTag.Id && include.names.length > 0) { let worldId = include.from.id as Id; let worldDef = this.#findWorldDef(worldId.name); if (worldDef != null) { let w = worldDef; this.#validateIncludeNames(include, w); } } // Check for include cycles and feature gates if (include.from.tag == UsePathTag.Id) { let id = include.from.id as Id; let sym = this.#findSymbol(id.name); if (sym != null) { let s = sym; // Check feature gate (bad-gate2): can't include gated world from non-gated context this.#checkGatedReference(s, id.span, "world"); // Check for include cycle - if we're already resolving this world, it's a cycle if (this.#isIncludingWorld(id.name)) { throw new ResolveError( `interface or world \`${id.name}\` depends on itself`, id.span ); } // Recursively resolve the included world to detect transitive cycles let worldDef2 = this.#findWorldDef(id.name); if (worldDef2 != null) { this.#resolveWorldIncludes(worldDef2); } } } } /** Validate include rename names - kebab-names (functions) and resources can be renamed, not IDs (interfaces). */ #validateIncludeNames(include: Include, world: WorldDef): void { for (let incName in include.names) { let name = incName.name.name; // Check if this name exists as a function (kebab-name) or resource in the world let isRenameableItem = this.#isRenameableItemInWorld(world, name); if (!isRenameableItem) { // Name either doesn't exist or is an interface (ID), not a function/resource throw new ResolveError( `no import or export kebab-name \`${name}\`. Note that an ID does not support renaming`, include.from.getName().span ); } } } /** Check if a name in the world is renameable (function or resource). */ #isRenameableItemInWorld(world: WorldDef, name: String): boolean { for (let item in world.items) { if (item.tag == WorldItemTag.Import) { let imp = item.importItem as Import; // Functions are "kebab-names" - interfaces paths don't support renaming if (imp.kind.tag == ExternKindTag.Func) { let funcName = imp.kind.name as Id; if (funcName.name == name) { return true; } } } else if (item.tag == WorldItemTag.Export) { let exp = item.exportItem as Export; if (exp.kind.tag == ExternKindTag.Func) { let funcName = exp.kind.name as Id; if (funcName.name == name) { return true; } } } else if (item.tag == WorldItemTag.TypeDef) { // Resources defined in the world can be renamed let td = item.typeDef as TypeDef; if (td.tag == TypeDefTag.Resource && td.name.name == name) { return true; } } } return false; } /** Resolve only the includes within a world (for cycle detection). */ #resolveWorldIncludes(world: WorldDef): void { // Track this world for include cycle detection this.#includingWorlds.push(world.name.name); // Only process includes - we don't need to fully resolve the world again for (let item in world.items) { if (item.tag == WorldItemTag.Include) { let inc = item.include as Include; // Set gated context based on the include's docs let prevGatedContext = this.#inGatedContext; if (isGated(inc.docs)) { this.#inGatedContext = true; } this.#resolveInclude(inc); this.#inGatedContext = prevGatedContext; } } this.#includingWorlds.pop(); } /** Check if a world is currently being included (for cycle detection). */ #isIncludingWorld(name: String): boolean { for (var i = 0; i < this.#includingWorlds.length; i += 1) { if (this.#includingWorlds[i] == name) { return true; } } return false; } // -------------------------------------------------------------------------- // Transitive Dependency Conflict Detection // -------------------------------------------------------------------------- /** * Check for transitive dependency conflicts in a world. * * A conflict occurs when: * 1. An interface is imported with an inline definition (import name: interface {...}) * and an exported interface transitively depends on that same interface name. * 2. An interface is imported by path and transitively depends on an interface that * is also exported (creating incompatible use of the same interface). * * This creates an incompatibility because the import and export views of the * interface may be different. */ #checkTransitiveDependencyConflicts(world: WorldDef): void { // Collect names of inline interface imports (all, for path export conflict detection) let inlineImports = new GrowableArray(); // Collect non-empty inline imports (for inline export conflict detection) // Empty inline imports don't cause conflicts with inline exports because // uses would resolve to the package-level interface instead let nonEmptyInlineImports = new GrowableArray(); // Collect names of path imports let pathImports = new GrowableArray(); // Collect names of path exports (interfaces exported by path reference) let pathExports = new GrowableArray(); // Collect inline interface exports (export name: interface {...}) let inlineExports = new GrowableArray(); for (let item in world.items) { if (item.tag == WorldItemTag.Import) { let imp = item.importItem as Import; if (imp.kind.tag == ExternKindTag.Interface) { // Inline interface import: import name: interface {...} let name = imp.kind.name as Id; inlineImports.push(name.name); // Track non-empty ones separately for Check 3 let items = imp.kind.items as GrowableArray; if (items.length > 0) { nonEmptyInlineImports.push(name.name); } } else if (imp.kind.tag == ExternKindTag.Path) { // Path import: import foo (reference to package interface) let path = imp.kind.path as UsePath; if (path.tag == UsePathTag.Id) { let id = path.id as Id; pathImports.push(id.name); } } } else if (item.tag == WorldItemTag.Export) { let exp = item.exportItem as Export; if (exp.kind.tag == ExternKindTag.Path) { // Path export: export foo (where foo is a package interface) let path = exp.kind.path as UsePath; if (path.tag == UsePathTag.Id) { let id = path.id as Id; pathExports.push(id.name); } } else if (exp.kind.tag == ExternKindTag.Interface) { // Inline interface export: export name: interface {...} let name = exp.kind.name as Id; inlineExports.push(name.name); } } } // Check 1: Path exports with dependencies on inline imports for (let exportName in pathExports) { let iface = this.#findInterface(exportName); if (iface != null) { let ifaceDef = iface; let deps = this.#collectTransitiveDependencies(ifaceDef); // Check if any dependency is also an inline import for (let dep in deps) { if (this.#containsString(inlineImports, dep)) { // Found a conflict! let pkgName = this.#getPackageNameStr(); throw new ResolveError( "failed to elaborate world imports/exports of `" + world.name.name + "`\n" + "interface `" + pkgName + "/" + exportName + "` transitively depends on an interface in incompatible ways", world.name.span ); } } } } // Check 2: Path imports with dependencies on path exports (or vice versa) // This catches cases like: import i3 (depends on i1), export i1, export i3 for (let importName in pathImports) { let iface = this.#findInterface(importName); if (iface != null) { let ifaceDef = iface; let deps = this.#collectTransitiveDependencies(ifaceDef); // Check if any dependency is also a path export for (let dep in deps) { if (this.#containsString(pathExports, dep)) { // Found a conflict! An imported interface depends on an exported interface. let pkgName = this.#getPackageNameStr(); // Find which exported interface causes the conflict var conflictExport = importName; if (this.#containsString(pathExports, importName)) { conflictExport = importName; // The import itself is also exported } throw new ResolveError( "failed to elaborate world imports/exports of `" + world.name.name + "`\n" + "interface `" + pkgName + "/" + conflictExport + "` transitively depends on an interface in incompatible ways", world.name.span ); } } } } // Check 3: Inline exports with dependencies on inline imports or dependencies that conflict with exports for (let exportName in inlineExports) { // Check the inline export's use statements for transitive dependencies for (let item in world.items) { if (item.tag == WorldItemTag.Export) { let exp = item.exportItem as Export; if (exp.kind.tag == ExternKindTag.Interface) { let name = exp.kind.name as Id; if (name.name == exportName) { // Check the items in this inline interface for use statements let items = exp.kind.items as GrowableArray; let deps = this.#collectDependenciesFromItems(items); // Check if any dependency is also an inline import // Use nonEmptyInlineImports because empty inline imports don't cause conflicts // with inline exports (uses resolve to package-level interface) for (let dep in deps) { if (this.#containsString(nonEmptyInlineImports, dep)) { throw new ResolveError( "failed to elaborate world imports/exports of `" + world.name.name + "`\n" + "interface `" + exportName + "` transitively depends on an interface in incompatible ways", world.name.span ); } // Check if this dependency (whether imported or not) has transitive deps on path exports let depIface = this.#findInterface(dep); if (depIface != null) { let depDeps = this.#collectTransitiveDependencies(depIface); for (var m = 0; m < depDeps.length; m += 1) { if (this.#containsString(pathExports, depDeps[m])) { throw new ResolveError( "failed to elaborate world imports/exports of `" + world.name.name + "`\n" + "interface `" + exportName + "` transitively depends on an interface in incompatible ways", world.name.span ); } } } } } } } } } } /** Collect transitive interface dependencies from an interface definition. */ #collectTransitiveDependencies(iface: InterfaceDef): Array { let visited = new GrowableArray(); let result = new GrowableArray(); this.#collectDepsRecursive(iface, visited, result); return result; } /** Recursively collect interface dependencies. */ #collectDepsRecursive(iface: InterfaceDef, visited: GrowableArray, result: GrowableArray): void { let name = iface.name.name; if (this.#containsString(visited, name)) { return; // Already visited } visited.push(name); // Check all items for use statements for (let item in iface.items) { if (item.tag == InterfaceItemTag.Use) { let use = item.use as Use; if (use.from.tag == UsePathTag.Id) { // Local interface reference let refId = use.from.id as Id; let refName = refId.name; result.push(refName); // Recursively collect dependencies from the referenced interface let refIface = this.#findInterface(refName); if (refIface != null) { this.#collectDepsRecursive(refIface, visited, result); } } } } } /** Collect direct dependencies from interface items (for inline interfaces). */ #collectDependenciesFromItems(items: Array): Array { let result = new GrowableArray(); let visited = new GrowableArray(); for (let item in items) { if (item.tag == InterfaceItemTag.Use) { let use = item.use as Use; if (use.from.tag == UsePathTag.Id) { let refId = use.from.id as Id; let refName = refId.name; result.push(refName); // Recursively collect from the referenced interface let refIface = this.#findInterface(refName); if (refIface != null) { this.#collectDepsRecursive(refIface, visited, result); } } } } return result; } /** Check if a string array contains a value. */ #containsString(arr: Array, val: String): boolean { for (var i = 0; i < arr.length; i += 1) { if (arr[i] == val) { return true; } } return false; } /** Get the current package name as a string. */ #getPackageNameStr(): String { if (this.#packageName == null) { return "unknown"; } let pkg = this.#packageName as PackageName; return `${pkg.namespace.name}:${pkg.name.name}`; } }