// selfhost/cmd/wcc/check.ww — minimal port of cmd/wcc/check.c. // // Status: name-resolution + primitive-type seeding only. Full type // inference, conversion rules, tagged-union dispatch typing, return- // type checking, etc. all live in cmd/wcc/check.c (937 lines) and // will land here in subsequent commits. // // What this version does: // 1. Creates a top scope and seeds it with primitive type names so // `i32`, `str`, `*u8` etc. resolve. // 2. Walks the file's top-level decls (use/def/type/fn/let) and // installs Sym entries for each. // 3. Recursively walks fn bodies; for every nkind.N_IDENT used as an // expression or as a type name, looks it up and counts the // resolved vs. unresolved. // 4. Returns a summary the caller (wwdump -r) prints; the test // asserts unresolved == 0 on every selfhost fixture, which is // the floor signal that the frontend can name-resolve real ww. use os; use mem; use tok; type checker = struct { a: *arena, tc: *tctx, top: *scope, cur: *scope, nresolved: i32, nunresolved: i32, errs: i32, verbose: i32, // when non-zero, log each unresolved name fnret: *node, // enclosing fn's return type AST (for `?`) curmod: str, // importing-module bareword for the decl // currently being walked; "" for primary // compilation unit. Drives same-module // preference in bare-leaf lookups. file: *node, // N_FILE root; used by checkmoduleshadow // to consult the declaring source's own // `use` directives. }; // seedprimitives — install the built-in type names so `i32`, `str`, // etc. can be looked up like ordinary symbols. fn seedprimitives(c: *checker) void = { scopedefine(c.top, "void", skind.SK_TYPE, c.tc.tyvoid, nil); scopedefine(c.top, "bool", skind.SK_TYPE, c.tc.tybool, nil); scopedefine(c.top, "rune", skind.SK_TYPE, c.tc.tyrune, nil); scopedefine(c.top, "i8", skind.SK_TYPE, c.tc.tyi8, nil); scopedefine(c.top, "i16", skind.SK_TYPE, c.tc.tyi16, nil); scopedefine(c.top, "i32", skind.SK_TYPE, c.tc.tyi32, nil); scopedefine(c.top, "i64", skind.SK_TYPE, c.tc.tyi64, nil); scopedefine(c.top, "u8", skind.SK_TYPE, c.tc.tyu8, nil); scopedefine(c.top, "u16", skind.SK_TYPE, c.tc.tyu16, nil); scopedefine(c.top, "u32", skind.SK_TYPE, c.tc.tyu32, nil); scopedefine(c.top, "u64", skind.SK_TYPE, c.tc.tyu64, nil); scopedefine(c.top, "int", skind.SK_TYPE, c.tc.tyint, nil); scopedefine(c.top, "uint", skind.SK_TYPE, c.tc.tyuint, nil); scopedefine(c.top, "uintptr", skind.SK_TYPE, c.tc.tyuintptr, nil); scopedefine(c.top, "f32", skind.SK_TYPE, c.tc.tyf32, nil); scopedefine(c.top, "f64", skind.SK_TYPE, c.tc.tyf64, nil); scopedefine(c.top, "str", skind.SK_TYPE, c.tc.tystr, nil); scopedefine(c.top, "never", skind.SK_TYPE, c.tc.tynever, nil); // `nil`, `true`, `false` are keywords — handled at the lex/parser // level, no symbol needed. // `len`, `alloc`, `free`, `append` are pseudo-builtins; scopedefine // them so their use sites resolve. The actual semantics live in cgen. scopedefine(c.top, "len", skind.SK_FN, nil, nil); scopedefine(c.top, "alloc", skind.SK_FN, nil, nil); scopedefine(c.top, "free", skind.SK_FN, nil, nil); scopedefine(c.top, "append", skind.SK_FN, nil, nil); }; // declmod — module-tag stamp for a top-level decl. // // The driver concatenates imported sources before the primary file and // emits `// MODULE: foo` directives the lexer pins onto each decl's // `module` field. We treat a decl as "imported" iff its module // directive matches some `use IDENT;` bareword in this compilation // unit. Primary-file decls return "" so they coexist (mod="") with // imported decls of the same leaf name in scopelookupinmodule. fn declmod(file: *node, d: *node) str = { let empty: str; if (d == nil) { return empty; }; if (d.module.len == 0) { return empty; }; if (file == nil) { return empty; }; let u: *node = file.list; for (u != nil) { if (u.kind == nkind.N_USE) { if (streq(u.str, d.module)) { return d.module; }; }; u = u.next; }; return empty; }; // srcimports — does the source file that contributed decl-module // `modtag` carry `use ;`? Mirrors cstage's src_imports — // `modtag.len == 0` means primary, matching declmod's empty-str // return for primary-source decls. fn srcimports(file: *node, modtag: str, name: str) bool = { if (file == nil) { return false; }; if (name.len == 0) { return false; }; let u: *node = file.list; for (u != nil) { if (u.kind == nkind.N_USE) { // Skip self-imports: lib/fmt/fmttest.ww carries // `use fmt;` while its module tag is also "fmt". // That directive doesn't introduce a foreign // module bareword and lib/fmt's own // `fn bsprintf(fmt: str, ...)` is not a shadow. if (u.module.len > 0) { if (streq(u.module, u.str)) { u = u.next; continue; }; }; let um: str = declmod(file, u); let m: bool = false; if (modtag.len == 0) { if (um.len == 0) { m = true; }; } else { if (streq(um, modtag)) { m = true; }; }; if (m) { if (streq(u.str, name)) { return true; }; }; }; u = u.next; }; return false; }; // checkmoduleshadow — enforce "value names and module names are // disjoint" at nested-scope binds. Mirrors cstage check_module_shadow // (cmd/wcc/check.c). Fires for fn params / lets / forrange iters / // mcase bindings whose name matches an in-scope `use foo;` import // declared in the same source file. Top-level decls are exempt // (their same-leaf-as-module pattern is the intentional coexistence // shape — `use fnmatch; fn fnmatch(...)` etc.). fn checkmoduleshadow(c: *checker, name: str, kindstr: str) void = { if (name.len == 0) { return; }; if (c.cur == c.top) { return; }; let seen: bool = false; let s: *scope = c.cur; for (s != nil) { let r: *sym = scopelookuplocal(s, name); if (r != nil) { if (r.skind == skind.SK_USE) { seen = true; s = nil; }; }; if (s != nil) { s = s.parent; }; }; if (!seen) { return; }; if (!srcimports(c.file, c.curmod, name)) { return; }; os.write(2, kindstr.ptr, kindstr.len: u64); os.write(2, " '".ptr, 2u64); os.write(2, name.ptr, name.len: u64); os.write(2, "' shadows imported module '".ptr, 27u64); os.write(2, name.ptr, name.len: u64); os.write(2, "'\n".ptr, 2u64); c.errs += 1; }; // installdecl — install the top-level decl's name into the top scope. // We don't compute its type yet (that's the resolve pass) — just bind // the name so forward references resolve. // // Architectural note: wwstage uses COEXISTENCE rather than the cstage // promote-SK_USE-in-place approach in cmd/wcc/check.c. SK_USE and any // same-leaf SK_TYPE/SK_FN/SK_DEF/SK_VAR live as separate entries in // the same scope-bucket, distinguished by `sym.mod`. The dot-prefix // lookup in resolvewalk + scopelookupinmodule's mod-filter already // disambiguate `fnmatch.flag` against an `fn fnmatch(...)` of the same // leaf — no `use_alias` flag needed. So the cstage L1722-class bug // (promotion missing use_alias) is structurally non-reachable here. // Don't port the use_alias flag from cstage without first re-reading // the architecture: adding a field to `sym` changes its size and risks // the wwstage cgen amalloc-undersize trap (rob-pike). #11 (wwstage // checkfile pass) will reconsider this when wwstage grows a real check // pass on the cgen path. // TODO(#11): cstage check.c errors on duplicate top-level type/def/fn // (see cmd/wcc/check.c L1800/L1839/L1860 "duplicate ") and on // duplicate top-level let (cmd/wcc/check.c L1880, "duplicate let %s") // once #32 lands. Wwstage's installdecl just drops the second insert // silently. Add `if (s == nil) err(...)` here once #11 wires checkfile // into w6c_ww. Silent-accept matches the deferred-check design — see // test/wcc/708 and test/wcc/696 for the same cstage-only neg-case // precedent. fn installdecl(c: *checker, file: *node, d: *node) void = { if (d == nil) { return; }; let k: nkind = d.kind; let nm: str = d.str; let mod: str = declmod(file, d); if (k == nkind.N_USE) { scopedefine(c.top, nm, skind.SK_USE, nil, d); return; }; if (k == nkind.N_DEF) { scopedefineinmodule(c.top, nm, mod, skind.SK_DEF, nil, d); return; }; if (k == nkind.N_TYPEDECL) { scopedefineinmodule(c.top, nm, mod, skind.SK_TYPE, nil, d); return; }; if (k == nkind.N_FNDECL) { scopedefineinmodule(c.top, nm, mod, skind.SK_FN, nil, d); return; }; if (k == nkind.N_LET) { scopedefineinmodule(c.top, nm, mod, skind.SK_VAR, nil, d); return; }; }; // resolvewalk — recursive AST walk that, for every nkind.N_IDENT and // nkind.N_TNAME seen, looks up the name and bumps the resolved/unresolved // counters. Local lets are installed in the current scope as soon as // their init/type expressions have been walked (forward use of a let // before its declaration would resolve to nothing — same semantics as // the C checker's collect-then-resolve flow within a function). // Also runs the typed checks (match exhaustiveness, ? subset) in // the same pass — they need the same scope state. fn resolvewalk(c: *checker, n: *node) void = { if (n == nil) { return; }; let k: nkind = n.kind; // Typed checks fire on the way down so the scrutinee/operand // is examined before the arm bodies install new bindings. if (k == nkind.N_MATCH) { checkmatchexhaust(c, n); }; if (k == nkind.N_TRYPROP) { checktryprop(c, n); }; if (k == nkind.N_TYPETEST) { checkisas(c, n); }; if (k == nkind.N_TYPEASSERT) { checkisas(c, n); }; if (k == nkind.N_LET) { checkletassign(c, n); }; if (k == nkind.N_RETURN) { checkretassign(c, n); }; // `use IDENT;` — name is a module label, not a free ident. if (k == nkind.N_USE) { return; }; if (k == nkind.N_IDENT) { let nm: str = n.str; if (nm.len > 0) { let s: *sym = scopelookupprefer(c.cur, c.curmod, nm); if (s == nil) { c.nunresolved += 1; if (c.verbose != 0) { os.write(2, " unresolved id: ".ptr, 17u64); os.write(2, nm.ptr, nm.len: u64); os.write(2, "\n".ptr, 1u64); }; } else { c.nresolved += 1; }; }; }; if (k == nkind.N_TNAME) { let nm: str = n.str; if (nm.len > 0) { let s: *sym = scopelookupprefer(c.cur, c.curmod, nm); // `pkg.Type` — strip the last dot prefix and look up // the leaf with a mod filter so same-leaf-name types // from different imports (`bufio.stream` vs // `io.stream`) disambiguate to the right one. // Mirrors cmd/wcc/check.c resolve_typename. if (s == nil) { let dot: i32 = nm.len - 1; for (dot >= 0) { if (nm[dot] == 46u8) { break; }; dot -= 1; }; if (dot > 0) { let head: str; head.ptr = nm.ptr; head.len = dot; let m: *sym = scopelookup(c.cur, head); if (m != nil) { let leaf: str; leaf.ptr = nm.ptr + (dot + 1): u64; leaf.len = nm.len - (dot + 1); s = scopelookupinmodule(c.cur, head, leaf); }; }; }; if (s == nil) { c.nunresolved += 1; if (c.verbose != 0) { os.write(2, " unresolved tname: ".ptr, 20u64); os.write(2, nm.ptr, nm.len: u64); os.write(2, "\n".ptr, 1u64); }; } else { c.nresolved += 1; }; }; }; // `for (let x .. slice) body` / `for (let (a, b) .. slice) body` — // each binding name becomes a fresh local. Walk the slice expr first // so its idents resolve before the bindings shadow anything, then // install bindings and walk the body/else. // // TODO(#11): cstage check.c (post-#32) errors `binding '%s' // redeclared in same scope` when the tuple-pattern lists the same // name twice (`for (let (a, a) .. xs)`). Wwstage's resolvewalk has // no per-block scope (see resolvefnbody's docstring) and is used // only by wwdump_ww as a diagnostic, so silent-accept here avoids // false-positives on legal cross-block shadow until #11 adds the // scoping infrastructure. if (k == nkind.N_FORRANGE) { if (n.lhs != nil) { resolvewalk(c, n.lhs); }; if (n.list != nil) { let m: *node = n.list; for (m != nil) { let bnm: str = m.str; if (bnm.len > 0) { checkmoduleshadow(c, bnm, "binding"); scopedefine(c.cur, bnm, skind.SK_VAR, nil, m); }; m = m.next; }; } else { let bnm: str = n.str; if (bnm.len > 0) { checkmoduleshadow(c, bnm, "binding"); scopedefine(c.cur, bnm, skind.SK_VAR, nil, n); }; }; if (n.body != nil) { resolvewalk(c, n.body); }; if (n.els != nil) { resolvewalk(c, n.els); }; return; }; // `match (e) { case let v: T => stmt; ... }` — the binding `v` // is declared by the case arm and visible inside its body. Push a // fresh scope so `case let e: str` doesn't collide with an outer // `let e: *T` (scopedefine drops same-scope dupes silently and // would leave references to `e` resolving to the outer type). // Mirrors cmd/wcc/check.c's newscope/saved-restore around cstmt. if (k == nkind.N_MCASE) { if (n.lhs != nil) { resolvewalk(c, n.lhs); }; let outer: *scope = c.cur; c.cur = newscope(c.a, outer); let nm: str = n.str; if (nm.len > 0) { checkmoduleshadow(c, nm, "binding"); scopedefine(c.cur, nm, skind.SK_VAR, nil, n); }; if (n.body != nil) { resolvewalk(c, n.body); }; c.cur = outer; return; }; if (k == nkind.N_DOT) { // Walk only the base; the .field name is a member, not a // free identifier. if (n.lhs != nil) { resolvewalk(c, n.lhs); }; return; }; if (k == nkind.N_FIELD) { if (n.lhs != nil) { resolvewalk(c, n.lhs); }; return; }; if (k == nkind.N_TFIELD) { if (n.lhs != nil) { resolvewalk(c, n.lhs); }; return; }; // Walk children (mirroring ast.ww's printer descent order). if (n.attr != nil) { resolvewalk(c, n.attr); }; if (n.lhs != nil) { resolvewalk(c, n.lhs); }; if (n.rhs != nil) { resolvewalk(c, n.rhs); }; if (n.cond != nil) { resolvewalk(c, n.cond); }; if (n.body != nil) { resolvewalk(c, n.body); }; if (n.els != nil) { resolvewalk(c, n.els); }; if (n.list != nil) { let m: *node = n.list; for (m != nil) { resolvewalk(c, m); m = m.next; }; }; // After walking children: a local `let X: T = init;` registers // `X` so subsequent statements can resolve it. Top-level lets // are installed in installdecl, so this duplicate install at // the file scope just no-ops (scopedefine returns nil on dup). // // TODO(#11): cstage check.c (post-#32) errors `let '%s' redeclared // in same scope` here. Wwstage resolvewalk has no per-block scope // (see resolvefnbody's docstring) so a same-fn-body // `let a=1; { let a=2; };` would falsely trip if we guarded // scopedefine's nil return today. Silent-accept matches the // deferred-check design until #11 adds per-block scoping; see // test/wcc/708 and test/wcc/696 for the same cstage-only neg-case // precedent. if (k == nkind.N_LET) { let nm: str = n.str; if (nm.len > 0) { checkmoduleshadow(c, nm, "let"); scopedefine(c.cur, nm, skind.SK_VAR, nil, n); }; }; }; // ---- type-level helpers (AST-level, no resolved tinfo) -------------- // // The selfhost check operates on AST type expressions rather than // resolved Type structs. These helpers mirror what cmd/wcc/check.c // does with tinfo, but only on the subset of cases this checker // needs to enforce: tagged-union exhaustiveness, ? subset // propagation, and !-flag semantics. // unwrapbang — strip an nkind.N_TBANG wrapper; leaves other nodes alone. fn unwrapbang(n: *node) *node = { if (n == nil) { return nil; }; if (n.kind == nkind.N_TBANG) { return n.lhs; }; return n; }; // resolvealias — if n is an nkind.N_TNAME pointing at a typedecl, return // the typedecl's body (possibly recursively). Pass-through for any // other node. The chain stops once we hit a non-nkind.N_TNAME node or a // name we can't resolve. fn resolvealias(c: *checker, n: *node) *node = { let cur: *node = n; for (cur != nil) { if (cur.kind != nkind.N_TNAME) { return cur; }; let s: *sym = scopelookup(c.cur, cur.str); if (s == nil) { return cur; }; if (s.skind != skind.SK_TYPE) { return cur; }; let body: *node = nil; if (s.decl != nil) { body = s.decl.lhs; }; if (body == nil) { return cur; }; cur = unwrapbang(body); }; return n; }; // typeeqast — structural equality on AST type expressions, mod // the `!` wrapper. Mirrors variant_match in cgen + check.c: NAMED // types compare by string (the closest stand-in for pointer // identity at the AST level); other nodes recurse by kind. fn typeeqast(a: *node, b: *node) bool = { let aa: *node = unwrapbang(a); let bb: *node = unwrapbang(b); if (aa == nil) { return bb == nil; }; if (bb == nil) { return false; }; if (aa.kind != bb.kind) { return false; }; let k: nkind = aa.kind; if (k == nkind.N_TNAME) { return streq(aa.str, bb.str); }; if (k == nkind.N_TPTR) { return typeeqast(aa.lhs, bb.lhs); }; if (k == nkind.N_TSLICE){ return typeeqast(aa.lhs, bb.lhs); }; if (k == nkind.N_TCHAN) { return typeeqast(aa.lhs, bb.lhs); }; // Conservative: anything else (struct/fn/tagged/tuple/array) // fails the cheap check. Selfhost code doesn't currently rely // on equality at these shapes for the targeted checks. return false; }; // varianterr — does this variant carry the `!` mark? Either // the variant itself is nkind.N_TBANG or it's an alias whose typedecl // body is `!T`. Mirrors C check.c's iserror-after-NAMED rule. fn varianterr(c: *checker, v: *node) bool = { if (v == nil) { return false; }; if (v.kind == nkind.N_TBANG) { return true; }; if (v.kind == nkind.N_TNAME) { let s: *sym = scopelookup(c.cur, v.str); if (s != nil) { if (s.skind == skind.SK_TYPE) { if (s.decl != nil) { if (s.decl.lhs != nil) { if (s.decl.lhs.kind == nkind.N_TBANG) { return true; }; }; }; }; }; }; return false; }; // taggedhaserr — true iff any variant of `n` (assumed // nkind.N_TTAGGED) is `!`-marked. Picks the explicit-flag semantics over // the legacy "first variant = success" rule. fn taggedhaserr(c: *checker, n: *node) bool = { let v: *node = n.list; for (v != nil) { if (varianterr(c, v)) { return true; }; v = v.next; }; return false; }; // iserrvariant — under flag-aware mode (any !-marked variant), // returns true iff `v` is `!`-marked. Under legacy mode (no flags), // returns true iff `v` is not the first variant of `tagged`. fn iserrvariant(c: *checker, tagged: *node, v: *node) bool = { if (taggedhaserr(c, tagged)) { return varianterr(c, v); }; // Legacy: first variant of the union is success. if (tagged.list == v) { return false; }; return true; }; // scruttype — resolve the type expression for a match's // scrutinee. Handles nkind.N_IDENT (look up local/param's declared // type) and nkind.N_DOT (struct-field access). Returns nil if we // can't statically determine the type. Used by exhaustiveness. fn scruttype(c: *checker, e: *node) *node = { if (e == nil) { return nil; }; if (e.kind == nkind.N_IDENT) { let s: *sym = scopelookup(c.cur, e.str); if (s == nil) { return nil; }; if (s.decl == nil) { return nil; }; // For nkind.N_LET / nkind.N_PARAM: declared type is decl.lhs. return s.decl.lhs; }; return nil; }; // mktname — fabricate an nkind.N_TNAME node with str = `nm`. Used by // exprtype to return primitive type nodes for literal // expressions. The arena keeps them around as long as the checker. fn mktname(c: *checker, nm: str) *node = { let n: *node = newnode(c.a, nkind.N_TNAME, "", 0, 0); n.str = nm; return n; }; // exprtype — best-effort type-AST inference for an expression // node. Handles literals, identifiers, calls, and casts; returns // nil for shapes we don't statically know (binary ops, struct // field access into non-primitive types, etc). fn exprtype(c: *checker, e: *node) *node = { if (e == nil) { return nil; }; let k: nkind = e.kind; if (k == nkind.N_INTLIT) { return mktname(c, "untyped_int"); }; if (k == nkind.N_FLOATLIT) { return mktname(c, "untyped_float"); }; if (k == nkind.N_STRLIT) { return mktname(c, "str"); }; if (k == nkind.N_RUNELIT) { return mktname(c, "rune"); }; if (k == nkind.N_TRUE) { return mktname(c, "bool"); }; if (k == nkind.N_FALSE) { return mktname(c, "bool"); }; if (k == nkind.N_VOIDLIT) { return mktname(c, "void"); }; if (k == nkind.N_NIL) { return mktname(c, "untyped_nil"); }; if (k == nkind.N_IDENT) { let s: *sym = scopelookup(c.cur, e.str); if (s == nil) { return nil; }; if (s.decl == nil) { return nil; }; return s.decl.lhs; }; if (k == nkind.N_CAST) { // `expr: T` — explicit cast; the type expr is e.rhs. return e.rhs; }; if (k == nkind.N_CALL) { let callee: *node = e.lhs; if (callee == nil) { return nil; }; let nm: str; nm.ptr = nil; nm.len = 0; if (callee.kind == nkind.N_IDENT) { nm = callee.str; }; if (callee.kind == nkind.N_DOT) { nm = callee.str; }; if (nm.len == 0) { return nil; }; let s: *sym = scopelookup(c.cur, nm); if (s == nil) { return nil; }; if (s.skind != skind.SK_FN) { return nil; }; if (s.decl == nil) { return nil; }; return s.decl.lhs; // fn-decl's lhs is the return type }; if (k == nkind.N_TRYPROP) { // success unwrap: the success-variant type of operand's // tagged union. let opt: *node = exprtype(c, e.lhs); let ou: *node = resolvealias(c, unwrapbang(opt)); if (ou == nil) { return nil; }; if (ou.kind != nkind.N_TTAGGED) { return nil; }; // Hare semantics: success = first non-error variant if // any !-flag is present; else first variant. if (taggedhaserr(c, ou)) { let v: *node = ou.list; for (v != nil) { if (!iserrvariant(c, ou, v)) { return v; }; v = v.next; }; return nil; }; return ou.list; }; if (k == nkind.N_TYPEASSERT) { // `e as T` → T return e.rhs; }; if (k == nkind.N_TYPETEST) { // `e is T` → bool return mktname(c, "bool"); }; return nil; }; // isuntypedint / is_str_like / is_bool_like — helpers used // by the assignability check below to allow common AST shapes // through without needing real type inference. fn isuntypedint(t: *node) bool = { if (t == nil) { return false; }; if (t.kind != nkind.N_TNAME) { return false; }; return streq(t.str, "untyped_int"); }; fn isuntypedfloat(t: *node) bool = { if (t == nil) { return false; }; if (t.kind != nkind.N_TNAME) { return false; }; return streq(t.str, "untyped_float"); }; fn isuntypednil(t: *node) bool = { if (t == nil) { return false; }; if (t.kind != nkind.N_TNAME) { return false; }; return streq(t.str, "untyped_nil"); }; fn isnumerictname(t: *node) bool = { if (t == nil) { return false; }; if (t.kind != nkind.N_TNAME) { return false; }; let s: str = t.str; if (streq(s, "i8")) { return true; }; if (streq(s, "i16")) { return true; }; if (streq(s, "i32")) { return true; }; if (streq(s, "i64")) { return true; }; if (streq(s, "u8")) { return true; }; if (streq(s, "u16")) { return true; }; if (streq(s, "u32")) { return true; }; if (streq(s, "u64")) { return true; }; if (streq(s, "int")) { return true; }; if (streq(s, "uint")) { return true; }; if (streq(s, "uintptr")) { return true; }; if (streq(s, "rune")) { return true; }; if (streq(s, "f32")) { return true; }; if (streq(s, "f64")) { return true; }; return false; }; fn isstrtname(t: *node) bool = { if (t == nil) { return false; }; if (t.kind != nkind.N_TNAME) { return false; }; return streq(t.str, "str"); }; // isassignable — AST-level approximation of C check.c // type_assignable. Returns true when we know the assignment is // OK, false only when we're confident it isn't, and "skip" (true) // when we can't tell — to avoid false positives. The trailing bool // `confident` lets the caller decide whether to emit an error // when the result is false: if !confident, the caller should not // flag it. fn isassignable(c: *checker, dst: *node, src: *node, confident: *bool) bool = { *confident = false; if (dst == nil) { return true; }; // no declared target if (src == nil) { return true; }; // unknown src type *confident = true; let du: *node = resolvealias(c, unwrapbang(dst)); let su: *node = resolvealias(c, unwrapbang(src)); if (du == nil) { *confident = false; return true; }; if (su == nil) { *confident = false; return true; }; if (typeeqast(du, su)) { return true; }; // untyped numeric → any numeric named type. if (isuntypedint(su)) { if (isnumerictname(du)) { return true; }; // (T | ...) tagged: only OK if some variant accepts untyped_int. if (du.kind == nkind.N_TTAGGED) { let v: *node = du.list; for (v != nil) { let vu: *node = resolvealias(c, unwrapbang(v)); if (vu != nil) { if (isnumerictname(vu)) { return true; }; }; v = v.next; }; *confident = false; return true; }; // Known non-numeric primitive: confidently wrong. if (du.kind == nkind.N_TNAME) { if (streq(du.str, "bool")) { return false; }; if (streq(du.str, "void")) { return false; }; if (streq(du.str, "str")) { return false; }; }; // Unknown shapes: stay quiet. *confident = false; return true; }; if (isuntypedfloat(su)) { if (isnumerictname(du)) { return true; }; if (du.kind == nkind.N_TNAME) { if (streq(du.str, "bool")) { return false; }; if (streq(du.str, "void")) { return false; }; if (streq(du.str, "str")) { return false; }; }; *confident = false; return true; }; if (isuntypednil(su)) { // nil → ptr/slice/chan/fn/nullable if (du.kind == nkind.N_TPTR) { return true; }; if (du.kind == nkind.N_TSLICE) { return true; }; if (du.kind == nkind.N_TCHAN) { return true; }; if (du.kind == nkind.N_TFN) { return true; }; // nullable `(*T | void)` — already accepted by typeeqast // when matched whole; nil is OK there too. if (du.kind == nkind.N_TTAGGED) { let v: *node = du.list; for (v != nil) { if (v.kind == nkind.N_TPTR) { return true; }; if (v.kind == nkind.N_TSLICE){ return true; }; v = v.next; }; }; *confident = false; return true; }; // Tagged-union variant inclusion: src is one of dst's variants. if (du.kind == nkind.N_TTAGGED && su.kind != nkind.N_TTAGGED) { let v: *node = du.list; for (v != nil) { let vu: *node = resolvealias(c, unwrapbang(v)); if (vu != nil) { if (typeeqast(vu, su)) { return true; }; }; v = v.next; }; return false; }; // tagged → tagged: structural variant list compare. Skip // (don't be confident) — common when forwarding a fallible // return through another fn with the same shape but possibly // a different surface spelling. if (du.kind == nkind.N_TTAGGED && su.kind == nkind.N_TTAGGED) { *confident = false; return true; }; // Two known primitives with different names are confidently // incompatible. `i32 ↔ bool`, `str ↔ i32`, etc. if (du.kind == nkind.N_TNAME && su.kind == nkind.N_TNAME) { let known_d: bool = isnumerictname(du) || isstrtname(du); if (!known_d) { if (streq(du.str, "bool")) { known_d = true; }; }; if (!known_d) { if (streq(du.str, "void")) { known_d = true; }; }; let known_s: bool = isnumerictname(su) || isstrtname(su); if (!known_s) { if (streq(su.str, "bool")) { known_s = true; }; }; if (!known_s) { if (streq(su.str, "void")) { known_s = true; }; }; if (known_d) { if (known_s) { // Both primitives, different names → no. return false; }; }; }; // Anything else: don't claim confidence. *confident = false; return true; }; // ---- match exhaustiveness -------------------------------------------- // // For every match arm, verify that every variant of the scrutinee's // tagged-union type is handled by some case (or a default arm // exists). Multi-pattern `case A | B =>` covers all alts. fn casecovers(c: *checker, cs: *node, want: *node) bool = { if (cs.lhs != nil) { if (typeeqast(cs.lhs, want)) { return true; }; }; let alt: *node = cs.list; for (alt != nil) { if (typeeqast(alt, want)) { return true; }; alt = alt.next; }; return false; }; fn errmatchvariant(c: *checker, n: *node, vname: *node) void = { os.write(2, "match: variant not handled".ptr, 26u64); if (vname != nil) { if (vname.kind == nkind.N_TNAME) { os.write(2, " (".ptr, 2u64); os.write(2, vname.str.ptr, vname.str.len: u64); os.write(2, ")".ptr, 1u64); }; }; os.write(2, "\n".ptr, 1u64); c.errs += 1; }; // casevariantin — true iff `pat` (a `case T` pattern, including // each alt of a multi-pattern) names a variant of the tagged // union `tagged`. fn casevariantin(tagged: *node, pat: *node) bool = { let v: *node = tagged.list; for (v != nil) { if (typeeqast(v, pat)) { return true; }; v = v.next; }; return false; }; fn errbadcase(c: *checker, pat: *node) void = { os.write(2, "case: not a variant of scrutinee".ptr, 32u64); if (pat != nil) { if (pat.kind == nkind.N_TNAME) { os.write(2, " (".ptr, 2u64); os.write(2, pat.str.ptr, pat.str.len: u64); os.write(2, ")".ptr, 1u64); }; }; os.write(2, "\n".ptr, 1u64); c.errs += 1; }; fn checkmatchexhaust(c: *checker, n: *node) void = { if (n == nil) { return; }; if (n.lhs == nil) { return; }; let st: *node = scruttype(c, n.lhs); let u: *node = resolvealias(c, unwrapbang(st)); if (u == nil) { return; }; if (u.kind != nkind.N_TTAGGED) { return; }; // Validity: every `case T` pattern (and multi-pattern alts) // must name a variant of u. Catches typos and dead arms that // the dispatch would never reach. let cs0: *node = n.list; for (cs0 != nil) { if (cs0.lhs != nil) { if (!casevariantin(u, cs0.lhs)) { errbadcase(c, cs0.lhs); }; let alt: *node = cs0.list; for (alt != nil) { if (!casevariantin(u, alt)) { errbadcase(c, alt); }; alt = alt.next; }; }; cs0 = cs0.next; }; // Default arm absorbs anything; skip exhaustiveness. let cs: *node = n.list; for (cs != nil) { if (cs.lhs == nil) { return; }; // default cs = cs.next; }; // For each variant of u, look for a covering case. let v: *node = u.list; for (v != nil) { let covered: bool = false; let cs2: *node = n.list; for (cs2 != nil) { if (casecovers(c, cs2, v)) { covered = true; cs2 = nil; } else { cs2 = cs2.next; }; }; if (!covered) { errmatchvariant(c, n, v); }; v = v.next; }; }; // ---- let init / return assignability -------------------------------- // // AST-level approximation: when we can infer src's type and dst is // explicitly declared, verify isassignable. We only emit an error // when isassignable says "false with confidence." If we can't tell // (binary ops, complex exprs we don't infer), we stay quiet — full // type inference lives only on the C side. fn errnotassign(c: *checker, dst: *node, src: *node, where: str) void = { os.write(2, where.ptr, where.len: u64); os.write(2, ": not assignable".ptr, 16u64); if (src != nil) { if (src.kind == nkind.N_TNAME) { os.write(2, " (".ptr, 2u64); os.write(2, src.str.ptr, src.str.len: u64); os.write(2, " → ".ptr, 5u64); if (dst != nil) { if (dst.kind == nkind.N_TNAME) { os.write(2, dst.str.ptr, dst.str.len: u64); }; }; os.write(2, ")".ptr, 1u64); }; }; os.write(2, "\n".ptr, 1u64); c.errs += 1; }; fn checkletassign(c: *checker, n: *node) void = { if (n == nil) { return; }; if (n.lhs == nil) { return; }; // no declared type, nothing to check if (n.rhs == nil) { return; }; // no init let src: *node = exprtype(c, n.rhs); if (src == nil) { return; }; // can't infer let conf: bool = false; let ok: bool = isassignable(c, n.lhs, src, &conf); if (!conf) { return; }; if (!ok) { errnotassign(c, n.lhs, src, "let"); }; }; fn checkretassign(c: *checker, n: *node) void = { if (n == nil) { return; }; if (n.lhs == nil) { // bare `return;` — OK iff fnret is void or a tagged union // with a void variant. Skip flagging for now; cgen handles // the void-variant tag synthesis already. return; }; if (c.fnret == nil) { return; }; let src: *node = exprtype(c, n.lhs); if (src == nil) { return; }; let conf: bool = false; let ok: bool = isassignable(c, c.fnret, src, &conf); if (!conf) { return; }; if (!ok) { errnotassign(c, c.fnret, src, "return"); }; }; // ---- is / as validity ------------------------------------------------ // // `e is T` and `e as T` require that e's declared type be a tagged // union and that T name one of its variants. Operates on AST type // expressions; falls back silently when we can't determine e's // type (matches the case-variant rule for match). fn checkisas(c: *checker, n: *node) void = { if (n == nil) { return; }; // e is in n.lhs (value), T is in n.rhs (type expr). let st: *node = scruttype(c, n.lhs); let u: *node = resolvealias(c, unwrapbang(st)); if (u == nil) { return; }; if (u.kind != nkind.N_TTAGGED) { os.write(2, "is/as: operand is not a tagged union\n".ptr, 37u64); c.errs += 1; return; }; let want: *node = n.rhs; if (want == nil) { return; }; if (!casevariantin(u, want)) { os.write(2, "is/as: not a variant of operand".ptr, 31u64); if (want.kind == nkind.N_TNAME) { os.write(2, " (".ptr, 2u64); os.write(2, want.str.ptr, want.str.len: u64); os.write(2, ")".ptr, 1u64); }; os.write(2, "\n".ptr, 1u64); c.errs += 1; }; }; // ---- ? subset propagation -------------------------------------------- // // For `expr?`, the operand's error subset must be a subset of the // enclosing fn's return-type variants. Mirrors C check.c. Operand // is nkind.N_TRYPROP; its lhs is the value-bearing expr; we look at the // expr's *declared* type for nkind.N_IDENT/nkind.N_CALL cases. fn exprtypeoftry(c: *checker, e: *node) *node = { if (e == nil) { return nil; }; if (e.kind == nkind.N_IDENT) { let s: *sym = scopelookup(c.cur, e.str); if (s == nil) { return nil; }; if (s.decl == nil) { return nil; }; return s.decl.lhs; }; if (e.kind == nkind.N_CALL) { // callee return type lookup: callee is e.lhs (nkind.N_IDENT or // nkind.N_DOT). We need the fn-decl's lhs (return-type AST). let callee: *node = e.lhs; if (callee == nil) { return nil; }; let nm: str; nm.ptr = nil; nm.len = 0; if (callee.kind == nkind.N_IDENT) { nm = callee.str; }; if (callee.kind == nkind.N_DOT) { nm = callee.str; }; if (nm.len == 0) { return nil; }; let s: *sym = scopelookup(c.cur, nm); if (s == nil) { return nil; }; if (s.skind != skind.SK_FN) { return nil; }; if (s.decl == nil) { return nil; }; return s.decl.lhs; }; return nil; }; fn checktryprop(c: *checker, n: *node) void = { if (n == nil) { return; }; let t: *node = exprtypeoftry(c, n.lhs); let u: *node = resolvealias(c, unwrapbang(t)); if (u == nil) { return; }; if (u.kind != nkind.N_TTAGGED) { return; }; // Does the operand have any error variants? let haserr: bool = false; let v: *node = u.list; for (v != nil) { if (iserrvariant(c, u, v)) { haserr = true; }; v = v.next; }; if (!haserr) { return; }; // Enclosing fn must return a tagged union with each operand // error variant present. let r: *node = resolvealias(c, unwrapbang(c.fnret)); if (r == nil) { os.write(2, "?: enclosing fn has no tagged-union return\n".ptr, 43u64); c.errs += 1; return; }; if (r.kind != nkind.N_TTAGGED) { os.write(2, "?: enclosing fn return is not tagged\n".ptr, 37u64); c.errs += 1; return; }; let ev: *node = u.list; for (ev != nil) { if (iserrvariant(c, u, ev)) { let found: bool = false; let rv: *node = r.list; for (rv != nil) { if (typeeqast(rv, ev)) { found = true; rv = nil; } else { rv = rv.next; }; }; if (!found) { os.write(2, "?: error variant not in enclosing return\n".ptr, 41u64); c.errs += 1; }; }; ev = ev.next; }; }; // install_param — when entering a fn body, define its params in a // fresh local scope. // // TODO(#11): cstage check.c (post-#32) errors `param '%s' redeclared` // when two params share a name. The fn body's scope IS fresh here // (resolvefnbody opens it before calling us), so guarding scopedefine's // nil return would be sound — but we defer until #11 wires checkfile // into w6c_ww so the diagnostic class lands as a single coordinated // step rather than dribbling in. Matches the cstage-only neg-case // precedent at test/wcc/708 + test/wcc/696. fn installparams(c: *checker, params: *node) void = { let p: *node = params; for (p != nil) { if (p.kind == nkind.N_PARAM) { let nm: str = p.str; if (nm.len > 0) { checkmoduleshadow(c, nm, "param"); scopedefine(c.cur, nm, skind.SK_PARAM, nil, p); }; }; p = p.next; }; }; // resolvefnbody — open a child scope for the fn, install its params, // then walk the body. Local lets installed by walk_stmt (a future // extension); for the current pass we just resolve-walk without // per-statement scopes. fn resolvefnbody(c: *checker, fnnode: *node) void = { let outer: *scope = c.cur; c.cur = newscope(c.a, c.cur); installparams(c, fnnode.list); let prevret: *node = c.fnret; c.fnret = fnnode.lhs; // return type AST, used by `?` check if (fnnode.body != nil) { resolvewalk(c, fnnode.body); }; c.fnret = prevret; c.cur = outer; }; export fn checkinit(c: *checker, a: *arena, tc: *tctx) void = { c.a = a; c.tc = tc; c.top = newscope(a, nil); c.cur = c.top; c.nresolved = 0; c.nunresolved = 0; c.errs = 0; c.verbose = 0; c.fnret = nil; let empty: str; c.curmod = empty; c.file = nil; seedprimitives(c); }; export fn checkfile(c: *checker, file: *node) void = { if (file == nil) { return; }; if (file.kind != nkind.N_FILE) { return; }; c.file = file; // Pass 1: install all top-level names. let d: *node = file.list; for (d != nil) { installdecl(c, file, d); d = d.next; }; // Pass 2: walk decl bodies/types and resolve identifiers. // Track the per-decl module bareword so bare-leaf lookups inside // the body prefer same-module entries over alphabetically-earlier // same-leaf imports. d = file.list; for (d != nil) { c.curmod = declmod(file, d); let k: nkind = d.kind; if (k == nkind.N_FNDECL) { if (d.lhs != nil) { resolvewalk(c, d.lhs); }; // return type resolvefnbody(c, d); } else { if (k == nkind.N_DEF) { if (d.lhs != nil) { resolvewalk(c, d.lhs); }; if (d.rhs != nil) { resolvewalk(c, d.rhs); }; } else { if (k == nkind.N_TYPEDECL) { if (d.lhs != nil) { resolvewalk(c, d.lhs); }; } else { if (k == nkind.N_LET) { if (d.lhs != nil) { resolvewalk(c, d.lhs); }; if (d.rhs != nil) { resolvewalk(c, d.rhs); }; };};};}; d = d.next; }; let empty: str; c.curmod = empty; };