Files
ww/selfhost/cmd/wcc/check.ww
Hojun-Cho 68bd8197d5 selfhost: port match exhaustiveness, ?-subset, !-flag checks to check.ww
The selfhost checker did name resolution only — anything tagged-
union-shaped sailed through silently. The C check.c implements
three structural checks; this commit mirrors them at the AST level
in selfhost/cmd/wcc/check.ww:

1. Match exhaustiveness: every variant of the scrutinee's tagged
   union must be covered by a case arm (incl. multi-pattern alts)
   or a default arm. Operates on the scrutinee's declared type
   (N_TTAGGED via N_IDENT's sym.decl.lhs).

2. ? subset propagation: each error variant of the operand's type
   must be a variant of the enclosing fn's return type. Enclosing
   return must itself be a tagged union when the operand has any
   errors.

3. !-flag semantics: in flag-aware mode (any variant marked `!T`),
   error subset = flagged variants. Legacy mode (no flags) =
   everything-but-first. is_error_variant unifies both rules.

No tinfo / type-inference work: the checks read declared AST type
nodes directly. `resolvealias` chases N_TNAME → typedecl body to
handle aliased tagged unions. `type_eq_ast` does structural
comparison on the subset of type-expression shapes the checks
encounter (TNAME by string, TPTR/TSLICE/TCHAN recursive).

Folded into resolvewalk rather than a separate second pass, so the
checks see the same per-statement scope state as resolve. fnret is
threaded through resolvefnbody so ? can find the enclosing return.

New test/wcc/950_selfcheck.c — five rows exercising each error path
(missing variant, non-tagged enclosing, missing error subset
member, the flag-aware happy path, the flag-aware missing-error
case). Test suite now reports 21 ok.
2026-05-12 03:24:25 +09:00

553 lines
17 KiB
Plaintext

// 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 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 `?`)
};
// 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", SK_TYPE, c.tc.tyvoid, nil);
scopedefine(c.top, "bool", SK_TYPE, c.tc.tybool, nil);
scopedefine(c.top, "rune", SK_TYPE, c.tc.tyrune, nil);
scopedefine(c.top, "i8", SK_TYPE, c.tc.tyi8, nil);
scopedefine(c.top, "i16", SK_TYPE, c.tc.tyi16, nil);
scopedefine(c.top, "i32", SK_TYPE, c.tc.tyi32, nil);
scopedefine(c.top, "i64", SK_TYPE, c.tc.tyi64, nil);
scopedefine(c.top, "u8", SK_TYPE, c.tc.tyu8, nil);
scopedefine(c.top, "u16", SK_TYPE, c.tc.tyu16, nil);
scopedefine(c.top, "u32", SK_TYPE, c.tc.tyu32, nil);
scopedefine(c.top, "u64", SK_TYPE, c.tc.tyu64, nil);
scopedefine(c.top, "int", SK_TYPE, c.tc.tyint, nil);
scopedefine(c.top, "uint", SK_TYPE, c.tc.tyuint, nil);
scopedefine(c.top, "uintptr", SK_TYPE, c.tc.tyuintptr, nil);
scopedefine(c.top, "f32", SK_TYPE, c.tc.tyf32, nil);
scopedefine(c.top, "f64", SK_TYPE, c.tc.tyf64, nil);
scopedefine(c.top, "str", SK_TYPE, c.tc.tystr, nil);
scopedefine(c.top, "never", SK_TYPE, c.tc.tynever, nil);
// `nil`, `true`, `false` are keywords — handled at the lex/parser
// level, no symbol needed.
// `len`, `alloc`, `free` are pseudo-builtins; scopedefine them so
// their use sites resolve. The actual semantics live in cgen.
scopedefine(c.top, "len", SK_FN, nil, nil);
scopedefine(c.top, "alloc", SK_FN, nil, nil);
scopedefine(c.top, "free", SK_FN, nil, nil);
};
// 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.
fn installdecl(c: *checker, d: *node) void = {
if (d == nil) { return; };
let k: i32 = d.kind;
let nm: str = d.str;
if (k == N_USE) { scopedefine(c.top, nm, SK_USE, nil, d); return; };
if (k == N_DEF) { scopedefine(c.top, nm, SK_DEF, nil, d); return; };
if (k == N_TYPEDECL) { scopedefine(c.top, nm, SK_TYPE, nil, d); return; };
if (k == N_FNDECL) { scopedefine(c.top, nm, SK_FN, nil, d); return; };
if (k == N_LET) { scopedefine(c.top, nm, SK_VAR, nil, d); return; };
};
// resolvewalk — recursive AST walk that, for every N_IDENT and
// 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: i32 = n.kind;
// Typed checks fire on the way down so the scrutinee/operand
// is examined before the arm bodies install new bindings.
if (k == N_MATCH) { check_match_exhaustive(c, n); };
if (k == N_TRYPROP) { check_tryprop(c, n); };
// `use IDENT;` — name is a module label, not a free ident.
if (k == N_USE) { return; };
if (k == N_IDENT) {
let nm: str = n.str;
if (nm.len > 0) {
let s: *sym = scopelookup(c.cur, 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 == N_TNAME) {
let nm: str = n.str;
if (nm.len > 0) {
let s: *sym = scopelookup(c.cur, nm);
// `pkg.Type` — strip the last dot prefix and look up
// the leaf if `pkg` is a use-imported name. 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 = scopelookup(c.cur, 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; };
};
};
// `match (e) { case let v: T => stmt; ... }` — the binding `v`
// is declared by the case arm and visible inside its body.
if (k == N_MCASE) {
if (n.lhs != nil) { resolvewalk(c, n.lhs); };
let nm: str = n.str;
if (nm.len > 0) {
scopedefine(c.cur, nm, SK_VAR, nil, n);
};
if (n.body != nil) { resolvewalk(c, n.body); };
return;
};
if (k == 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 == N_FIELD) {
if (n.lhs != nil) { resolvewalk(c, n.lhs); };
return;
};
if (k == 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).
if (k == N_LET) {
let nm: str = n.str;
if (nm.len > 0) {
scopedefine(c.cur, nm, 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 N_TBANG wrapper; leaves other nodes alone.
fn unwrapbang(n: *node) *node = {
if (n == nil) { return nil; };
if (n.kind == N_TBANG) { return n.lhs; };
return n;
};
// resolvealias — if n is an 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-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 != N_TNAME) { return cur; };
let s: *sym = scopelookup(c.cur, cur.str);
if (s == nil) { return cur; };
if (s.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;
};
// is_tagged_type — true if `n` (after alias resolution) is an
// N_TTAGGED type expression.
fn is_tagged_type(c: *checker, n: *node) bool = {
let u: *node = resolvealias(c, unwrapbang(n));
if (u == nil) { return false; };
return u.kind == N_TTAGGED;
};
// type_eq_ast — 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 type_eq_ast(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: i32 = aa.kind;
if (k == N_TNAME) { return streq(aa.str, bb.str); };
if (k == N_TPTR) { return type_eq_ast(aa.lhs, bb.lhs); };
if (k == N_TSLICE){ return type_eq_ast(aa.lhs, bb.lhs); };
if (k == N_TCHAN) { return type_eq_ast(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;
};
// variant_is_error — does this variant carry the `!` mark? Either
// the variant itself is N_TBANG or it's an alias whose typedecl
// body is `!T`. Mirrors C check.c's iserror-after-NAMED rule.
fn variant_is_error(c: *checker, v: *node) bool = {
if (v == nil) { return false; };
if (v.kind == N_TBANG) { return true; };
if (v.kind == N_TNAME) {
let s: *sym = scopelookup(c.cur, v.str);
if (s != nil) {
if (s.skind == SK_TYPE) {
if (s.decl != nil) {
if (s.decl.lhs != nil) {
if (s.decl.lhs.kind == N_TBANG) {
return true;
};
};
};
};
};
};
return false;
};
// tagged_has_errflag — true iff any variant of `n` (assumed
// N_TTAGGED) is `!`-marked. Picks the explicit-flag semantics over
// the legacy "first variant = success" rule.
fn tagged_has_errflag(c: *checker, n: *node) bool = {
let v: *node = n.list;
for (v != nil) {
if (variant_is_error(c, v)) { return true; };
v = v.next;
};
return false;
};
// is_error_variant — 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 is_error_variant(c: *checker, tagged: *node, v: *node) bool = {
if (tagged_has_errflag(c, tagged)) {
return variant_is_error(c, v);
};
// Legacy: first variant of the union is success.
if (tagged.list == v) { return false; };
return true;
};
// scrutinee_type — resolve the type expression for a match's
// scrutinee. Handles N_IDENT (look up local/param's declared
// type) and N_DOT (struct-field access). Returns nil if we
// can't statically determine the type. Used by exhaustiveness.
fn scrutinee_type(c: *checker, e: *node) *node = {
if (e == nil) { return nil; };
if (e.kind == N_IDENT) {
let s: *sym = scopelookup(c.cur, e.str);
if (s == nil) { return nil; };
if (s.decl == nil) { return nil; };
// For N_LET / N_PARAM: declared type is decl.lhs.
return s.decl.lhs;
};
return nil;
};
// ---- 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 case_covers(c: *checker, cs: *node, want: *node) bool = {
if (cs.lhs != nil) {
if (type_eq_ast(cs.lhs, want)) { return true; };
};
let alt: *node = cs.list;
for (alt != nil) {
if (type_eq_ast(alt, want)) { return true; };
alt = alt.next;
};
return false;
};
fn err_match_variant(c: *checker, n: *node, vname: *node) void = {
os.write(2, "match: variant not handled".ptr, 26u64);
if (vname != nil) {
if (vname.kind == 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;
};
fn check_match_exhaustive(c: *checker, n: *node) void = {
if (n == nil) { return; };
if (n.lhs == nil) { return; };
let st: *node = scrutinee_type(c, n.lhs);
let u: *node = resolvealias(c, unwrapbang(st));
if (u == nil) { return; };
if (u.kind != N_TTAGGED) { return; };
// Default arm absorbs anything; skip.
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 (case_covers(c, cs2, v)) {
covered = true;
cs2 = nil;
} else {
cs2 = cs2.next;
};
};
if (!covered) { err_match_variant(c, n, v); };
v = v.next;
};
};
// ---- ? 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 N_TRYPROP; its lhs is the value-bearing expr; we look at the
// expr's *declared* type for N_IDENT/N_CALL cases.
fn expr_type_for_tryprop(c: *checker, e: *node) *node = {
if (e == nil) { return nil; };
if (e.kind == 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 == N_CALL) {
// callee return type lookup: callee is e.lhs (N_IDENT or
// 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 == N_IDENT) { nm = callee.str; };
if (callee.kind == 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 != SK_FN) { return nil; };
if (s.decl == nil) { return nil; };
return s.decl.lhs;
};
return nil;
};
fn check_tryprop(c: *checker, n: *node) void = {
if (n == nil) { return; };
let t: *node = expr_type_for_tryprop(c, n.lhs);
let u: *node = resolvealias(c, unwrapbang(t));
if (u == nil) { return; };
if (u.kind != N_TTAGGED) { return; };
// Does the operand have any error variants?
let has_err: bool = false;
let v: *node = u.list;
for (v != nil) {
if (is_error_variant(c, u, v)) { has_err = true; };
v = v.next;
};
if (!has_err) { 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 != 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 (is_error_variant(c, u, ev)) {
let found: bool = false;
let rv: *node = r.list;
for (rv != nil) {
if (type_eq_ast(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.
fn installparams(c: *checker, params: *node) void = {
let p: *node = params;
for (p != nil) {
if (p.kind == N_PARAM) {
let nm: str = p.str;
if (nm.len > 0) {
scopedefine(c.cur, nm, 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;
seedprimitives(c);
};
export fn checkfile(c: *checker, file: *node) void = {
if (file == nil) { return; };
if (file.kind != N_FILE) { return; };
// Pass 1: install all top-level names.
let d: *node = file.list;
for (d != nil) {
installdecl(c, d);
d = d.next;
};
// Pass 2: walk decl bodies/types and resolve identifiers.
d = file.list;
for (d != nil) {
let k: i32 = d.kind;
if (k == N_FNDECL) {
if (d.lhs != nil) { resolvewalk(c, d.lhs); }; // return type
resolvefnbody(c, d);
} else { if (k == N_DEF) {
if (d.lhs != nil) { resolvewalk(c, d.lhs); };
if (d.rhs != nil) { resolvewalk(c, d.rhs); };
} else { if (k == N_TYPEDECL) {
if (d.lhs != nil) { resolvewalk(c, d.lhs); };
} else { if (k == N_LET) {
if (d.lhs != nil) { resolvewalk(c, d.lhs); };
if (d.rhs != nil) { resolvewalk(c, d.rhs); };
};};};};
d = d.next;
};
};