ww: import toolchain — C bootstrap + ww-side self-host (phases 0-10)
C bootstrap (phases 0-9):
cmd/wwc, cmd/6c, cmd/6a, cmd/6l, cmd/ww, rt, lib/*.
ww-side self-host (phase 10):
selfhost/cmd/wwc — ww-cgen frontend; bootstrap fixed point.
selfhost/cmd/6a — assembler; byte-identical to C 6a (test 991).
selfhost/cmd/6l — linker w/ archive (.a) support; byte-identical
to C 6l (test 992).
selfhost/cmd/ww — driver (build/run/version); byte-identical to
C ww (test 993).
make test: 15/15. make bootstrap: ww2.s == ww3.s, ww2.o == ww3.o,
ww2 == ww3 byte-identical, with the full ww-tooled chain.
This commit is contained in:
681
selfhost/cmd/6a/asm.ww
Normal file
681
selfhost/cmd/6a/asm.ww
Normal file
@@ -0,0 +1,681 @@
|
||||
// selfhost/cmd/6a/asm.ww — port of cmd/6a/asm.c.
|
||||
//
|
||||
// Encode the parsed aprog list into amd64 machine bytes, appending to
|
||||
// asm_.text. Relocations for CALL/branch targets that resolve to
|
||||
// externals are queued in asm_.relocs.
|
||||
//
|
||||
// Encoding subset matches what 6c emits — see cmd/6a/asm.c for the
|
||||
// authoritative list. Helpers (rcode/rhi/modrm/emit_rex etc.) are
|
||||
// fully ported; a_encode itself is still a stub pending the full
|
||||
// switch over A_*.
|
||||
|
||||
use os;
|
||||
use mem;
|
||||
use types;
|
||||
|
||||
// ---- text buffer growth ------------------------------------------------
|
||||
|
||||
export fn a_emit_byte(a: *asm_, b: u8) void = {
|
||||
if (a.textlen + 1u64 > a.textcap) {
|
||||
let nc: u64 = a.textcap;
|
||||
if (nc == 0u64) { nc = 4096u64; };
|
||||
nc = nc * 2u64;
|
||||
let nb: *u8 = os.alloc(nc): *u8;
|
||||
let i: u64 = 0u64;
|
||||
for (i < a.textlen) { nb[i] = a.text[i]; i += 1u64; };
|
||||
a.text = nb;
|
||||
a.textcap = nc;
|
||||
};
|
||||
a.text[a.textlen] = b;
|
||||
a.textlen += 1u64;
|
||||
};
|
||||
|
||||
export fn a_emit_u32(a: *asm_, v: u32) void = {
|
||||
a_emit_byte(a, (v & 255u32): u8);
|
||||
a_emit_byte(a, ((v >> 8u32) & 255u32): u8);
|
||||
a_emit_byte(a, ((v >> 16u32) & 255u32): u8);
|
||||
a_emit_byte(a, ((v >> 24u32) & 255u32): u8);
|
||||
};
|
||||
|
||||
export fn a_addreloc(a: *asm_, off: u64, kind: i32, s: *asym, add: i64) void = {
|
||||
let r: *areloc = amalloc(a.a, 48u64): *areloc;
|
||||
r.off = off;
|
||||
r.kind = kind;
|
||||
r.asy = s;
|
||||
r.addend = add;
|
||||
r.rnext = a.relocs;
|
||||
a.relocs = r;
|
||||
};
|
||||
|
||||
// ---- register codes ----------------------------------------------------
|
||||
|
||||
// Low 3 bits of register encoding.
|
||||
fn rcode(r: i32) i32 = {
|
||||
if (r == D_AX) { return 0; }; if (r == D_CX) { return 1; };
|
||||
if (r == D_DX) { return 2; }; if (r == D_BX) { return 3; };
|
||||
if (r == D_SP) { return 4; }; if (r == D_BP) { return 5; };
|
||||
if (r == D_SI) { return 6; }; if (r == D_DI) { return 7; };
|
||||
if (r == D_R8) { return 0; }; if (r == D_R9) { return 1; };
|
||||
if (r == D_R10) { return 2; }; if (r == D_R11) { return 3; };
|
||||
if (r == D_R12) { return 4; }; if (r == D_R13) { return 5; };
|
||||
if (r == D_R14) { return 6; }; if (r == D_R15) { return 7; };
|
||||
if (r == D_X0) { return 0; }; if (r == D_X1) { return 1; };
|
||||
if (r == D_X2) { return 2; }; if (r == D_X3) { return 3; };
|
||||
if (r == D_X4) { return 4; }; if (r == D_X5) { return 5; };
|
||||
if (r == D_X6) { return 6; }; if (r == D_X7) { return 7; };
|
||||
if (r == D_X8) { return 0; }; if (r == D_X9) { return 1; };
|
||||
if (r == D_X10) { return 2; }; if (r == D_X11) { return 3; };
|
||||
if (r == D_X12) { return 4; }; if (r == D_X13) { return 5; };
|
||||
if (r == D_X14) { return 6; }; if (r == D_X15) { return 7; };
|
||||
return 0;
|
||||
};
|
||||
|
||||
// 1 if r needs the REX high bit (R8..R15 or X8..X15).
|
||||
fn rhi(r: i32) i32 = {
|
||||
if (r >= D_R8) { if (r <= D_R15) { return 1; }; };
|
||||
if (r >= D_X8) { if (r <= D_X15) { return 1; }; };
|
||||
return 0;
|
||||
};
|
||||
|
||||
fn is_xmm(r: i32) bool = {
|
||||
if (r >= D_X0) { if (r <= D_X15) { return true; }; };
|
||||
return false;
|
||||
};
|
||||
|
||||
// ModR/M byte builder.
|
||||
fn modrm_byte(mod: i32, reg: i32, rm: i32) u8 = {
|
||||
return (((mod & 3) << 6) | ((reg & 7) << 3) | (rm & 7)): u8;
|
||||
};
|
||||
|
||||
// REX prefix; W=1 for 64-bit operand size.
|
||||
fn emit_rex(a: *asm_, regbit: i32, rmbit: i32, w: i32) void = {
|
||||
let b: u8 = 64u8; // 0x40
|
||||
if (w != 0) { b = b | 8u8; };
|
||||
if (regbit != 0) { b = b | 4u8; };
|
||||
if (rmbit != 0) { b = b | 1u8; };
|
||||
if (b != 64u8) { a_emit_byte(a, b); }
|
||||
else { if (w != 0) { a_emit_byte(a, b); }; };
|
||||
};
|
||||
|
||||
// ModR/M + (optional) SIB + displacement for [base+disp].
|
||||
// Special-cases SP (needs SIB) and BP (forces explicit disp).
|
||||
fn emit_modrm_mem(a: *asm_, reg_field: i32, base: i32, disp: i64) void = {
|
||||
let rm: i32 = rcode(base);
|
||||
let needsib: bool = (rm == 4);
|
||||
let forced_disp: bool = false;
|
||||
if (rm == 5) { if (disp == 0i64) { forced_disp = true; }; };
|
||||
|
||||
let mod: i32 = 2;
|
||||
if (disp == 0i64) {
|
||||
if (!forced_disp) { mod = 0; }
|
||||
else { mod = 1; };
|
||||
} else {
|
||||
if (disp >= -128i64) { if (disp <= 127i64) { mod = 1; }; };
|
||||
};
|
||||
|
||||
a_emit_byte(a, modrm_byte(mod, reg_field, rm));
|
||||
if (needsib) {
|
||||
a_emit_byte(a, 36u8); // 0x24: scale=0 idx=4(none) base=4
|
||||
};
|
||||
if (mod == 1) {
|
||||
a_emit_byte(a, (disp: u64 & 255u64): u8);
|
||||
} else { if (mod == 2) {
|
||||
a_emit_u32(a, disp: u32);
|
||||
};};
|
||||
};
|
||||
|
||||
// reg→reg "src, dst" generic encoding (89 /r, 01 /r, etc.).
|
||||
fn encode_rr(a: *asm_, opcode: u8, src: i32, dst: i32) void = {
|
||||
emit_rex(a, rhi(src), rhi(dst), 1);
|
||||
a_emit_byte(a, opcode);
|
||||
a_emit_byte(a, modrm_byte(3, rcode(src), rcode(dst)));
|
||||
};
|
||||
|
||||
// reg→mem(base, disp) (e.g. MOVQ src reg into mem; opcode = 0x89).
|
||||
fn encode_rm(a: *asm_, opcode: u8, src_reg: i32, base: i32, disp: i64) void = {
|
||||
emit_rex(a, rhi(src_reg), rhi(base), 1);
|
||||
a_emit_byte(a, opcode);
|
||||
emit_modrm_mem(a, rcode(src_reg), base, disp);
|
||||
};
|
||||
|
||||
// mem(base, disp) → reg (e.g. MOVQ mem into reg; opcode = 0x8B).
|
||||
fn encode_mr(a: *asm_, opcode: u8, dst_reg: i32, base: i32, disp: i64) void = {
|
||||
emit_rex(a, rhi(dst_reg), rhi(base), 1);
|
||||
a_emit_byte(a, opcode);
|
||||
emit_modrm_mem(a, rcode(dst_reg), base, disp);
|
||||
};
|
||||
|
||||
// OPCODE /n imm32 reg form (e.g. ADDQ $imm, reg).
|
||||
fn encode_ri_imm32(a: *asm_, opcode: u8, subop: i32, dst: i32, imm: i32) void = {
|
||||
emit_rex(a, 0, rhi(dst), 1);
|
||||
a_emit_byte(a, opcode);
|
||||
a_emit_byte(a, modrm_byte(3, subop, rcode(dst)));
|
||||
a_emit_u32(a, imm: u32);
|
||||
};
|
||||
|
||||
// Unary on reg: F7 /n reg, etc.
|
||||
fn encode_unary(a: *asm_, opcode: u8, subop: i32, dst: i32) void = {
|
||||
emit_rex(a, 0, rhi(dst), 1);
|
||||
a_emit_byte(a, opcode);
|
||||
a_emit_byte(a, modrm_byte(3, subop, rcode(dst)));
|
||||
};
|
||||
|
||||
// SSE2 helpers. Plan 9 syntax: source first, destination second.
|
||||
// For ADDSD-style ops we put dst in the reg field, src in r/m.
|
||||
fn sse_rr(a: *asm_, prefix: u8, op2: u8, reg_op: i32, rm_op: i32) void = {
|
||||
if (prefix != 0u8) { a_emit_byte(a, prefix); };
|
||||
emit_rex(a, rhi(reg_op), rhi(rm_op), 0);
|
||||
a_emit_byte(a, 15u8); // 0x0F
|
||||
a_emit_byte(a, op2);
|
||||
a_emit_byte(a, modrm_byte(3, rcode(reg_op), rcode(rm_op)));
|
||||
};
|
||||
|
||||
fn sse_mr_load(a: *asm_, prefix: u8, op2: u8, reg_op: i32, base: i32, disp: i64) void = {
|
||||
if (prefix != 0u8) { a_emit_byte(a, prefix); };
|
||||
emit_rex(a, rhi(reg_op), rhi(base), 0);
|
||||
a_emit_byte(a, 15u8);
|
||||
a_emit_byte(a, op2);
|
||||
emit_modrm_mem(a, rcode(reg_op), base, disp);
|
||||
};
|
||||
|
||||
// REX.W variant of sse_rr (CVTTSD2SI / CVTSI2SD).
|
||||
fn sse_rr_w(a: *asm_, prefix: u8, op2: u8, reg_op: i32, rm_op: i32) void = {
|
||||
if (prefix != 0u8) { a_emit_byte(a, prefix); };
|
||||
emit_rex(a, rhi(reg_op), rhi(rm_op), 1);
|
||||
a_emit_byte(a, 15u8);
|
||||
a_emit_byte(a, op2);
|
||||
a_emit_byte(a, modrm_byte(3, rcode(reg_op), rcode(rm_op)));
|
||||
};
|
||||
|
||||
// ---- label resolution / fixups ----------------------------------------
|
||||
|
||||
fn streq(a: str, b: str) bool = {
|
||||
if (a.len != b.len) { return false; };
|
||||
let i: i32 = 0;
|
||||
for (i < a.len) {
|
||||
if (a[i] != b[i]) { return false; };
|
||||
i += 1;
|
||||
};
|
||||
return true;
|
||||
};
|
||||
|
||||
fn resolve_label(a: *asm_, name: str) u64 = {
|
||||
let s: *asym = a.syms;
|
||||
for (s != nil) {
|
||||
if (s.defined != 0) { if (streq(s.name, name)) { return s.addr; }; };
|
||||
s = s.snext;
|
||||
};
|
||||
return 0u64;
|
||||
};
|
||||
|
||||
fn label_defined(a: *asm_, name: str) bool = {
|
||||
let s: *asym = a.syms;
|
||||
for (s != nil) {
|
||||
if (s.defined != 0) { if (streq(s.name, name)) { return true; }; };
|
||||
s = s.snext;
|
||||
};
|
||||
return false;
|
||||
};
|
||||
|
||||
// ---- fixup helper -----------------------------------------------------
|
||||
|
||||
fn add_fixup(a: *asm_, off: u64, label: str) void = {
|
||||
let f: *afixup = amalloc(a.a, 48u64): *afixup;
|
||||
f.off = off;
|
||||
f.label = label;
|
||||
f.fnext = a.fixups;
|
||||
a.fixups = f;
|
||||
};
|
||||
|
||||
fn is_gpr(t: i32) bool = {
|
||||
if (t >= D_AX) { if (t <= D_R15) { return true; }; };
|
||||
return false;
|
||||
};
|
||||
|
||||
// `a_intern` lives in parse.ww — flat-scope concat lets us call it
|
||||
// directly without an @symbol declaration here.
|
||||
|
||||
// ---- a_encode ---------------------------------------------------------
|
||||
|
||||
export fn a_encode(a: *asm_) i32 = {
|
||||
let p: *aprog = a.head;
|
||||
for (p != nil) {
|
||||
// Define any pending label at the current PC.
|
||||
if (p.label.len > 0) {
|
||||
let s: *asym = a_intern(a, p.label);
|
||||
s.defined = 1;
|
||||
s.is_text = 1;
|
||||
s.addr = a.textlen;
|
||||
};
|
||||
let op: i32 = p.as_;
|
||||
|
||||
if (op == A_NOP) {
|
||||
p = p.link; continue;
|
||||
};
|
||||
if (op == A_TEXT) {
|
||||
let s: *asym = a_intern(a, p.to.asym);
|
||||
s.defined = 1;
|
||||
s.is_text = 1;
|
||||
s.is_global = 1;
|
||||
s.addr = a.textlen;
|
||||
p = p.link; continue;
|
||||
};
|
||||
if (op == A_DATA) {
|
||||
let s: *asym = a_intern(a, p.to.asym);
|
||||
s.defined = 1;
|
||||
s.is_text = 1;
|
||||
s.is_global = 1;
|
||||
s.addr = a.textlen;
|
||||
let i: u64 = 0u64;
|
||||
for (i < p.nbytes) { a_emit_byte(a, p.bytes[i]); i += 1u64; };
|
||||
p = p.link; continue;
|
||||
};
|
||||
if (op == A_RET) {
|
||||
a_emit_byte(a, 195u8); // 0xC3
|
||||
p = p.link; continue;
|
||||
};
|
||||
if (op == A_SYSCALL) {
|
||||
a_emit_byte(a, 15u8);
|
||||
a_emit_byte(a, 5u8);
|
||||
p = p.link; continue;
|
||||
};
|
||||
if (op == A_PUSHQ) {
|
||||
if (rhi(p.to.atype) != 0) { a_emit_byte(a, 65u8); }; // 0x41
|
||||
a_emit_byte(a, (80 + rcode(p.to.atype)): u8); // 0x50
|
||||
p = p.link; continue;
|
||||
};
|
||||
if (op == A_POPQ) {
|
||||
if (rhi(p.to.atype) != 0) { a_emit_byte(a, 65u8); };
|
||||
a_emit_byte(a, (88 + rcode(p.to.atype)): u8); // 0x58
|
||||
p = p.link; continue;
|
||||
};
|
||||
if (op == A_NEGQ) { encode_unary(a, 247u8, 3, p.to.atype); p = p.link; continue; };
|
||||
if (op == A_NOTQ) { encode_unary(a, 247u8, 2, p.to.atype); p = p.link; continue; };
|
||||
if (op == A_IDIVQ) { encode_unary(a, 247u8, 7, p.to.atype); p = p.link; continue; };
|
||||
if (op == A_DIVQ) { encode_unary(a, 247u8, 6, p.to.atype); p = p.link; continue; };
|
||||
|
||||
if (op == A_MOVQ) {
|
||||
let ft: i32 = p.from.atype;
|
||||
let tt: i32 = p.to.atype;
|
||||
if (ft == D_CONST) { if (is_gpr(tt)) {
|
||||
let v: i64 = p.from.offset;
|
||||
if (v >= -2147483648i64) { if (v <= 2147483647i64) {
|
||||
encode_ri_imm32(a, 199u8, 0, tt, v: i32);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
// movabs r64, imm64: REX.W B8+rd imm64
|
||||
emit_rex(a, 0, rhi(tt), 1);
|
||||
a_emit_byte(a, (184 + rcode(tt)): u8);
|
||||
let k: i32 = 0;
|
||||
for (k < 8) {
|
||||
a_emit_byte(a, ((v: u64 >> (k: u64 * 8u64)) & 255u64): u8);
|
||||
k += 1;
|
||||
};
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (is_gpr(ft)) { if (is_gpr(tt)) {
|
||||
encode_rr(a, 137u8, ft, tt); // 0x89
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (ft == D_INDIR) { if (is_gpr(tt)) {
|
||||
encode_mr(a, 139u8, tt, p.from.reg, p.from.offset); // 0x8B
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (is_gpr(ft)) { if (tt == D_INDIR) {
|
||||
encode_rm(a, 137u8, ft, p.to.reg, p.to.offset);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (ft == D_CONST) { if (tt == D_INDIR) {
|
||||
emit_rex(a, 0, rhi(p.to.reg), 1);
|
||||
a_emit_byte(a, 199u8);
|
||||
emit_modrm_mem(a, 0, p.to.reg, p.to.offset);
|
||||
a_emit_u32(a, p.from.offset: u32);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (ft == D_EXTERN) { if (is_gpr(tt)) {
|
||||
// RIP-relative load: 48 8B /r mod=00 rm=5 disp32
|
||||
emit_rex(a, rhi(tt), 0, 1);
|
||||
a_emit_byte(a, 139u8);
|
||||
a_emit_byte(a, modrm_byte(0, rcode(tt), 5));
|
||||
let reloff: u64 = a.textlen;
|
||||
a_emit_u32(a, 0u32);
|
||||
let s: *asym = a_intern(a, p.from.asym);
|
||||
a_addreloc(a, reloff, 2, s, -4i64);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (is_gpr(ft)) { if (tt == D_EXTERN) {
|
||||
// RIP-relative store: 48 89 /r mod=00 rm=5 disp32
|
||||
emit_rex(a, rhi(ft), 0, 1);
|
||||
a_emit_byte(a, 137u8);
|
||||
a_emit_byte(a, modrm_byte(0, rcode(ft), 5));
|
||||
let reloff: u64 = a.textlen;
|
||||
a_emit_u32(a, 0u32);
|
||||
let s: *asym = a_intern(a, p.to.asym);
|
||||
a_addreloc(a, reloff, 2, s, -4i64);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
os.write(2, "6a: unsupported MOVQ shape\n".ptr, 27u64);
|
||||
a.errs += 1;
|
||||
p = p.link; continue;
|
||||
};
|
||||
|
||||
if (op == A_MOVB) {
|
||||
let ft: i32 = p.from.atype;
|
||||
let tt: i32 = p.to.atype;
|
||||
if (is_gpr(ft)) { if (tt == D_INDIR) {
|
||||
emit_rex(a, rhi(ft), rhi(p.to.reg), 0);
|
||||
a_emit_byte(a, 136u8); // 0x88
|
||||
emit_modrm_mem(a, rcode(ft), p.to.reg, p.to.offset);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (ft == D_INDIR) { if (is_gpr(tt)) {
|
||||
emit_rex(a, rhi(tt), rhi(p.from.reg), 0);
|
||||
a_emit_byte(a, 138u8); // 0x8A
|
||||
emit_modrm_mem(a, rcode(tt), p.from.reg, p.from.offset);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
os.write(2, "6a: unsupported MOVB shape\n".ptr, 27u64);
|
||||
a.errs += 1;
|
||||
p = p.link; continue;
|
||||
};
|
||||
|
||||
if (op == A_MOVZBQ) {
|
||||
let ft: i32 = p.from.atype;
|
||||
let tt: i32 = p.to.atype;
|
||||
if (ft == D_INDIR) { if (is_gpr(tt)) {
|
||||
emit_rex(a, rhi(tt), rhi(p.from.reg), 1);
|
||||
a_emit_byte(a, 15u8);
|
||||
a_emit_byte(a, 182u8); // 0xB6
|
||||
emit_modrm_mem(a, rcode(tt), p.from.reg, p.from.offset);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
os.write(2, "6a: unsupported MOVZBQ shape\n".ptr, 29u64);
|
||||
a.errs += 1;
|
||||
p = p.link; continue;
|
||||
};
|
||||
|
||||
if (op == A_MOVL) {
|
||||
let ft: i32 = p.from.atype;
|
||||
let tt: i32 = p.to.atype;
|
||||
if (is_gpr(ft)) { if (tt == D_INDIR) {
|
||||
emit_rex(a, rhi(ft), rhi(p.to.reg), 0);
|
||||
a_emit_byte(a, 137u8);
|
||||
emit_modrm_mem(a, rcode(ft), p.to.reg, p.to.offset);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (ft == D_INDIR) { if (is_gpr(tt)) {
|
||||
emit_rex(a, rhi(tt), rhi(p.from.reg), 0);
|
||||
a_emit_byte(a, 139u8);
|
||||
emit_modrm_mem(a, rcode(tt), p.from.reg, p.from.offset);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (is_gpr(ft)) { if (is_gpr(tt)) {
|
||||
emit_rex(a, rhi(ft), rhi(tt), 0);
|
||||
a_emit_byte(a, 137u8);
|
||||
a_emit_byte(a, modrm_byte(3, rcode(ft), rcode(tt)));
|
||||
p = p.link; continue;
|
||||
};};
|
||||
os.write(2, "6a: unsupported MOVL shape\n".ptr, 27u64);
|
||||
a.errs += 1;
|
||||
p = p.link; continue;
|
||||
};
|
||||
|
||||
if (op == A_MOVSXD) {
|
||||
let ft: i32 = p.from.atype;
|
||||
let tt: i32 = p.to.atype;
|
||||
if (ft == D_INDIR) { if (is_gpr(tt)) {
|
||||
emit_rex(a, rhi(tt), rhi(p.from.reg), 1);
|
||||
a_emit_byte(a, 99u8); // 0x63
|
||||
emit_modrm_mem(a, rcode(tt), p.from.reg, p.from.offset);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
os.write(2, "6a: unsupported MOVSXD shape\n".ptr, 29u64);
|
||||
a.errs += 1;
|
||||
p = p.link; continue;
|
||||
};
|
||||
|
||||
if (op == A_MOVSD) {
|
||||
let ft: i32 = p.from.atype;
|
||||
let tt: i32 = p.to.atype;
|
||||
if (is_xmm(ft)) { if (is_xmm(tt)) {
|
||||
sse_rr(a, 242u8, 16u8, tt, ft);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (ft == D_INDIR) { if (is_xmm(tt)) {
|
||||
sse_mr_load(a, 242u8, 16u8, tt, p.from.reg, p.from.offset);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (is_xmm(ft)) { if (tt == D_INDIR) {
|
||||
sse_mr_load(a, 242u8, 17u8, ft, p.to.reg, p.to.offset);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
os.write(2, "6a: unsupported MOVSD shape\n".ptr, 28u64);
|
||||
a.errs += 1;
|
||||
p = p.link; continue;
|
||||
};
|
||||
|
||||
if (op == A_ADDSD) { sse_rr(a, 242u8, 88u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
if (op == A_SUBSD) { sse_rr(a, 242u8, 92u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
if (op == A_MULSD) { sse_rr(a, 242u8, 89u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
if (op == A_DIVSD) { sse_rr(a, 242u8, 94u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
if (op == A_UCOMISD) { sse_rr(a, 102u8, 46u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
if (op == A_CVTTSD2SI) { sse_rr_w(a, 242u8, 44u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
if (op == A_CVTSI2SD) { sse_rr_w(a, 242u8, 42u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
|
||||
if (op == A_MOVSS) {
|
||||
let ft: i32 = p.from.atype;
|
||||
let tt: i32 = p.to.atype;
|
||||
if (is_xmm(ft)) { if (is_xmm(tt)) {
|
||||
sse_rr(a, 243u8, 16u8, tt, ft); p = p.link; continue;
|
||||
};};
|
||||
if (ft == D_INDIR) { if (is_xmm(tt)) {
|
||||
sse_mr_load(a, 243u8, 16u8, tt, p.from.reg, p.from.offset);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (is_xmm(ft)) { if (tt == D_INDIR) {
|
||||
sse_mr_load(a, 243u8, 17u8, ft, p.to.reg, p.to.offset);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
os.write(2, "6a: unsupported MOVSS shape\n".ptr, 28u64);
|
||||
a.errs += 1;
|
||||
p = p.link; continue;
|
||||
};
|
||||
|
||||
if (op == A_ADDSS) { sse_rr(a, 243u8, 88u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
if (op == A_SUBSS) { sse_rr(a, 243u8, 92u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
if (op == A_MULSS) { sse_rr(a, 243u8, 89u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
if (op == A_DIVSS) { sse_rr(a, 243u8, 94u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
if (op == A_UCOMISS) { sse_rr(a, 0u8, 46u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
if (op == A_CVTTSS2SI) { sse_rr_w(a, 243u8, 44u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
if (op == A_CVTSI2SS) { sse_rr_w(a, 243u8, 42u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
if (op == A_CVTSD2SS) { sse_rr(a, 242u8, 90u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
if (op == A_CVTSS2SD) { sse_rr(a, 243u8, 90u8, p.to.atype, p.from.atype); p = p.link; continue; };
|
||||
|
||||
if (op == A_ADDQ) {
|
||||
let ft: i32 = p.from.atype;
|
||||
let tt: i32 = p.to.atype;
|
||||
if (ft == D_CONST) { if (is_gpr(tt)) {
|
||||
encode_ri_imm32(a, 129u8, 0, tt, p.from.offset: i32); // 0x81
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (ft == D_CONST) { if (tt == D_INDIR) {
|
||||
emit_rex(a, 0, rhi(p.to.reg), 1);
|
||||
a_emit_byte(a, 129u8);
|
||||
emit_modrm_mem(a, 0, p.to.reg, p.to.offset);
|
||||
a_emit_u32(a, p.from.offset: u32);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (is_gpr(ft)) { if (tt == D_INDIR) {
|
||||
encode_rm(a, 1u8, ft, p.to.reg, p.to.offset);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (ft == D_INDIR) { if (is_gpr(tt)) {
|
||||
encode_mr(a, 3u8, tt, p.from.reg, p.from.offset);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
encode_rr(a, 1u8, ft, tt);
|
||||
p = p.link; continue;
|
||||
};
|
||||
|
||||
if (op == A_SUBQ) {
|
||||
let ft: i32 = p.from.atype;
|
||||
let tt: i32 = p.to.atype;
|
||||
if (ft == D_CONST) { if (is_gpr(tt)) {
|
||||
encode_ri_imm32(a, 129u8, 5, tt, p.from.offset: i32);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (ft == D_CONST) { if (tt == D_INDIR) {
|
||||
emit_rex(a, 0, rhi(p.to.reg), 1);
|
||||
a_emit_byte(a, 129u8);
|
||||
emit_modrm_mem(a, 5, p.to.reg, p.to.offset);
|
||||
a_emit_u32(a, p.from.offset: u32);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (is_gpr(ft)) { if (tt == D_INDIR) {
|
||||
encode_rm(a, 41u8, ft, p.to.reg, p.to.offset); // 0x29
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (ft == D_INDIR) { if (is_gpr(tt)) {
|
||||
encode_mr(a, 43u8, tt, p.from.reg, p.from.offset); // 0x2B
|
||||
p = p.link; continue;
|
||||
};};
|
||||
encode_rr(a, 41u8, ft, tt);
|
||||
p = p.link; continue;
|
||||
};
|
||||
|
||||
if (op == A_ANDQ) { encode_rr(a, 33u8, p.from.atype, p.to.atype); p = p.link; continue; }; // 0x21
|
||||
if (op == A_ORQ) { encode_rr(a, 9u8, p.from.atype, p.to.atype); p = p.link; continue; }; // 0x09
|
||||
if (op == A_XORQ) {
|
||||
let ft: i32 = p.from.atype;
|
||||
let tt: i32 = p.to.atype;
|
||||
if (ft == D_CONST) { if (is_gpr(tt)) {
|
||||
encode_ri_imm32(a, 129u8, 6, tt, p.from.offset: i32);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
encode_rr(a, 49u8, ft, tt); // 0x31
|
||||
p = p.link; continue;
|
||||
};
|
||||
if (op == A_IMULQ) {
|
||||
emit_rex(a, rhi(p.to.atype), rhi(p.from.atype), 1);
|
||||
a_emit_byte(a, 15u8);
|
||||
a_emit_byte(a, 175u8); // 0xAF
|
||||
a_emit_byte(a, modrm_byte(3, rcode(p.to.atype), rcode(p.from.atype)));
|
||||
p = p.link; continue;
|
||||
};
|
||||
if (op == A_SHLQ) { encode_unary(a, 211u8, 4, p.to.atype); p = p.link; continue; }; // 0xD3
|
||||
if (op == A_SHRQ) { encode_unary(a, 211u8, 5, p.to.atype); p = p.link; continue; };
|
||||
if (op == A_CMPQ) {
|
||||
let ft: i32 = p.from.atype;
|
||||
let tt: i32 = p.to.atype;
|
||||
if (ft == D_CONST) { if (is_gpr(tt)) {
|
||||
encode_ri_imm32(a, 129u8, 7, tt, p.from.offset: i32);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
encode_rr(a, 57u8, ft, tt); // 0x39
|
||||
p = p.link; continue;
|
||||
};
|
||||
|
||||
if (op == A_LEAQ) {
|
||||
let ft: i32 = p.from.atype;
|
||||
let tt: i32 = p.to.atype;
|
||||
if (ft == D_INDIR) { if (is_gpr(tt)) {
|
||||
encode_mr(a, 141u8, tt, p.from.reg, p.from.offset); // 0x8D
|
||||
p = p.link; continue;
|
||||
};};
|
||||
if (ft == D_EXTERN) { if (is_gpr(tt)) {
|
||||
emit_rex(a, rhi(tt), 0, 1);
|
||||
a_emit_byte(a, 141u8);
|
||||
a_emit_byte(a, modrm_byte(0, rcode(tt), 5));
|
||||
let reloff: u64 = a.textlen;
|
||||
a_emit_u32(a, 0u32);
|
||||
let s: *asym = a_intern(a, p.from.asym);
|
||||
a_addreloc(a, reloff, 2, s, -4i64);
|
||||
p = p.link; continue;
|
||||
};};
|
||||
p = p.link; continue;
|
||||
};
|
||||
|
||||
if (op == A_CALL) {
|
||||
let tt: i32 = p.to.atype;
|
||||
if (tt == D_EXTERN) {
|
||||
a_emit_byte(a, 232u8); // 0xE8
|
||||
let reloff: u64 = a.textlen;
|
||||
a_emit_u32(a, 0u32);
|
||||
let s: *asym = a_intern(a, p.to.asym);
|
||||
a_addreloc(a, reloff, 4, s, -4i64);
|
||||
p = p.link; continue;
|
||||
};
|
||||
if (tt == D_BRANCH) {
|
||||
a_emit_byte(a, 232u8);
|
||||
add_fixup(a, a.textlen, p.to.asym);
|
||||
a_emit_u32(a, 0u32);
|
||||
p = p.link; continue;
|
||||
};
|
||||
if (is_gpr(tt)) {
|
||||
if (rhi(tt) != 0) { a_emit_byte(a, 65u8); };
|
||||
a_emit_byte(a, 255u8); // 0xFF
|
||||
a_emit_byte(a, modrm_byte(3, 2, rcode(tt)));
|
||||
p = p.link; continue;
|
||||
};
|
||||
p = p.link; continue;
|
||||
};
|
||||
|
||||
if (op == A_JMP) {
|
||||
a_emit_byte(a, 233u8); // 0xE9
|
||||
add_fixup(a, a.textlen, p.to.asym);
|
||||
a_emit_u32(a, 0u32);
|
||||
p = p.link; continue;
|
||||
};
|
||||
|
||||
// Conditional jumps. 0x0F + cc + rel32.
|
||||
let cc: u8 = 0u8;
|
||||
let is_jcc: bool = true;
|
||||
if (op == A_JE) { cc = 132u8; } // 0x84
|
||||
else { if (op == A_JZ) { cc = 132u8; }
|
||||
else { if (op == A_JNE) { cc = 133u8; }
|
||||
else { if (op == A_JNZ) { cc = 133u8; }
|
||||
else { if (op == A_JL) { cc = 140u8; }
|
||||
else { if (op == A_JLE) { cc = 142u8; }
|
||||
else { if (op == A_JG) { cc = 143u8; }
|
||||
else { if (op == A_JGE) { cc = 141u8; }
|
||||
else { if (op == A_JB) { cc = 130u8; }
|
||||
else { if (op == A_JBE) { cc = 134u8; }
|
||||
else { if (op == A_JA) { cc = 135u8; }
|
||||
else { if (op == A_JAE) { cc = 131u8; }
|
||||
else { is_jcc = false; };};};};};};};};};};};};
|
||||
if (is_jcc) {
|
||||
a_emit_byte(a, 15u8);
|
||||
a_emit_byte(a, cc);
|
||||
add_fixup(a, a.textlen, p.to.asym);
|
||||
a_emit_u32(a, 0u32);
|
||||
p = p.link; continue;
|
||||
};
|
||||
|
||||
os.write(2, "6a: unsupported opcode\n".ptr, 23u64);
|
||||
a.errs += 1;
|
||||
p = p.link;
|
||||
};
|
||||
|
||||
// Second pass: patch fixups (forward label refs).
|
||||
let f: *afixup = a.fixups;
|
||||
for (f != nil) {
|
||||
if (!label_defined(a, f.label)) {
|
||||
os.write(2, "6a: undefined label '".ptr, 21u64);
|
||||
let lbl: str = f.label;
|
||||
os.write(2, lbl.ptr, lbl.len: u64);
|
||||
os.write(2, "'\n".ptr, 2u64);
|
||||
a.errs += 1;
|
||||
f = f.fnext;
|
||||
continue;
|
||||
};
|
||||
let target: u64 = resolve_label(a, f.label);
|
||||
let rel: i64 = target: i64 - (f.off: i64 + 4i64);
|
||||
let rel32: u32 = rel: u32;
|
||||
a.text[f.off] = (rel32 & 255u32): u8;
|
||||
a.text[f.off + 1u64] = ((rel32 >> 8u32) & 255u32): u8;
|
||||
a.text[f.off + 2u64] = ((rel32 >> 16u32) & 255u32): u8;
|
||||
a.text[f.off + 3u64] = ((rel32 >> 24u32) & 255u32): u8;
|
||||
f = f.fnext;
|
||||
};
|
||||
return a.errs;
|
||||
};
|
||||
66
selfhost/cmd/6a/lex.ww
Normal file
66
selfhost/cmd/6a/lex.ww
Normal file
@@ -0,0 +1,66 @@
|
||||
// selfhost/cmd/6a/lex.ww — port of cmd/6a/lex.c.
|
||||
//
|
||||
// Character-level helpers for 6a's line-oriented parser. The parser
|
||||
// itself is in parse.ww; here we keep tokenisers for identifiers and
|
||||
// numbers so parse.ww stays focused on syntax.
|
||||
|
||||
export fn a_isidstart(c: i32) bool = {
|
||||
if (c == 95) { return true; };
|
||||
if (c >= 65) { if (c <= 90) { return true; }; }; // A-Z
|
||||
if (c >= 97) { if (c <= 122) { return true; }; }; // a-z
|
||||
return false;
|
||||
};
|
||||
|
||||
export fn a_isidcont(c: i32) bool = {
|
||||
if (a_isidstart(c)) { return true; };
|
||||
if (c >= 48) { if (c <= 57) { return true; }; }; // 0-9
|
||||
if (c == 46) { return true; }; // .
|
||||
return false;
|
||||
};
|
||||
|
||||
// a_parsenum — read a leading [+-]?[0x|0X|0]?digits from p[0..n-1].
|
||||
// Returns (value, consumed). Stops at first non-digit.
|
||||
// Plain Plan 9-style: $123 / $0x1f / $-7. Decimal default; 0x prefix
|
||||
// for hex; 0 prefix for octal when followed by a digit (else just 0).
|
||||
export fn a_parsenum(p: *u8, n: u64) (i64, u64) = {
|
||||
let i: u64 = 0u64;
|
||||
let neg: bool = false;
|
||||
if (i < n) {
|
||||
if (p[i] == 45u8) { neg = true; i += 1u64; }
|
||||
else { if (p[i] == 43u8) { i += 1u64; }; };
|
||||
};
|
||||
let base: i64 = 10i64;
|
||||
if (i + 1u64 < n) {
|
||||
if (p[i] == 48u8) {
|
||||
if (p[i + 1u64] == 120u8) { base = 16i64; i += 2u64; }
|
||||
else { if (p[i + 1u64] == 88u8) { base = 16i64; i += 2u64; }
|
||||
else { if (p[i + 1u64] >= 48u8) { if (p[i + 1u64] <= 55u8) {
|
||||
base = 8i64; i += 1u64;
|
||||
};};};};
|
||||
};
|
||||
};
|
||||
let v: i64 = 0i64;
|
||||
let scan: bool = true;
|
||||
for (scan) {
|
||||
if (i >= n) { scan = false; }
|
||||
else {
|
||||
let c: u8 = p[i];
|
||||
let d: i64 = -1i64;
|
||||
if (c >= 48u8) { if (c <= 57u8) { d = (c - 48u8): i64; }; };
|
||||
if (d < 0i64) {
|
||||
if (base == 16i64) {
|
||||
if (c >= 97u8) { if (c <= 102u8) { d = (c - 97u8): i64 + 10i64; }; };
|
||||
if (c >= 65u8) { if (c <= 70u8) { d = (c - 65u8): i64 + 10i64; }; };
|
||||
};
|
||||
};
|
||||
if (d < 0i64) { scan = false; }
|
||||
else { if (d >= base) { scan = false; }
|
||||
else {
|
||||
v = v * base + d;
|
||||
i += 1u64;
|
||||
}; };
|
||||
};
|
||||
};
|
||||
if (neg) { v = -v; };
|
||||
return v, i;
|
||||
};
|
||||
2168
selfhost/cmd/6a/main.combined.ww
Normal file
2168
selfhost/cmd/6a/main.combined.ww
Normal file
File diff suppressed because it is too large
Load Diff
110
selfhost/cmd/6a/main.ww
Normal file
110
selfhost/cmd/6a/main.ww
Normal file
@@ -0,0 +1,110 @@
|
||||
// selfhost/cmd/6a/main.ww — port of cmd/6a/main.c.
|
||||
//
|
||||
// 6a = amd64 assembler. Read .s, parse, encode, emit ELF .o.
|
||||
//
|
||||
// 6a_ww -o file.o file.s
|
||||
|
||||
use os;
|
||||
use mem;
|
||||
use types;
|
||||
use lex;
|
||||
use parse;
|
||||
use asm;
|
||||
use obj;
|
||||
|
||||
fn streq_cs(a: *u8, lit: str) bool = {
|
||||
let n: u64 = lit.len: u64;
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
let li: i32 = i: i32;
|
||||
if (a[i] != lit[li]) { return false; };
|
||||
i += 1u64;
|
||||
};
|
||||
if (a[i] != 0u8) { return false; };
|
||||
return true;
|
||||
};
|
||||
|
||||
fn cstrlen(p: *u8) u64 = {
|
||||
let n: u64 = 0u64;
|
||||
for (p[n] != 0u8) { n += 1u64; };
|
||||
return n;
|
||||
};
|
||||
|
||||
// Slurp the whole file into a fresh buffer.
|
||||
fn slurp(path_cs: *u8) (*u8, u64) = {
|
||||
let fd: i32 = os.open(path_cs, os.O_RDONLY, 0i32);
|
||||
if (fd < 0) { return nil, 0u64; };
|
||||
let n: i64 = os.filesize(fd);
|
||||
if (n < 0i64) { os.close(fd); return nil, 0u64; };
|
||||
let nz: u64 = n: u64;
|
||||
let buf: *u8 = os.alloc(nz + 1u64): *u8;
|
||||
let got: i64 = os.readfull(fd, buf, nz);
|
||||
os.close(fd);
|
||||
if (got != n) { return nil, 0u64; };
|
||||
buf[nz] = 0u8;
|
||||
return buf, nz;
|
||||
};
|
||||
|
||||
export fn main(argc: i32, argv: **u8) i32 = {
|
||||
let src_cs: *u8 = nil;
|
||||
let out_cs: *u8 = nil;
|
||||
|
||||
let i: i32 = 1;
|
||||
for (i < argc) {
|
||||
let a: *u8 = argv[i];
|
||||
if (streq_cs(a, "-o")) {
|
||||
i += 1;
|
||||
if (i >= argc) {
|
||||
os.write(2, "6a: -o requires arg\n".ptr, 20u64);
|
||||
return 2;
|
||||
};
|
||||
out_cs = argv[i];
|
||||
} else { if (a[0u64] == 45u8) {
|
||||
os.write(2, "6a: unknown flag\n".ptr, 17u64);
|
||||
return 2;
|
||||
} else {
|
||||
if (src_cs != nil) {
|
||||
os.write(2, "6a: only one input\n".ptr, 19u64);
|
||||
return 2;
|
||||
};
|
||||
src_cs = a;
|
||||
}; };
|
||||
i += 1;
|
||||
};
|
||||
|
||||
if (src_cs == nil) {
|
||||
os.write(2, "usage: 6a_ww -o file.o file.s\n".ptr, 30u64);
|
||||
return 2;
|
||||
};
|
||||
if (out_cs == nil) {
|
||||
os.write(2, "6a: missing -o\n".ptr, 15u64);
|
||||
return 2;
|
||||
};
|
||||
|
||||
let buf: *u8;
|
||||
let blen: u64;
|
||||
buf, blen = slurp(src_cs);
|
||||
if (buf == nil) {
|
||||
os.write(2, "6a: cannot read input\n".ptr, 22u64);
|
||||
return 1;
|
||||
};
|
||||
|
||||
let ar: *arena = newarena();
|
||||
let asm: asm_;
|
||||
let nlen: u64 = cstrlen(src_cs);
|
||||
let fname: str = astrndup(ar, src_cs, nlen);
|
||||
a_init(&asm, ar, fname, buf, blen);
|
||||
|
||||
if (a_parse(&asm) != 0) { return 1; };
|
||||
if (a_encode(&asm) != 0) { return 1; };
|
||||
|
||||
// Open output for write.
|
||||
let fd: i32 = os.open(out_cs, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 420i32); // 0o644
|
||||
if (fd < 0) {
|
||||
os.write(2, "6a: cannot open output\n".ptr, 23u64);
|
||||
return 1;
|
||||
};
|
||||
let rc: i32 = a_emit_elf(&asm, fd);
|
||||
os.close(fd);
|
||||
return rc;
|
||||
};
|
||||
293
selfhost/cmd/6a/obj.ww
Normal file
293
selfhost/cmd/6a/obj.ww
Normal file
@@ -0,0 +1,293 @@
|
||||
// selfhost/cmd/6a/obj.ww — port of cmd/6a/obj.c.
|
||||
//
|
||||
// Emit a tiny ELF64 relocatable object. Layout (in file order):
|
||||
// [0] ELF header
|
||||
// [1] Section .text (program bytes)
|
||||
// [2] Section .rela.text (relocations)
|
||||
// [3] Section .symtab
|
||||
// [4] Section .strtab
|
||||
// [5] Section .shstrtab
|
||||
// [6] Section header table
|
||||
//
|
||||
// Symtab indices: 0 = STN_UNDEF, 1.. = our syms. Only GLOBAL symbols.
|
||||
|
||||
use os;
|
||||
use mem;
|
||||
use types;
|
||||
|
||||
// ---- ELF constants ----------------------------------------------------
|
||||
def ELFCLASS64: u8 = 2u8;
|
||||
def ELFDATA2LSB: u8 = 1u8;
|
||||
def EV_CURRENT_W: u32 = 1u32;
|
||||
def ET_REL_W: u16 = 1u16;
|
||||
def EM_X86_64_W: u16 = 62u16;
|
||||
|
||||
def SHT_NULL_C: u32 = 0u32;
|
||||
def SHT_PROGBITS_C: u32 = 1u32;
|
||||
def SHT_SYMTAB_C: u32 = 2u32;
|
||||
def SHT_STRTAB_C: u32 = 3u32;
|
||||
def SHT_RELA_C: u32 = 4u32;
|
||||
|
||||
def SHF_ALLOC: u64 = 2u64;
|
||||
def SHF_EXECINSTR: u64 = 4u64;
|
||||
def SHF_INFO_LINK: u64 = 64u64; // 0x40
|
||||
|
||||
def STB_GLOBAL: u8 = 1u8;
|
||||
def STT_NOTYPE: u8 = 0u8;
|
||||
def STT_FUNC: u8 = 2u8;
|
||||
|
||||
// Sizes of fixed structures.
|
||||
def EHDR_SZ: u64 = 64u64;
|
||||
def SHDR_SZ: u64 = 64u64;
|
||||
def SYM_SZ: u64 = 24u64;
|
||||
def RELA_SZ: u64 = 24u64;
|
||||
|
||||
// ---- LE byte writers (own the bytes — write into a *u8 + offset) ----
|
||||
|
||||
fn wr_u8(p: *u8, off: u64, v: u8) void = { p[off] = v; };
|
||||
fn wr_u16(p: *u8, off: u64, v: u16) void = {
|
||||
p[off] = (v & 255u16): u8;
|
||||
p[off + 1u64] = ((v >> 8u16) & 255u16): u8;
|
||||
};
|
||||
fn wr_u32(p: *u8, off: u64, v: u32) void = {
|
||||
p[off] = (v & 255u32): u8;
|
||||
p[off + 1u64] = ((v >> 8u32) & 255u32): u8;
|
||||
p[off + 2u64] = ((v >> 16u32) & 255u32): u8;
|
||||
p[off + 3u64] = ((v >> 24u32) & 255u32): u8;
|
||||
};
|
||||
fn wr_u64(p: *u8, off: u64, v: u64) void = {
|
||||
wr_u32(p, off, (v & 4294967295u64): u32);
|
||||
wr_u32(p, off + 4u64, ((v >> 32u64) & 4294967295u64): u32);
|
||||
};
|
||||
|
||||
// ---- growable byte buffer ---------------------------------------------
|
||||
|
||||
type buf = struct {
|
||||
a: *arena,
|
||||
p: *u8,
|
||||
n: u64,
|
||||
cap: u64,
|
||||
};
|
||||
|
||||
fn buf_init(b: *buf, a: *arena) void = {
|
||||
b.a = a;
|
||||
b.cap = 256u64;
|
||||
b.n = 0u64;
|
||||
b.p = amalloc(a, b.cap): *u8;
|
||||
};
|
||||
|
||||
fn buf_grow(b: *buf, need: u64) void = {
|
||||
if (b.n + need <= b.cap) { return; };
|
||||
let nc: u64 = b.cap;
|
||||
for (nc < b.n + need) { nc = nc * 2u64; };
|
||||
let np: *u8 = amalloc(b.a, nc): *u8;
|
||||
let i: u64 = 0u64;
|
||||
for (i < b.n) { np[i] = b.p[i]; i += 1u64; };
|
||||
b.p = np;
|
||||
b.cap = nc;
|
||||
};
|
||||
|
||||
fn buf_putb(b: *buf, src: *u8, n: u64) void = {
|
||||
buf_grow(b, n);
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) { b.p[b.n + i] = src[i]; i += 1u64; };
|
||||
b.n += n;
|
||||
};
|
||||
|
||||
// Write a NUL-terminated C-string copy of `s` into b. Returns offset
|
||||
// where it started (suitable for st_name / sh_name fields).
|
||||
fn buf_put_cstr(b: *buf, s: str) u32 = {
|
||||
let off: u32 = b.n: u32;
|
||||
buf_grow(b, s.len: u64 + 1u64);
|
||||
let i: i32 = 0;
|
||||
for (i < s.len) { b.p[b.n] = s[i]; b.n += 1u64; i += 1; };
|
||||
b.p[b.n] = 0u8;
|
||||
b.n += 1u64;
|
||||
return off;
|
||||
};
|
||||
|
||||
// ---- emit_elf ---------------------------------------------------------
|
||||
|
||||
export fn a_emit_elf(a: *asm_, fd: i32) i32 = {
|
||||
let shstr: buf; buf_init(&shstr, a.a);
|
||||
let str_: buf; buf_init(&str_, a.a);
|
||||
let sym: buf; buf_init(&sym, a.a);
|
||||
let rela: buf; buf_init(&rela, a.a);
|
||||
|
||||
// Index 0 = empty.
|
||||
let zero: u8 = 0u8;
|
||||
buf_putb(&shstr, &zero, 1u64);
|
||||
buf_putb(&str_, &zero, 1u64);
|
||||
|
||||
// Section name offsets.
|
||||
let shn_text: u32 = buf_put_cstr(&shstr, ".text");
|
||||
let shn_rela: u32 = buf_put_cstr(&shstr, ".rela.text");
|
||||
let shn_symtab: u32 = buf_put_cstr(&shstr, ".symtab");
|
||||
let shn_strtab: u32 = buf_put_cstr(&shstr, ".strtab");
|
||||
let shn_shstrtab: u32 = buf_put_cstr(&shstr, ".shstrtab");
|
||||
|
||||
// Symbol 0 — STN_UNDEF (24 zero bytes).
|
||||
let zsym: [24]u8;
|
||||
let zi: i32 = 0;
|
||||
for (zi < 24) { zsym[zi] = 0u8; zi += 1; };
|
||||
buf_putb(&sym, zsym.ptr, 24u64);
|
||||
|
||||
let SH_TEXT: u16 = 1u16;
|
||||
|
||||
// Build symbols.
|
||||
let idx: i32 = 1;
|
||||
let s: *asym = a.syms;
|
||||
for (s != nil) {
|
||||
let entry: [24]u8;
|
||||
let ei: i32 = 0;
|
||||
for (ei < 24) { entry[ei] = 0u8; ei += 1; };
|
||||
let st_name: u32 = buf_put_cstr(&str_, s.name);
|
||||
wr_u32(entry.ptr, 0u64, st_name);
|
||||
if (s.defined != 0) {
|
||||
wr_u8(entry.ptr, 4u64, ((STB_GLOBAL << 4u8) | STT_FUNC));
|
||||
wr_u16(entry.ptr, 6u64, SH_TEXT);
|
||||
wr_u64(entry.ptr, 8u64, s.addr);
|
||||
} else {
|
||||
wr_u8(entry.ptr, 4u64, ((STB_GLOBAL << 4u8) | STT_NOTYPE));
|
||||
wr_u16(entry.ptr, 6u64, 0u16);
|
||||
};
|
||||
buf_putb(&sym, entry.ptr, 24u64);
|
||||
s.idx = idx;
|
||||
idx += 1;
|
||||
s = s.snext;
|
||||
};
|
||||
|
||||
// Build relocations.
|
||||
let r: *areloc = a.relocs;
|
||||
for (r != nil) {
|
||||
let entry: [24]u8;
|
||||
wr_u64(entry.ptr, 0u64, r.off);
|
||||
let r_info: u64 = (r.asy.idx: u64 << 32u64) | (r.kind: u64 & 4294967295u64);
|
||||
wr_u64(entry.ptr, 8u64, r_info);
|
||||
wr_u64(entry.ptr, 16u64, r.addend: u64);
|
||||
buf_putb(&rela, entry.ptr, 24u64);
|
||||
r = r.rnext;
|
||||
};
|
||||
|
||||
// File offsets.
|
||||
let off: u64 = EHDR_SZ;
|
||||
let off_text: u64 = off; off = off + a.textlen;
|
||||
let off_rela: u64 = off; off = off + rela.n;
|
||||
let off_sym: u64 = off; off = off + sym.n;
|
||||
let off_str: u64 = off; off = off + str_.n;
|
||||
let off_shstr: u64 = off; off = off + shstr.n;
|
||||
for ((off & 7u64) != 0u64) { off += 1u64; };
|
||||
let off_shdr: u64 = off;
|
||||
let NSECT: u16 = 6u16;
|
||||
|
||||
// ---- Ehdr ----
|
||||
let eh: [64]u8;
|
||||
let i: i32 = 0;
|
||||
for (i < 64) { eh[i] = 0u8; i += 1; };
|
||||
eh[0] = 127u8; // 0x7f
|
||||
eh[1] = 69u8; // 'E'
|
||||
eh[2] = 76u8; // 'L'
|
||||
eh[3] = 70u8; // 'F'
|
||||
eh[4] = ELFCLASS64;
|
||||
eh[5] = ELFDATA2LSB;
|
||||
eh[6] = EV_CURRENT_W: u8;
|
||||
wr_u16(eh.ptr, 16u64, ET_REL_W);
|
||||
wr_u16(eh.ptr, 18u64, EM_X86_64_W);
|
||||
wr_u32(eh.ptr, 20u64, EV_CURRENT_W);
|
||||
wr_u64(eh.ptr, 24u64, 0u64); // e_entry
|
||||
wr_u64(eh.ptr, 32u64, 0u64); // e_phoff
|
||||
wr_u64(eh.ptr, 40u64, off_shdr); // e_shoff
|
||||
wr_u32(eh.ptr, 48u64, 0u32); // e_flags
|
||||
wr_u16(eh.ptr, 52u64, 64u16); // e_ehsize
|
||||
wr_u16(eh.ptr, 54u64, 0u16); // e_phentsize
|
||||
wr_u16(eh.ptr, 56u64, 0u16); // e_phnum
|
||||
wr_u16(eh.ptr, 58u64, 64u16); // e_shentsize
|
||||
wr_u16(eh.ptr, 60u64, NSECT); // e_shnum
|
||||
wr_u16(eh.ptr, 62u64, 5u16); // e_shstrndx
|
||||
|
||||
if (os.writefull(fd, eh.ptr, 64u64) != 64i64) { return -1; };
|
||||
if (a.textlen > 0u64) {
|
||||
if (os.writefull(fd, a.text, a.textlen) != a.textlen: i64) { return -1; };
|
||||
};
|
||||
if (rela.n > 0u64) {
|
||||
if (os.writefull(fd, rela.p, rela.n) != rela.n: i64) { return -1; };
|
||||
};
|
||||
if (sym.n > 0u64) {
|
||||
if (os.writefull(fd, sym.p, sym.n) != sym.n: i64) { return -1; };
|
||||
};
|
||||
if (str_.n > 0u64) {
|
||||
if (os.writefull(fd, str_.p, str_.n) != str_.n: i64) { return -1; };
|
||||
};
|
||||
if (shstr.n > 0u64) {
|
||||
if (os.writefull(fd, shstr.p, shstr.n) != shstr.n: i64) { return -1; };
|
||||
};
|
||||
|
||||
// Pad to 8 before shdrs.
|
||||
let written: u64 = EHDR_SZ + a.textlen + rela.n + sym.n + str_.n + shstr.n;
|
||||
for ((written & 7u64) != 0u64) {
|
||||
os.writefull(fd, &zero, 1u64);
|
||||
written += 1u64;
|
||||
};
|
||||
|
||||
// Section header table — 6 headers of 64 bytes each = 384 bytes.
|
||||
let shbuf: [64]u8;
|
||||
// SHT_NULL
|
||||
let sn: i32 = 0;
|
||||
for (sn < 64) { shbuf[sn] = 0u8; sn += 1; };
|
||||
os.writefull(fd, shbuf.ptr, 64u64);
|
||||
// .text
|
||||
sn = 0;
|
||||
for (sn < 64) { shbuf[sn] = 0u8; sn += 1; };
|
||||
wr_u32(shbuf.ptr, 0u64, shn_text);
|
||||
wr_u32(shbuf.ptr, 4u64, SHT_PROGBITS_C);
|
||||
wr_u64(shbuf.ptr, 8u64, SHF_ALLOC | SHF_EXECINSTR);
|
||||
wr_u64(shbuf.ptr, 24u64, off_text);
|
||||
wr_u64(shbuf.ptr, 32u64, a.textlen);
|
||||
wr_u64(shbuf.ptr, 48u64, 1u64); // sh_addralign
|
||||
os.writefull(fd, shbuf.ptr, 64u64);
|
||||
// .rela.text
|
||||
sn = 0;
|
||||
for (sn < 64) { shbuf[sn] = 0u8; sn += 1; };
|
||||
wr_u32(shbuf.ptr, 0u64, shn_rela);
|
||||
wr_u32(shbuf.ptr, 4u64, SHT_RELA_C);
|
||||
wr_u64(shbuf.ptr, 8u64, SHF_INFO_LINK);
|
||||
wr_u64(shbuf.ptr, 24u64, off_rela);
|
||||
wr_u64(shbuf.ptr, 32u64, rela.n);
|
||||
wr_u32(shbuf.ptr, 40u64, 3u32); // sh_link = symtab idx
|
||||
wr_u32(shbuf.ptr, 44u64, 1u32); // sh_info = .text idx
|
||||
wr_u64(shbuf.ptr, 48u64, 8u64);
|
||||
wr_u64(shbuf.ptr, 56u64, RELA_SZ);
|
||||
os.writefull(fd, shbuf.ptr, 64u64);
|
||||
// .symtab
|
||||
sn = 0;
|
||||
for (sn < 64) { shbuf[sn] = 0u8; sn += 1; };
|
||||
wr_u32(shbuf.ptr, 0u64, shn_symtab);
|
||||
wr_u32(shbuf.ptr, 4u64, SHT_SYMTAB_C);
|
||||
wr_u64(shbuf.ptr, 24u64, off_sym);
|
||||
wr_u64(shbuf.ptr, 32u64, sym.n);
|
||||
wr_u32(shbuf.ptr, 40u64, 4u32); // sh_link = strtab
|
||||
wr_u32(shbuf.ptr, 44u64, 1u32); // sh_info = one local (STN_UNDEF)
|
||||
wr_u64(shbuf.ptr, 48u64, 8u64);
|
||||
wr_u64(shbuf.ptr, 56u64, SYM_SZ);
|
||||
os.writefull(fd, shbuf.ptr, 64u64);
|
||||
// .strtab
|
||||
sn = 0;
|
||||
for (sn < 64) { shbuf[sn] = 0u8; sn += 1; };
|
||||
wr_u32(shbuf.ptr, 0u64, shn_strtab);
|
||||
wr_u32(shbuf.ptr, 4u64, SHT_STRTAB_C);
|
||||
wr_u64(shbuf.ptr, 24u64, off_str);
|
||||
wr_u64(shbuf.ptr, 32u64, str_.n);
|
||||
wr_u64(shbuf.ptr, 48u64, 1u64);
|
||||
os.writefull(fd, shbuf.ptr, 64u64);
|
||||
// .shstrtab
|
||||
sn = 0;
|
||||
for (sn < 64) { shbuf[sn] = 0u8; sn += 1; };
|
||||
wr_u32(shbuf.ptr, 0u64, shn_shstrtab);
|
||||
wr_u32(shbuf.ptr, 4u64, SHT_STRTAB_C);
|
||||
wr_u64(shbuf.ptr, 24u64, off_shstr);
|
||||
wr_u64(shbuf.ptr, 32u64, shstr.n);
|
||||
wr_u64(shbuf.ptr, 48u64, 1u64);
|
||||
os.writefull(fd, shbuf.ptr, 64u64);
|
||||
|
||||
return 0;
|
||||
};
|
||||
583
selfhost/cmd/6a/parse.ww
Normal file
583
selfhost/cmd/6a/parse.ww
Normal file
@@ -0,0 +1,583 @@
|
||||
// selfhost/cmd/6a/parse.ww — port of cmd/6a/parse.c.
|
||||
//
|
||||
// Line-oriented parser for the asm subset emitted by 6c.
|
||||
// Grammar:
|
||||
// line := blank | comment | label | text | instr
|
||||
// blank := /^\s*$/
|
||||
// comment := /^\s*\/\/.*$/
|
||||
// label := /^IDENT:$/
|
||||
// text := TEXT name,$framesize
|
||||
// instr := \tMNEM\t[OP1[, OP2]]
|
||||
// OP := $NUM | REG | NUM(REG) | (REG) | name(SB) | label
|
||||
|
||||
use os;
|
||||
use mem;
|
||||
use lex;
|
||||
use types;
|
||||
|
||||
fn streq_lit(p: *u8, n: u64, lit: str) bool = {
|
||||
if (n != lit.len: u64) { return false; };
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
let li: i32 = i: i32;
|
||||
if (p[i] != lit[li]) { return false; };
|
||||
i += 1u64;
|
||||
};
|
||||
return true;
|
||||
};
|
||||
|
||||
// opcode_lookup — name (length-bounded *u8) → A_*. Returns 0 (A_NOP)
|
||||
// if not found.
|
||||
fn opcode_lookup(p: *u8, n: u64) i32 = {
|
||||
if (streq_lit(p, n, "MOVQ")) { return A_MOVQ; };
|
||||
if (streq_lit(p, n, "MOVL")) { return A_MOVL; };
|
||||
if (streq_lit(p, n, "MOVB")) { return A_MOVB; };
|
||||
if (streq_lit(p, n, "MOVZBQ")) { return A_MOVZBQ; };
|
||||
if (streq_lit(p, n, "MOVSXD")) { return A_MOVSXD; };
|
||||
if (streq_lit(p, n, "MOVSD")) { return A_MOVSD; };
|
||||
if (streq_lit(p, n, "ADDSD")) { return A_ADDSD; };
|
||||
if (streq_lit(p, n, "SUBSD")) { return A_SUBSD; };
|
||||
if (streq_lit(p, n, "MULSD")) { return A_MULSD; };
|
||||
if (streq_lit(p, n, "DIVSD")) { return A_DIVSD; };
|
||||
if (streq_lit(p, n, "UCOMISD")) { return A_UCOMISD; };
|
||||
if (streq_lit(p, n, "CVTTSD2SI")) { return A_CVTTSD2SI; };
|
||||
if (streq_lit(p, n, "CVTSI2SD")) { return A_CVTSI2SD; };
|
||||
if (streq_lit(p, n, "MOVSS")) { return A_MOVSS; };
|
||||
if (streq_lit(p, n, "ADDSS")) { return A_ADDSS; };
|
||||
if (streq_lit(p, n, "SUBSS")) { return A_SUBSS; };
|
||||
if (streq_lit(p, n, "MULSS")) { return A_MULSS; };
|
||||
if (streq_lit(p, n, "DIVSS")) { return A_DIVSS; };
|
||||
if (streq_lit(p, n, "UCOMISS")) { return A_UCOMISS; };
|
||||
if (streq_lit(p, n, "CVTTSS2SI")) { return A_CVTTSS2SI; };
|
||||
if (streq_lit(p, n, "CVTSI2SS")) { return A_CVTSI2SS; };
|
||||
if (streq_lit(p, n, "CVTSD2SS")) { return A_CVTSD2SS; };
|
||||
if (streq_lit(p, n, "CVTSS2SD")) { return A_CVTSS2SD; };
|
||||
if (streq_lit(p, n, "ADDQ")) { return A_ADDQ; };
|
||||
if (streq_lit(p, n, "SUBQ")) { return A_SUBQ; };
|
||||
if (streq_lit(p, n, "IMULQ")) { return A_IMULQ; };
|
||||
if (streq_lit(p, n, "IDIVQ")) { return A_IDIVQ; };
|
||||
if (streq_lit(p, n, "DIVQ")) { return A_DIVQ; };
|
||||
if (streq_lit(p, n, "NEGQ")) { return A_NEGQ; };
|
||||
if (streq_lit(p, n, "NOTQ")) { return A_NOTQ; };
|
||||
if (streq_lit(p, n, "ANDQ")) { return A_ANDQ; };
|
||||
if (streq_lit(p, n, "ORQ")) { return A_ORQ; };
|
||||
if (streq_lit(p, n, "XORQ")) { return A_XORQ; };
|
||||
if (streq_lit(p, n, "SHLQ")) { return A_SHLQ; };
|
||||
if (streq_lit(p, n, "SHRQ")) { return A_SHRQ; };
|
||||
if (streq_lit(p, n, "CMPQ")) { return A_CMPQ; };
|
||||
if (streq_lit(p, n, "PUSHQ")) { return A_PUSHQ; };
|
||||
if (streq_lit(p, n, "POPQ")) { return A_POPQ; };
|
||||
if (streq_lit(p, n, "LEAQ")) { return A_LEAQ; };
|
||||
if (streq_lit(p, n, "CALL")) { return A_CALL; };
|
||||
if (streq_lit(p, n, "RET")) { return A_RET; };
|
||||
if (streq_lit(p, n, "JMP")) { return A_JMP; };
|
||||
if (streq_lit(p, n, "JE")) { return A_JE; };
|
||||
if (streq_lit(p, n, "JNE")) { return A_JNE; };
|
||||
if (streq_lit(p, n, "JL")) { return A_JL; };
|
||||
if (streq_lit(p, n, "JLE")) { return A_JLE; };
|
||||
if (streq_lit(p, n, "JG")) { return A_JG; };
|
||||
if (streq_lit(p, n, "JGE")) { return A_JGE; };
|
||||
if (streq_lit(p, n, "JB")) { return A_JB; };
|
||||
if (streq_lit(p, n, "JBE")) { return A_JBE; };
|
||||
if (streq_lit(p, n, "JA")) { return A_JA; };
|
||||
if (streq_lit(p, n, "JAE")) { return A_JAE; };
|
||||
if (streq_lit(p, n, "JZ")) { return A_JZ; };
|
||||
if (streq_lit(p, n, "JNZ")) { return A_JNZ; };
|
||||
if (streq_lit(p, n, "SYSCALL")) { return A_SYSCALL; };
|
||||
if (streq_lit(p, n, "TEXT")) { return A_TEXT; };
|
||||
if (streq_lit(p, n, "DATA")) { return A_DATA; };
|
||||
return A_NOP;
|
||||
};
|
||||
|
||||
// reg_lookup — name → D_*. Returns D_NONE if not found.
|
||||
fn reg_lookup(p: *u8, n: u64) i32 = {
|
||||
if (streq_lit(p, n, "AX")) { return D_AX; };
|
||||
if (streq_lit(p, n, "BX")) { return D_BX; };
|
||||
if (streq_lit(p, n, "CX")) { return D_CX; };
|
||||
if (streq_lit(p, n, "DX")) { return D_DX; };
|
||||
if (streq_lit(p, n, "SP")) { return D_SP; };
|
||||
if (streq_lit(p, n, "BP")) { return D_BP; };
|
||||
if (streq_lit(p, n, "SI")) { return D_SI; };
|
||||
if (streq_lit(p, n, "DI")) { return D_DI; };
|
||||
if (streq_lit(p, n, "R8")) { return D_R8; };
|
||||
if (streq_lit(p, n, "R9")) { return D_R9; };
|
||||
if (streq_lit(p, n, "R10")) { return D_R10; };
|
||||
if (streq_lit(p, n, "R11")) { return D_R11; };
|
||||
if (streq_lit(p, n, "R12")) { return D_R12; };
|
||||
if (streq_lit(p, n, "R13")) { return D_R13; };
|
||||
if (streq_lit(p, n, "R14")) { return D_R14; };
|
||||
if (streq_lit(p, n, "R15")) { return D_R15; };
|
||||
if (streq_lit(p, n, "X0")) { return D_X0; };
|
||||
if (streq_lit(p, n, "X1")) { return D_X1; };
|
||||
if (streq_lit(p, n, "X2")) { return D_X2; };
|
||||
if (streq_lit(p, n, "X3")) { return D_X3; };
|
||||
if (streq_lit(p, n, "X4")) { return D_X4; };
|
||||
if (streq_lit(p, n, "X5")) { return D_X5; };
|
||||
if (streq_lit(p, n, "X6")) { return D_X6; };
|
||||
if (streq_lit(p, n, "X7")) { return D_X7; };
|
||||
if (streq_lit(p, n, "X8")) { return D_X8; };
|
||||
if (streq_lit(p, n, "X9")) { return D_X9; };
|
||||
if (streq_lit(p, n, "X10")) { return D_X10; };
|
||||
if (streq_lit(p, n, "X11")) { return D_X11; };
|
||||
if (streq_lit(p, n, "X12")) { return D_X12; };
|
||||
if (streq_lit(p, n, "X13")) { return D_X13; };
|
||||
if (streq_lit(p, n, "X14")) { return D_X14; };
|
||||
if (streq_lit(p, n, "X15")) { return D_X15; };
|
||||
if (streq_lit(p, n, "SB")) { return D_PSB; };
|
||||
if (streq_lit(p, n, "FP")) { return D_PFP; };
|
||||
return D_NONE;
|
||||
};
|
||||
|
||||
export fn a_init(a: *asm_, ar: *arena, file: str, src: *u8, len: u64) void = {
|
||||
a.a = ar;
|
||||
a.file = file;
|
||||
a.src = src;
|
||||
a.srclen = len;
|
||||
a.pos = 0u64;
|
||||
a.line = 1;
|
||||
a.head = nil;
|
||||
a.tail = nil;
|
||||
a.text = nil;
|
||||
a.textcap = 0u64;
|
||||
a.textlen = 0u64;
|
||||
a.syms = nil;
|
||||
a.relocs = nil;
|
||||
a.fixups = nil;
|
||||
a.errs = 0;
|
||||
};
|
||||
|
||||
fn streq_str(a: str, b: str) bool = {
|
||||
if (a.len != b.len) { return false; };
|
||||
let i: i32 = 0;
|
||||
for (i < a.len) {
|
||||
if (a[i] != b[i]) { return false; };
|
||||
i += 1;
|
||||
};
|
||||
return true;
|
||||
};
|
||||
|
||||
export fn a_intern(a: *asm_, name: str) *asym = {
|
||||
let s: *asym = a.syms;
|
||||
for (s != nil) {
|
||||
if (streq_str(s.name, name)) { return s; };
|
||||
s = s.snext;
|
||||
};
|
||||
let n: *asym = amalloc(a.a, 64u64): *asym;
|
||||
n.name = name;
|
||||
n.snext = a.syms;
|
||||
a.syms = n;
|
||||
return n;
|
||||
};
|
||||
|
||||
fn perr(a: *asm_, msg: str) void = {
|
||||
os.write(2, "6a: ".ptr, 4u64);
|
||||
let f: str = a.file;
|
||||
os.write(2, f.ptr, f.len: u64);
|
||||
os.write(2, ": ".ptr, 2u64);
|
||||
os.write(2, msg.ptr, msg.len: u64);
|
||||
os.write(2, "\n".ptr, 1u64);
|
||||
a.errs += 1;
|
||||
};
|
||||
|
||||
// dup_str — copy n bytes from p into a fresh heap str.
|
||||
fn dup_str(a: *arena, p: *u8, n: u64) str = {
|
||||
return astrndup(a, p, n);
|
||||
};
|
||||
|
||||
// ---- line iteration & whitespace --------------------------------------
|
||||
|
||||
// Read next line into a fresh heap buffer; returns (ptr, len) or (nil,0)
|
||||
// at EOF. Advances a.pos past the newline.
|
||||
fn next_line(a: *asm_) (*u8, u64) = {
|
||||
if (a.pos >= a.srclen) { return nil, 0u64; };
|
||||
let start: u64 = a.pos;
|
||||
for (a.pos < a.srclen) {
|
||||
if (a.src[a.pos] == 10u8) { a.pos = a.pos; a.pos += 0u64; } // no-op; explicit break via condition
|
||||
else { a.pos += 1u64; continue; };
|
||||
// hit newline
|
||||
let n: u64 = a.pos - start;
|
||||
let buf: *u8 = amalloc(a.a, n + 1u64): *u8;
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) { buf[i] = a.src[start + i]; i += 1u64; };
|
||||
buf[n] = 0u8;
|
||||
a.pos += 1u64; // skip newline
|
||||
return buf, n;
|
||||
};
|
||||
// EOF without trailing newline
|
||||
let n: u64 = a.pos - start;
|
||||
if (n == 0u64) { return nil, 0u64; };
|
||||
let buf: *u8 = amalloc(a.a, n + 1u64): *u8;
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) { buf[i] = a.src[start + i]; i += 1u64; };
|
||||
buf[n] = 0u8;
|
||||
return buf, n;
|
||||
};
|
||||
|
||||
fn skip_ws(p: *u8, off: u64, n: u64) u64 = {
|
||||
let i: u64 = off;
|
||||
for (i < n) {
|
||||
if (p[i] != 32u8) { if (p[i] != 9u8) { return i; }; };
|
||||
i += 1u64;
|
||||
};
|
||||
return i;
|
||||
};
|
||||
|
||||
// parse_operand — parse one operand from p[off..n), populate out.
|
||||
// Returns new offset (clamped to n on error).
|
||||
fn parse_operand(a: *asm_, p: *u8, off_in: u64, n: u64, out: *aoperand) u64 = {
|
||||
let off: u64 = skip_ws(p, off_in, n);
|
||||
out.atype = D_NONE;
|
||||
out.reg = 0;
|
||||
out.offset = 0i64;
|
||||
let empty_str: str;
|
||||
empty_str.ptr = nil; empty_str.len = 0;
|
||||
out.asym = empty_str;
|
||||
if (off >= n) { return off; };
|
||||
let c0: u8 = p[off];
|
||||
|
||||
// $NUM
|
||||
if (c0 == 36u8) { // '$'
|
||||
off += 1u64;
|
||||
let v: i64;
|
||||
let used: u64;
|
||||
v, used = a_parsenum(p + off, n - off);
|
||||
out.atype = D_CONST;
|
||||
out.offset = v;
|
||||
return off + used;
|
||||
};
|
||||
|
||||
// (REG)
|
||||
if (c0 == 40u8) { // '('
|
||||
off += 1u64;
|
||||
let rstart: u64 = off;
|
||||
for (off < n) {
|
||||
if (p[off] == 41u8) { off = off; off += 0u64; } // no-op marker
|
||||
else { off += 1u64; continue; };
|
||||
let rn: u64 = off - rstart;
|
||||
let r: i32 = reg_lookup(p + rstart, rn);
|
||||
if (r == 0) { perr(a, "bad register in indirect"); return n; };
|
||||
out.atype = D_INDIR;
|
||||
out.reg = r;
|
||||
out.offset = 0i64;
|
||||
return off + 1u64; // past ')'
|
||||
};
|
||||
perr(a, "missing ')' in indirect");
|
||||
return n;
|
||||
};
|
||||
|
||||
// number(REG) — possibly signed — or bare $NUM-less constant
|
||||
let cur: u64 = off;
|
||||
let is_num: bool = false;
|
||||
if (cur < n) {
|
||||
if (p[cur] == 45u8) { is_num = true; }
|
||||
else { if (p[cur] >= 48u8) { if (p[cur] <= 57u8) { is_num = true; }; }; };
|
||||
};
|
||||
if (is_num) {
|
||||
let v: i64;
|
||||
let used: u64;
|
||||
v, used = a_parsenum(p + off, n - off);
|
||||
let after: u64 = off + used;
|
||||
if (after < n) { if (p[after] == 40u8) { // '('
|
||||
let rstart: u64 = after + 1u64;
|
||||
let cur2: u64 = rstart;
|
||||
for (cur2 < n) {
|
||||
if (p[cur2] == 41u8) { cur2 = cur2; cur2 += 0u64; }
|
||||
else { cur2 += 1u64; continue; };
|
||||
let rn: u64 = cur2 - rstart;
|
||||
let r: i32 = reg_lookup(p + rstart, rn);
|
||||
if (r == 0) { perr(a, "bad register"); return n; };
|
||||
out.atype = D_INDIR;
|
||||
out.reg = r;
|
||||
out.offset = v;
|
||||
return cur2 + 1u64;
|
||||
};
|
||||
perr(a, "missing ')'");
|
||||
return n;
|
||||
};};
|
||||
out.atype = D_CONST;
|
||||
out.offset = v;
|
||||
return after;
|
||||
};
|
||||
|
||||
// IDENT — register, symbol(SB), or branch label
|
||||
if (a_isidstart(c0: i32)) {
|
||||
let istart: u64 = off;
|
||||
for (off < n) {
|
||||
if (a_isidcont(p[off]: i32)) { off += 1u64; continue; };
|
||||
off = off; off += 0u64; // loop break
|
||||
let in_: u64 = off - istart;
|
||||
// IDENT(SB) — external
|
||||
if (off < n) { if (p[off] == 40u8) { // '('
|
||||
let rstart: u64 = off + 1u64;
|
||||
let cur2: u64 = rstart;
|
||||
for (cur2 < n) {
|
||||
if (p[cur2] == 41u8) { cur2 = cur2; cur2 += 0u64; }
|
||||
else { cur2 += 1u64; continue; };
|
||||
let rn: u64 = cur2 - rstart;
|
||||
let r: i32 = reg_lookup(p + rstart, rn);
|
||||
if (r == D_PSB) {
|
||||
out.atype = D_EXTERN;
|
||||
out.asym = dup_str(a.a, p + istart, in_);
|
||||
} else {
|
||||
out.atype = D_INDIR;
|
||||
out.reg = r;
|
||||
out.offset = 0i64;
|
||||
};
|
||||
return cur2 + 1u64;
|
||||
};
|
||||
perr(a, "missing ')'");
|
||||
return n;
|
||||
};};
|
||||
let r: i32 = reg_lookup(p + istart, in_);
|
||||
if (r != D_NONE) {
|
||||
out.atype = r;
|
||||
return off;
|
||||
};
|
||||
out.atype = D_BRANCH;
|
||||
out.asym = dup_str(a.a, p + istart, in_);
|
||||
return off;
|
||||
};
|
||||
// EOF inside ident
|
||||
let in_: u64 = off - istart;
|
||||
let r: i32 = reg_lookup(p + istart, in_);
|
||||
if (r != D_NONE) { out.atype = r; return off; };
|
||||
out.atype = D_BRANCH;
|
||||
out.asym = dup_str(a.a, p + istart, in_);
|
||||
return off;
|
||||
};
|
||||
|
||||
perr(a, "unrecognised operand");
|
||||
return n;
|
||||
};
|
||||
|
||||
// Append a fresh aprog to the list with given opcode and label.
|
||||
fn add_prog(a: *asm_, opc: i32, lbl: str) *aprog = {
|
||||
let pr: *aprog = amalloc(a.a, 96u64): *aprog;
|
||||
pr.as_ = opc;
|
||||
pr.line = a.line;
|
||||
pr.label = lbl;
|
||||
pr.link = nil;
|
||||
pr.bytes = nil;
|
||||
pr.nbytes = 0u64;
|
||||
pr.from = amalloc(a.a, 48u64): *aoperand;
|
||||
pr.to = amalloc(a.a, 48u64): *aoperand;
|
||||
if (a.head == nil) { a.head = pr; }
|
||||
else {
|
||||
// `a.tail.link = pr` would be a chained-dot write through a
|
||||
// pointer field, which the C cgen we bootstrap on doesn't
|
||||
// support (silently drops the store). Bind a local first.
|
||||
let tail: *aprog = a.tail;
|
||||
tail.link = pr;
|
||||
};
|
||||
a.tail = pr;
|
||||
return pr;
|
||||
};
|
||||
|
||||
export fn a_parse(a: *asm_) i32 = {
|
||||
let pending: str;
|
||||
pending.ptr = nil; pending.len = 0;
|
||||
|
||||
for (true) {
|
||||
let line: *u8;
|
||||
let n: u64;
|
||||
line, n = next_line(a);
|
||||
if (line == nil) { return a.errs; };
|
||||
|
||||
// skip leading ws
|
||||
let i: u64 = skip_ws(line, 0u64, n);
|
||||
// blank or //-comment
|
||||
if (i >= n) { a.line += 1; continue; };
|
||||
if (i + 1u64 < n) {
|
||||
if (line[i] == 47u8) { if (line[i + 1u64] == 47u8) {
|
||||
a.line += 1; continue;
|
||||
};};
|
||||
};
|
||||
|
||||
// Label? IDENT: starting at column 0 (no leading tab).
|
||||
// Only if the identifier is followed by ':'. Otherwise, fall
|
||||
// through to mnemonic parsing so e.g. `TEXT foo,$0` (which
|
||||
// also starts with an idchar in column 0) gets parsed.
|
||||
if (line[0u64] != 9u8) {
|
||||
if (a_isidstart(line[i]: i32)) {
|
||||
let q: u64 = i;
|
||||
let scan_id: bool = true;
|
||||
for (scan_id) {
|
||||
if (q >= n) { scan_id = false; }
|
||||
else { if (a_isidcont(line[q]: i32)) { q += 1u64; }
|
||||
else { scan_id = false; }; };
|
||||
};
|
||||
if (q < n) { if (line[q] == 58u8) { // ':'
|
||||
let nm: str = dup_str(a.a, line + i, q - i);
|
||||
// Pending label gets a NOP prog so addresses pin.
|
||||
if (pending.len > 0) {
|
||||
let np: *aprog = add_prog(a, A_NOP, pending);
|
||||
};
|
||||
pending = nm;
|
||||
a.line += 1;
|
||||
continue;
|
||||
};};
|
||||
// not a label — fall through to mnemonic parse
|
||||
};
|
||||
};
|
||||
|
||||
// MNEMONIC at the start of the rest. Scan to first ws/EOL.
|
||||
let mstart: u64 = i;
|
||||
let m: u64 = mstart;
|
||||
let scan: bool = true;
|
||||
for (scan) {
|
||||
if (m >= n) { scan = false; }
|
||||
else { if (line[m] == 32u8) { scan = false; }
|
||||
else { if (line[m] == 9u8) { scan = false; }
|
||||
else { m += 1u64; }; }; };
|
||||
};
|
||||
let mlen: u64 = m - mstart;
|
||||
let opc: i32 = opcode_lookup(line + mstart, mlen);
|
||||
if (opc == 0) {
|
||||
if (mlen > 0u64) {
|
||||
perr(a, "unknown opcode");
|
||||
};
|
||||
pending.ptr = nil; pending.len = 0;
|
||||
a.line += 1; continue;
|
||||
};
|
||||
|
||||
let pr: *aprog = add_prog(a, opc, pending);
|
||||
pending.ptr = nil; pending.len = 0;
|
||||
|
||||
// Skip ws after mnemonic
|
||||
let r0: u64 = skip_ws(line, m, n);
|
||||
|
||||
if (opc == A_TEXT) {
|
||||
// TEXT name,$framesize — find first ',' as the end of name.
|
||||
let q: u64 = r0;
|
||||
let comma_pos: u64 = n;
|
||||
let scan_t: bool = true;
|
||||
for (scan_t) {
|
||||
if (q >= n) { scan_t = false; }
|
||||
else { if (line[q] == 44u8) { comma_pos = q; scan_t = false; }
|
||||
else { q += 1u64; }; };
|
||||
};
|
||||
let to_op: *aoperand = pr.to;
|
||||
to_op.atype = D_EXTERN;
|
||||
to_op.asym = dup_str(a.a, line + r0, comma_pos - r0);
|
||||
if (comma_pos < n) {
|
||||
let p2: u64 = comma_pos + 1u64;
|
||||
p2 = skip_ws(line, p2, n);
|
||||
if (p2 < n) { if (line[p2] == 36u8) { p2 += 1u64; }; };
|
||||
let v: i64;
|
||||
let used: u64;
|
||||
v, used = a_parsenum(line + p2, n - p2);
|
||||
let from_op: *aoperand = pr.from;
|
||||
from_op.atype = D_CONST;
|
||||
from_op.offset = v;
|
||||
};
|
||||
a.line += 1; continue;
|
||||
};
|
||||
|
||||
if (opc == A_DATA) {
|
||||
// DATA name(SB),"escaped bytes" — find first '(' as end of name.
|
||||
let q: u64 = r0;
|
||||
let lparen: u64 = n;
|
||||
let scan_d: bool = true;
|
||||
for (scan_d) {
|
||||
if (q >= n) { scan_d = false; }
|
||||
else { if (line[q] == 40u8) { lparen = q; scan_d = false; }
|
||||
else { q += 1u64; }; };
|
||||
};
|
||||
let to_op: *aoperand = pr.to;
|
||||
to_op.atype = D_EXTERN;
|
||||
to_op.asym = dup_str(a.a, line + r0, lparen - r0);
|
||||
// Skip past `(SB)` to land just after ')'.
|
||||
let p2: u64 = lparen;
|
||||
let scan_d2: bool = true;
|
||||
for (scan_d2) {
|
||||
if (p2 >= n) { scan_d2 = false; }
|
||||
else { if (line[p2] == 41u8) { p2 += 1u64; scan_d2 = false; }
|
||||
else { p2 += 1u64; }; };
|
||||
};
|
||||
// Skip ws / ',' / tab between `)` and the `"`.
|
||||
let scan_d3: bool = true;
|
||||
for (scan_d3) {
|
||||
if (p2 >= n) { scan_d3 = false; }
|
||||
else { if (line[p2] == 32u8) { p2 += 1u64; }
|
||||
else { if (line[p2] == 44u8) { p2 += 1u64; }
|
||||
else { if (line[p2] == 9u8) { p2 += 1u64; }
|
||||
else { scan_d3 = false; }; }; }; };
|
||||
};
|
||||
if (p2 >= n) { perr(a, "DATA missing payload"); a.line += 1; continue; };
|
||||
if (line[p2] != 34u8) { perr(a, "DATA expects \"...\""); a.line += 1; continue; };
|
||||
p2 += 1u64; // past opening "
|
||||
// Parse escape sequence into a fresh growable buffer.
|
||||
let cap: u64 = 32u64;
|
||||
let blen: u64 = 0u64;
|
||||
let dbuf: *u8 = amalloc(a.a, cap): *u8;
|
||||
for (p2 < n) {
|
||||
if (line[p2] == 34u8) { p2 = p2; p2 += 0u64; p2 = n + 1u64; }
|
||||
else {
|
||||
let ch: u8 = line[p2];
|
||||
p2 += 1u64;
|
||||
if (ch == 92u8) { // '\'
|
||||
if (p2 < n) {
|
||||
let e: u8 = line[p2];
|
||||
p2 += 1u64;
|
||||
if (e == 110u8) { ch = 10u8; } // 'n'
|
||||
else { if (e == 116u8) { ch = 9u8; }
|
||||
else { if (e == 114u8) { ch = 13u8; }
|
||||
else { if (e == 92u8) { ch = 92u8; }
|
||||
else { if (e == 34u8) { ch = 34u8; }
|
||||
else { if (e == 48u8) { ch = 0u8; }
|
||||
else { if (e == 120u8) { // 'x'
|
||||
if (p2 + 1u64 < n) {
|
||||
let hi: u8 = line[p2];
|
||||
let lo: u8 = line[p2 + 1u64];
|
||||
p2 += 2u64;
|
||||
let h: u8 = 0u8;
|
||||
let l: u8 = 0u8;
|
||||
if (hi <= 57u8) { h = hi - 48u8; }
|
||||
else { h = (hi | 32u8) - 97u8 + 10u8; };
|
||||
if (lo <= 57u8) { l = lo - 48u8; }
|
||||
else { l = (lo | 32u8) - 97u8 + 10u8; };
|
||||
ch = (h << 4u8) | l;
|
||||
};
|
||||
}
|
||||
else { ch = e; };};};};};};};
|
||||
};
|
||||
};
|
||||
if (blen + 1u64 > cap) {
|
||||
let ncap: u64 = cap * 2u64;
|
||||
let nb: *u8 = amalloc(a.a, ncap): *u8;
|
||||
let bi: u64 = 0u64;
|
||||
for (bi < blen) { nb[bi] = dbuf[bi]; bi += 1u64; };
|
||||
dbuf = nb;
|
||||
cap = ncap;
|
||||
};
|
||||
dbuf[blen] = ch;
|
||||
blen += 1u64;
|
||||
};
|
||||
};
|
||||
pr.bytes = dbuf;
|
||||
pr.nbytes = blen;
|
||||
a.line += 1; continue;
|
||||
};
|
||||
|
||||
// Generic instruction: 0/1/2 operands separated by ','.
|
||||
// Find top-level comma.
|
||||
let comma: i64 = -1i64;
|
||||
let q: u64 = r0;
|
||||
for (q < n) {
|
||||
if (line[q] == 44u8) {
|
||||
if (comma < 0i64) { comma = q: i64; };
|
||||
};
|
||||
q += 1u64;
|
||||
};
|
||||
if (comma >= 0i64) {
|
||||
let cu: u64 = comma: u64;
|
||||
parse_operand(a, line, r0, cu, pr.from);
|
||||
parse_operand(a, line + (cu + 1u64), 0u64, n - (cu + 1u64), pr.to);
|
||||
} else { if (r0 < n) {
|
||||
parse_operand(a, line, r0, n, pr.to);
|
||||
};};
|
||||
|
||||
a.line += 1;
|
||||
};
|
||||
return a.errs;
|
||||
};
|
||||
193
selfhost/cmd/6a/types.ww
Normal file
193
selfhost/cmd/6a/types.ww
Normal file
@@ -0,0 +1,193 @@
|
||||
// selfhost/cmd/6a/types.ww — types + constants shared across the
|
||||
// 6a port. Mirrors cmd/6a/a.h and cmd/6c/6.out.h.
|
||||
|
||||
use mem;
|
||||
|
||||
// ---- registers + operand kinds (from 6.out.h) -------------------------
|
||||
// These must stay numerically aligned with the C enum so that ww-cgen
|
||||
// output (which reads them via `D_AX(SB)` etc.) lands on the same
|
||||
// integers when read by ww-6a.
|
||||
def D_NONE: i32 = 0;
|
||||
|
||||
def D_AX: i32 = 1;
|
||||
def D_CX: i32 = 2;
|
||||
def D_DX: i32 = 3;
|
||||
def D_BX: i32 = 4;
|
||||
def D_SP: i32 = 5;
|
||||
def D_BP: i32 = 6;
|
||||
def D_SI: i32 = 7;
|
||||
def D_DI: i32 = 8;
|
||||
def D_R8: i32 = 9;
|
||||
def D_R9: i32 = 10;
|
||||
def D_R10: i32 = 11;
|
||||
def D_R11: i32 = 12;
|
||||
def D_R12: i32 = 13;
|
||||
def D_R13: i32 = 14;
|
||||
def D_R14: i32 = 15;
|
||||
def D_R15: i32 = 16;
|
||||
|
||||
def D_X0: i32 = 17;
|
||||
def D_X1: i32 = 18;
|
||||
def D_X2: i32 = 19;
|
||||
def D_X3: i32 = 20;
|
||||
def D_X4: i32 = 21;
|
||||
def D_X5: i32 = 22;
|
||||
def D_X6: i32 = 23;
|
||||
def D_X7: i32 = 24;
|
||||
def D_X8: i32 = 25;
|
||||
def D_X9: i32 = 26;
|
||||
def D_X10: i32 = 27;
|
||||
def D_X11: i32 = 28;
|
||||
def D_X12: i32 = 29;
|
||||
def D_X13: i32 = 30;
|
||||
def D_X14: i32 = 31;
|
||||
def D_X15: i32 = 32;
|
||||
|
||||
def D_PSP: i32 = 33;
|
||||
def D_PFP: i32 = 34;
|
||||
def D_PSB: i32 = 35;
|
||||
|
||||
def D_CONST: i32 = 36;
|
||||
def D_BRANCH: i32 = 37;
|
||||
def D_EXTERN: i32 = 38;
|
||||
def D_INDIR: i32 = 39;
|
||||
|
||||
// ---- opcodes ----------------------------------------------------------
|
||||
def A_NOP: i32 = 0;
|
||||
def A_TEXT: i32 = 1;
|
||||
def A_DATA: i32 = 2;
|
||||
def A_GLOBL: i32 = 3;
|
||||
def A_END: i32 = 4;
|
||||
|
||||
def A_MOVQ: i32 = 5;
|
||||
def A_MOVL: i32 = 6;
|
||||
def A_MOVB: i32 = 7;
|
||||
def A_MOVZBQ: i32 = 8;
|
||||
def A_MOVSXD: i32 = 9;
|
||||
|
||||
def A_MOVSD: i32 = 10;
|
||||
def A_ADDSD: i32 = 11;
|
||||
def A_SUBSD: i32 = 12;
|
||||
def A_MULSD: i32 = 13;
|
||||
def A_DIVSD: i32 = 14;
|
||||
def A_UCOMISD: i32 = 15;
|
||||
def A_CVTTSD2SI: i32 = 16;
|
||||
def A_CVTSI2SD: i32 = 17;
|
||||
|
||||
def A_MOVSS: i32 = 18;
|
||||
def A_ADDSS: i32 = 19;
|
||||
def A_SUBSS: i32 = 20;
|
||||
def A_MULSS: i32 = 21;
|
||||
def A_DIVSS: i32 = 22;
|
||||
def A_UCOMISS: i32 = 23;
|
||||
def A_CVTTSS2SI: i32 = 24;
|
||||
def A_CVTSI2SS: i32 = 25;
|
||||
def A_CVTSD2SS: i32 = 26;
|
||||
def A_CVTSS2SD: i32 = 27;
|
||||
|
||||
def A_ADDQ: i32 = 28;
|
||||
def A_SUBQ: i32 = 29;
|
||||
def A_IMULQ: i32 = 30;
|
||||
def A_IDIVQ: i32 = 31;
|
||||
def A_DIVQ: i32 = 32;
|
||||
def A_NEGQ: i32 = 33;
|
||||
def A_NOTQ: i32 = 34;
|
||||
def A_ANDQ: i32 = 35;
|
||||
def A_ORQ: i32 = 36;
|
||||
def A_XORQ: i32 = 37;
|
||||
def A_SHLQ: i32 = 38;
|
||||
def A_SHRQ: i32 = 39;
|
||||
def A_CMPQ: i32 = 40;
|
||||
|
||||
def A_PUSHQ: i32 = 41;
|
||||
def A_POPQ: i32 = 42;
|
||||
def A_LEAQ: i32 = 43;
|
||||
|
||||
def A_CALL: i32 = 44;
|
||||
def A_RET: i32 = 45;
|
||||
def A_JMP: i32 = 46;
|
||||
def A_JE: i32 = 47;
|
||||
def A_JNE: i32 = 48;
|
||||
def A_JL: i32 = 49;
|
||||
def A_JLE: i32 = 50;
|
||||
def A_JG: i32 = 51;
|
||||
def A_JGE: i32 = 52;
|
||||
def A_JB: i32 = 53;
|
||||
def A_JBE: i32 = 54;
|
||||
def A_JA: i32 = 55;
|
||||
def A_JAE: i32 = 56;
|
||||
def A_JZ: i32 = 57;
|
||||
def A_JNZ: i32 = 58;
|
||||
|
||||
def A_SYSCALL: i32 = 59;
|
||||
|
||||
// ---- structs (mirror cmd/6a/a.h) --------------------------------------
|
||||
|
||||
type aoperand = struct {
|
||||
atype: i32, // D_NONE / D_AX..D_R15 / D_CONST / D_INDIR / D_EXTERN / D_BRANCH
|
||||
reg: i32,
|
||||
offset: i64,
|
||||
asym: str,
|
||||
};
|
||||
|
||||
// `from` and `to` are pointer-to-aoperand (rather than embedded). The
|
||||
// C cgen we currently bootstrap on doesn't support chained-dot through
|
||||
// embedded structs (e.g. p.to.atype where `to` is a value field), but
|
||||
// it does support chained-dot through pointer fields. Allocating each
|
||||
// operand once per prog lets us write `p.to.atype` straightforwardly.
|
||||
type aprog = struct {
|
||||
as_: i32,
|
||||
from: *aoperand,
|
||||
to: *aoperand,
|
||||
line: i32,
|
||||
label: str,
|
||||
link: *aprog,
|
||||
bytes: *u8, // payload for A_DATA
|
||||
nbytes: u64,
|
||||
};
|
||||
|
||||
type asym = struct {
|
||||
name: str,
|
||||
defined: i32,
|
||||
is_text: i32,
|
||||
is_global: i32,
|
||||
addr: u64,
|
||||
idx: i32,
|
||||
snext: *asym,
|
||||
};
|
||||
|
||||
type areloc = struct {
|
||||
off: u64,
|
||||
kind: i32,
|
||||
asy: *asym,
|
||||
addend: i64,
|
||||
rnext: *areloc,
|
||||
};
|
||||
|
||||
type afixup = struct {
|
||||
off: u64, // where the rel32 lands in .text
|
||||
label: str,
|
||||
fnext: *afixup,
|
||||
};
|
||||
|
||||
type asm_ = struct {
|
||||
a: *arena,
|
||||
file: str,
|
||||
src: *u8,
|
||||
srclen: u64,
|
||||
pos: u64,
|
||||
line: i32,
|
||||
|
||||
head: *aprog,
|
||||
tail: *aprog,
|
||||
|
||||
text: *u8,
|
||||
textcap: u64,
|
||||
textlen: u64,
|
||||
|
||||
syms: *asym,
|
||||
relocs: *areloc,
|
||||
fixups: *afixup,
|
||||
|
||||
errs: i32,
|
||||
};
|
||||
1077
selfhost/cmd/6l/main.combined.ww
Normal file
1077
selfhost/cmd/6l/main.combined.ww
Normal file
File diff suppressed because it is too large
Load Diff
120
selfhost/cmd/6l/main.ww
Normal file
120
selfhost/cmd/6l/main.ww
Normal file
@@ -0,0 +1,120 @@
|
||||
// selfhost/cmd/6l/main.ww — port of cmd/6l/main.c.
|
||||
//
|
||||
// 6l = amd64 static linker. Reads relocatable ELF .o files and
|
||||
// SysV `ar` archives, resolves symbols, applies relocations, writes
|
||||
// a static ELF executable.
|
||||
//
|
||||
// 6l_ww -o out file1.o file2.o libwwrt.a ...
|
||||
|
||||
use os;
|
||||
use mem;
|
||||
use sym;
|
||||
use obj;
|
||||
use pass;
|
||||
use out;
|
||||
|
||||
def BASE: u64 = 4194304u64; // 0x400000
|
||||
def CODE_VA_OFF: u64 = 4096u64; // .text starts at base + 0x1000
|
||||
|
||||
// Linker context lives in main's frame; arena gets passed in.
|
||||
fn make_lnk(a: *arena) *lnk = {
|
||||
let l: *lnk = amalloc(a, 96u64): *lnk;
|
||||
l.a = a;
|
||||
return l;
|
||||
};
|
||||
|
||||
fn streq_cs(a: *u8, lit: str) bool = {
|
||||
let n: u64 = lit.len: u64;
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
let li: i32 = i: i32;
|
||||
if (a[i] != lit[li]) { return false; };
|
||||
i += 1u64;
|
||||
};
|
||||
if (a[i] != 0u8) { return false; };
|
||||
return true;
|
||||
};
|
||||
|
||||
export fn main(argc: i32, argv: **u8) i32 = {
|
||||
|
||||
let out_path: *u8 = nil;
|
||||
// Inputs: store as **u8 (heap'd from a fixed-size buffer).
|
||||
let max_inputs: i32 = 64;
|
||||
let inputs: **u8 = os.alloc((max_inputs: u64) * 8u64): **u8;
|
||||
let ninputs: i32 = 0;
|
||||
|
||||
let i: i32 = 1;
|
||||
for (i < argc) {
|
||||
let a: *u8 = argv[i];
|
||||
if (streq_cs(a, "-o")) {
|
||||
i += 1;
|
||||
if (i >= argc) {
|
||||
os.write(2, "6l: -o requires argument\n".ptr, 25u64);
|
||||
return 2;
|
||||
};
|
||||
out_path = argv[i];
|
||||
} else { if (a[0u64] == 45u8) {
|
||||
os.write(2, "6l: unknown flag\n".ptr, 17u64);
|
||||
return 2;
|
||||
} else {
|
||||
if (ninputs >= max_inputs) {
|
||||
os.write(2, "6l: too many inputs\n".ptr, 20u64);
|
||||
return 2;
|
||||
};
|
||||
inputs[ninputs] = a;
|
||||
ninputs += 1;
|
||||
}; };
|
||||
i += 1;
|
||||
};
|
||||
|
||||
if (out_path == nil) {
|
||||
os.write(2, "usage: 6l_ww -o exe file1.o [file2.o...]\n".ptr, 41u64);
|
||||
return 2;
|
||||
};
|
||||
if (ninputs == 0) {
|
||||
os.write(2, "6l: no inputs\n".ptr, 14u64);
|
||||
return 2;
|
||||
};
|
||||
|
||||
let a: *arena = newarena();
|
||||
let l: *lnk = make_lnk(a);
|
||||
|
||||
// Seed _start so a libwwrt-style start.o is recognised as wanted.
|
||||
l_intern(l, "_start");
|
||||
|
||||
let k: i32 = 0;
|
||||
for (k < ninputs) {
|
||||
if (l_load(l, inputs[k]) != 0) {
|
||||
return 1;
|
||||
};
|
||||
k += 1;
|
||||
};
|
||||
|
||||
if (l_resolve(l) != 0) { return 1; };
|
||||
if (l_relocate(l, BASE + CODE_VA_OFF) != 0) { return 1; };
|
||||
|
||||
let entry_sym: *lsym = l_lookup(l, "_start");
|
||||
if (entry_sym == nil) { entry_sym = l_lookup(l, "main"); }
|
||||
else { if (entry_sym.defined == 0) { entry_sym = l_lookup(l, "main"); }; };
|
||||
if (entry_sym == nil) {
|
||||
os.write(2, "6l: no _start or main symbol\n".ptr, 29u64);
|
||||
return 1;
|
||||
};
|
||||
if (entry_sym.defined == 0) {
|
||||
os.write(2, "6l: no _start or main symbol\n".ptr, 29u64);
|
||||
return 1;
|
||||
};
|
||||
|
||||
// Open output: O_WRONLY|O_CREAT|O_TRUNC, mode 0755.
|
||||
let flags: i32 = os.O_WRONLY | os.O_CREAT | os.O_TRUNC;
|
||||
let fd: i32 = os.open(out_path, flags, 493i32); // 0o755
|
||||
if (fd < 0) {
|
||||
os.write(2, "6l: cannot open output\n".ptr, 23u64);
|
||||
return 1;
|
||||
};
|
||||
|
||||
let entry_va: u64 = BASE + CODE_VA_OFF + entry_sym.val;
|
||||
let rc: i32 = l_emit_elf(l, fd, BASE, entry_va);
|
||||
os.close(fd);
|
||||
return rc;
|
||||
};
|
||||
486
selfhost/cmd/6l/obj.ww
Normal file
486
selfhost/cmd/6l/obj.ww
Normal file
@@ -0,0 +1,486 @@
|
||||
// selfhost/cmd/6l/obj.ww — port of cmd/6l/obj.c.
|
||||
//
|
||||
// Loads relocatable ELF64 .o files emitted by 6a, appends .text to
|
||||
// the combined image, and pulls in symbols + relocations with
|
||||
// offsets adjusted to the combined section.
|
||||
//
|
||||
// Also handles SysV `ar` archives (libwwrt.a). The two-pass loader
|
||||
// indexes members on the first pass and iteratively pulls members
|
||||
// that define currently-undefined symbols on subsequent passes.
|
||||
|
||||
use os;
|
||||
use mem;
|
||||
use sym;
|
||||
|
||||
def ET_REL: i32 = 1;
|
||||
def EM_X86_64: i32 = 62;
|
||||
def SHT_PROGBITS: i32 = 1;
|
||||
def SHT_SYMTAB: i32 = 2;
|
||||
def SHT_STRTAB: i32 = 3;
|
||||
def SHT_RELA: i32 = 4;
|
||||
|
||||
// ---- little-endian byte readers ----------------------------------------
|
||||
// 6a/6l use straight LE on amd64. Reading via byte offsets keeps us off
|
||||
// the cgen's u16 field-load story for now (MOVZBQ exists; MOVZWQ doesn't).
|
||||
|
||||
fn rd_u16(p: *u8, off: u64) u16 = {
|
||||
let b0: u16 = p[off]: u16;
|
||||
let b1: u16 = p[off + 1u64]: u16;
|
||||
return b0 | (b1 << 8u16);
|
||||
};
|
||||
|
||||
fn rd_u32(p: *u8, off: u64) u32 = {
|
||||
let b0: u32 = p[off]: u32;
|
||||
let b1: u32 = p[off + 1u64]: u32;
|
||||
let b2: u32 = p[off + 2u64]: u32;
|
||||
let b3: u32 = p[off + 3u64]: u32;
|
||||
return b0 | (b1 << 8u32) | (b2 << 16u32) | (b3 << 24u32);
|
||||
};
|
||||
|
||||
fn rd_u64(p: *u8, off: u64) u64 = {
|
||||
let lo: u64 = rd_u32(p, off): u64;
|
||||
let hi: u64 = rd_u32(p, off + 4u64): u64;
|
||||
return lo | (hi << 32u64);
|
||||
};
|
||||
|
||||
// ---- ELF64 section header offsets (40 bytes total) --------------------
|
||||
def SHDR_SIZE: u64 = 64u64; // sizeof(Shdr) per ELF64 spec
|
||||
def SHDR_NAME: u64 = 0u64;
|
||||
def SHDR_TYPE: u64 = 4u64;
|
||||
def SHDR_OFFSET: u64 = 24u64;
|
||||
def SHDR_SIZE_F: u64 = 32u64;
|
||||
def SHDR_LINK: u64 = 40u64;
|
||||
|
||||
// ELF64 ehdr field offsets
|
||||
def EHDR_SIZE: u64 = 64u64;
|
||||
def EHDR_TYPE: u64 = 16u64;
|
||||
def EHDR_MACHINE: u64 = 18u64;
|
||||
def EHDR_SHOFF: u64 = 40u64;
|
||||
def EHDR_SHENTSIZE: u64 = 58u64;
|
||||
def EHDR_SHNUM: u64 = 60u64;
|
||||
def EHDR_SHSTRNDX: u64 = 62u64;
|
||||
|
||||
// ELF64 sym entry: 24 bytes
|
||||
def SYM_SIZE: u64 = 24u64;
|
||||
def SYM_NAME: u64 = 0u64;
|
||||
def SYM_INFO: u64 = 4u64;
|
||||
def SYM_SHNDX: u64 = 6u64;
|
||||
def SYM_VALUE: u64 = 8u64;
|
||||
|
||||
// ELF64 RELA entry: 24 bytes
|
||||
def RELA_SIZE: u64 = 24u64;
|
||||
def RELA_OFFSET: u64 = 0u64;
|
||||
def RELA_INFO: u64 = 8u64;
|
||||
def RELA_ADDEND: u64 = 16u64;
|
||||
|
||||
// ---- file slurp --------------------------------------------------------
|
||||
|
||||
fn read_all(path_cs: *u8) (*u8, u64) = {
|
||||
let fd: i32 = os.open(path_cs, os.O_RDONLY, 0i32);
|
||||
if (fd < 0) { return nil, 0u64; };
|
||||
let n: i64 = os.filesize(fd);
|
||||
if (n < 0i64) { os.close(fd); return nil, 0u64; };
|
||||
let buf: *u8 = os.alloc(n: u64): *u8;
|
||||
let got: i64 = os.readfull(fd, buf, n: u64);
|
||||
os.close(fd);
|
||||
if (got != n) { return nil, 0u64; };
|
||||
return buf, n: u64;
|
||||
};
|
||||
|
||||
// ---- text buffer growth ------------------------------------------------
|
||||
|
||||
fn emit_text(l: *lnk, src: *u8, n: u64) void = {
|
||||
if (l.textlen + n > l.textcap) {
|
||||
let nc: u64 = l.textcap;
|
||||
if (nc == 0u64) { nc = 4096u64; };
|
||||
for (nc < l.textlen + n) { nc = nc * 2u64; };
|
||||
// Grow by mmap'ing a fresh region and copying. The old buffer
|
||||
// is leaked into the page allocator; for a linker run this is
|
||||
// trivial waste.
|
||||
let nb: *u8 = os.alloc(nc): *u8;
|
||||
let i: u64 = 0u64;
|
||||
for (i < l.textlen) {
|
||||
nb[i] = l.text[i];
|
||||
i += 1u64;
|
||||
};
|
||||
l.text = nb;
|
||||
l.textcap = nc;
|
||||
};
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
l.text[l.textlen + i] = src[i];
|
||||
i += 1u64;
|
||||
};
|
||||
l.textlen += n;
|
||||
};
|
||||
|
||||
// ---- C-string helpers --------------------------------------------------
|
||||
|
||||
fn cstrlen(p: *u8) u64 = {
|
||||
let n: u64 = 0u64;
|
||||
for (p[n] != 0u8) { n += 1u64; };
|
||||
return n;
|
||||
};
|
||||
|
||||
fn cstr_eq(p: *u8, lit: str) bool = {
|
||||
let n: u64 = lit.len: u64;
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
let li: i32 = i: i32;
|
||||
if (p[i] != lit[li]) { return false; };
|
||||
i += 1u64;
|
||||
};
|
||||
if (p[i] != 0u8) { return false; };
|
||||
return true;
|
||||
};
|
||||
|
||||
// Build a ww str from a NUL-terminated *u8 (for passing to l_intern).
|
||||
fn cstr_to_str(a: *arena, p: *u8) str = {
|
||||
let n: u64 = cstrlen(p);
|
||||
return astrndup(a, p, n);
|
||||
};
|
||||
|
||||
// ---- archive (SysV ar) types and helpers -------------------------------
|
||||
//
|
||||
// Each archive member starts with a 60-byte ar_hdr. The fields we care
|
||||
// about are the first byte (member type) and the size at offset 48 (a
|
||||
// 10-byte, space-padded decimal). Member bodies are 2-byte aligned.
|
||||
|
||||
type defent = struct {
|
||||
name: str,
|
||||
dnext: *defent,
|
||||
};
|
||||
|
||||
type armember = struct {
|
||||
data: *u8, // arena copy of the member's ELF bytes
|
||||
size: u64,
|
||||
defs: *defent, // linked list of defined globals
|
||||
loaded: i32,
|
||||
mnext: *armember,
|
||||
};
|
||||
|
||||
fn is_archive(p: *u8, len: u64) bool = {
|
||||
if (len < 8u64) { return false; };
|
||||
if (p[0u64] != 33u8) { return false; }; // '!'
|
||||
if (p[1u64] != 60u8) { return false; }; // '<'
|
||||
if (p[2u64] != 97u8) { return false; }; // 'a'
|
||||
if (p[3u64] != 114u8) { return false; }; // 'r'
|
||||
if (p[4u64] != 99u8) { return false; }; // 'c'
|
||||
if (p[5u64] != 104u8) { return false; }; // 'h'
|
||||
if (p[6u64] != 62u8) { return false; }; // '>'
|
||||
if (p[7u64] != 10u8) { return false; }; // '\n'
|
||||
return true;
|
||||
};
|
||||
|
||||
// ar_field — parse a space-padded decimal integer of width n.
|
||||
fn ar_field(p: *u8, n: u64) u64 = {
|
||||
let v: u64 = 0u64;
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
let c: u8 = p[i];
|
||||
if (c < 48u8) { return v; }; // space, NUL, etc.
|
||||
if (c > 57u8) { return v; };
|
||||
v = v * 10u64 + ((c - 48u8): u64);
|
||||
i += 1u64;
|
||||
};
|
||||
return v;
|
||||
};
|
||||
|
||||
// elf_globals — return a linked list of names of globally-defined
|
||||
// (STB_GLOBAL) symbols whose section is `.text`. Names are arena
|
||||
// copies, so the source ELF buffer can be freed afterward.
|
||||
fn elf_globals(a: *arena, buf: *u8, len: u64) *defent = {
|
||||
if (len < EHDR_SIZE) { return nil; };
|
||||
if (buf[0u64] != 127u8) { return nil; };
|
||||
if (buf[1u64] != 69u8) { return nil; };
|
||||
if (buf[2u64] != 76u8) { return nil; };
|
||||
if (buf[3u64] != 70u8) { return nil; };
|
||||
|
||||
let shoff: u64 = rd_u64(buf, EHDR_SHOFF);
|
||||
let shnum: u32 = rd_u16(buf, EHDR_SHNUM): u32;
|
||||
let shstrndx: u32 = rd_u16(buf, EHDR_SHSTRNDX): u32;
|
||||
|
||||
let shstr_sh_off: u64 = rd_u64(buf, shoff + (shstrndx: u64) * SHDR_SIZE + SHDR_OFFSET);
|
||||
let shstr: *u8 = buf + shstr_sh_off;
|
||||
|
||||
let idx_text: i32 = -1;
|
||||
let idx_symtab: i32 = -1;
|
||||
let i: u32 = 0u32;
|
||||
for (i < shnum) {
|
||||
let sh_off: u64 = shoff + (i: u64) * SHDR_SIZE;
|
||||
let sh_type: u32 = rd_u32(buf, sh_off + SHDR_TYPE);
|
||||
let sh_name: u32 = rd_u32(buf, sh_off + SHDR_NAME);
|
||||
let nm: *u8 = shstr + (sh_name: u64);
|
||||
if (sh_type == SHT_PROGBITS: u32) {
|
||||
if (cstr_eq(nm, ".text")) { idx_text = i: i32; };
|
||||
};
|
||||
if (sh_type == SHT_SYMTAB: u32) { idx_symtab = i: i32; };
|
||||
i += 1u32;
|
||||
};
|
||||
if (idx_text < 0) { return nil; };
|
||||
if (idx_symtab < 0) { return nil; };
|
||||
|
||||
let sym_sh: u64 = shoff + (idx_symtab: u64) * SHDR_SIZE;
|
||||
let sym_off: u64 = rd_u64(buf, sym_sh + SHDR_OFFSET);
|
||||
let sym_size: u64 = rd_u64(buf, sym_sh + SHDR_SIZE_F);
|
||||
let sym_link: u32 = rd_u32(buf, sym_sh + SHDR_LINK);
|
||||
let nsyms: u64 = sym_size / SYM_SIZE;
|
||||
|
||||
let str_sh: u64 = shoff + (sym_link: u64) * SHDR_SIZE;
|
||||
let str_off: u64 = rd_u64(buf, str_sh + SHDR_OFFSET);
|
||||
let strtab: *u8 = buf + str_off;
|
||||
|
||||
let head: *defent = nil;
|
||||
let si: u64 = 1u64;
|
||||
for (si < nsyms) {
|
||||
let sym_p: u64 = sym_off + si * SYM_SIZE;
|
||||
let st_name: u32 = rd_u32(buf, sym_p + SYM_NAME);
|
||||
let st_info: u8 = buf[sym_p + SYM_INFO];
|
||||
let st_shndx: u16 = rd_u16(buf, sym_p + SYM_SHNDX);
|
||||
let bind: u32 = (st_info: u32) >> 4u32;
|
||||
// STB_GLOBAL = 1; defined in .text.
|
||||
if (bind == 1u32) {
|
||||
if (st_shndx != 0u16) {
|
||||
if ((st_shndx: i32) == idx_text) {
|
||||
let nm_p: *u8 = strtab + (st_name: u64);
|
||||
if (nm_p[0u64] != 0u8) {
|
||||
let nm: str = cstr_to_str(a, nm_p);
|
||||
let de: *defent = amalloc(a, 32u64): *defent;
|
||||
de.name = nm;
|
||||
de.dnext = head;
|
||||
head = de;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
si += 1u64;
|
||||
};
|
||||
return head;
|
||||
};
|
||||
|
||||
// member_defines_undef — true if any of m's defined globals matches a
|
||||
// currently-undefined symbol in the linker's symbol table. Names not
|
||||
// already interned are uninteresting (the link doesn't need them yet).
|
||||
fn member_defines_undef(l: *lnk, m: *armember) bool = {
|
||||
let de: *defent = m.defs;
|
||||
for (de != nil) {
|
||||
let s: *lsym = l_lookup(l, de.name);
|
||||
if (s != nil) {
|
||||
if (s.defined == 0) { return true; };
|
||||
};
|
||||
de = de.dnext;
|
||||
};
|
||||
return false;
|
||||
};
|
||||
|
||||
// load_archive — port of cmd/6l/obj.c:load_archive.
|
||||
//
|
||||
// Pass 1 indexes every regular member. Pass 2 iteratively pulls in any
|
||||
// member that supplies a currently-undefined symbol; each pull may
|
||||
// introduce fresh undefs, so we loop until quiescent.
|
||||
fn load_archive(l: *lnk, path_cs: *u8, buf: *u8, len: u64) i32 = {
|
||||
let head: *armember = nil;
|
||||
let tail: *armember = nil;
|
||||
let pos: u64 = 8u64; // past "!<arch>\n"
|
||||
for (pos + 60u64 <= len) {
|
||||
let hdr_size: u64 = ar_field(buf + pos + 48u64, 10u64);
|
||||
let hdr_end: u64 = pos + 60u64;
|
||||
if (hdr_end + hdr_size > len) { break; };
|
||||
let first: u8 = buf[pos];
|
||||
// Skip the symbol table ('/'), long-name table ('//'), and
|
||||
// any padding entries (NUL or space leading byte).
|
||||
if (first != 47u8) { if (first != 0u8) { if (first != 32u8) {
|
||||
let m: *armember = amalloc(l.a, 48u64): *armember;
|
||||
m.size = hdr_size;
|
||||
let mb: *u8 = amalloc(l.a, hdr_size): *u8;
|
||||
let i: u64 = 0u64;
|
||||
for (i < hdr_size) {
|
||||
mb[i] = buf[hdr_end + i];
|
||||
i += 1u64;
|
||||
};
|
||||
m.data = mb;
|
||||
m.defs = elf_globals(l.a, mb, hdr_size);
|
||||
m.loaded = 0;
|
||||
m.mnext = nil;
|
||||
if (head == nil) { head = m; }
|
||||
else { tail.mnext = m; };
|
||||
tail = m;
|
||||
}; }; };
|
||||
pos = hdr_end + hdr_size;
|
||||
if ((hdr_size & 1u64) != 0u64) { pos = pos + 1u64; };
|
||||
};
|
||||
|
||||
let changed: i32 = 1;
|
||||
for (changed != 0) {
|
||||
changed = 0;
|
||||
let m: *armember = head;
|
||||
for (m != nil) {
|
||||
if (m.loaded == 0) {
|
||||
if (member_defines_undef(l, m)) {
|
||||
if (load_image(l, path_cs, m.data, m.size) == 0) {
|
||||
m.loaded = 1;
|
||||
changed = 1;
|
||||
};
|
||||
};
|
||||
};
|
||||
m = m.mnext;
|
||||
};
|
||||
};
|
||||
return 0;
|
||||
};
|
||||
|
||||
// ---- main loader -------------------------------------------------------
|
||||
|
||||
export fn l_load(l: *lnk, path_cs: *u8) i32 = {
|
||||
let bufp: *u8;
|
||||
let buflen: u64;
|
||||
bufp, buflen = read_all(path_cs);
|
||||
if (bufp == nil) {
|
||||
os.write(2, "6l: cannot read object\n".ptr, 23u64);
|
||||
return -1;
|
||||
};
|
||||
if (is_archive(bufp, buflen)) {
|
||||
return load_archive(l, path_cs, bufp, buflen);
|
||||
};
|
||||
return load_image(l, path_cs, bufp, buflen);
|
||||
};
|
||||
|
||||
fn load_image(l: *lnk, path_cs: *u8, buf: *u8, len: u64) i32 = {
|
||||
if (len < EHDR_SIZE) { return -1; };
|
||||
// magic: 0x7f, 'E', 'L', 'F'
|
||||
if (buf[0u64] != 127u8) { return -1; };
|
||||
if (buf[1u64] != 69u8) { return -1; };
|
||||
if (buf[2u64] != 76u8) { return -1; };
|
||||
if (buf[3u64] != 70u8) { return -1; };
|
||||
if (buf[4u64] != 2u8) { return -1; }; // ELFCLASS64
|
||||
if (rd_u16(buf, EHDR_TYPE) != ET_REL: u16) { return -1; };
|
||||
if (rd_u16(buf, EHDR_MACHINE) != EM_X86_64: u16) { return -1; };
|
||||
|
||||
let shoff: u64 = rd_u64(buf, EHDR_SHOFF);
|
||||
let shnum: u32 = rd_u16(buf, EHDR_SHNUM): u32;
|
||||
let shstrndx: u32 = rd_u16(buf, EHDR_SHSTRNDX): u32;
|
||||
|
||||
let shstr_sh_off: u64 = rd_u64(buf, shoff + (shstrndx: u64) * SHDR_SIZE + SHDR_OFFSET);
|
||||
let shstr: *u8 = buf + shstr_sh_off;
|
||||
|
||||
// find .text, .symtab, .rela.text
|
||||
let idx_text: i32 = -1;
|
||||
let idx_symtab: i32 = -1;
|
||||
let idx_rela: i32 = -1;
|
||||
let i: u32 = 0u32;
|
||||
for (i < shnum) {
|
||||
let sh_off: u64 = shoff + (i: u64) * SHDR_SIZE;
|
||||
let sh_type: u32 = rd_u32(buf, sh_off + SHDR_TYPE);
|
||||
let sh_name: u32 = rd_u32(buf, sh_off + SHDR_NAME);
|
||||
let nm: *u8 = shstr + (sh_name: u64);
|
||||
if (sh_type == SHT_PROGBITS: u32) {
|
||||
if (cstr_eq(nm, ".text")) { idx_text = i: i32; };
|
||||
};
|
||||
if (sh_type == SHT_SYMTAB: u32) { idx_symtab = i: i32; };
|
||||
if (sh_type == SHT_RELA: u32) {
|
||||
if (cstr_eq(nm, ".rela.text")) { idx_rela = i: i32; };
|
||||
};
|
||||
i += 1u32;
|
||||
};
|
||||
if (idx_text < 0) {
|
||||
os.write(2, "6l: missing .text\n".ptr, 18u64);
|
||||
return -1;
|
||||
};
|
||||
if (idx_symtab < 0) {
|
||||
os.write(2, "6l: missing .symtab\n".ptr, 20u64);
|
||||
return -1;
|
||||
};
|
||||
|
||||
let text_sh: u64 = shoff + (idx_text: u64) * SHDR_SIZE;
|
||||
let text_off: u64 = rd_u64(buf, text_sh + SHDR_OFFSET);
|
||||
let text_size: u64 = rd_u64(buf, text_sh + SHDR_SIZE_F);
|
||||
|
||||
let sym_sh: u64 = shoff + (idx_symtab: u64) * SHDR_SIZE;
|
||||
let sym_off: u64 = rd_u64(buf, sym_sh + SHDR_OFFSET);
|
||||
let sym_size: u64 = rd_u64(buf, sym_sh + SHDR_SIZE_F);
|
||||
let sym_link: u32 = rd_u32(buf, sym_sh + SHDR_LINK);
|
||||
let nsyms: u64 = sym_size / SYM_SIZE;
|
||||
|
||||
let str_sh: u64 = shoff + (sym_link: u64) * SHDR_SIZE;
|
||||
let str_off: u64 = rd_u64(buf, str_sh + SHDR_OFFSET);
|
||||
let strtab: *u8 = buf + str_off;
|
||||
|
||||
// Track this object.
|
||||
let ob: *lobj = amalloc(l.a, 64u64): *lobj;
|
||||
ob.path = cstr_to_str(l.a, path_cs);
|
||||
ob.buf = buf;
|
||||
ob.len = len;
|
||||
ob.text_off = l.textlen;
|
||||
ob.text_size = text_size;
|
||||
ob.onext = l.objs;
|
||||
l.objs = ob;
|
||||
|
||||
// Append .text bytes to the combined image.
|
||||
emit_text(l, buf + text_off, text_size);
|
||||
|
||||
// Walk symbols. We don't keep a per-object map[] of *lsym. Instead
|
||||
// the reloc loop re-walks symtab and re-interns by name. Simpler
|
||||
// than dancing around the cgen's u64-shift gaps.
|
||||
let si: u64 = 1u64; // skip index 0 (always undef sentinel)
|
||||
for (si < nsyms) {
|
||||
let sym_p: u64 = sym_off + si * SYM_SIZE;
|
||||
let st_name: u32 = rd_u32(buf, sym_p + SYM_NAME);
|
||||
let st_shndx: u16 = rd_u16(buf, sym_p + SYM_SHNDX);
|
||||
let st_value: u64 = rd_u64(buf, sym_p + SYM_VALUE);
|
||||
let nm_p: *u8 = strtab + (st_name: u64);
|
||||
if (nm_p[0u64] != 0u8) {
|
||||
let nm: str = cstr_to_str(l.a, nm_p);
|
||||
let gs: *lsym = l_intern(l, nm);
|
||||
if (st_shndx != 0u16) {
|
||||
if ((st_shndx: i32) == idx_text) {
|
||||
if (gs.defined != 0) {
|
||||
os.write(2, "6l: duplicate symbol\n".ptr, 21u64);
|
||||
l.errs += 1;
|
||||
} else {
|
||||
gs.defined = 1;
|
||||
gs.owner = ob;
|
||||
gs.idx_in_owner = si: i32;
|
||||
gs.val = ob.text_off + st_value;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
si += 1u64;
|
||||
};
|
||||
|
||||
// Per-object relocation collection.
|
||||
if (idx_rela >= 0) {
|
||||
let rela_sh: u64 = shoff + (idx_rela: u64) * SHDR_SIZE;
|
||||
let rela_off: u64 = rd_u64(buf, rela_sh + SHDR_OFFSET);
|
||||
let rela_size: u64 = rd_u64(buf, rela_sh + SHDR_SIZE_F);
|
||||
let nrel: u64 = rela_size / RELA_SIZE;
|
||||
let ri: u64 = 0u64;
|
||||
for (ri < nrel) {
|
||||
let rp: u64 = rela_off + ri * RELA_SIZE;
|
||||
let r_off: u64 = rd_u64(buf, rp + RELA_OFFSET);
|
||||
let r_info: u64 = rd_u64(buf, rp + RELA_INFO);
|
||||
let r_addend: u64 = rd_u64(buf, rp + RELA_ADDEND);
|
||||
let r_sym_idx: u32 = (r_info >> 32u64): u32;
|
||||
let r_kind: i32 = ((r_info & 4294967295u64): u32): i32;
|
||||
let nr: *lrel = amalloc(l.a, 48u64): *lrel;
|
||||
nr.off = ob.text_off + r_off;
|
||||
nr.kind = r_kind;
|
||||
nr.addend = r_addend: i64;
|
||||
// Look up the referenced sym by name (re-walk symtab).
|
||||
if ((r_sym_idx: u64) < nsyms) {
|
||||
let s_p: u64 = sym_off + (r_sym_idx: u64) * SYM_SIZE;
|
||||
let s_name: u32 = rd_u32(buf, s_p + SYM_NAME);
|
||||
let s_nm: *u8 = strtab + (s_name: u64);
|
||||
if (s_nm[0u64] != 0u8) {
|
||||
let nm: str = cstr_to_str(l.a, s_nm);
|
||||
nr.sym = l_intern(l, nm);
|
||||
};
|
||||
};
|
||||
nr.rnext = l.rels;
|
||||
l.rels = nr;
|
||||
ri += 1u64;
|
||||
};
|
||||
};
|
||||
|
||||
return 0;
|
||||
};
|
||||
91
selfhost/cmd/6l/out.ww
Normal file
91
selfhost/cmd/6l/out.ww
Normal file
@@ -0,0 +1,91 @@
|
||||
// selfhost/cmd/6l/out.ww — port of cmd/6l/out.c.
|
||||
//
|
||||
// Emit a static ELF64 executable. File layout (per the C original):
|
||||
// [0..64) Ehdr
|
||||
// [64..120) Phdr (one PT_LOAD)
|
||||
// [120..0x1000) zero pad
|
||||
// [0x1000..) .text bytes
|
||||
// Single PT_LOAD covers the whole file, R+X. No interpreter, no .bss.
|
||||
|
||||
use os;
|
||||
use sym;
|
||||
|
||||
def ET_EXEC: u16 = 2u16;
|
||||
def EM_X86_64_W: u16 = 62u16;
|
||||
def EV_CURRENT: u32 = 1u32;
|
||||
def ELFCLASS64: u8 = 2u8;
|
||||
def ELFDATA2LSB: u8 = 1u8;
|
||||
def PT_LOAD: u32 = 1u32;
|
||||
def PF_X: u32 = 1u32;
|
||||
def PF_R: u32 = 4u32;
|
||||
|
||||
def TEXT_OFF: u64 = 4096u64; // 0x1000
|
||||
|
||||
// ---- little-endian byte writers ----------------------------------------
|
||||
|
||||
fn wr_u16(buf: *u8, off: u64, v: u16) void = {
|
||||
buf[off] = (v & 255u16): u8;
|
||||
buf[off + 1u64] = ((v >> 8u16) & 255u16): u8;
|
||||
};
|
||||
|
||||
fn wr_u32(buf: *u8, off: u64, v: u32) void = {
|
||||
buf[off] = (v & 255u32): u8;
|
||||
buf[off + 1u64] = ((v >> 8u32) & 255u32): u8;
|
||||
buf[off + 2u64] = ((v >> 16u32) & 255u32): u8;
|
||||
buf[off + 3u64] = ((v >> 24u32) & 255u32): u8;
|
||||
};
|
||||
|
||||
fn wr_u64(buf: *u8, off: u64, v: u64) void = {
|
||||
wr_u32(buf, off, (v & 4294967295u64): u32);
|
||||
wr_u32(buf, off + 4u64, ((v >> 32u64) & 4294967295u64): u32);
|
||||
};
|
||||
|
||||
// ---- emit ---------------------------------------------------------------
|
||||
|
||||
export fn l_emit_elf(l: *lnk, fd: i32, base: u64, entry: u64) i32 = {
|
||||
let filesz: u64 = TEXT_OFF + l.textlen;
|
||||
|
||||
// One contiguous header buffer covering [0..0x1000), then .text.
|
||||
let hdr: *u8 = os.alloc(TEXT_OFF): *u8; // zero-initialised by mmap
|
||||
|
||||
// --- Ehdr (64 bytes) ---
|
||||
hdr[0u64] = 127u8; // 0x7f
|
||||
hdr[1u64] = 69u8; // 'E'
|
||||
hdr[2u64] = 76u8; // 'L'
|
||||
hdr[3u64] = 70u8; // 'F'
|
||||
hdr[4u64] = ELFCLASS64;
|
||||
hdr[5u64] = ELFDATA2LSB;
|
||||
hdr[6u64] = EV_CURRENT: u8;
|
||||
wr_u16(hdr, 16u64, ET_EXEC); // e_type
|
||||
wr_u16(hdr, 18u64, EM_X86_64_W); // e_machine
|
||||
wr_u32(hdr, 20u64, EV_CURRENT); // e_version
|
||||
wr_u64(hdr, 24u64, entry); // e_entry
|
||||
wr_u64(hdr, 32u64, 64u64); // e_phoff = sizeof(Ehdr)
|
||||
wr_u64(hdr, 40u64, 0u64); // e_shoff
|
||||
wr_u32(hdr, 48u64, 0u32); // e_flags
|
||||
wr_u16(hdr, 52u64, 64u16); // e_ehsize
|
||||
wr_u16(hdr, 54u64, 56u16); // e_phentsize
|
||||
wr_u16(hdr, 56u64, 1u16); // e_phnum
|
||||
wr_u16(hdr, 58u64, 0u16); // e_shentsize
|
||||
wr_u16(hdr, 60u64, 0u16); // e_shnum
|
||||
wr_u16(hdr, 62u64, 0u16); // e_shstrndx
|
||||
|
||||
// --- Phdr (56 bytes) at offset 64 ---
|
||||
wr_u32(hdr, 64u64, PT_LOAD); // p_type
|
||||
wr_u32(hdr, 68u64, PF_R | PF_X); // p_flags
|
||||
wr_u64(hdr, 72u64, 0u64); // p_offset
|
||||
wr_u64(hdr, 80u64, base); // p_vaddr
|
||||
wr_u64(hdr, 88u64, base); // p_paddr
|
||||
wr_u64(hdr, 96u64, filesz); // p_filesz
|
||||
wr_u64(hdr, 104u64, filesz); // p_memsz
|
||||
wr_u64(hdr, 112u64, TEXT_OFF); // p_align
|
||||
|
||||
// Write [0..0x1000) then .text.
|
||||
let n1: i64 = os.writefull(fd, hdr, TEXT_OFF);
|
||||
if (n1 != TEXT_OFF: i64) { return -1; };
|
||||
if (l.textlen > 0u64) {
|
||||
let n2: i64 = os.writefull(fd, l.text, l.textlen);
|
||||
if (n2 != l.textlen: i64) { return -1; };
|
||||
};
|
||||
return 0;
|
||||
};
|
||||
64
selfhost/cmd/6l/pass.ww
Normal file
64
selfhost/cmd/6l/pass.ww
Normal file
@@ -0,0 +1,64 @@
|
||||
// selfhost/cmd/6l/pass.ww — port of cmd/6l/pass.c.
|
||||
//
|
||||
// Resolution + relocation. l_resolve flags every undefined symbol
|
||||
// referenced by a relocation. l_relocate walks the rel list and
|
||||
// patches the .text bytes in place once the final virtual base is
|
||||
// known. Supported relocation kinds: PC32 (=2), PLT32 (=4); both
|
||||
// are 32-bit PC-relative displacements (PLT32 == PC32 for static).
|
||||
|
||||
use os;
|
||||
use sym;
|
||||
|
||||
def R_X86_64_PC32: i32 = 2;
|
||||
def R_X86_64_PLT32: i32 = 4;
|
||||
|
||||
export fn l_resolve(l: *lnk) i32 = {
|
||||
let r: *lrel = l.rels;
|
||||
for (r != nil) {
|
||||
if (r.sym != nil) {
|
||||
if (r.sym.defined == 0) {
|
||||
os.write(2, "6l: undefined reference to '".ptr, 28u64);
|
||||
let nm: str = r.sym.name;
|
||||
os.write(2, nm.ptr, nm.len: u64);
|
||||
os.write(2, "'\n".ptr, 2u64);
|
||||
l.errs += 1;
|
||||
};
|
||||
};
|
||||
r = r.rnext;
|
||||
};
|
||||
return l.errs;
|
||||
};
|
||||
|
||||
fn patch_u32(p: *u8, v: u32) void = {
|
||||
p[0] = (v & 255u32): u8;
|
||||
p[1] = ((v >> 8u32) & 255u32): u8;
|
||||
p[2] = ((v >> 16u32) & 255u32): u8;
|
||||
p[3] = ((v >> 24u32) & 255u32): u8;
|
||||
};
|
||||
|
||||
export fn l_relocate(l: *lnk, base: u64) i32 = {
|
||||
let r: *lrel = l.rels;
|
||||
for (r != nil) {
|
||||
if (r.sym != nil) {
|
||||
if (r.sym.defined != 0) {
|
||||
let k: i32 = r.kind;
|
||||
if (k == R_X86_64_PC32) {
|
||||
let site: u64 = base + r.off;
|
||||
let target: i64 = (base + r.sym.val): i64;
|
||||
let rel: i64 = (target - site: i64) + r.addend;
|
||||
patch_u32(l.text + r.off, rel: u32);
|
||||
} else { if (k == R_X86_64_PLT32) {
|
||||
let site: u64 = base + r.off;
|
||||
let target: i64 = (base + r.sym.val): i64;
|
||||
let rel: i64 = (target - site: i64) + r.addend;
|
||||
patch_u32(l.text + r.off, rel: u32);
|
||||
} else {
|
||||
os.write(2, "6l: unsupported reloc kind\n".ptr, 27u64);
|
||||
l.errs += 1;
|
||||
};};
|
||||
};
|
||||
};
|
||||
r = r.rnext;
|
||||
};
|
||||
return l.errs;
|
||||
};
|
||||
75
selfhost/cmd/6l/sym.ww
Normal file
75
selfhost/cmd/6l/sym.ww
Normal file
@@ -0,0 +1,75 @@
|
||||
// selfhost/cmd/6l/sym.ww — port of cmd/6l/sym.c.
|
||||
//
|
||||
// Linker symbol table. Singly-linked list, usually a few hundred
|
||||
// entries; hashing isn't worth it yet.
|
||||
|
||||
use mem;
|
||||
|
||||
type lsym = struct {
|
||||
name: str,
|
||||
val: u64, // offset within combined .text once linked
|
||||
defined: i32, // 1 if some lobj defines this symbol
|
||||
owner: *lobj,
|
||||
idx_in_owner: i32,
|
||||
snext: *lsym,
|
||||
};
|
||||
|
||||
type lrel = struct {
|
||||
off: u64, // offset within combined .text
|
||||
kind: i32, // R_X86_64_*
|
||||
sym: *lsym,
|
||||
addend: i64,
|
||||
rnext: *lrel,
|
||||
};
|
||||
|
||||
type lobj = struct {
|
||||
path: str,
|
||||
buf: *u8, // object bytes
|
||||
len: u64,
|
||||
text_off: u64, // offset of .text in combined output
|
||||
text_size: u64,
|
||||
onext: *lobj,
|
||||
};
|
||||
|
||||
type lnk = struct {
|
||||
a: *arena,
|
||||
objs: *lobj,
|
||||
syms: *lsym,
|
||||
rels: *lrel,
|
||||
text: *u8, // combined .text
|
||||
textcap: u64,
|
||||
textlen: u64,
|
||||
errs: i32,
|
||||
};
|
||||
|
||||
fn streq(a: str, b: str) bool = {
|
||||
if (a.len != b.len) { return false; };
|
||||
let i: i32 = 0;
|
||||
for (i < a.len) {
|
||||
if (a[i] != b[i]) { return false; };
|
||||
i += 1;
|
||||
};
|
||||
return true;
|
||||
};
|
||||
|
||||
export fn l_intern(l: *lnk, name: str) *lsym = {
|
||||
let s: *lsym = l.syms;
|
||||
for (s != nil) {
|
||||
if (streq(s.name, name)) { return s; };
|
||||
s = s.snext;
|
||||
};
|
||||
let n: *lsym = amalloc(l.a, 64u64): *lsym;
|
||||
n.name = name;
|
||||
n.snext = l.syms;
|
||||
l.syms = n;
|
||||
return n;
|
||||
};
|
||||
|
||||
export fn l_lookup(l: *lnk, name: str) *lsym = {
|
||||
let s: *lsym = l.syms;
|
||||
for (s != nil) {
|
||||
if (streq(s.name, name)) { return s; };
|
||||
s = s.snext;
|
||||
};
|
||||
return nil;
|
||||
};
|
||||
975
selfhost/cmd/ww/main.combined.ww
Normal file
975
selfhost/cmd/ww/main.combined.ww
Normal file
@@ -0,0 +1,975 @@
|
||||
// os — process and filesystem facade. The body of each call lands
|
||||
// either in libwwrt.a (rt_syscall trampoline) or libc bindings,
|
||||
// depending on how the program was linked.
|
||||
|
||||
@symbol("rt_syscall") fn syscall0(num: i64) i64;
|
||||
@symbol("rt_syscall") fn syscall1(num: i64, a: i64) i64;
|
||||
@symbol("rt_syscall") fn syscall2(num: i64, a: i64, b: i64) i64;
|
||||
@symbol("rt_syscall") fn syscall3(num: i64, a: i64, b: i64, c: i64) i64;
|
||||
@symbol("rt_syscall") fn syscall4(num: i64, a: i64, b: i64, c: i64, d: i64) i64;
|
||||
|
||||
@symbol("rt_alloc") fn alloc(n: u64) *void;
|
||||
@symbol("rt_free") fn free(p: *void, n: u64) void;
|
||||
@symbol("rt_abort") fn abort(msg: str) void;
|
||||
|
||||
// Hare-style runtime check. Caller passes a message that's printed
|
||||
// to stderr before exit(1).
|
||||
export fn assert(cond: bool, msg: str) void = {
|
||||
if (!cond) { abort(msg); };
|
||||
};
|
||||
|
||||
def SYS_READ: i64 = 0;
|
||||
def SYS_WRITE: i64 = 1;
|
||||
def SYS_OPEN: i64 = 2;
|
||||
def SYS_CLOSE: i64 = 3;
|
||||
def SYS_LSEEK: i64 = 8;
|
||||
def SYS_ACCESS: i64 = 21;
|
||||
def SYS_GETPID: i64 = 39;
|
||||
def SYS_FORK: i64 = 57;
|
||||
def SYS_EXECVE: i64 = 59;
|
||||
def SYS_EXIT: i64 = 60;
|
||||
def SYS_WAIT4: i64 = 61;
|
||||
def SYS_UNLINK: i64 = 87;
|
||||
|
||||
// open(2) flags. Linux values, matching <fcntl.h>.
|
||||
def O_RDONLY: i32 = 0;
|
||||
def O_WRONLY: i32 = 1;
|
||||
def O_RDWR: i32 = 2;
|
||||
def O_CREAT: i32 = 64; // 0x40
|
||||
def O_TRUNC: i32 = 512; // 0x200
|
||||
|
||||
// lseek(2) whence.
|
||||
def SEEK_SET: i32 = 0;
|
||||
def SEEK_CUR: i32 = 1;
|
||||
def SEEK_END: i32 = 2;
|
||||
|
||||
export fn exit(code: i32) void = {
|
||||
syscall1(SYS_EXIT, code: i64);
|
||||
};
|
||||
|
||||
// Raw, non-fallible primitives. These return Linux's int conventions
|
||||
// (negative = -errno, non-negative = bytes/fd/etc). Callers wanting a
|
||||
// Hare-style fallible API use the wrappers below.
|
||||
export fn write(fd: i32, buf: *u8, n: u64) i64 = {
|
||||
return syscall3(SYS_WRITE, fd: i64, buf: i64, n: i64);
|
||||
};
|
||||
|
||||
export fn read(fd: i32, buf: *u8, n: u64) i64 = {
|
||||
return syscall3(SYS_READ, fd: i64, buf: i64, n: i64);
|
||||
};
|
||||
|
||||
export fn close(fd: i32) i32 = {
|
||||
return syscall1(SYS_CLOSE, fd: i64): i32;
|
||||
};
|
||||
|
||||
// Fallible wrappers. The error variant is a plain str (Plan 9 errstr
|
||||
// model, see lib/errors); the sum type makes success/failure explicit
|
||||
// without overloading length-zero.
|
||||
export fn tryread(fd: i32, buf: *u8, n: u64) (i64 | str) = {
|
||||
let r: i64 = read(fd, buf, n);
|
||||
if (r < 0) { return "read failed"; };
|
||||
return r;
|
||||
};
|
||||
|
||||
export fn trywrite(fd: i32, buf: *u8, n: u64) (i64 | str) = {
|
||||
let r: i64 = write(fd, buf, n);
|
||||
if (r < 0) { return "write failed"; };
|
||||
return r;
|
||||
};
|
||||
|
||||
// open — Linux open(2). Path must be NUL-terminated; callers using ww
|
||||
// `str` must ensure the bytes are followed by a 0 byte (literals are,
|
||||
// arena-copied paths usually are by construction). Returns -errno on
|
||||
// failure, fd otherwise. Higher-level callers prefer `tryopen`.
|
||||
export fn open(path: *u8, flags: i32, mode: i32) i32 = {
|
||||
return syscall3(SYS_OPEN, path: i64, flags: i64, mode: i64): i32;
|
||||
};
|
||||
|
||||
export fn tryopen(path: *u8, flags: i32, mode: i32) (i32 | str) = {
|
||||
let fd: i32 = open(path, flags, mode);
|
||||
if (fd < 0) { return "open failed"; };
|
||||
return fd;
|
||||
};
|
||||
|
||||
// lseek — set/inspect the fd's position. Returns the new offset or
|
||||
// a negative errno. We use this for fstat-free file-size discovery
|
||||
// (open ⇒ lseek to end ⇒ lseek back).
|
||||
export fn lseek(fd: i32, off: i64, whence: i32) i64 = {
|
||||
return syscall3(SYS_LSEEK, fd: i64, off, whence: i64);
|
||||
};
|
||||
|
||||
// filesize — convenience: returns the byte length of an open fd by
|
||||
// seeking to the end and back. -1 on error.
|
||||
export fn filesize(fd: i32) i64 = {
|
||||
let end: i64 = lseek(fd, 0i64, SEEK_END);
|
||||
if (end < 0) { return -1i64; };
|
||||
let r: i64 = lseek(fd, 0i64, SEEK_SET);
|
||||
if (r < 0) { return -1i64; };
|
||||
return end;
|
||||
};
|
||||
|
||||
// readfull — keep reading until `n` bytes have arrived or the fd
|
||||
// closes early. Returns bytes read (0..=n) or -1 on read error.
|
||||
export fn readfull(fd: i32, buf: *u8, n: u64) i64 = {
|
||||
let got: u64 = 0u64;
|
||||
for (got < n) {
|
||||
let r: i64 = read(fd, buf + got, n - got);
|
||||
if (r < 0) { return -1i64; };
|
||||
if (r == 0) { return got: i64; }; // short read: caller decides
|
||||
got += r: u64;
|
||||
};
|
||||
return got: i64;
|
||||
};
|
||||
|
||||
// writefull — keep writing until `n` bytes have been accepted or the
|
||||
// fd refuses progress. Returns bytes written or -1.
|
||||
export fn writefull(fd: i32, buf: *u8, n: u64) i64 = {
|
||||
let sent: u64 = 0u64;
|
||||
for (sent < n) {
|
||||
let r: i64 = write(fd, buf + sent, n - sent);
|
||||
if (r < 0) { return -1i64; };
|
||||
if (r == 0) { return sent: i64; };
|
||||
sent += r: u64;
|
||||
};
|
||||
return sent: i64;
|
||||
};
|
||||
|
||||
// ---- process and filesystem helpers used by the `ww` driver ----------
|
||||
|
||||
// access(2): returns 0 if the file is reachable, negative errno
|
||||
// otherwise. mode is the bitset described in <unistd.h> (F_OK=0).
|
||||
export fn access(path: *u8, mode: i32) i32 = {
|
||||
return syscall2(SYS_ACCESS, path: i64, mode: i64): i32;
|
||||
};
|
||||
|
||||
// unlink(2).
|
||||
export fn unlink(path: *u8) i32 = {
|
||||
return syscall1(SYS_UNLINK, path: i64): i32;
|
||||
};
|
||||
|
||||
// getpid(2). Used by the driver to mint unique scratch paths.
|
||||
export fn getpid() i32 = {
|
||||
return syscall0(SYS_GETPID): i32;
|
||||
};
|
||||
|
||||
// fork(2): 0 in the child, child pid in the parent, negative errno
|
||||
// on failure.
|
||||
export fn fork() i32 = {
|
||||
return syscall0(SYS_FORK): i32;
|
||||
};
|
||||
|
||||
// execve(2): on success, does not return.
|
||||
export fn execve(path: *u8, argv: **u8, envp: **u8) i32 = {
|
||||
return syscall3(SYS_EXECVE, path: i64, argv: i64, envp: i64): i32;
|
||||
};
|
||||
|
||||
// wait4(2): wait for `pid` (or any child if -1), store status in
|
||||
// `*status_out`, return the pid that ended (or negative errno).
|
||||
export fn wait4(pid: i32, status_out: *i32, options: i32, rusage: *void) i32 = {
|
||||
return syscall4(SYS_WAIT4, pid: i64, status_out: i64,
|
||||
options: i64, rusage: i64): i32;
|
||||
};
|
||||
|
||||
// selfhost/cmd/wwc/mem.ww — port of cmd/wwc/mem.c.
|
||||
//
|
||||
// Bump arena allocator. Backed by the runtime page allocator
|
||||
// (rt_alloc / rt_free), no libc. Each chunk is mmap'd; when the
|
||||
// current chunk runs out we link a fresh one. Freeing the arena
|
||||
// unmaps the chain.
|
||||
//
|
||||
// Memory handed out is 16-byte aligned. The C version under
|
||||
// cmd/wwc/ is retained until the three-stage bootstrap diffs clean.
|
||||
|
||||
use os;
|
||||
|
||||
def ALIGN: u64 = 16u64;
|
||||
def INIT_CHUNK: u64 = 65536u64;
|
||||
def MAX_CHUNK: u64 = 4194304u64;
|
||||
def ARENA_SZ: u64 = 48u64; // sizeof(arena), kept in sync below
|
||||
|
||||
type arena = struct {
|
||||
buf: *u8,
|
||||
off: u64,
|
||||
cap: u64,
|
||||
next: *arena,
|
||||
total: u64,
|
||||
};
|
||||
|
||||
fn roundup(n: u64, a: u64) u64 = {
|
||||
return (n + a - 1u64) & ~(a - 1u64);
|
||||
};
|
||||
|
||||
export fn newarena() *arena = {
|
||||
let a: *arena = os.alloc(ARENA_SZ): *arena;
|
||||
a.buf = os.alloc(INIT_CHUNK): *u8;
|
||||
a.off = 0u64;
|
||||
a.cap = INIT_CHUNK;
|
||||
a.next = nil;
|
||||
a.total = 0u64;
|
||||
return a;
|
||||
};
|
||||
|
||||
// Grow: link a fresh chunk in front of the head. We push the old
|
||||
// chunk into `next` so the head always describes the current bump
|
||||
// region. Chunk size doubles up to MAX_CHUNK.
|
||||
fn grow(a: *arena, need: u64) bool = {
|
||||
let want: u64 = a.cap * 2u64;
|
||||
if (want < need) { want = need; };
|
||||
if (want > MAX_CHUNK) { want = MAX_CHUNK; };
|
||||
if (want < need) { return false; }; // single allocation too big
|
||||
|
||||
let old: *arena = os.alloc(ARENA_SZ): *arena;
|
||||
old.buf = a.buf;
|
||||
old.off = a.off;
|
||||
old.cap = a.cap;
|
||||
old.next = a.next;
|
||||
old.total = 0u64;
|
||||
|
||||
a.buf = os.alloc(want): *u8;
|
||||
a.off = 0u64;
|
||||
a.cap = want;
|
||||
a.next = old;
|
||||
return true;
|
||||
};
|
||||
|
||||
export fn amalloc(a: *arena, n: u64) *void = {
|
||||
let need: u64 = roundup(n, ALIGN);
|
||||
if (need > a.cap - a.off) {
|
||||
if (!grow(a, need)) { return nil; };
|
||||
};
|
||||
let p: *u8 = a.buf + a.off;
|
||||
a.off += need;
|
||||
a.total += need;
|
||||
// Zero the region. Plan 9 amalloc zeroes; we mirror that here so
|
||||
// the checker can assume freshly allocated nodes start at 0.
|
||||
let i: u64 = 0u64;
|
||||
for (i < need) {
|
||||
p[i] = 0u8;
|
||||
i += 1u64;
|
||||
};
|
||||
return p: *void;
|
||||
};
|
||||
|
||||
// astrndup — copy `n` bytes into the arena and produce a NUL-terminated
|
||||
// view. Returns a `str` whose ptr is arena-owned and whose len is `n`
|
||||
// (the trailing NUL is past `len`, so callers reading exactly n bytes
|
||||
// see no padding). Used by the lexer to capture token text.
|
||||
export fn astrndup(a: *arena, src: *u8, n: u64) str = {
|
||||
let p: *u8 = amalloc(a, n + 1u64): *u8;
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
p[i] = src[i];
|
||||
i += 1u64;
|
||||
};
|
||||
p[n] = 0u8;
|
||||
let r: str;
|
||||
r.ptr = p;
|
||||
r.len = n: i32;
|
||||
return r;
|
||||
};
|
||||
|
||||
export fn freearena(a: *arena) void = {
|
||||
for (a != nil) {
|
||||
let next: *arena = a.next;
|
||||
os.free(a.buf: *void, a.cap);
|
||||
os.free(a: *void, ARENA_SZ);
|
||||
a = next;
|
||||
};
|
||||
};
|
||||
|
||||
// selfhost/cmd/ww/main.ww — port of cmd/ww/main.c.
|
||||
//
|
||||
// The user-facing driver. Plan 9 cc(1) / Hare hare(1) analogue:
|
||||
//
|
||||
// ww build foo.ww → 6c foo.ww > foo.s ; 6a foo.s > foo.o ;
|
||||
// 6l -o foo foo.o libwwrt.a
|
||||
// ww run foo.ww → build then exec
|
||||
// ww version → print version
|
||||
//
|
||||
// Tool paths default to siblings of $0 so a fresh build runs out of
|
||||
// out/bin/. Env-var overrides (WW_6C / WW_6A / WW_6L / WW_LIB) are
|
||||
// not yet supported in this port; the bootstrap doesn't need them.
|
||||
|
||||
use os;
|
||||
use mem;
|
||||
|
||||
// All path/string scratch buffers go on the runtime page allocator.
|
||||
// One page is plenty for any path we build.
|
||||
def PATH_MAX: u64 = 4096u64;
|
||||
def CMD_MAX: u64 = 8192u64;
|
||||
|
||||
// ---- C-string helpers --------------------------------------------------
|
||||
|
||||
fn cstrlen(p: *u8) u64 = {
|
||||
let n: u64 = 0u64;
|
||||
for (p[n] != 0u8) { n += 1u64; };
|
||||
return n;
|
||||
};
|
||||
|
||||
fn cstreq(a: *u8, b: *u8) bool = {
|
||||
let i: u64 = 0u64;
|
||||
for (a[i] == b[i]) {
|
||||
if (a[i] == 0u8) { return true; };
|
||||
i += 1u64;
|
||||
};
|
||||
return false;
|
||||
};
|
||||
|
||||
// cstreq_lit — compare a NUL-terminated *u8 to a ww string literal.
|
||||
fn cstreq_lit(a: *u8, lit: str) bool = {
|
||||
let n: i32 = lit.len;
|
||||
let i: i32 = 0;
|
||||
for (i < n) {
|
||||
if (a[i] != lit[i]) { return false; };
|
||||
i += 1;
|
||||
};
|
||||
return a[n] == 0u8;
|
||||
};
|
||||
|
||||
// startswith — does a have b as a prefix?
|
||||
fn cstr_startswith(a: *u8, b: *u8) bool = {
|
||||
let i: u64 = 0u64;
|
||||
for (b[i] != 0u8) {
|
||||
if (a[i] != b[i]) { return false; };
|
||||
i += 1u64;
|
||||
};
|
||||
return true;
|
||||
};
|
||||
|
||||
// memcpy
|
||||
fn bytecpy(dst: *u8, src: *u8, n: u64) void = {
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
dst[i] = src[i];
|
||||
i += 1u64;
|
||||
};
|
||||
};
|
||||
|
||||
// Copy a NUL-terminated *u8 into dst starting at off; return the new
|
||||
// offset (without writing a NUL).
|
||||
fn cstr_into(dst: *u8, off: u64, src: *u8) u64 = {
|
||||
let i: u64 = 0u64;
|
||||
for (src[i] != 0u8) {
|
||||
dst[off + i] = src[i];
|
||||
i += 1u64;
|
||||
};
|
||||
return off + i;
|
||||
};
|
||||
|
||||
// Same, but for a ww `str` (no NUL on the source side; we copy len bytes).
|
||||
fn str_into(dst: *u8, off: u64, src: str) u64 = {
|
||||
let n: i32 = src.len;
|
||||
let i: i32 = 0;
|
||||
for (i < n) {
|
||||
let iu: u64 = i: u64;
|
||||
dst[off + iu] = src[i];
|
||||
i += 1;
|
||||
};
|
||||
let nu: u64 = n: u64;
|
||||
return off + nu;
|
||||
};
|
||||
|
||||
// Write a single byte, return new offset.
|
||||
fn byte_into(dst: *u8, off: u64, c: u8) u64 = {
|
||||
dst[off] = c;
|
||||
return off + 1u64;
|
||||
};
|
||||
|
||||
// NUL-terminate at off and return the same off (handy when passing the
|
||||
// buffer to a syscall that expects a C-string).
|
||||
fn cstr_seal(dst: *u8, off: u64) void = {
|
||||
dst[off] = 0u8;
|
||||
};
|
||||
|
||||
// ---- Tool-path resolution ---------------------------------------------
|
||||
|
||||
// dirname-equivalent: copy argv[0] up to (but not including) the last
|
||||
// '/' into dst, NUL-terminated. If no slash, write ".".
|
||||
fn self_dir_into(dst: *u8, dstsz: u64, argv0: *u8) void = {
|
||||
let n: u64 = cstrlen(argv0);
|
||||
let cut: u64 = 0u64;
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
if (argv0[i] == 47u8) { cut = i; }; // '/'
|
||||
i += 1u64;
|
||||
};
|
||||
if (cut == 0u64) {
|
||||
dst[0u64] = 46u8; // '.'
|
||||
dst[1u64] = 0u8;
|
||||
return;
|
||||
};
|
||||
if (cut + 1u64 >= dstsz) { cut = dstsz - 2u64; };
|
||||
bytecpy(dst, argv0, cut);
|
||||
dst[cut] = 0u8;
|
||||
};
|
||||
|
||||
// Build "$dir/$name" (NUL-terminated) into a fresh page-sized buffer.
|
||||
fn join_path(dir: *u8, name: *u8) *u8 = {
|
||||
let buf: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
let off: u64 = cstr_into(buf, 0u64, dir);
|
||||
off = byte_into(buf, off, 47u8);
|
||||
off = cstr_into(buf, off, name);
|
||||
cstr_seal(buf, off);
|
||||
return buf;
|
||||
};
|
||||
|
||||
// Same, but the second component is a ww `str` literal.
|
||||
fn join_path_lit(dir: *u8, name: str) *u8 = {
|
||||
let buf: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
let off: u64 = cstr_into(buf, 0u64, dir);
|
||||
off = byte_into(buf, off, 47u8);
|
||||
off = str_into(buf, off, name);
|
||||
cstr_seal(buf, off);
|
||||
return buf;
|
||||
};
|
||||
|
||||
// ---- Subprocess plumbing ----------------------------------------------
|
||||
|
||||
// proc_run — fork, execve `path` with `argv` (NULL-terminated), wait.
|
||||
// Returns 0 on clean exit-0, 1 on any non-zero exit or signal kill,
|
||||
// -1 on fork/wait failure.
|
||||
fn proc_run(path: *u8, argv: **u8) i32 = {
|
||||
let pid: i32 = os.fork();
|
||||
if (pid < 0) {
|
||||
os.write(2, "ww: fork failed\n".ptr, 16u64);
|
||||
return -1;
|
||||
};
|
||||
if (pid == 0) {
|
||||
os.execve(path, argv, nil: **u8);
|
||||
os.write(2, "ww: execve failed\n".ptr, 18u64);
|
||||
os.exit(127);
|
||||
};
|
||||
let status: i32 = 0;
|
||||
let r: i32 = os.wait4(pid, &status, 0i32, nil: *void);
|
||||
if (r < 0) {
|
||||
os.write(2, "ww: wait4 failed\n".ptr, 17u64);
|
||||
return -1;
|
||||
};
|
||||
// Linux wait status: low byte = signal (0 if exited cleanly),
|
||||
// next byte = exit code.
|
||||
if ((status & 127i32) != 0) { return 1; };
|
||||
let code: i32 = (status >> 8i32) & 255i32;
|
||||
if (code != 0) { return 1; };
|
||||
return 0;
|
||||
};
|
||||
|
||||
// ---- `use` resolution + source concatenation --------------------------
|
||||
//
|
||||
// Recursive expansion: for each `use IDENT;` we find at the top of
|
||||
// `path`, resolve via the colon-separated `dirs`, expand the imported
|
||||
// file first, then append our own bytes. Already-visited paths are
|
||||
// skipped (linear scan; typical builds visit a handful of modules).
|
||||
|
||||
type strnode = struct {
|
||||
s: str,
|
||||
snext: *strnode,
|
||||
};
|
||||
|
||||
type expctx = struct {
|
||||
a: *arena, // arena for path strings + the visited list
|
||||
out: i32, // fd we're writing the combined source to
|
||||
dirs: *u8, // ":"-separated search path (NUL-terminated)
|
||||
visit: *strnode,
|
||||
};
|
||||
|
||||
fn visit_seen(c: *expctx, path: str) bool = {
|
||||
let n: *strnode = c.visit;
|
||||
for (n != nil) {
|
||||
if (n.s.len == path.len) {
|
||||
let i: i32 = 0;
|
||||
let eq: bool = true;
|
||||
for (i < path.len) {
|
||||
if (n.s[i] != path[i]) { eq = false; i = path.len; }
|
||||
else { i += 1; };
|
||||
};
|
||||
if (eq) { return true; };
|
||||
};
|
||||
n = n.snext;
|
||||
};
|
||||
return false;
|
||||
};
|
||||
|
||||
fn visit_add(c: *expctx, path: str) void = {
|
||||
let n: *strnode = amalloc(c.a, 32u64): *strnode;
|
||||
n.s = path;
|
||||
n.snext = c.visit;
|
||||
c.visit = n;
|
||||
};
|
||||
|
||||
// Try <dir>/<name>.ww then <dir>/<name>/<name>.ww. Returns NUL-terminated
|
||||
// arena-resident path if found, else nil.
|
||||
fn locate_in(a: *arena, dir: *u8, dir_len: u64, name: *u8, name_len: u64) *u8 = {
|
||||
// candidate 1: <dir>/<name>.ww
|
||||
let buf: *u8 = amalloc(a, PATH_MAX): *u8;
|
||||
let off: u64 = 0u64;
|
||||
let i: u64 = 0u64;
|
||||
for (i < dir_len) { buf[off + i] = dir[i]; i += 1u64; };
|
||||
off += dir_len;
|
||||
buf[off] = 47u8; off += 1u64; // '/'
|
||||
i = 0u64;
|
||||
for (i < name_len) { buf[off + i] = name[i]; i += 1u64; };
|
||||
off += name_len;
|
||||
buf[off] = 46u8; off += 1u64; // '.'
|
||||
buf[off] = 119u8; off += 1u64; // 'w'
|
||||
buf[off] = 119u8; off += 1u64; // 'w'
|
||||
buf[off] = 0u8;
|
||||
if (os.access(buf, 0i32) == 0) { return buf; };
|
||||
|
||||
// candidate 2: <dir>/<name>/<name>.ww
|
||||
let buf2: *u8 = amalloc(a, PATH_MAX): *u8;
|
||||
off = 0u64;
|
||||
i = 0u64;
|
||||
for (i < dir_len) { buf2[off + i] = dir[i]; i += 1u64; };
|
||||
off += dir_len;
|
||||
buf2[off] = 47u8; off += 1u64;
|
||||
i = 0u64;
|
||||
for (i < name_len) { buf2[off + i] = name[i]; i += 1u64; };
|
||||
off += name_len;
|
||||
buf2[off] = 47u8; off += 1u64;
|
||||
i = 0u64;
|
||||
for (i < name_len) { buf2[off + i] = name[i]; i += 1u64; };
|
||||
off += name_len;
|
||||
buf2[off] = 46u8; off += 1u64;
|
||||
buf2[off] = 119u8; off += 1u64;
|
||||
buf2[off] = 119u8; off += 1u64;
|
||||
buf2[off] = 0u8;
|
||||
if (os.access(buf2, 0i32) == 0) { return buf2; };
|
||||
return nil;
|
||||
};
|
||||
|
||||
// Walk a colon-separated dirlist, return first hit or nil.
|
||||
fn locate_import(a: *arena, dirs: *u8, name: *u8, name_len: u64) *u8 = {
|
||||
let total: u64 = cstrlen(dirs);
|
||||
let p: u64 = 0u64;
|
||||
for (p < total) {
|
||||
let q: u64 = p;
|
||||
for (q < total) {
|
||||
if (dirs[q] == 58u8) { break; }; // ':'
|
||||
q += 1u64;
|
||||
};
|
||||
let seg_len: u64 = q - p;
|
||||
if (seg_len > 0u64) {
|
||||
let hit: *u8 = locate_in(a, dirs + p, seg_len, name, name_len);
|
||||
if (hit != nil) { return hit; };
|
||||
};
|
||||
p = q + 1u64;
|
||||
};
|
||||
return nil;
|
||||
};
|
||||
|
||||
// ---- file slurp -------------------------------------------------------
|
||||
|
||||
fn read_all(path_cs: *u8) (*u8, u64) = {
|
||||
let fd: i32 = os.open(path_cs, os.O_RDONLY, 0i32);
|
||||
if (fd < 0) { return nil, 0u64; };
|
||||
let n: i64 = os.filesize(fd);
|
||||
if (n < 0i64) { os.close(fd); return nil, 0u64; };
|
||||
let nu: u64 = n: u64;
|
||||
let buf: *u8 = os.alloc(nu + 1u64): *u8;
|
||||
let got: i64 = os.readfull(fd, buf, nu);
|
||||
os.close(fd);
|
||||
if (got != n) { return nil, 0u64; };
|
||||
buf[nu] = 0u8;
|
||||
return buf, nu;
|
||||
};
|
||||
|
||||
fn is_ident_byte(c: u8) bool = {
|
||||
if (c >= 97u8) { if (c <= 122u8) { return true; }; }; // a..z
|
||||
if (c >= 65u8) { if (c <= 90u8) { return true; }; }; // A..Z
|
||||
if (c >= 48u8) { if (c <= 57u8) { return true; }; }; // 0..9
|
||||
if (c == 95u8) { return true; }; // _
|
||||
if (c == 46u8) { return true; }; // .
|
||||
return false;
|
||||
};
|
||||
|
||||
// Scan one `use IDENT;` line out of [start, end). Returns the start of
|
||||
// the ident and its length, or (nil, 0) if no `use` here. The caller
|
||||
// passes a slice of the source: src points at the line start.
|
||||
fn scan_use(src: *u8, len: u64) (*u8, u64) = {
|
||||
let i: u64 = 0u64;
|
||||
// skip leading whitespace
|
||||
for (i < len) {
|
||||
if (src[i] != 32u8) { if (src[i] != 9u8) { break; }; };
|
||||
i += 1u64;
|
||||
};
|
||||
if (i + 4u64 > len) { return nil, 0u64; };
|
||||
if (src[i] != 117u8) { return nil, 0u64; }; // 'u'
|
||||
if (src[i + 1u64] != 115u8) { return nil, 0u64; }; // 's'
|
||||
if (src[i + 2u64] != 101u8) { return nil, 0u64; }; // 'e'
|
||||
let sep: u8 = src[i + 3u64];
|
||||
if (sep != 32u8) { if (sep != 9u8) { return nil, 0u64; }; };
|
||||
i += 4u64;
|
||||
for (i < len) {
|
||||
if (src[i] != 32u8) { if (src[i] != 9u8) { break; }; };
|
||||
i += 1u64;
|
||||
};
|
||||
let id_start: u64 = i;
|
||||
for (i < len) {
|
||||
if (!is_ident_byte(src[i])) { break; };
|
||||
i += 1u64;
|
||||
};
|
||||
let id_len: u64 = i - id_start;
|
||||
if (id_len == 0u64) { return nil, 0u64; };
|
||||
return src + id_start, id_len;
|
||||
};
|
||||
|
||||
// Recursively expand `path` into c.out. Imported files are emitted
|
||||
// before their importer; cycles are broken via the visited set.
|
||||
fn expand(c: *expctx, path_cs: *u8) void = {
|
||||
let plen: u64 = cstrlen(path_cs);
|
||||
let path_str: str = astrndup(c.a, path_cs, plen);
|
||||
if (visit_seen(c, path_str)) { return; };
|
||||
visit_add(c, path_str);
|
||||
|
||||
let bufp: *u8;
|
||||
let blen: u64;
|
||||
bufp, blen = read_all(path_cs);
|
||||
if (bufp == nil) {
|
||||
os.write(2, "ww: cannot read source\n".ptr, 23u64);
|
||||
return;
|
||||
};
|
||||
|
||||
// Pass 1: scan top-of-file `use X;` lines, recursively expand.
|
||||
let i: u64 = 0u64;
|
||||
for (i < blen) {
|
||||
// Find the end of the current line.
|
||||
let j: u64 = i;
|
||||
for (j < blen) {
|
||||
if (bufp[j] == 10u8) { break; }; // '\n'
|
||||
j += 1u64;
|
||||
};
|
||||
let id_p: *u8;
|
||||
let id_n: u64;
|
||||
id_p, id_n = scan_use(bufp + i, j - i);
|
||||
if (id_p != nil) {
|
||||
let ipath: *u8 = locate_import(c.a, c.dirs, id_p, id_n);
|
||||
if (ipath != nil) {
|
||||
expand(c, ipath);
|
||||
};
|
||||
};
|
||||
i = j + 1u64;
|
||||
};
|
||||
|
||||
// Pass 2: emit our own bytes, then a trailing newline.
|
||||
os.writefull(c.out, bufp, blen);
|
||||
os.writefull(c.out, "\n".ptr, 1u64);
|
||||
};
|
||||
|
||||
// ---- Build pipeline ---------------------------------------------------
|
||||
|
||||
// Strip the trailing ".ww" off `src` (a NUL-terminated path) into
|
||||
// `stem`, NUL-terminated. If there's no .ww, the stem is the whole
|
||||
// path.
|
||||
fn make_stem(stem: *u8, src: *u8) void = {
|
||||
let n: u64 = cstrlen(src);
|
||||
let stop: u64 = n;
|
||||
if (n >= 3u64) {
|
||||
if (src[n - 3u64] == 46u8) { // '.'
|
||||
if (src[n - 2u64] == 119u8) { // 'w'
|
||||
if (src[n - 1u64] == 119u8) { // 'w'
|
||||
stop = n - 3u64;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
let i: u64 = 0u64;
|
||||
for (i < stop) { stem[i] = src[i]; i += 1u64; };
|
||||
stem[stop] = 0u8;
|
||||
};
|
||||
|
||||
// Append a literal suffix to `stem` (which already lives in a buffer).
|
||||
fn append_lit(stem: *u8, suffix: str) *u8 = {
|
||||
let buf: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
let off: u64 = cstr_into(buf, 0u64, stem);
|
||||
off = str_into(buf, off, suffix);
|
||||
cstr_seal(buf, off);
|
||||
return buf;
|
||||
};
|
||||
|
||||
// build_one — compile `src` into the executable named `out`.
|
||||
// self_dir: NUL-terminated dir containing this driver (and 6c/6a/6l)
|
||||
// src: NUL-terminated path to the .ww file
|
||||
// out: NUL-terminated desired output path
|
||||
// incs: NUL-terminated colon-list of -I dirs (may be empty)
|
||||
fn build_one(self_dir: *u8, src: *u8, out: *u8, incs: *u8) i32 = {
|
||||
let a: *arena = newarena();
|
||||
|
||||
let c6: *u8 = join_path_lit(self_dir, "6c");
|
||||
let a6: *u8 = join_path_lit(self_dir, "6a");
|
||||
let l6: *u8 = join_path_lit(self_dir, "6l");
|
||||
|
||||
// Default lib search path: <self_dir>/../../lib
|
||||
let dotdot_lib: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
{
|
||||
let off: u64 = cstr_into(dotdot_lib, 0u64, self_dir);
|
||||
off = str_into(dotdot_lib, off, "/../../lib");
|
||||
cstr_seal(dotdot_lib, off);
|
||||
};
|
||||
|
||||
// Compose searchpath: incs + ':' + dotdot_lib (or just dotdot_lib).
|
||||
let searchpath: *u8 = os.alloc(PATH_MAX * 2u64): *u8;
|
||||
{
|
||||
let off: u64 = 0u64;
|
||||
if (incs[0u64] != 0u8) {
|
||||
off = cstr_into(searchpath, off, incs);
|
||||
off = byte_into(searchpath, off, 58u8); // ':'
|
||||
};
|
||||
off = cstr_into(searchpath, off, dotdot_lib);
|
||||
cstr_seal(searchpath, off);
|
||||
};
|
||||
|
||||
// stem, .s, .o, .combined.ww, libwwrt.a
|
||||
let stem: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
make_stem(stem, src);
|
||||
let asmf: *u8 = append_lit(stem, ".s");
|
||||
let objf: *u8 = append_lit(stem, ".o");
|
||||
let combined: *u8 = append_lit(stem, ".combined.ww");
|
||||
|
||||
// libwwrt.a path: <self_dir>/../lib/libwwrt.a
|
||||
let libwwrt: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
{
|
||||
let off: u64 = cstr_into(libwwrt, 0u64, self_dir);
|
||||
off = str_into(libwwrt, off, "/../lib/libwwrt.a");
|
||||
cstr_seal(libwwrt, off);
|
||||
};
|
||||
|
||||
// Step 1: expand `use`s into the combined file.
|
||||
let cf: i32 = os.open(combined, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 420i32); // 0o644
|
||||
if (cf < 0) {
|
||||
os.write(2, "ww: cannot open combined\n".ptr, 25u64);
|
||||
return 1;
|
||||
};
|
||||
{
|
||||
let c: expctx;
|
||||
c.a = a;
|
||||
c.out = cf;
|
||||
c.dirs = searchpath;
|
||||
c.visit = nil;
|
||||
expand(&c, src);
|
||||
};
|
||||
os.close(cf);
|
||||
|
||||
// Step 2: 6c -o <stem>.s <stem>.combined.ww
|
||||
{
|
||||
let argv: **u8 = os.alloc(40u64): **u8;
|
||||
argv[0] = "6c\0".ptr;
|
||||
argv[1] = "-o\0".ptr;
|
||||
argv[2] = asmf;
|
||||
argv[3] = combined;
|
||||
argv[4] = nil;
|
||||
if (proc_run(c6, argv) != 0) {
|
||||
os.write(2, "ww: 6c failed\n".ptr, 14u64);
|
||||
return 1;
|
||||
};
|
||||
};
|
||||
|
||||
// Step 3: 6a -o <stem>.o <stem>.s
|
||||
{
|
||||
let argv: **u8 = os.alloc(40u64): **u8;
|
||||
argv[0] = "6a\0".ptr;
|
||||
argv[1] = "-o\0".ptr;
|
||||
argv[2] = objf;
|
||||
argv[3] = asmf;
|
||||
argv[4] = nil;
|
||||
if (proc_run(a6, argv) != 0) {
|
||||
os.write(2, "ww: 6a failed\n".ptr, 14u64);
|
||||
return 1;
|
||||
};
|
||||
};
|
||||
|
||||
// Step 4: 6l -o <out> <stem>.o libwwrt.a
|
||||
{
|
||||
let argv: **u8 = os.alloc(48u64): **u8;
|
||||
argv[0] = "6l\0".ptr;
|
||||
argv[1] = "-o\0".ptr;
|
||||
argv[2] = out;
|
||||
argv[3] = objf;
|
||||
argv[4] = libwwrt;
|
||||
argv[5] = nil;
|
||||
if (proc_run(l6, argv) != 0) {
|
||||
os.write(2, "ww: 6l failed\n".ptr, 14u64);
|
||||
return 1;
|
||||
};
|
||||
};
|
||||
return 0;
|
||||
};
|
||||
|
||||
// ---- Subcommand handlers ----------------------------------------------
|
||||
|
||||
fn write_usage(fd: i32) void = {
|
||||
let s: str = "usage: ww [-V] <subcommand> [args...]\n -V print version and exit\n build <path> compile module to a static binary\n run <path> build then exec\n version print version and exit\n";
|
||||
os.write(fd, s.ptr, s.len: u64);
|
||||
};
|
||||
|
||||
fn do_version() i32 = {
|
||||
os.write(1, "ww 0.0\n".ptr, 7u64);
|
||||
return 0;
|
||||
};
|
||||
|
||||
// Compute the basename of src (without trailing ".ww") into a fresh
|
||||
// buffer. Used as the default output path for `ww build`.
|
||||
fn default_out_path(src: *u8) *u8 = {
|
||||
let n: u64 = cstrlen(src);
|
||||
let start: u64 = 0u64;
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
if (src[i] == 47u8) { start = i + 1u64; }; // '/'
|
||||
i += 1u64;
|
||||
};
|
||||
let out: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
let off: u64 = 0u64;
|
||||
let j: u64 = start;
|
||||
for (j < n) {
|
||||
out[off] = src[j];
|
||||
off += 1u64;
|
||||
j += 1u64;
|
||||
};
|
||||
// Strip ".ww" if present.
|
||||
if (off >= 3u64) {
|
||||
if (out[off - 3u64] == 46u8) {
|
||||
if (out[off - 2u64] == 119u8) {
|
||||
if (out[off - 1u64] == 119u8) {
|
||||
off -= 3u64;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
cstr_seal(out, off);
|
||||
return out;
|
||||
};
|
||||
|
||||
fn do_build(self_dir: *u8, argv: **u8, argc: i32, start: i32) i32 = {
|
||||
let src: *u8 = nil;
|
||||
let incs: *u8 = os.alloc(PATH_MAX * 2u64): *u8;
|
||||
let inc_off: u64 = 0u64;
|
||||
cstr_seal(incs, 0u64);
|
||||
|
||||
let i: i32 = start;
|
||||
for (i < argc) {
|
||||
let p: *u8 = argv[i];
|
||||
// -I <dir>
|
||||
if (p[0u64] == 45u8) {
|
||||
if (p[1u64] == 73u8) { // '-I'
|
||||
let dir: *u8 = nil;
|
||||
if (p[2u64] != 0u8) {
|
||||
dir = p + 2u64;
|
||||
} else {
|
||||
if (i + 1 >= argc) {
|
||||
os.write(2, "ww build: -I needs an argument\n".ptr, 31u64);
|
||||
return 2;
|
||||
};
|
||||
i += 1;
|
||||
dir = argv[i];
|
||||
};
|
||||
if (inc_off > 0u64) {
|
||||
incs[inc_off] = 58u8; // ':'
|
||||
inc_off += 1u64;
|
||||
};
|
||||
inc_off = cstr_into(incs, inc_off, dir);
|
||||
cstr_seal(incs, inc_off);
|
||||
} else {
|
||||
// -lLIB silently ignored for now (driver doesn't yet
|
||||
// pass extra archives to 6l).
|
||||
if (p[1u64] != 108u8) {
|
||||
os.write(2, "ww build: unknown flag\n".ptr, 23u64);
|
||||
return 2;
|
||||
};
|
||||
};
|
||||
} else {
|
||||
if (src == nil) { src = p; };
|
||||
};
|
||||
i += 1;
|
||||
};
|
||||
|
||||
if (src == nil) {
|
||||
os.write(2, "ww build: missing source\n".ptr, 25u64);
|
||||
return 2;
|
||||
};
|
||||
let out: *u8 = default_out_path(src);
|
||||
return build_one(self_dir, src, out, incs);
|
||||
};
|
||||
|
||||
// Format the scratch path /tmp/ww_run_<pid> into buf. Returns NUL-
|
||||
// terminated buf. Pid is folded in decimal manually since we don't
|
||||
// import strconv.
|
||||
fn make_run_tmp(buf: *u8) void = {
|
||||
let off: u64 = 0u64;
|
||||
off = str_into(buf, off, "/tmp/ww_run_");
|
||||
let pid: i32 = os.getpid();
|
||||
// itoa for non-negative pid
|
||||
let dig: [16]u8;
|
||||
let n: i32 = 0;
|
||||
if (pid <= 0) {
|
||||
dig[n] = 48u8; // '0'
|
||||
n += 1;
|
||||
} else {
|
||||
let v: i32 = pid;
|
||||
for (v > 0) {
|
||||
dig[n] = ((v % 10) + 48): u8;
|
||||
n += 1;
|
||||
v = v / 10;
|
||||
};
|
||||
};
|
||||
let k: i32 = n - 1;
|
||||
for (k >= 0) {
|
||||
buf[off] = dig[k];
|
||||
off += 1u64;
|
||||
k -= 1;
|
||||
};
|
||||
cstr_seal(buf, off);
|
||||
};
|
||||
|
||||
fn do_run(self_dir: *u8, argv: **u8, argc: i32, start: i32) i32 = {
|
||||
if (start >= argc) {
|
||||
os.write(2, "ww run: missing source\n".ptr, 23u64);
|
||||
return 2;
|
||||
};
|
||||
let tmp: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
make_run_tmp(tmp);
|
||||
if (build_one(self_dir, argv[start], tmp, "\0".ptr) != 0) { return 1; };
|
||||
let exec_argv: **u8 = os.alloc(16u64): **u8;
|
||||
exec_argv[0] = tmp;
|
||||
exec_argv[1] = nil;
|
||||
let rc: i32 = proc_run(tmp, exec_argv);
|
||||
os.unlink(tmp);
|
||||
return rc;
|
||||
};
|
||||
|
||||
// ---- Entry -------------------------------------------------------------
|
||||
|
||||
export fn main(argc: i32, argv: **u8) i32 = {
|
||||
if (argc < 1) {
|
||||
write_usage(2);
|
||||
return 2;
|
||||
};
|
||||
|
||||
// self_dir = dirname(argv[0])
|
||||
let self_dir: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
self_dir_into(self_dir, PATH_MAX, argv[0]);
|
||||
|
||||
if (argc < 2) {
|
||||
write_usage(2);
|
||||
return 2;
|
||||
};
|
||||
let cmd: *u8 = argv[1];
|
||||
if (cstreq_lit(cmd, "-V")) { return do_version(); };
|
||||
if (cstreq_lit(cmd, "version")) { return do_version(); };
|
||||
if (cstreq_lit(cmd, "-h")) {
|
||||
write_usage(1);
|
||||
return 0;
|
||||
};
|
||||
if (cstreq_lit(cmd, "--help")) {
|
||||
write_usage(1);
|
||||
return 0;
|
||||
};
|
||||
if (cstreq_lit(cmd, "build")) {
|
||||
return do_build(self_dir, argv, argc, 2);
|
||||
};
|
||||
if (cstreq_lit(cmd, "run")) {
|
||||
return do_run(self_dir, argv, argc, 2);
|
||||
};
|
||||
os.write(2, "ww: unknown subcommand\n".ptr, 23u64);
|
||||
write_usage(2);
|
||||
return 2;
|
||||
};
|
||||
|
||||
695
selfhost/cmd/ww/main.ww
Normal file
695
selfhost/cmd/ww/main.ww
Normal file
@@ -0,0 +1,695 @@
|
||||
// selfhost/cmd/ww/main.ww — port of cmd/ww/main.c.
|
||||
//
|
||||
// The user-facing driver. Plan 9 cc(1) / Hare hare(1) analogue:
|
||||
//
|
||||
// ww build foo.ww → 6c foo.ww > foo.s ; 6a foo.s > foo.o ;
|
||||
// 6l -o foo foo.o libwwrt.a
|
||||
// ww run foo.ww → build then exec
|
||||
// ww version → print version
|
||||
//
|
||||
// Tool paths default to siblings of $0 so a fresh build runs out of
|
||||
// out/bin/. Env-var overrides (WW_6C / WW_6A / WW_6L / WW_LIB) are
|
||||
// not yet supported in this port; the bootstrap doesn't need them.
|
||||
|
||||
use os;
|
||||
use mem;
|
||||
|
||||
// All path/string scratch buffers go on the runtime page allocator.
|
||||
// One page is plenty for any path we build.
|
||||
def PATH_MAX: u64 = 4096u64;
|
||||
def CMD_MAX: u64 = 8192u64;
|
||||
|
||||
// ---- C-string helpers --------------------------------------------------
|
||||
|
||||
fn cstrlen(p: *u8) u64 = {
|
||||
let n: u64 = 0u64;
|
||||
for (p[n] != 0u8) { n += 1u64; };
|
||||
return n;
|
||||
};
|
||||
|
||||
fn cstreq(a: *u8, b: *u8) bool = {
|
||||
let i: u64 = 0u64;
|
||||
for (a[i] == b[i]) {
|
||||
if (a[i] == 0u8) { return true; };
|
||||
i += 1u64;
|
||||
};
|
||||
return false;
|
||||
};
|
||||
|
||||
// cstreq_lit — compare a NUL-terminated *u8 to a ww string literal.
|
||||
fn cstreq_lit(a: *u8, lit: str) bool = {
|
||||
let n: i32 = lit.len;
|
||||
let i: i32 = 0;
|
||||
for (i < n) {
|
||||
if (a[i] != lit[i]) { return false; };
|
||||
i += 1;
|
||||
};
|
||||
return a[n] == 0u8;
|
||||
};
|
||||
|
||||
// startswith — does a have b as a prefix?
|
||||
fn cstr_startswith(a: *u8, b: *u8) bool = {
|
||||
let i: u64 = 0u64;
|
||||
for (b[i] != 0u8) {
|
||||
if (a[i] != b[i]) { return false; };
|
||||
i += 1u64;
|
||||
};
|
||||
return true;
|
||||
};
|
||||
|
||||
// memcpy
|
||||
fn bytecpy(dst: *u8, src: *u8, n: u64) void = {
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
dst[i] = src[i];
|
||||
i += 1u64;
|
||||
};
|
||||
};
|
||||
|
||||
// Copy a NUL-terminated *u8 into dst starting at off; return the new
|
||||
// offset (without writing a NUL).
|
||||
fn cstr_into(dst: *u8, off: u64, src: *u8) u64 = {
|
||||
let i: u64 = 0u64;
|
||||
for (src[i] != 0u8) {
|
||||
dst[off + i] = src[i];
|
||||
i += 1u64;
|
||||
};
|
||||
return off + i;
|
||||
};
|
||||
|
||||
// Same, but for a ww `str` (no NUL on the source side; we copy len bytes).
|
||||
fn str_into(dst: *u8, off: u64, src: str) u64 = {
|
||||
let n: i32 = src.len;
|
||||
let i: i32 = 0;
|
||||
for (i < n) {
|
||||
let iu: u64 = i: u64;
|
||||
dst[off + iu] = src[i];
|
||||
i += 1;
|
||||
};
|
||||
let nu: u64 = n: u64;
|
||||
return off + nu;
|
||||
};
|
||||
|
||||
// Write a single byte, return new offset.
|
||||
fn byte_into(dst: *u8, off: u64, c: u8) u64 = {
|
||||
dst[off] = c;
|
||||
return off + 1u64;
|
||||
};
|
||||
|
||||
// NUL-terminate at off and return the same off (handy when passing the
|
||||
// buffer to a syscall that expects a C-string).
|
||||
fn cstr_seal(dst: *u8, off: u64) void = {
|
||||
dst[off] = 0u8;
|
||||
};
|
||||
|
||||
// ---- Tool-path resolution ---------------------------------------------
|
||||
|
||||
// dirname-equivalent: copy argv[0] up to (but not including) the last
|
||||
// '/' into dst, NUL-terminated. If no slash, write ".".
|
||||
fn self_dir_into(dst: *u8, dstsz: u64, argv0: *u8) void = {
|
||||
let n: u64 = cstrlen(argv0);
|
||||
let cut: u64 = 0u64;
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
if (argv0[i] == 47u8) { cut = i; }; // '/'
|
||||
i += 1u64;
|
||||
};
|
||||
if (cut == 0u64) {
|
||||
dst[0u64] = 46u8; // '.'
|
||||
dst[1u64] = 0u8;
|
||||
return;
|
||||
};
|
||||
if (cut + 1u64 >= dstsz) { cut = dstsz - 2u64; };
|
||||
bytecpy(dst, argv0, cut);
|
||||
dst[cut] = 0u8;
|
||||
};
|
||||
|
||||
// Build "$dir/$name" (NUL-terminated) into a fresh page-sized buffer.
|
||||
fn join_path(dir: *u8, name: *u8) *u8 = {
|
||||
let buf: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
let off: u64 = cstr_into(buf, 0u64, dir);
|
||||
off = byte_into(buf, off, 47u8);
|
||||
off = cstr_into(buf, off, name);
|
||||
cstr_seal(buf, off);
|
||||
return buf;
|
||||
};
|
||||
|
||||
// Same, but the second component is a ww `str` literal.
|
||||
fn join_path_lit(dir: *u8, name: str) *u8 = {
|
||||
let buf: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
let off: u64 = cstr_into(buf, 0u64, dir);
|
||||
off = byte_into(buf, off, 47u8);
|
||||
off = str_into(buf, off, name);
|
||||
cstr_seal(buf, off);
|
||||
return buf;
|
||||
};
|
||||
|
||||
// ---- Subprocess plumbing ----------------------------------------------
|
||||
|
||||
// proc_run — fork, execve `path` with `argv` (NULL-terminated), wait.
|
||||
// Returns 0 on clean exit-0, 1 on any non-zero exit or signal kill,
|
||||
// -1 on fork/wait failure.
|
||||
fn proc_run(path: *u8, argv: **u8) i32 = {
|
||||
let pid: i32 = os.fork();
|
||||
if (pid < 0) {
|
||||
os.write(2, "ww: fork failed\n".ptr, 16u64);
|
||||
return -1;
|
||||
};
|
||||
if (pid == 0) {
|
||||
os.execve(path, argv, nil: **u8);
|
||||
os.write(2, "ww: execve failed\n".ptr, 18u64);
|
||||
os.exit(127);
|
||||
};
|
||||
let status: i32 = 0;
|
||||
let r: i32 = os.wait4(pid, &status, 0i32, nil: *void);
|
||||
if (r < 0) {
|
||||
os.write(2, "ww: wait4 failed\n".ptr, 17u64);
|
||||
return -1;
|
||||
};
|
||||
// Linux wait status: low byte = signal (0 if exited cleanly),
|
||||
// next byte = exit code.
|
||||
if ((status & 127i32) != 0) { return 1; };
|
||||
let code: i32 = (status >> 8i32) & 255i32;
|
||||
if (code != 0) { return 1; };
|
||||
return 0;
|
||||
};
|
||||
|
||||
// ---- `use` resolution + source concatenation --------------------------
|
||||
//
|
||||
// Recursive expansion: for each `use IDENT;` we find at the top of
|
||||
// `path`, resolve via the colon-separated `dirs`, expand the imported
|
||||
// file first, then append our own bytes. Already-visited paths are
|
||||
// skipped (linear scan; typical builds visit a handful of modules).
|
||||
|
||||
type strnode = struct {
|
||||
s: str,
|
||||
snext: *strnode,
|
||||
};
|
||||
|
||||
type expctx = struct {
|
||||
a: *arena, // arena for path strings + the visited list
|
||||
out: i32, // fd we're writing the combined source to
|
||||
dirs: *u8, // ":"-separated search path (NUL-terminated)
|
||||
visit: *strnode,
|
||||
};
|
||||
|
||||
fn visit_seen(c: *expctx, path: str) bool = {
|
||||
let n: *strnode = c.visit;
|
||||
for (n != nil) {
|
||||
if (n.s.len == path.len) {
|
||||
let i: i32 = 0;
|
||||
let eq: bool = true;
|
||||
for (i < path.len) {
|
||||
if (n.s[i] != path[i]) { eq = false; i = path.len; }
|
||||
else { i += 1; };
|
||||
};
|
||||
if (eq) { return true; };
|
||||
};
|
||||
n = n.snext;
|
||||
};
|
||||
return false;
|
||||
};
|
||||
|
||||
fn visit_add(c: *expctx, path: str) void = {
|
||||
let n: *strnode = amalloc(c.a, 32u64): *strnode;
|
||||
n.s = path;
|
||||
n.snext = c.visit;
|
||||
c.visit = n;
|
||||
};
|
||||
|
||||
// Try <dir>/<name>.ww then <dir>/<name>/<name>.ww. Returns NUL-terminated
|
||||
// arena-resident path if found, else nil.
|
||||
fn locate_in(a: *arena, dir: *u8, dir_len: u64, name: *u8, name_len: u64) *u8 = {
|
||||
// candidate 1: <dir>/<name>.ww
|
||||
let buf: *u8 = amalloc(a, PATH_MAX): *u8;
|
||||
let off: u64 = 0u64;
|
||||
let i: u64 = 0u64;
|
||||
for (i < dir_len) { buf[off + i] = dir[i]; i += 1u64; };
|
||||
off += dir_len;
|
||||
buf[off] = 47u8; off += 1u64; // '/'
|
||||
i = 0u64;
|
||||
for (i < name_len) { buf[off + i] = name[i]; i += 1u64; };
|
||||
off += name_len;
|
||||
buf[off] = 46u8; off += 1u64; // '.'
|
||||
buf[off] = 119u8; off += 1u64; // 'w'
|
||||
buf[off] = 119u8; off += 1u64; // 'w'
|
||||
buf[off] = 0u8;
|
||||
if (os.access(buf, 0i32) == 0) { return buf; };
|
||||
|
||||
// candidate 2: <dir>/<name>/<name>.ww
|
||||
let buf2: *u8 = amalloc(a, PATH_MAX): *u8;
|
||||
off = 0u64;
|
||||
i = 0u64;
|
||||
for (i < dir_len) { buf2[off + i] = dir[i]; i += 1u64; };
|
||||
off += dir_len;
|
||||
buf2[off] = 47u8; off += 1u64;
|
||||
i = 0u64;
|
||||
for (i < name_len) { buf2[off + i] = name[i]; i += 1u64; };
|
||||
off += name_len;
|
||||
buf2[off] = 47u8; off += 1u64;
|
||||
i = 0u64;
|
||||
for (i < name_len) { buf2[off + i] = name[i]; i += 1u64; };
|
||||
off += name_len;
|
||||
buf2[off] = 46u8; off += 1u64;
|
||||
buf2[off] = 119u8; off += 1u64;
|
||||
buf2[off] = 119u8; off += 1u64;
|
||||
buf2[off] = 0u8;
|
||||
if (os.access(buf2, 0i32) == 0) { return buf2; };
|
||||
return nil;
|
||||
};
|
||||
|
||||
// Walk a colon-separated dirlist, return first hit or nil.
|
||||
fn locate_import(a: *arena, dirs: *u8, name: *u8, name_len: u64) *u8 = {
|
||||
let total: u64 = cstrlen(dirs);
|
||||
let p: u64 = 0u64;
|
||||
for (p < total) {
|
||||
let q: u64 = p;
|
||||
for (q < total) {
|
||||
if (dirs[q] == 58u8) { break; }; // ':'
|
||||
q += 1u64;
|
||||
};
|
||||
let seg_len: u64 = q - p;
|
||||
if (seg_len > 0u64) {
|
||||
let hit: *u8 = locate_in(a, dirs + p, seg_len, name, name_len);
|
||||
if (hit != nil) { return hit; };
|
||||
};
|
||||
p = q + 1u64;
|
||||
};
|
||||
return nil;
|
||||
};
|
||||
|
||||
// ---- file slurp -------------------------------------------------------
|
||||
|
||||
fn read_all(path_cs: *u8) (*u8, u64) = {
|
||||
let fd: i32 = os.open(path_cs, os.O_RDONLY, 0i32);
|
||||
if (fd < 0) { return nil, 0u64; };
|
||||
let n: i64 = os.filesize(fd);
|
||||
if (n < 0i64) { os.close(fd); return nil, 0u64; };
|
||||
let nu: u64 = n: u64;
|
||||
let buf: *u8 = os.alloc(nu + 1u64): *u8;
|
||||
let got: i64 = os.readfull(fd, buf, nu);
|
||||
os.close(fd);
|
||||
if (got != n) { return nil, 0u64; };
|
||||
buf[nu] = 0u8;
|
||||
return buf, nu;
|
||||
};
|
||||
|
||||
fn is_ident_byte(c: u8) bool = {
|
||||
if (c >= 97u8) { if (c <= 122u8) { return true; }; }; // a..z
|
||||
if (c >= 65u8) { if (c <= 90u8) { return true; }; }; // A..Z
|
||||
if (c >= 48u8) { if (c <= 57u8) { return true; }; }; // 0..9
|
||||
if (c == 95u8) { return true; }; // _
|
||||
if (c == 46u8) { return true; }; // .
|
||||
return false;
|
||||
};
|
||||
|
||||
// Scan one `use IDENT;` line out of [start, end). Returns the start of
|
||||
// the ident and its length, or (nil, 0) if no `use` here. The caller
|
||||
// passes a slice of the source: src points at the line start.
|
||||
fn scan_use(src: *u8, len: u64) (*u8, u64) = {
|
||||
let i: u64 = 0u64;
|
||||
// skip leading whitespace
|
||||
for (i < len) {
|
||||
if (src[i] != 32u8) { if (src[i] != 9u8) { break; }; };
|
||||
i += 1u64;
|
||||
};
|
||||
if (i + 4u64 > len) { return nil, 0u64; };
|
||||
if (src[i] != 117u8) { return nil, 0u64; }; // 'u'
|
||||
if (src[i + 1u64] != 115u8) { return nil, 0u64; }; // 's'
|
||||
if (src[i + 2u64] != 101u8) { return nil, 0u64; }; // 'e'
|
||||
let sep: u8 = src[i + 3u64];
|
||||
if (sep != 32u8) { if (sep != 9u8) { return nil, 0u64; }; };
|
||||
i += 4u64;
|
||||
for (i < len) {
|
||||
if (src[i] != 32u8) { if (src[i] != 9u8) { break; }; };
|
||||
i += 1u64;
|
||||
};
|
||||
let id_start: u64 = i;
|
||||
for (i < len) {
|
||||
if (!is_ident_byte(src[i])) { break; };
|
||||
i += 1u64;
|
||||
};
|
||||
let id_len: u64 = i - id_start;
|
||||
if (id_len == 0u64) { return nil, 0u64; };
|
||||
return src + id_start, id_len;
|
||||
};
|
||||
|
||||
// Recursively expand `path` into c.out. Imported files are emitted
|
||||
// before their importer; cycles are broken via the visited set.
|
||||
fn expand(c: *expctx, path_cs: *u8) void = {
|
||||
let plen: u64 = cstrlen(path_cs);
|
||||
let path_str: str = astrndup(c.a, path_cs, plen);
|
||||
if (visit_seen(c, path_str)) { return; };
|
||||
visit_add(c, path_str);
|
||||
|
||||
let bufp: *u8;
|
||||
let blen: u64;
|
||||
bufp, blen = read_all(path_cs);
|
||||
if (bufp == nil) {
|
||||
os.write(2, "ww: cannot read source\n".ptr, 23u64);
|
||||
return;
|
||||
};
|
||||
|
||||
// Pass 1: scan top-of-file `use X;` lines, recursively expand.
|
||||
let i: u64 = 0u64;
|
||||
for (i < blen) {
|
||||
// Find the end of the current line.
|
||||
let j: u64 = i;
|
||||
for (j < blen) {
|
||||
if (bufp[j] == 10u8) { break; }; // '\n'
|
||||
j += 1u64;
|
||||
};
|
||||
let id_p: *u8;
|
||||
let id_n: u64;
|
||||
id_p, id_n = scan_use(bufp + i, j - i);
|
||||
if (id_p != nil) {
|
||||
let ipath: *u8 = locate_import(c.a, c.dirs, id_p, id_n);
|
||||
if (ipath != nil) {
|
||||
expand(c, ipath);
|
||||
};
|
||||
};
|
||||
i = j + 1u64;
|
||||
};
|
||||
|
||||
// Pass 2: emit our own bytes, then a trailing newline.
|
||||
os.writefull(c.out, bufp, blen);
|
||||
os.writefull(c.out, "\n".ptr, 1u64);
|
||||
};
|
||||
|
||||
// ---- Build pipeline ---------------------------------------------------
|
||||
|
||||
// Strip the trailing ".ww" off `src` (a NUL-terminated path) into
|
||||
// `stem`, NUL-terminated. If there's no .ww, the stem is the whole
|
||||
// path.
|
||||
fn make_stem(stem: *u8, src: *u8) void = {
|
||||
let n: u64 = cstrlen(src);
|
||||
let stop: u64 = n;
|
||||
if (n >= 3u64) {
|
||||
if (src[n - 3u64] == 46u8) { // '.'
|
||||
if (src[n - 2u64] == 119u8) { // 'w'
|
||||
if (src[n - 1u64] == 119u8) { // 'w'
|
||||
stop = n - 3u64;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
let i: u64 = 0u64;
|
||||
for (i < stop) { stem[i] = src[i]; i += 1u64; };
|
||||
stem[stop] = 0u8;
|
||||
};
|
||||
|
||||
// Append a literal suffix to `stem` (which already lives in a buffer).
|
||||
fn append_lit(stem: *u8, suffix: str) *u8 = {
|
||||
let buf: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
let off: u64 = cstr_into(buf, 0u64, stem);
|
||||
off = str_into(buf, off, suffix);
|
||||
cstr_seal(buf, off);
|
||||
return buf;
|
||||
};
|
||||
|
||||
// build_one — compile `src` into the executable named `out`.
|
||||
// self_dir: NUL-terminated dir containing this driver (and 6c/6a/6l)
|
||||
// src: NUL-terminated path to the .ww file
|
||||
// out: NUL-terminated desired output path
|
||||
// incs: NUL-terminated colon-list of -I dirs (may be empty)
|
||||
fn build_one(self_dir: *u8, src: *u8, out: *u8, incs: *u8) i32 = {
|
||||
let a: *arena = newarena();
|
||||
|
||||
let c6: *u8 = join_path_lit(self_dir, "6c");
|
||||
let a6: *u8 = join_path_lit(self_dir, "6a");
|
||||
let l6: *u8 = join_path_lit(self_dir, "6l");
|
||||
|
||||
// Default lib search path: <self_dir>/../../lib
|
||||
let dotdot_lib: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
{
|
||||
let off: u64 = cstr_into(dotdot_lib, 0u64, self_dir);
|
||||
off = str_into(dotdot_lib, off, "/../../lib");
|
||||
cstr_seal(dotdot_lib, off);
|
||||
};
|
||||
|
||||
// Compose searchpath: incs + ':' + dotdot_lib (or just dotdot_lib).
|
||||
let searchpath: *u8 = os.alloc(PATH_MAX * 2u64): *u8;
|
||||
{
|
||||
let off: u64 = 0u64;
|
||||
if (incs[0u64] != 0u8) {
|
||||
off = cstr_into(searchpath, off, incs);
|
||||
off = byte_into(searchpath, off, 58u8); // ':'
|
||||
};
|
||||
off = cstr_into(searchpath, off, dotdot_lib);
|
||||
cstr_seal(searchpath, off);
|
||||
};
|
||||
|
||||
// stem, .s, .o, .combined.ww, libwwrt.a
|
||||
let stem: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
make_stem(stem, src);
|
||||
let asmf: *u8 = append_lit(stem, ".s");
|
||||
let objf: *u8 = append_lit(stem, ".o");
|
||||
let combined: *u8 = append_lit(stem, ".combined.ww");
|
||||
|
||||
// libwwrt.a path: <self_dir>/../lib/libwwrt.a
|
||||
let libwwrt: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
{
|
||||
let off: u64 = cstr_into(libwwrt, 0u64, self_dir);
|
||||
off = str_into(libwwrt, off, "/../lib/libwwrt.a");
|
||||
cstr_seal(libwwrt, off);
|
||||
};
|
||||
|
||||
// Step 1: expand `use`s into the combined file.
|
||||
let cf: i32 = os.open(combined, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 420i32); // 0o644
|
||||
if (cf < 0) {
|
||||
os.write(2, "ww: cannot open combined\n".ptr, 25u64);
|
||||
return 1;
|
||||
};
|
||||
{
|
||||
let c: expctx;
|
||||
c.a = a;
|
||||
c.out = cf;
|
||||
c.dirs = searchpath;
|
||||
c.visit = nil;
|
||||
expand(&c, src);
|
||||
};
|
||||
os.close(cf);
|
||||
|
||||
// Step 2: 6c -o <stem>.s <stem>.combined.ww
|
||||
{
|
||||
let argv: **u8 = os.alloc(40u64): **u8;
|
||||
argv[0] = "6c\0".ptr;
|
||||
argv[1] = "-o\0".ptr;
|
||||
argv[2] = asmf;
|
||||
argv[3] = combined;
|
||||
argv[4] = nil;
|
||||
if (proc_run(c6, argv) != 0) {
|
||||
os.write(2, "ww: 6c failed\n".ptr, 14u64);
|
||||
return 1;
|
||||
};
|
||||
};
|
||||
|
||||
// Step 3: 6a -o <stem>.o <stem>.s
|
||||
{
|
||||
let argv: **u8 = os.alloc(40u64): **u8;
|
||||
argv[0] = "6a\0".ptr;
|
||||
argv[1] = "-o\0".ptr;
|
||||
argv[2] = objf;
|
||||
argv[3] = asmf;
|
||||
argv[4] = nil;
|
||||
if (proc_run(a6, argv) != 0) {
|
||||
os.write(2, "ww: 6a failed\n".ptr, 14u64);
|
||||
return 1;
|
||||
};
|
||||
};
|
||||
|
||||
// Step 4: 6l -o <out> <stem>.o libwwrt.a
|
||||
{
|
||||
let argv: **u8 = os.alloc(48u64): **u8;
|
||||
argv[0] = "6l\0".ptr;
|
||||
argv[1] = "-o\0".ptr;
|
||||
argv[2] = out;
|
||||
argv[3] = objf;
|
||||
argv[4] = libwwrt;
|
||||
argv[5] = nil;
|
||||
if (proc_run(l6, argv) != 0) {
|
||||
os.write(2, "ww: 6l failed\n".ptr, 14u64);
|
||||
return 1;
|
||||
};
|
||||
};
|
||||
return 0;
|
||||
};
|
||||
|
||||
// ---- Subcommand handlers ----------------------------------------------
|
||||
|
||||
fn write_usage(fd: i32) void = {
|
||||
let s: str = "usage: ww [-V] <subcommand> [args...]\n -V print version and exit\n build <path> compile module to a static binary\n run <path> build then exec\n version print version and exit\n";
|
||||
os.write(fd, s.ptr, s.len: u64);
|
||||
};
|
||||
|
||||
fn do_version() i32 = {
|
||||
os.write(1, "ww 0.0\n".ptr, 7u64);
|
||||
return 0;
|
||||
};
|
||||
|
||||
// Compute the basename of src (without trailing ".ww") into a fresh
|
||||
// buffer. Used as the default output path for `ww build`.
|
||||
fn default_out_path(src: *u8) *u8 = {
|
||||
let n: u64 = cstrlen(src);
|
||||
let start: u64 = 0u64;
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
if (src[i] == 47u8) { start = i + 1u64; }; // '/'
|
||||
i += 1u64;
|
||||
};
|
||||
let out: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
let off: u64 = 0u64;
|
||||
let j: u64 = start;
|
||||
for (j < n) {
|
||||
out[off] = src[j];
|
||||
off += 1u64;
|
||||
j += 1u64;
|
||||
};
|
||||
// Strip ".ww" if present.
|
||||
if (off >= 3u64) {
|
||||
if (out[off - 3u64] == 46u8) {
|
||||
if (out[off - 2u64] == 119u8) {
|
||||
if (out[off - 1u64] == 119u8) {
|
||||
off -= 3u64;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
cstr_seal(out, off);
|
||||
return out;
|
||||
};
|
||||
|
||||
fn do_build(self_dir: *u8, argv: **u8, argc: i32, start: i32) i32 = {
|
||||
let src: *u8 = nil;
|
||||
let incs: *u8 = os.alloc(PATH_MAX * 2u64): *u8;
|
||||
let inc_off: u64 = 0u64;
|
||||
cstr_seal(incs, 0u64);
|
||||
|
||||
let i: i32 = start;
|
||||
for (i < argc) {
|
||||
let p: *u8 = argv[i];
|
||||
// -I <dir>
|
||||
if (p[0u64] == 45u8) {
|
||||
if (p[1u64] == 73u8) { // '-I'
|
||||
let dir: *u8 = nil;
|
||||
if (p[2u64] != 0u8) {
|
||||
dir = p + 2u64;
|
||||
} else {
|
||||
if (i + 1 >= argc) {
|
||||
os.write(2, "ww build: -I needs an argument\n".ptr, 31u64);
|
||||
return 2;
|
||||
};
|
||||
i += 1;
|
||||
dir = argv[i];
|
||||
};
|
||||
if (inc_off > 0u64) {
|
||||
incs[inc_off] = 58u8; // ':'
|
||||
inc_off += 1u64;
|
||||
};
|
||||
inc_off = cstr_into(incs, inc_off, dir);
|
||||
cstr_seal(incs, inc_off);
|
||||
} else {
|
||||
// -lLIB silently ignored for now (driver doesn't yet
|
||||
// pass extra archives to 6l).
|
||||
if (p[1u64] != 108u8) {
|
||||
os.write(2, "ww build: unknown flag\n".ptr, 23u64);
|
||||
return 2;
|
||||
};
|
||||
};
|
||||
} else {
|
||||
if (src == nil) { src = p; };
|
||||
};
|
||||
i += 1;
|
||||
};
|
||||
|
||||
if (src == nil) {
|
||||
os.write(2, "ww build: missing source\n".ptr, 25u64);
|
||||
return 2;
|
||||
};
|
||||
let out: *u8 = default_out_path(src);
|
||||
return build_one(self_dir, src, out, incs);
|
||||
};
|
||||
|
||||
// Format the scratch path /tmp/ww_run_<pid> into buf. Returns NUL-
|
||||
// terminated buf. Pid is folded in decimal manually since we don't
|
||||
// import strconv.
|
||||
fn make_run_tmp(buf: *u8) void = {
|
||||
let off: u64 = 0u64;
|
||||
off = str_into(buf, off, "/tmp/ww_run_");
|
||||
let pid: i32 = os.getpid();
|
||||
// itoa for non-negative pid
|
||||
let dig: [16]u8;
|
||||
let n: i32 = 0;
|
||||
if (pid <= 0) {
|
||||
dig[n] = 48u8; // '0'
|
||||
n += 1;
|
||||
} else {
|
||||
let v: i32 = pid;
|
||||
for (v > 0) {
|
||||
dig[n] = ((v % 10) + 48): u8;
|
||||
n += 1;
|
||||
v = v / 10;
|
||||
};
|
||||
};
|
||||
let k: i32 = n - 1;
|
||||
for (k >= 0) {
|
||||
buf[off] = dig[k];
|
||||
off += 1u64;
|
||||
k -= 1;
|
||||
};
|
||||
cstr_seal(buf, off);
|
||||
};
|
||||
|
||||
fn do_run(self_dir: *u8, argv: **u8, argc: i32, start: i32) i32 = {
|
||||
if (start >= argc) {
|
||||
os.write(2, "ww run: missing source\n".ptr, 23u64);
|
||||
return 2;
|
||||
};
|
||||
let tmp: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
make_run_tmp(tmp);
|
||||
if (build_one(self_dir, argv[start], tmp, "\0".ptr) != 0) { return 1; };
|
||||
let exec_argv: **u8 = os.alloc(16u64): **u8;
|
||||
exec_argv[0] = tmp;
|
||||
exec_argv[1] = nil;
|
||||
let rc: i32 = proc_run(tmp, exec_argv);
|
||||
os.unlink(tmp);
|
||||
return rc;
|
||||
};
|
||||
|
||||
// ---- Entry -------------------------------------------------------------
|
||||
|
||||
export fn main(argc: i32, argv: **u8) i32 = {
|
||||
if (argc < 1) {
|
||||
write_usage(2);
|
||||
return 2;
|
||||
};
|
||||
|
||||
// self_dir = dirname(argv[0])
|
||||
let self_dir: *u8 = os.alloc(PATH_MAX): *u8;
|
||||
self_dir_into(self_dir, PATH_MAX, argv[0]);
|
||||
|
||||
if (argc < 2) {
|
||||
write_usage(2);
|
||||
return 2;
|
||||
};
|
||||
let cmd: *u8 = argv[1];
|
||||
if (cstreq_lit(cmd, "-V")) { return do_version(); };
|
||||
if (cstreq_lit(cmd, "version")) { return do_version(); };
|
||||
if (cstreq_lit(cmd, "-h")) {
|
||||
write_usage(1);
|
||||
return 0;
|
||||
};
|
||||
if (cstreq_lit(cmd, "--help")) {
|
||||
write_usage(1);
|
||||
return 0;
|
||||
};
|
||||
if (cstreq_lit(cmd, "build")) {
|
||||
return do_build(self_dir, argv, argc, 2);
|
||||
};
|
||||
if (cstreq_lit(cmd, "run")) {
|
||||
return do_run(self_dir, argv, argc, 2);
|
||||
};
|
||||
os.write(2, "ww: unknown subcommand\n".ptr, 23u64);
|
||||
write_usage(2);
|
||||
return 2;
|
||||
};
|
||||
335
selfhost/cmd/wwc/ast.ww
Normal file
335
selfhost/cmd/wwc/ast.ww
Normal file
@@ -0,0 +1,335 @@
|
||||
// selfhost/cmd/wwc/ast.ww — port of cmd/wwc/ast.c (Node defs + printer).
|
||||
//
|
||||
// Status: AST printer is fully ported. Constructor `newnode` is here.
|
||||
// The parser (parse.ww) is currently minimal — see its file header.
|
||||
//
|
||||
// Calling-convention shim: same as tok/lex — `node` is too big to pass
|
||||
// by value (8 *node pointers + 2 strs + a few ints), so callers always
|
||||
// hand around `*node`. Only `newnode` allocates and returns a *node.
|
||||
|
||||
use os;
|
||||
use strconv;
|
||||
use mem;
|
||||
use tok;
|
||||
|
||||
// ---- Nkind ------------------------------------------------------------
|
||||
//
|
||||
// Mirror of cmd/wwc/ww.h Nkind. Values must stay numerically equal so
|
||||
// the AST diff probe in 990_selfhost works.
|
||||
|
||||
def N_NONE: i32 = 0;
|
||||
|
||||
def N_INTLIT: i32 = 1;
|
||||
def N_FLOATLIT: i32 = 2;
|
||||
def N_STRLIT: i32 = 3;
|
||||
def N_RUNELIT: i32 = 4;
|
||||
def N_TRUE: i32 = 5;
|
||||
def N_FALSE: i32 = 6;
|
||||
def N_NIL: i32 = 7;
|
||||
def N_IDENT: i32 = 8;
|
||||
|
||||
def N_BIN: i32 = 9;
|
||||
def N_UN: i32 = 10;
|
||||
def N_CALL: i32 = 11;
|
||||
def N_INDEX: i32 = 12;
|
||||
def N_DOT: i32 = 13;
|
||||
def N_CAST: i32 = 14;
|
||||
def N_STRUCTLIT:i32 = 15;
|
||||
def N_ARRLIT: i32 = 16;
|
||||
def N_FIELD: i32 = 17;
|
||||
def N_ASSIGN: i32 = 18;
|
||||
def N_ALLOC: i32 = 19;
|
||||
def N_FREE: i32 = 20;
|
||||
def N_RECV: i32 = 21;
|
||||
def N_SLICE: i32 = 22;
|
||||
def N_SPREAD: i32 = 23;
|
||||
|
||||
def N_BLOCK: i32 = 24;
|
||||
def N_EXPRSTMT: i32 = 25;
|
||||
def N_LET: i32 = 26;
|
||||
def N_RETURN: i32 = 27;
|
||||
def N_IF: i32 = 28;
|
||||
def N_FOR: i32 = 29;
|
||||
def N_FORRANGE: i32 = 30;
|
||||
def N_DEFER: i32 = 31;
|
||||
def N_BREAK: i32 = 32;
|
||||
def N_CONTINUE: i32 = 33;
|
||||
def N_SWITCH: i32 = 34;
|
||||
def N_CASE: i32 = 35;
|
||||
|
||||
def N_FILE: i32 = 36;
|
||||
def N_USE: i32 = 37;
|
||||
def N_DEF: i32 = 38;
|
||||
def N_TYPEDECL: i32 = 39;
|
||||
def N_FNDECL: i32 = 40;
|
||||
def N_PARAM: i32 = 41;
|
||||
|
||||
def N_TNAME: i32 = 42;
|
||||
def N_TPTR: i32 = 43;
|
||||
def N_TSLICE: i32 = 44;
|
||||
def N_TARRAY: i32 = 45;
|
||||
def N_TFN: i32 = 46;
|
||||
def N_TSTRUCT: i32 = 47;
|
||||
def N_TFIELD: i32 = 48;
|
||||
def N_TCHAN: i32 = 49;
|
||||
|
||||
def N_ATTR: i32 = 50;
|
||||
def N_TTUPLE: i32 = 51;
|
||||
def N_TTAGGED: i32 = 52;
|
||||
def N_TUPLE: i32 = 53;
|
||||
def N_MATCH: i32 = 54;
|
||||
def N_MCASE: i32 = 55;
|
||||
def N_TRYPROP: i32 = 56;
|
||||
def N_TRYUNW: i32 = 57;
|
||||
def N_MLET: i32 = 58;
|
||||
def N_MASSIGN: i32 = 59;
|
||||
|
||||
def N_LAST: i32 = 60;
|
||||
|
||||
// ---- Node -------------------------------------------------------------
|
||||
|
||||
type node = struct {
|
||||
kind: i32,
|
||||
file: str,
|
||||
line: i32,
|
||||
col: i32,
|
||||
op: i32, // for N_BIN / N_UN / N_ASSIGN
|
||||
str: str,
|
||||
uval: u64,
|
||||
fval: f64,
|
||||
lhs: *node,
|
||||
rhs: *node,
|
||||
cond: *node,
|
||||
body: *node,
|
||||
els: *node,
|
||||
list: *node,
|
||||
next: *node,
|
||||
attr: *node,
|
||||
exported: i32, // bool — `export` keyword present
|
||||
type_: *void, // filled in by checker; type.ww treats it as *tinfo
|
||||
tsuffix: str, // typed numeric literal suffix ("i32", "u64", ...)
|
||||
};
|
||||
|
||||
export fn newnode(a: *arena, k: i32, file: str, line: i32, col: i32) *node = {
|
||||
let n: *node = amalloc(a, 192u64): *node; // 192 ≥ struct size
|
||||
n.kind = k;
|
||||
n.file = file;
|
||||
n.line = line;
|
||||
n.col = col;
|
||||
return n;
|
||||
};
|
||||
|
||||
// ---- printer ----------------------------------------------------------
|
||||
|
||||
fn nkname(k: i32) str = {
|
||||
if (k == N_NONE) { return "none"; };
|
||||
if (k == N_INTLIT) { return "int"; };
|
||||
if (k == N_FLOATLIT) { return "float"; };
|
||||
if (k == N_STRLIT) { return "str"; };
|
||||
if (k == N_RUNELIT) { return "rune"; };
|
||||
if (k == N_TRUE) { return "true"; };
|
||||
if (k == N_FALSE) { return "false"; };
|
||||
if (k == N_NIL) { return "nil"; };
|
||||
if (k == N_IDENT) { return "id"; };
|
||||
if (k == N_BIN) { return "bin"; };
|
||||
if (k == N_UN) { return "un"; };
|
||||
if (k == N_CALL) { return "call"; };
|
||||
if (k == N_INDEX) { return "index"; };
|
||||
if (k == N_DOT) { return "dot"; };
|
||||
if (k == N_CAST) { return "cast"; };
|
||||
if (k == N_STRUCTLIT) { return "structlit"; };
|
||||
if (k == N_ARRLIT) { return "arrlit"; };
|
||||
if (k == N_FIELD) { return "field"; };
|
||||
if (k == N_ASSIGN) { return "assign"; };
|
||||
if (k == N_ALLOC) { return "alloc"; };
|
||||
if (k == N_FREE) { return "free"; };
|
||||
if (k == N_RECV) { return "recv"; };
|
||||
if (k == N_SLICE) { return "slice"; };
|
||||
if (k == N_SPREAD) { return "spread"; };
|
||||
if (k == N_BLOCK) { return "block"; };
|
||||
if (k == N_EXPRSTMT) { return "exprstmt"; };
|
||||
if (k == N_LET) { return "let"; };
|
||||
if (k == N_RETURN) { return "return"; };
|
||||
if (k == N_IF) { return "if"; };
|
||||
if (k == N_FOR) { return "for"; };
|
||||
if (k == N_FORRANGE) { return "forrange"; };
|
||||
if (k == N_DEFER) { return "defer"; };
|
||||
if (k == N_BREAK) { return "break"; };
|
||||
if (k == N_CONTINUE) { return "continue"; };
|
||||
if (k == N_SWITCH) { return "switch"; };
|
||||
if (k == N_CASE) { return "case"; };
|
||||
if (k == N_FILE) { return "file"; };
|
||||
if (k == N_USE) { return "use"; };
|
||||
if (k == N_DEF) { return "def"; };
|
||||
if (k == N_TYPEDECL) { return "typedecl"; };
|
||||
if (k == N_FNDECL) { return "fn"; };
|
||||
if (k == N_PARAM) { return "param"; };
|
||||
if (k == N_TNAME) { return "tname"; };
|
||||
if (k == N_TPTR) { return "tptr"; };
|
||||
if (k == N_TSLICE) { return "tslice"; };
|
||||
if (k == N_TARRAY) { return "tarray"; };
|
||||
if (k == N_TFN) { return "tfn"; };
|
||||
if (k == N_TSTRUCT) { return "tstruct"; };
|
||||
if (k == N_TFIELD) { return "tfield"; };
|
||||
if (k == N_TCHAN) { return "tchan"; };
|
||||
if (k == N_ATTR) { return "attr"; };
|
||||
if (k == N_TTUPLE) { return "ttuple"; };
|
||||
if (k == N_TTAGGED) { return "ttagged"; };
|
||||
if (k == N_TUPLE) { return "tuple"; };
|
||||
if (k == N_MATCH) { return "match"; };
|
||||
if (k == N_MCASE) { return "mcase"; };
|
||||
if (k == N_TRYPROP) { return "tryprop"; };
|
||||
if (k == N_TRYUNW) { return "tryunw"; };
|
||||
if (k == N_MLET) { return "mlet"; };
|
||||
if (k == N_MASSIGN) { return "massign"; };
|
||||
if (k == N_LAST) { return "last"; };
|
||||
return "?";
|
||||
};
|
||||
|
||||
fn ind(fd: i32, d: i32) void = {
|
||||
let i: i32 = 0;
|
||||
for (i < d) {
|
||||
os.write(fd, " ".ptr, 2u64);
|
||||
i += 1;
|
||||
};
|
||||
};
|
||||
|
||||
fn putc1(fd: i32, b: u8) void = {
|
||||
let buf: [1]u8;
|
||||
buf[0] = b;
|
||||
os.write(fd, buf.ptr, 1u64);
|
||||
};
|
||||
|
||||
fn putq(fd: i32, s: str) void = {
|
||||
putc1(fd, 34u8); // '"'
|
||||
let i: i32 = 0;
|
||||
for (i < s.len) {
|
||||
let c: u8 = s[i];
|
||||
if (c == 34u8) { // '"'
|
||||
os.write(fd, "\\\"".ptr, 2u64);
|
||||
} else { if (c == 92u8) { // '\\'
|
||||
os.write(fd, "\\\\".ptr, 2u64);
|
||||
} else { if (c == 10u8) { // '\n'
|
||||
os.write(fd, "\\n".ptr, 2u64);
|
||||
} else { if (c == 9u8) { // '\t'
|
||||
os.write(fd, "\\t".ptr, 2u64);
|
||||
} else { if (c < 32u8) {
|
||||
let hi: u8 = c >> 4u8;
|
||||
let lo: u8 = c & 15u8;
|
||||
let h: u8 = 0u8;
|
||||
let l: u8 = 0u8;
|
||||
if (hi < 10u8) { h = hi + 48u8; } else { h = (hi - 10u8) + 97u8; };
|
||||
if (lo < 10u8) { l = lo + 48u8; } else { l = (lo - 10u8) + 97u8; };
|
||||
let buf: [4]u8;
|
||||
buf[0] = 92u8;
|
||||
buf[1] = 120u8;
|
||||
buf[2] = h;
|
||||
buf[3] = l;
|
||||
os.write(fd, buf.ptr, 4u64);
|
||||
} else {
|
||||
putc1(fd, c);
|
||||
};};};};};
|
||||
i += 1;
|
||||
};
|
||||
putc1(fd, 34u8);
|
||||
};
|
||||
|
||||
fn pr(fd: i32, n: *node, d: i32) void = {
|
||||
if (n == nil) {
|
||||
ind(fd, d);
|
||||
os.write(fd, "()\n".ptr, 3u64);
|
||||
return;
|
||||
};
|
||||
ind(fd, d);
|
||||
putc1(fd, 40u8); // '('
|
||||
let nm: str = nkname(n.kind);
|
||||
os.write(fd, nm.ptr, nm.len: u64);
|
||||
|
||||
if (n.kind == N_INTLIT) {
|
||||
putc1(fd, 32u8);
|
||||
let buf: [32]u8;
|
||||
let m: i32 = strconv.u64toa(buf[0:32], n.uval);
|
||||
os.write(fd, buf.ptr, m: u64);
|
||||
} else { if (n.kind == N_RUNELIT) {
|
||||
putc1(fd, 32u8);
|
||||
let buf: [32]u8;
|
||||
let m: i32 = strconv.u64toa(buf[0:32], n.uval);
|
||||
os.write(fd, buf.ptr, m: u64);
|
||||
} else { if (
|
||||
n.kind == N_STRLIT ||
|
||||
n.kind == N_IDENT ||
|
||||
n.kind == N_USE ||
|
||||
n.kind == N_DOT ||
|
||||
n.kind == N_DEF ||
|
||||
n.kind == N_TYPEDECL ||
|
||||
n.kind == N_FNDECL ||
|
||||
n.kind == N_PARAM ||
|
||||
n.kind == N_LET ||
|
||||
n.kind == N_TNAME ||
|
||||
n.kind == N_TFIELD ||
|
||||
n.kind == N_FIELD ||
|
||||
n.kind == N_ATTR
|
||||
) {
|
||||
// Match C ast.c: print the str field whenever it's non-nil,
|
||||
// even if its length is zero (e.g. an empty STRLIT prints
|
||||
// `(str ""`).
|
||||
let s: str = n.str;
|
||||
if (s.ptr != nil) {
|
||||
putc1(fd, 32u8);
|
||||
putq(fd, s);
|
||||
};
|
||||
} else { if (
|
||||
n.kind == N_BIN ||
|
||||
n.kind == N_UN ||
|
||||
n.kind == N_ASSIGN
|
||||
) {
|
||||
putc1(fd, 32u8);
|
||||
let on: str = tokname(n.op);
|
||||
os.write(fd, on.ptr, on.len: u64);
|
||||
};};};};
|
||||
|
||||
if (n.kind == N_FNDECL) {
|
||||
if (n.exported != 0) { os.write(fd, " export".ptr, 7u64); };
|
||||
};
|
||||
if (n.kind == N_DEF) {
|
||||
if (n.exported != 0) { os.write(fd, " export".ptr, 7u64); };
|
||||
};
|
||||
if (n.kind == N_TYPEDECL) {
|
||||
if (n.exported != 0) { os.write(fd, " export".ptr, 7u64); };
|
||||
};
|
||||
putc1(fd, 10u8); // '\n'
|
||||
|
||||
if (n.attr != nil) {
|
||||
ind(fd, d + 1);
|
||||
os.write(fd, "(@\n".ptr, 3u64);
|
||||
let m: *node = n.attr;
|
||||
for (m != nil) {
|
||||
pr(fd, m, d + 2);
|
||||
m = m.next;
|
||||
};
|
||||
ind(fd, d + 1);
|
||||
os.write(fd, ")\n".ptr, 2u64);
|
||||
};
|
||||
if (n.lhs != nil) { pr(fd, n.lhs, d + 1); };
|
||||
if (n.rhs != nil) { pr(fd, n.rhs, d + 1); };
|
||||
if (n.cond != nil) { pr(fd, n.cond, d + 1); };
|
||||
if (n.body != nil) { pr(fd, n.body, d + 1); };
|
||||
if (n.els != nil) { pr(fd, n.els, d + 1); };
|
||||
if (n.list != nil) {
|
||||
ind(fd, d + 1);
|
||||
os.write(fd, "(list\n".ptr, 6u64);
|
||||
let m: *node = n.list;
|
||||
for (m != nil) {
|
||||
pr(fd, m, d + 2);
|
||||
m = m.next;
|
||||
};
|
||||
ind(fd, d + 1);
|
||||
os.write(fd, ")\n".ptr, 2u64);
|
||||
};
|
||||
ind(fd, d);
|
||||
os.write(fd, ")\n".ptr, 2u64);
|
||||
};
|
||||
|
||||
export fn astprint(fd: i32, n: *node) void = {
|
||||
pr(fd, n, 0);
|
||||
};
|
||||
2868
selfhost/cmd/wwc/cgen.ww
Normal file
2868
selfhost/cmd/wwc/cgen.ww
Normal file
File diff suppressed because it is too large
Load Diff
247
selfhost/cmd/wwc/check.ww
Normal file
247
selfhost/cmd/wwc/check.ww
Normal file
@@ -0,0 +1,247 @@
|
||||
// selfhost/cmd/wwc/check.ww — minimal port of cmd/wwc/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/wwc/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
|
||||
};
|
||||
|
||||
// seed_primitives — install the built-in type names so `i32`, `str`,
|
||||
// etc. can be looked up like ordinary symbols.
|
||||
fn seed_primitives(c: *checker) void = {
|
||||
scope_define(c.top, "void", SK_TYPE, c.tc.ty_void, nil);
|
||||
scope_define(c.top, "bool", SK_TYPE, c.tc.ty_bool, nil);
|
||||
scope_define(c.top, "rune", SK_TYPE, c.tc.ty_rune, nil);
|
||||
scope_define(c.top, "i8", SK_TYPE, c.tc.ty_i8, nil);
|
||||
scope_define(c.top, "i16", SK_TYPE, c.tc.ty_i16, nil);
|
||||
scope_define(c.top, "i32", SK_TYPE, c.tc.ty_i32, nil);
|
||||
scope_define(c.top, "i64", SK_TYPE, c.tc.ty_i64, nil);
|
||||
scope_define(c.top, "u8", SK_TYPE, c.tc.ty_u8, nil);
|
||||
scope_define(c.top, "u16", SK_TYPE, c.tc.ty_u16, nil);
|
||||
scope_define(c.top, "u32", SK_TYPE, c.tc.ty_u32, nil);
|
||||
scope_define(c.top, "u64", SK_TYPE, c.tc.ty_u64, nil);
|
||||
scope_define(c.top, "int", SK_TYPE, c.tc.ty_int, nil);
|
||||
scope_define(c.top, "uint", SK_TYPE, c.tc.ty_uint, nil);
|
||||
scope_define(c.top, "uintptr", SK_TYPE, c.tc.ty_uintptr, nil);
|
||||
scope_define(c.top, "f32", SK_TYPE, c.tc.ty_f32, nil);
|
||||
scope_define(c.top, "f64", SK_TYPE, c.tc.ty_f64, nil);
|
||||
scope_define(c.top, "str", SK_TYPE, c.tc.ty_str, nil);
|
||||
// `nil`, `true`, `false` are keywords — handled at the lex/parser
|
||||
// level, no symbol needed.
|
||||
// `len`, `alloc`, `free` are pseudo-builtins; scope_define them so
|
||||
// their use sites resolve. The actual semantics live in cgen.
|
||||
scope_define(c.top, "len", SK_FN, nil, nil);
|
||||
scope_define(c.top, "alloc", SK_FN, nil, nil);
|
||||
scope_define(c.top, "free", SK_FN, nil, nil);
|
||||
};
|
||||
|
||||
// install_decl — 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 install_decl(c: *checker, d: *node) void = {
|
||||
if (d == nil) { return; };
|
||||
let k: i32 = d.kind;
|
||||
let nm: str = d.str;
|
||||
if (k == N_USE) { scope_define(c.top, nm, SK_USE, nil, d); return; };
|
||||
if (k == N_DEF) { scope_define(c.top, nm, SK_DEF, nil, d); return; };
|
||||
if (k == N_TYPEDECL) { scope_define(c.top, nm, SK_TYPE, nil, d); return; };
|
||||
if (k == N_FNDECL) { scope_define(c.top, nm, SK_FN, nil, d); return; };
|
||||
if (k == N_LET) { scope_define(c.top, nm, SK_VAR, nil, d); return; };
|
||||
};
|
||||
|
||||
// resolve_walk — 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).
|
||||
fn resolve_walk(c: *checker, n: *node) void = {
|
||||
if (n == nil) { return; };
|
||||
let k: i32 = n.kind;
|
||||
|
||||
// `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 = scope_lookup(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 = scope_lookup(c.cur, nm);
|
||||
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) { resolve_walk(c, n.lhs); };
|
||||
let nm: str = n.str;
|
||||
if (nm.len > 0) {
|
||||
scope_define(c.cur, nm, SK_VAR, nil, n);
|
||||
};
|
||||
if (n.body != nil) { resolve_walk(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) { resolve_walk(c, n.lhs); };
|
||||
return;
|
||||
};
|
||||
|
||||
if (k == N_FIELD) {
|
||||
if (n.lhs != nil) { resolve_walk(c, n.lhs); };
|
||||
return;
|
||||
};
|
||||
|
||||
if (k == N_TFIELD) {
|
||||
if (n.lhs != nil) { resolve_walk(c, n.lhs); };
|
||||
return;
|
||||
};
|
||||
|
||||
// Walk children (mirroring ast.ww's printer descent order).
|
||||
if (n.attr != nil) { resolve_walk(c, n.attr); };
|
||||
if (n.lhs != nil) { resolve_walk(c, n.lhs); };
|
||||
if (n.rhs != nil) { resolve_walk(c, n.rhs); };
|
||||
if (n.cond != nil) { resolve_walk(c, n.cond); };
|
||||
if (n.body != nil) { resolve_walk(c, n.body); };
|
||||
if (n.els != nil) { resolve_walk(c, n.els); };
|
||||
if (n.list != nil) {
|
||||
let m: *node = n.list;
|
||||
for (m != nil) {
|
||||
resolve_walk(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 install_decl, so this duplicate install at
|
||||
// the file scope just no-ops (scope_define returns nil on dup).
|
||||
if (k == N_LET) {
|
||||
let nm: str = n.str;
|
||||
if (nm.len > 0) {
|
||||
scope_define(c.cur, nm, SK_VAR, nil, n);
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
// install_param — when entering a fn body, define its params in a
|
||||
// fresh local scope.
|
||||
fn install_params(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) {
|
||||
scope_define(c.cur, nm, SK_PARAM, nil, p);
|
||||
};
|
||||
};
|
||||
p = p.next;
|
||||
};
|
||||
};
|
||||
|
||||
// resolve_fnbody — 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 resolve_fnbody(c: *checker, fnnode: *node) void = {
|
||||
let outer: *scope = c.cur;
|
||||
c.cur = newscope(c.a, c.cur);
|
||||
install_params(c, fnnode.list);
|
||||
if (fnnode.body != nil) {
|
||||
resolve_walk(c, fnnode.body);
|
||||
};
|
||||
c.cur = outer;
|
||||
};
|
||||
|
||||
export fn check_init(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;
|
||||
seed_primitives(c);
|
||||
};
|
||||
|
||||
export fn check_file(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) {
|
||||
install_decl(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) { resolve_walk(c, d.lhs); }; // return type
|
||||
resolve_fnbody(c, d);
|
||||
} else { if (k == N_DEF) {
|
||||
if (d.lhs != nil) { resolve_walk(c, d.lhs); };
|
||||
if (d.rhs != nil) { resolve_walk(c, d.rhs); };
|
||||
} else { if (k == N_TYPEDECL) {
|
||||
if (d.lhs != nil) { resolve_walk(c, d.lhs); };
|
||||
} else { if (k == N_LET) {
|
||||
if (d.lhs != nil) { resolve_walk(c, d.lhs); };
|
||||
if (d.rhs != nil) { resolve_walk(c, d.rhs); };
|
||||
};};};};
|
||||
d = d.next;
|
||||
};
|
||||
};
|
||||
37
selfhost/cmd/wwc/err.ww
Normal file
37
selfhost/cmd/wwc/err.ww
Normal file
@@ -0,0 +1,37 @@
|
||||
// selfhost/cmd/wwc/err.ww — port of cmd/wwc/err.c.
|
||||
//
|
||||
// Diagnostics. Plan 9 style: short, no levels beyond fatal/error/warn.
|
||||
// Output goes through os.write so we don't pull in libc stdio.
|
||||
|
||||
use os;
|
||||
use fmt;
|
||||
|
||||
type pos = struct {
|
||||
file: str,
|
||||
line: i32,
|
||||
col: i32,
|
||||
};
|
||||
|
||||
let nerrors: i32 = 0;
|
||||
let nwarnings: i32 = 0;
|
||||
|
||||
export fn fatal(msg: str) void = {
|
||||
fmt.errln(msg);
|
||||
os.exit(1);
|
||||
};
|
||||
|
||||
export fn errorf(p: pos, msg: str) void = {
|
||||
os.write(2, p.file.ptr, p.file.len: u64);
|
||||
os.write(2, ": error: ".ptr, 9u64);
|
||||
os.write(2, msg.ptr, msg.len: u64);
|
||||
os.write(2, "\n".ptr, 1u64);
|
||||
nerrors += 1;
|
||||
};
|
||||
|
||||
export fn warnf(p: pos, msg: str) void = {
|
||||
os.write(2, p.file.ptr, p.file.len: u64);
|
||||
os.write(2, ": warning: ".ptr, 11u64);
|
||||
os.write(2, msg.ptr, msg.len: u64);
|
||||
os.write(2, "\n".ptr, 1u64);
|
||||
nwarnings += 1;
|
||||
};
|
||||
656
selfhost/cmd/wwc/lex.ww
Normal file
656
selfhost/cmd/wwc/lex.ww
Normal file
@@ -0,0 +1,656 @@
|
||||
// selfhost/cmd/wwc/lex.ww — port of cmd/wwc/lex.c.
|
||||
//
|
||||
// The DFA, the helpers, and the order of decisions all mirror the C
|
||||
// version exactly. The 990_selfhost test diffs the resulting token
|
||||
// stream against the C-side wwdump byte-for-byte; any divergence is
|
||||
// a port bug.
|
||||
//
|
||||
// Calling-convention note: 6c can't yet pass or return structs >16
|
||||
// bytes by value, so `tok` and `pos` are passed by pointer (out
|
||||
// params). The C version passes `Tok` by value; we differ here only
|
||||
// in shape, not in observable behaviour. Token kind values stay
|
||||
// numerically identical.
|
||||
|
||||
use os;
|
||||
use ascii;
|
||||
use mem;
|
||||
use tok;
|
||||
|
||||
type lex = struct {
|
||||
file: str,
|
||||
src: *u8, // raw bytes; not necessarily NUL-terminated
|
||||
srclen: u64,
|
||||
lpos: u64,
|
||||
line: i32,
|
||||
col: i32,
|
||||
a: *arena,
|
||||
errs: i32,
|
||||
};
|
||||
|
||||
export fn lexinit(l: *lex, a: *arena, file: str, src: *u8, len: u64) void = {
|
||||
l.file = file;
|
||||
l.src = src;
|
||||
l.srclen = len;
|
||||
l.lpos = 0u64;
|
||||
l.line = 1;
|
||||
l.col = 1;
|
||||
l.a = a;
|
||||
l.errs = 0;
|
||||
};
|
||||
|
||||
// srcb — byte at offset; helper that lifts the cast out of indexing.
|
||||
fn srcb(l: *lex, off: u64) i32 = {
|
||||
let i: i32 = off: i32;
|
||||
let b: u8 = l.src[i];
|
||||
return b: i32;
|
||||
};
|
||||
|
||||
fn lpeek(l: *lex, ahead: u64) i32 = {
|
||||
let p: u64 = l.lpos + ahead;
|
||||
if (p >= l.srclen) { return -1; };
|
||||
return srcb(l, p);
|
||||
};
|
||||
|
||||
fn lget(l: *lex) i32 = {
|
||||
if (l.lpos >= l.srclen) { return -1; };
|
||||
let c: i32 = srcb(l, l.lpos);
|
||||
l.lpos += 1u64;
|
||||
if (c == 10) { // '\n'
|
||||
l.line += 1;
|
||||
l.col = 1;
|
||||
} else {
|
||||
l.col += 1;
|
||||
};
|
||||
return c;
|
||||
};
|
||||
|
||||
fn cur_pos(l: *lex, out: *pos) void = {
|
||||
out.file = l.file;
|
||||
out.line = l.line;
|
||||
out.col = l.col;
|
||||
};
|
||||
|
||||
// putuint — write `v` (signed, but always non-negative here) to fd 2
|
||||
// in decimal. Standalone so err_at doesn't drag in fmt and create a
|
||||
// dependency cycle with strconv.
|
||||
fn putuint(fd: i32, v: i32) void = {
|
||||
let tmp: [16]u8;
|
||||
let i: i32 = 0;
|
||||
let n: i32 = v;
|
||||
for (n > 0) {
|
||||
tmp[i] = ((n % 10) + 48): u8;
|
||||
n = n / 10;
|
||||
i += 1;
|
||||
};
|
||||
if (i == 0) { tmp[0] = 48u8; i = 1; };
|
||||
let buf: [16]u8;
|
||||
let m: i32 = 0;
|
||||
for (i > 0) { i -= 1; buf[m] = tmp[i]; m += 1; };
|
||||
os.write(fd, buf.ptr, m: u64);
|
||||
};
|
||||
|
||||
fn err_at(l: *lex, p: *pos, msg: str) void = {
|
||||
let pf: str = p.file;
|
||||
os.write(2, pf.ptr, pf.len: u64);
|
||||
os.write(2, ":".ptr, 1u64);
|
||||
putuint(2, p.line);
|
||||
os.write(2, ":".ptr, 1u64);
|
||||
putuint(2, p.col);
|
||||
os.write(2, ": error: ".ptr, 9u64);
|
||||
os.write(2, msg.ptr, msg.len: u64);
|
||||
os.write(2, "\n".ptr, 1u64);
|
||||
l.errs += 1;
|
||||
};
|
||||
|
||||
fn skipws(l: *lex) bool = {
|
||||
for (true) {
|
||||
let c: i32 = lpeek(l, 0u64);
|
||||
if (c < 0) { return false; };
|
||||
if (c == 32) { lget(l); continue; };
|
||||
if (c == 9) { lget(l); continue; };
|
||||
if (c == 13) { lget(l); continue; };
|
||||
if (c == 10) { lget(l); continue; };
|
||||
if (c == 47) { // '/'
|
||||
let c2: i32 = lpeek(l, 1u64);
|
||||
if (c2 == 47) {
|
||||
for (true) {
|
||||
let cx: i32 = lpeek(l, 0u64);
|
||||
if (cx < 0) { return false; };
|
||||
if (cx == 10) { break; };
|
||||
lget(l);
|
||||
};
|
||||
continue;
|
||||
};
|
||||
if (c2 == 42) { // '*'
|
||||
lget(l); lget(l);
|
||||
let prev: i32 = -1;
|
||||
for (true) {
|
||||
let x: i32 = lget(l);
|
||||
if (x < 0) {
|
||||
let cp: pos;
|
||||
cur_pos(l, &cp);
|
||||
err_at(l, &cp, "unterminated /* comment");
|
||||
return false;
|
||||
};
|
||||
if (prev == 42) {
|
||||
if (x == 47) { break; };
|
||||
};
|
||||
prev = x;
|
||||
};
|
||||
continue;
|
||||
};
|
||||
};
|
||||
return true;
|
||||
};
|
||||
return false;
|
||||
};
|
||||
|
||||
fn parseint(p: *u8, n: u64, base: i32, ok: *bool) u64 = {
|
||||
let v: u64 = 0u64;
|
||||
let got: bool = false;
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
let ix: i32 = i: i32;
|
||||
let c: u8 = p[ix];
|
||||
if (c == 95u8) { // '_'
|
||||
i += 1u64;
|
||||
continue;
|
||||
};
|
||||
let d: i32 = -1;
|
||||
if (c >= 48u8) {
|
||||
if (c <= 57u8) { d = (c - 48u8): i32; };
|
||||
};
|
||||
if (d < 0) {
|
||||
if (c >= 97u8) {
|
||||
if (c <= 102u8) { d = ((c - 97u8) + 10u8): i32; };
|
||||
};
|
||||
};
|
||||
if (d < 0) {
|
||||
if (c >= 65u8) {
|
||||
if (c <= 70u8) { d = ((c - 65u8) + 10u8): i32; };
|
||||
};
|
||||
};
|
||||
if (d < 0) { *ok = false; return 0u64; };
|
||||
if (d >= base) { *ok = false; return 0u64; };
|
||||
v = v * (base: u64) + (d: u64);
|
||||
got = true;
|
||||
i += 1u64;
|
||||
};
|
||||
*ok = got;
|
||||
return v;
|
||||
};
|
||||
|
||||
fn escape(l: *lex, out: *i32) bool = {
|
||||
let c: i32 = lget(l);
|
||||
if (c < 0) { return false; };
|
||||
if (c == 110) { *out = 10; return true; };
|
||||
if (c == 116) { *out = 9; return true; };
|
||||
if (c == 114) { *out = 13; return true; };
|
||||
if (c == 92) { *out = 92; return true; };
|
||||
if (c == 39) { *out = 39; return true; };
|
||||
if (c == 34) { *out = 34; return true; };
|
||||
if (c == 48) { *out = 0; return true; };
|
||||
if (c == 97) { *out = 7; return true; };
|
||||
if (c == 98) { *out = 8; return true; };
|
||||
if (c == 102) { *out = 12; return true; };
|
||||
if (c == 118) { *out = 11; return true; };
|
||||
if (c == 120) {
|
||||
let hi: i32 = lget(l);
|
||||
let lo: i32 = lget(l);
|
||||
if (hi < 0) { return false; };
|
||||
if (lo < 0) { return false; };
|
||||
if (!ascii.ishex(hi: u8)) {
|
||||
let cp: pos; cur_pos(l, &cp);
|
||||
err_at(l, &cp, "bad \\x escape");
|
||||
return false;
|
||||
};
|
||||
if (!ascii.ishex(lo: u8)) {
|
||||
let cp: pos; cur_pos(l, &cp);
|
||||
err_at(l, &cp, "bad \\x escape");
|
||||
return false;
|
||||
};
|
||||
let h: i32 = ascii.digitval(hi: u8);
|
||||
let lv: i32 = ascii.digitval(lo: u8);
|
||||
*out = (h << 4) | lv;
|
||||
return true;
|
||||
};
|
||||
let cp: pos; cur_pos(l, &cp);
|
||||
err_at(l, &cp, "bad escape");
|
||||
return false;
|
||||
};
|
||||
|
||||
// scan_decimal_run — consume a run of decimal digits and underscores.
|
||||
fn scan_decimal_run(l: *lex) void = {
|
||||
for (true) {
|
||||
let c: i32 = lpeek(l, 0u64);
|
||||
if (c < 0) { break; };
|
||||
if (!ascii.isdigit(c: u8)) {
|
||||
if (c != 95) { break; };
|
||||
};
|
||||
lget(l);
|
||||
};
|
||||
};
|
||||
|
||||
fn scan_hex_run(l: *lex) void = {
|
||||
for (true) {
|
||||
let c: i32 = lpeek(l, 0u64);
|
||||
if (c < 0) { break; };
|
||||
if (!ascii.ishex(c: u8)) {
|
||||
if (c != 95) { break; };
|
||||
};
|
||||
lget(l);
|
||||
};
|
||||
};
|
||||
|
||||
fn scan_bin_run(l: *lex) void = {
|
||||
for (true) {
|
||||
let c: i32 = lpeek(l, 0u64);
|
||||
if (c == 48) { lget(l); continue; };
|
||||
if (c == 49) { lget(l); continue; };
|
||||
if (c == 95) { lget(l); continue; };
|
||||
break;
|
||||
};
|
||||
};
|
||||
|
||||
fn scan_oct_run(l: *lex) void = {
|
||||
for (true) {
|
||||
let c: i32 = lpeek(l, 0u64);
|
||||
if (c < 48) { break; };
|
||||
if (c > 55) {
|
||||
if (c != 95) { break; };
|
||||
};
|
||||
lget(l);
|
||||
};
|
||||
};
|
||||
|
||||
// scan_exp — consume the [eE][+-]?[0-9]+ tail of a float, if present.
|
||||
fn scan_exp(l: *lex) void = {
|
||||
let e: i32 = lpeek(l, 0u64);
|
||||
if (e != 101) { if (e != 69) { return; }; }; // 'e' or 'E'
|
||||
lget(l);
|
||||
let s: i32 = lpeek(l, 0u64);
|
||||
if (s == 43) { lget(l); }
|
||||
else { if (s == 45) { lget(l); }; };
|
||||
for (true) {
|
||||
let c: i32 = lpeek(l, 0u64);
|
||||
if (c < 0) { break; };
|
||||
if (!ascii.isdigit(c: u8)) { break; };
|
||||
lget(l);
|
||||
};
|
||||
};
|
||||
|
||||
fn lexnum(l: *lex, start: *pos, out: *tok) void = {
|
||||
out.kind = TK_INT;
|
||||
out.file = start.file;
|
||||
out.line = start.line;
|
||||
out.col = start.col;
|
||||
let begin: u64 = l.lpos;
|
||||
let base: i32 = 10;
|
||||
let isfloat: bool = false;
|
||||
|
||||
let c0: i32 = lpeek(l, 0u64);
|
||||
let c1: i32 = lpeek(l, 1u64);
|
||||
|
||||
if (c0 == 48) { // '0'
|
||||
if (c1 == 120) { // 'x'
|
||||
lget(l); lget(l); base = 16; scan_hex_run(l);
|
||||
} else { if (c1 == 88) { // 'X'
|
||||
lget(l); lget(l); base = 16; scan_hex_run(l);
|
||||
} else { if (c1 == 98) { // 'b'
|
||||
lget(l); lget(l); base = 2; scan_bin_run(l);
|
||||
} else { if (c1 == 66) { // 'B'
|
||||
lget(l); lget(l); base = 2; scan_bin_run(l);
|
||||
} else { if (c1 == 111) { // 'o'
|
||||
lget(l); lget(l); base = 8; scan_oct_run(l);
|
||||
} else { if (c1 == 79) { // 'O'
|
||||
lget(l); lget(l); base = 8; scan_oct_run(l);
|
||||
} else {
|
||||
scan_decimal_run(l);
|
||||
if (lpeek(l, 0u64) == 46) {
|
||||
let after: i32 = lpeek(l, 1u64);
|
||||
if (after >= 48) {
|
||||
if (after <= 57) {
|
||||
isfloat = true;
|
||||
lget(l);
|
||||
scan_decimal_run(l);
|
||||
scan_exp(l);
|
||||
};
|
||||
};
|
||||
};
|
||||
};};};};};};
|
||||
} else {
|
||||
scan_decimal_run(l);
|
||||
if (lpeek(l, 0u64) == 46) {
|
||||
let after: i32 = lpeek(l, 1u64);
|
||||
if (after >= 48) {
|
||||
if (after <= 57) {
|
||||
isfloat = true;
|
||||
lget(l);
|
||||
scan_decimal_run(l);
|
||||
scan_exp(l);
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
let n: u64 = l.lpos - begin;
|
||||
out.text = astrndup(l.a, l.src + begin, n);
|
||||
|
||||
if (isfloat) {
|
||||
// out.fval is already 0 from the top-of-lexnext clear.
|
||||
// We don't strtod the literal yet — the diff fixtures we
|
||||
// care about are float-free; any TK_FLOAT seen in source
|
||||
// gets a placeholder value until we wire a real parser.
|
||||
out.kind = TK_FLOAT;
|
||||
} else {
|
||||
let digs: *u8 = l.src + begin;
|
||||
let dn: u64 = n;
|
||||
if (base != 10) {
|
||||
digs = digs + 2u64;
|
||||
dn -= 2u64;
|
||||
};
|
||||
let ok: bool = false;
|
||||
out.uval = parseint(digs, dn, base, &ok);
|
||||
if (!ok) {
|
||||
err_at(l, start, "bad integer literal");
|
||||
out.kind = TK_ERR;
|
||||
};
|
||||
};
|
||||
|
||||
let pc: i32 = lpeek(l, 0u64);
|
||||
if (pc >= 0) {
|
||||
if (ascii.isidstart(pc: u8)) {
|
||||
let sb: u64 = l.lpos;
|
||||
for (true) {
|
||||
let cc: i32 = lpeek(l, 0u64);
|
||||
if (cc < 0) { break; };
|
||||
if (!ascii.isidpart(cc: u8)) { break; };
|
||||
lget(l);
|
||||
};
|
||||
let sl: u64 = l.lpos - sb;
|
||||
let p: *u8 = l.src + sb;
|
||||
let isok: bool = false;
|
||||
if (sl == 2u64) {
|
||||
if (p[0] == 105u8) {
|
||||
if (p[1] == 56u8) { isok = true; }; // i8
|
||||
};
|
||||
if (p[0] == 117u8) {
|
||||
if (p[1] == 56u8) { isok = true; }; // u8
|
||||
};
|
||||
};
|
||||
if (sl == 3u64) {
|
||||
if (p[0] == 105u8) {
|
||||
if (p[1] == 49u8) { if (p[2] == 54u8) { isok = true; }; }; // i16
|
||||
if (p[1] == 51u8) { if (p[2] == 50u8) { isok = true; }; }; // i32
|
||||
if (p[1] == 54u8) { if (p[2] == 52u8) { isok = true; }; }; // i64
|
||||
};
|
||||
if (p[0] == 117u8) {
|
||||
if (p[1] == 49u8) { if (p[2] == 54u8) { isok = true; }; };
|
||||
if (p[1] == 51u8) { if (p[2] == 50u8) { isok = true; }; };
|
||||
if (p[1] == 54u8) { if (p[2] == 52u8) { isok = true; }; };
|
||||
};
|
||||
if (p[0] == 102u8) {
|
||||
if (p[1] == 51u8) { if (p[2] == 50u8) { isok = true; }; }; // f32
|
||||
if (p[1] == 54u8) { if (p[2] == 52u8) { isok = true; }; }; // f64
|
||||
};
|
||||
};
|
||||
if (isok) {
|
||||
out.tsuffix = astrndup(l.a, p, sl);
|
||||
} else {
|
||||
l.lpos = sb;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
fn lexident(l: *lex, start: *pos, out: *tok) void = {
|
||||
let begin: u64 = l.lpos;
|
||||
for (true) {
|
||||
let c: i32 = lpeek(l, 0u64);
|
||||
if (c < 0) { break; };
|
||||
if (!ascii.isidpart(c: u8)) { break; };
|
||||
lget(l);
|
||||
};
|
||||
let n: u64 = l.lpos - begin;
|
||||
let p: *u8 = l.src + begin;
|
||||
let k: i32 = kwlookup(p, n: i32);
|
||||
out.file = start.file;
|
||||
out.line = start.line;
|
||||
out.col = start.col;
|
||||
if (k != TK_NONE) {
|
||||
out.kind = k;
|
||||
} else {
|
||||
out.kind = TK_IDENT;
|
||||
};
|
||||
out.text = astrndup(l.a, p, n);
|
||||
};
|
||||
|
||||
fn lexstr(l: *lex, start: *pos, out: *tok) void = {
|
||||
let cap: u64 = 32u64;
|
||||
let nb: u64 = 0u64;
|
||||
let buf: *u8 = amalloc(l.a, cap): *u8;
|
||||
for (true) {
|
||||
let c: i32 = lpeek(l, 0u64);
|
||||
if (c < 0) {
|
||||
err_at(l, start, "unterminated string");
|
||||
out.kind = TK_ERR;
|
||||
out.file = start.file;
|
||||
out.line = start.line;
|
||||
out.col = start.col;
|
||||
out.text = astrndup(l.a, "".ptr, 0u64);
|
||||
return;
|
||||
};
|
||||
if (c == 34) { lget(l); break; };
|
||||
let ch: i32 = 0;
|
||||
if (c == 92) {
|
||||
lget(l);
|
||||
if (!escape(l, &ch)) { ch = 0; };
|
||||
} else {
|
||||
ch = lget(l);
|
||||
};
|
||||
if (nb + 1u64 >= cap) {
|
||||
let ncap: u64 = cap * 2u64;
|
||||
let nb2: *u8 = amalloc(l.a, ncap): *u8;
|
||||
let i: u64 = 0u64;
|
||||
for (i < nb) {
|
||||
let ix: i32 = i: i32;
|
||||
nb2[ix] = buf[ix];
|
||||
i += 1u64;
|
||||
};
|
||||
buf = nb2;
|
||||
cap = ncap;
|
||||
};
|
||||
let nbi: i32 = nb: i32;
|
||||
buf[nbi] = ch: u8;
|
||||
nb += 1u64;
|
||||
};
|
||||
out.kind = TK_STR;
|
||||
out.file = start.file;
|
||||
out.line = start.line;
|
||||
out.col = start.col;
|
||||
let s: str;
|
||||
s.ptr = buf;
|
||||
s.len = nb: i32;
|
||||
out.text = s;
|
||||
};
|
||||
|
||||
fn lexrune(l: *lex, start: *pos, out: *tok) void = {
|
||||
let c: i32 = lpeek(l, 0u64);
|
||||
if (c < 0) {
|
||||
err_at(l, start, "unterminated rune");
|
||||
out.kind = TK_ERR;
|
||||
out.file = start.file;
|
||||
out.line = start.line;
|
||||
out.col = start.col;
|
||||
out.text = astrndup(l.a, "".ptr, 0u64);
|
||||
return;
|
||||
};
|
||||
let ch: i32 = 0;
|
||||
if (c == 92) {
|
||||
lget(l);
|
||||
if (!escape(l, &ch)) { ch = 0; };
|
||||
} else {
|
||||
ch = lget(l);
|
||||
};
|
||||
if (lpeek(l, 0u64) != 39) {
|
||||
err_at(l, start, "rune literal missing closing '");
|
||||
out.kind = TK_ERR;
|
||||
out.file = start.file;
|
||||
out.line = start.line;
|
||||
out.col = start.col;
|
||||
out.text = astrndup(l.a, "".ptr, 0u64);
|
||||
return;
|
||||
};
|
||||
lget(l);
|
||||
out.kind = TK_RUNE;
|
||||
out.file = start.file;
|
||||
out.line = start.line;
|
||||
out.col = start.col;
|
||||
out.uval = ch: u64;
|
||||
};
|
||||
|
||||
fn emit_simple(start: *pos, k: i32, out: *tok) void = {
|
||||
out.kind = k;
|
||||
out.file = start.file;
|
||||
out.line = start.line;
|
||||
out.col = start.col;
|
||||
};
|
||||
|
||||
// set_pos_from — copy file/line/col from a *pos into a tok. Used by
|
||||
// the err-token path where we already have a pos.
|
||||
fn set_pos_from(out: *tok, p: *pos) void = {
|
||||
out.file = p.file;
|
||||
out.line = p.line;
|
||||
out.col = p.col;
|
||||
};
|
||||
|
||||
export fn lexnext(l: *lex, out: *tok) void = {
|
||||
// Reset the out token so callers can rely on stale fields being
|
||||
// cleared (they only inspect kind, pos, text, uval, fval, tsuffix
|
||||
// per kind).
|
||||
out.kind = TK_NONE;
|
||||
out.uval = 0u64;
|
||||
// out.fval starts cleared by the caller's stack-local init (lex.ww
|
||||
// allocates the tok with `let t: tok;` which zeroes). We avoid
|
||||
// writing a 0.0 literal here so this file itself stays float-free
|
||||
// and the C/ww wwdump diff over it is byte-identical.
|
||||
let empty: str;
|
||||
empty.ptr = nil;
|
||||
empty.len = 0;
|
||||
out.text = empty;
|
||||
out.tsuffix = empty;
|
||||
|
||||
if (!skipws(l)) {
|
||||
let p: pos; cur_pos(l, &p);
|
||||
emit_simple(&p, TK_EOF, out);
|
||||
return;
|
||||
};
|
||||
let start: pos; cur_pos(l, &start);
|
||||
let c: i32 = lpeek(l, 0u64);
|
||||
|
||||
if (c >= 0) {
|
||||
if (ascii.isidstart(c: u8)) { lexident(l, &start, out); return; };
|
||||
if (ascii.isdigit(c: u8)) { lexnum(l, &start, out); return; };
|
||||
};
|
||||
|
||||
if (c == 34) { lget(l); lexstr(l, &start, out); return; };
|
||||
if (c == 39) { lget(l); lexrune(l, &start, out); return; };
|
||||
|
||||
lget(l);
|
||||
|
||||
if (c == 40) { emit_simple(&start, TK_LPAREN, out); return; };
|
||||
if (c == 41) { emit_simple(&start, TK_RPAREN, out); return; };
|
||||
if (c == 123) { emit_simple(&start, TK_LBRACE, out); return; };
|
||||
if (c == 125) { emit_simple(&start, TK_RBRACE, out); return; };
|
||||
if (c == 91) { emit_simple(&start, TK_LBRACK, out); return; };
|
||||
if (c == 93) { emit_simple(&start, TK_RBRACK, out); return; };
|
||||
if (c == 44) { emit_simple(&start, TK_COMMA, out); return; };
|
||||
if (c == 59) { emit_simple(&start, TK_SEMI, out); return; };
|
||||
if (c == 58) { emit_simple(&start, TK_COLON, out); return; };
|
||||
if (c == 64) { emit_simple(&start, TK_AT, out); return; };
|
||||
if (c == 63) { emit_simple(&start, TK_QUESTION, out); return; };
|
||||
if (c == 126) { emit_simple(&start, TK_TILDE, out); return; };
|
||||
|
||||
if (c == 46) { // '.'
|
||||
if (lpeek(l, 0u64) == 46) {
|
||||
if (lpeek(l, 1u64) == 46) {
|
||||
lget(l); lget(l);
|
||||
emit_simple(&start, TK_ELLIPSIS, out); return;
|
||||
};
|
||||
lget(l);
|
||||
emit_simple(&start, TK_DOTDOT, out); return;
|
||||
};
|
||||
emit_simple(&start, TK_DOT, out); return;
|
||||
};
|
||||
|
||||
if (c == 43) {
|
||||
if (lpeek(l, 0u64) == 61) { lget(l); emit_simple(&start, TK_PLUSEQ, out); return; };
|
||||
emit_simple(&start, TK_PLUS, out); return;
|
||||
};
|
||||
if (c == 45) {
|
||||
if (lpeek(l, 0u64) == 61) { lget(l); emit_simple(&start, TK_MINUSEQ, out); return; };
|
||||
if (lpeek(l, 0u64) == 62) { lget(l); emit_simple(&start, TK_ARROW, out); return; };
|
||||
emit_simple(&start, TK_MINUS, out); return;
|
||||
};
|
||||
if (c == 42) {
|
||||
if (lpeek(l, 0u64) == 61) { lget(l); emit_simple(&start, TK_STAREQ, out); return; };
|
||||
emit_simple(&start, TK_STAR, out); return;
|
||||
};
|
||||
if (c == 47) {
|
||||
if (lpeek(l, 0u64) == 61) { lget(l); emit_simple(&start, TK_SLASHEQ, out); return; };
|
||||
emit_simple(&start, TK_SLASH, out); return;
|
||||
};
|
||||
if (c == 37) {
|
||||
if (lpeek(l, 0u64) == 61) { lget(l); emit_simple(&start, TK_PERCENTEQ, out); return; };
|
||||
emit_simple(&start, TK_PERCENT, out); return;
|
||||
};
|
||||
if (c == 38) {
|
||||
if (lpeek(l, 0u64) == 38) { lget(l); emit_simple(&start, TK_AND, out); return; };
|
||||
if (lpeek(l, 0u64) == 61) { lget(l); emit_simple(&start, TK_AMPEQ, out); return; };
|
||||
emit_simple(&start, TK_AMP, out); return;
|
||||
};
|
||||
if (c == 124) {
|
||||
if (lpeek(l, 0u64) == 124) { lget(l); emit_simple(&start, TK_OR, out); return; };
|
||||
if (lpeek(l, 0u64) == 61) { lget(l); emit_simple(&start, TK_PIPEEQ, out); return; };
|
||||
emit_simple(&start, TK_PIPE, out); return;
|
||||
};
|
||||
if (c == 94) {
|
||||
if (lpeek(l, 0u64) == 61) { lget(l); emit_simple(&start, TK_CARETEQ, out); return; };
|
||||
emit_simple(&start, TK_CARET, out); return;
|
||||
};
|
||||
if (c == 61) {
|
||||
if (lpeek(l, 0u64) == 61) { lget(l); emit_simple(&start, TK_EQ, out); return; };
|
||||
if (lpeek(l, 0u64) == 62) { lget(l); emit_simple(&start, TK_FATARROW, out); return; };
|
||||
emit_simple(&start, TK_ASSIGN, out); return;
|
||||
};
|
||||
if (c == 33) {
|
||||
if (lpeek(l, 0u64) == 61) { lget(l); emit_simple(&start, TK_NEQ, out); return; };
|
||||
emit_simple(&start, TK_NOT, out); return;
|
||||
};
|
||||
if (c == 60) {
|
||||
if (lpeek(l, 0u64) == 60) {
|
||||
lget(l);
|
||||
if (lpeek(l, 0u64) == 61) { lget(l); emit_simple(&start, TK_LSHIFTEQ, out); return; };
|
||||
emit_simple(&start, TK_LSHIFT, out); return;
|
||||
};
|
||||
if (lpeek(l, 0u64) == 61) { lget(l); emit_simple(&start, TK_LE, out); return; };
|
||||
if (lpeek(l, 0u64) == 45) { lget(l); emit_simple(&start, TK_LARROW, out); return; };
|
||||
emit_simple(&start, TK_LT, out); return;
|
||||
};
|
||||
if (c == 62) {
|
||||
if (lpeek(l, 0u64) == 62) {
|
||||
lget(l);
|
||||
if (lpeek(l, 0u64) == 61) { lget(l); emit_simple(&start, TK_RSHIFTEQ, out); return; };
|
||||
emit_simple(&start, TK_RSHIFT, out); return;
|
||||
};
|
||||
if (lpeek(l, 0u64) == 61) { lget(l); emit_simple(&start, TK_GE, out); return; };
|
||||
emit_simple(&start, TK_GT, out); return;
|
||||
};
|
||||
|
||||
err_at(l, &start, "unexpected character");
|
||||
out.kind = TK_ERR;
|
||||
set_pos_from(out, &start);
|
||||
let one: [1]u8;
|
||||
one[0] = c: u8;
|
||||
out.text = astrndup(l.a, one.ptr, 1u64);
|
||||
};
|
||||
106
selfhost/cmd/wwc/mem.ww
Normal file
106
selfhost/cmd/wwc/mem.ww
Normal file
@@ -0,0 +1,106 @@
|
||||
// selfhost/cmd/wwc/mem.ww — port of cmd/wwc/mem.c.
|
||||
//
|
||||
// Bump arena allocator. Backed by the runtime page allocator
|
||||
// (rt_alloc / rt_free), no libc. Each chunk is mmap'd; when the
|
||||
// current chunk runs out we link a fresh one. Freeing the arena
|
||||
// unmaps the chain.
|
||||
//
|
||||
// Memory handed out is 16-byte aligned. The C version under
|
||||
// cmd/wwc/ is retained until the three-stage bootstrap diffs clean.
|
||||
|
||||
use os;
|
||||
|
||||
def ALIGN: u64 = 16u64;
|
||||
def INIT_CHUNK: u64 = 65536u64;
|
||||
def MAX_CHUNK: u64 = 4194304u64;
|
||||
def ARENA_SZ: u64 = 48u64; // sizeof(arena), kept in sync below
|
||||
|
||||
type arena = struct {
|
||||
buf: *u8,
|
||||
off: u64,
|
||||
cap: u64,
|
||||
next: *arena,
|
||||
total: u64,
|
||||
};
|
||||
|
||||
fn roundup(n: u64, a: u64) u64 = {
|
||||
return (n + a - 1u64) & ~(a - 1u64);
|
||||
};
|
||||
|
||||
export fn newarena() *arena = {
|
||||
let a: *arena = os.alloc(ARENA_SZ): *arena;
|
||||
a.buf = os.alloc(INIT_CHUNK): *u8;
|
||||
a.off = 0u64;
|
||||
a.cap = INIT_CHUNK;
|
||||
a.next = nil;
|
||||
a.total = 0u64;
|
||||
return a;
|
||||
};
|
||||
|
||||
// Grow: link a fresh chunk in front of the head. We push the old
|
||||
// chunk into `next` so the head always describes the current bump
|
||||
// region. Chunk size doubles up to MAX_CHUNK.
|
||||
fn grow(a: *arena, need: u64) bool = {
|
||||
let want: u64 = a.cap * 2u64;
|
||||
if (want < need) { want = need; };
|
||||
if (want > MAX_CHUNK) { want = MAX_CHUNK; };
|
||||
if (want < need) { return false; }; // single allocation too big
|
||||
|
||||
let old: *arena = os.alloc(ARENA_SZ): *arena;
|
||||
old.buf = a.buf;
|
||||
old.off = a.off;
|
||||
old.cap = a.cap;
|
||||
old.next = a.next;
|
||||
old.total = 0u64;
|
||||
|
||||
a.buf = os.alloc(want): *u8;
|
||||
a.off = 0u64;
|
||||
a.cap = want;
|
||||
a.next = old;
|
||||
return true;
|
||||
};
|
||||
|
||||
export fn amalloc(a: *arena, n: u64) *void = {
|
||||
let need: u64 = roundup(n, ALIGN);
|
||||
if (need > a.cap - a.off) {
|
||||
if (!grow(a, need)) { return nil; };
|
||||
};
|
||||
let p: *u8 = a.buf + a.off;
|
||||
a.off += need;
|
||||
a.total += need;
|
||||
// Zero the region. Plan 9 amalloc zeroes; we mirror that here so
|
||||
// the checker can assume freshly allocated nodes start at 0.
|
||||
let i: u64 = 0u64;
|
||||
for (i < need) {
|
||||
p[i] = 0u8;
|
||||
i += 1u64;
|
||||
};
|
||||
return p: *void;
|
||||
};
|
||||
|
||||
// astrndup — copy `n` bytes into the arena and produce a NUL-terminated
|
||||
// view. Returns a `str` whose ptr is arena-owned and whose len is `n`
|
||||
// (the trailing NUL is past `len`, so callers reading exactly n bytes
|
||||
// see no padding). Used by the lexer to capture token text.
|
||||
export fn astrndup(a: *arena, src: *u8, n: u64) str = {
|
||||
let p: *u8 = amalloc(a, n + 1u64): *u8;
|
||||
let i: u64 = 0u64;
|
||||
for (i < n) {
|
||||
p[i] = src[i];
|
||||
i += 1u64;
|
||||
};
|
||||
p[n] = 0u8;
|
||||
let r: str;
|
||||
r.ptr = p;
|
||||
r.len = n: i32;
|
||||
return r;
|
||||
};
|
||||
|
||||
export fn freearena(a: *arena) void = {
|
||||
for (a != nil) {
|
||||
let next: *arena = a.next;
|
||||
os.free(a.buf: *void, a.cap);
|
||||
os.free(a: *void, ARENA_SZ);
|
||||
a = next;
|
||||
};
|
||||
};
|
||||
960
selfhost/cmd/wwc/parse.ww
Normal file
960
selfhost/cmd/wwc/parse.ww
Normal file
@@ -0,0 +1,960 @@
|
||||
// selfhost/cmd/wwc/parse.ww — port of cmd/wwc/parse.c.
|
||||
//
|
||||
// Status: GROWING stub. Currently handles top-level `use IDENT;`,
|
||||
// `def NAME: TYPE = LIT;`, `type NAME = TYPE;`, and `fn NAME(params)
|
||||
// RET;` (header-only — bodies are recovered past). Unknown decls are
|
||||
// chewed token-by-token until the next ';' so the diff probe can
|
||||
// still anchor on partial fixtures.
|
||||
//
|
||||
// The full port is multi-session work — parse.c is 1,183 lines of
|
||||
// hand-rolled recursive descent + Pratt expression parser. Each
|
||||
// surface form lands here gradually so the AST diff in 990_selfhost
|
||||
// grows toward whole-language coverage one increment at a time.
|
||||
//
|
||||
// Calling-convention shim: 6c can't yet pass a sub-struct field
|
||||
// (e.g. p.cur.line where p.cur is a `tok` of size 76). The parser
|
||||
// stores the current token as flat primitive fields rather than a
|
||||
// nested `tok` struct; `refill` copies a freshly lexed token in.
|
||||
|
||||
use os;
|
||||
use mem;
|
||||
use tok;
|
||||
|
||||
type parser = struct {
|
||||
l: *lex,
|
||||
a: *arena,
|
||||
errs: i32,
|
||||
// nocast: while inside `[...]` we treat ':' as the slice
|
||||
// separator, not the cast operator. Mirrors parse.c's flag.
|
||||
nocast: i32,
|
||||
cur_kind: i32,
|
||||
cur_file: str,
|
||||
cur_line: i32,
|
||||
cur_col: i32,
|
||||
cur_text: str,
|
||||
cur_uval: u64,
|
||||
};
|
||||
|
||||
fn refill(p: *parser) void = {
|
||||
let t: tok;
|
||||
lexnext(p.l, &t);
|
||||
p.cur_kind = t.kind;
|
||||
p.cur_file = t.file;
|
||||
p.cur_line = t.line;
|
||||
p.cur_col = t.col;
|
||||
p.cur_text = t.text;
|
||||
p.cur_uval = t.uval;
|
||||
};
|
||||
|
||||
export fn parserinit(p: *parser, a: *arena, l: *lex) void = {
|
||||
p.l = l;
|
||||
p.a = a;
|
||||
p.errs = 0;
|
||||
p.nocast = 0;
|
||||
refill(p);
|
||||
};
|
||||
|
||||
fn advance(p: *parser) void = { refill(p); };
|
||||
|
||||
fn accept_tok(p: *parser, k: i32) bool = {
|
||||
if (p.cur_kind == k) { advance(p); return true; };
|
||||
return false;
|
||||
};
|
||||
|
||||
fn err_msg(p: *parser, msg: str) void = {
|
||||
let pre: str = "parse: ";
|
||||
os.write(2, pre.ptr, pre.len: u64);
|
||||
os.write(2, msg.ptr, msg.len: u64);
|
||||
os.write(2, "\n".ptr, 1u64);
|
||||
p.errs += 1;
|
||||
};
|
||||
|
||||
fn expect_tok(p: *parser, k: i32, what: str) bool = {
|
||||
if (p.cur_kind == k) { advance(p); return true; };
|
||||
err_msg(p, what);
|
||||
return false;
|
||||
};
|
||||
|
||||
// expectident — consume the current TK_IDENT and return its text.
|
||||
// Returns the empty str on error (and advances to make progress).
|
||||
fn expectident(p: *parser, into: *str) bool = {
|
||||
if (p.cur_kind != TK_IDENT) {
|
||||
err_msg(p, "expected identifier");
|
||||
advance(p);
|
||||
return false;
|
||||
};
|
||||
*into = p.cur_text;
|
||||
advance(p);
|
||||
return true;
|
||||
};
|
||||
|
||||
// ---- type expressions ------------------------------------------------
|
||||
//
|
||||
// Currently: TNAME (single ident, no dotted path yet) and TPTR (`*T`).
|
||||
// Other forms (slice, array, struct, fn, chan, tuple, tagged) will
|
||||
// land in subsequent commits.
|
||||
|
||||
fn parsetype(p: *parser) *node = {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
|
||||
if (p.cur_kind == TK_STAR) {
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_TPTR, pf, pl, pc);
|
||||
n.lhs = parsetype(p);
|
||||
return n;
|
||||
};
|
||||
|
||||
if (p.cur_kind == TK_LBRACK) {
|
||||
advance(p);
|
||||
if (p.cur_kind == TK_RBRACK) {
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_TSLICE, pf, pl, pc);
|
||||
n.lhs = parsetype(p);
|
||||
return n;
|
||||
};
|
||||
let n: *node = newnode(p.a, N_TARRAY, pf, pl, pc);
|
||||
n.rhs = parseexpr(p);
|
||||
expect_tok(p, TK_RBRACK, "expected ']' in array type");
|
||||
n.lhs = parsetype(p);
|
||||
return n;
|
||||
};
|
||||
|
||||
if (p.cur_kind == TK_STRUCT) {
|
||||
advance(p);
|
||||
expect_tok(p, TK_LBRACE, "expected '{' after struct");
|
||||
let n: *node = newnode(p.a, N_TSTRUCT, pf, pl, pc);
|
||||
let fhead: *node = nil;
|
||||
let ftail: *node = nil;
|
||||
for (p.cur_kind != TK_RBRACE) {
|
||||
if (p.cur_kind == TK_EOF) { break; };
|
||||
let fpf: str = p.cur_file;
|
||||
let fpl: i32 = p.cur_line;
|
||||
let fpc: i32 = p.cur_col;
|
||||
let f: *node = newnode(p.a, N_TFIELD, fpf, fpl, fpc);
|
||||
let fid: str;
|
||||
expectident(p, &fid);
|
||||
f.str = fid;
|
||||
expect_tok(p, TK_COLON, "expected ':' in field");
|
||||
f.lhs = parsetype(p);
|
||||
if (fhead == nil) { fhead = f; ftail = f; }
|
||||
else { ftail.next = f; ftail = f; };
|
||||
if (!accept_tok(p, TK_COMMA)) { break; };
|
||||
};
|
||||
expect_tok(p, TK_RBRACE, "expected '}' after struct fields");
|
||||
n.list = fhead;
|
||||
return n;
|
||||
};
|
||||
|
||||
if (p.cur_kind == TK_IDENT) {
|
||||
let n: *node = newnode(p.a, N_TNAME, pf, pl, pc);
|
||||
n.str = p.cur_text;
|
||||
advance(p);
|
||||
// Dotted path collapse (pkg.Type) deferred — fixtures don't
|
||||
// need it yet.
|
||||
return n;
|
||||
};
|
||||
|
||||
if (p.cur_kind == TK_LPAREN) {
|
||||
// (T) or (T, T, ...) or (T | T | ...)
|
||||
advance(p);
|
||||
let first: *node = parsetype(p);
|
||||
if (accept_tok(p, TK_PIPE)) {
|
||||
let n: *node = newnode(p.a, N_TTAGGED, pf, pl, pc);
|
||||
let head: *node = first;
|
||||
let tail: *node = first;
|
||||
for (true) {
|
||||
let e: *node = parsetype(p);
|
||||
tail.next = e;
|
||||
tail = e;
|
||||
if (!accept_tok(p, TK_PIPE)) { break; };
|
||||
};
|
||||
expect_tok(p, TK_RPAREN, "expected ')' in tagged-union type");
|
||||
n.list = head;
|
||||
return n;
|
||||
};
|
||||
if (!accept_tok(p, TK_COMMA)) {
|
||||
expect_tok(p, TK_RPAREN, "expected ')' after parenthesised type");
|
||||
return first;
|
||||
};
|
||||
let n: *node = newnode(p.a, N_TTUPLE, pf, pl, pc);
|
||||
let head: *node = first;
|
||||
let tail: *node = first;
|
||||
for (true) {
|
||||
let e: *node = parsetype(p);
|
||||
tail.next = e;
|
||||
tail = e;
|
||||
if (!accept_tok(p, TK_COMMA)) { break; };
|
||||
if (p.cur_kind == TK_RPAREN) { break; };
|
||||
};
|
||||
expect_tok(p, TK_RPAREN, "expected ')' in tuple type");
|
||||
n.list = head;
|
||||
return n;
|
||||
};
|
||||
|
||||
if (p.cur_kind == TK_FN) {
|
||||
advance(p);
|
||||
expect_tok(p, TK_LPAREN, "expected '(' after fn in type");
|
||||
let n: *node = newnode(p.a, N_TFN, pf, pl, pc);
|
||||
// Anonymous-or-named params: parseparams handles named only;
|
||||
// for fn-type expressions the C parser allows IDENT-less
|
||||
// (anonymous) params. Stub: only named params for now.
|
||||
n.list = parseparams(p);
|
||||
expect_tok(p, TK_RPAREN, "expected ')' after fn type params");
|
||||
n.lhs = parsetype(p);
|
||||
return n;
|
||||
};
|
||||
|
||||
err_msg(p, "expected type");
|
||||
advance(p);
|
||||
return newnode(p.a, N_TNAME, pf, pl, pc);
|
||||
};
|
||||
|
||||
// ---- expressions (Pratt) ---------------------------------------------
|
||||
//
|
||||
// Forwards: parseexpr → parsebin → parseunary → parsepostfix(parseprimary).
|
||||
// Tuple literals, match expressions, struct literals, slice [lo:hi],
|
||||
// and the ?/! try operators are not yet wired — they'll arrive as the
|
||||
// AST diff fixture grows to need them.
|
||||
|
||||
fn bprec(k: i32) i32 = {
|
||||
if (k == TK_OR) { return 1; };
|
||||
if (k == TK_AND) { return 2; };
|
||||
if (k == TK_EQ) { return 3; };
|
||||
if (k == TK_NEQ) { return 3; };
|
||||
if (k == TK_LT) { return 4; };
|
||||
if (k == TK_LE) { return 4; };
|
||||
if (k == TK_GT) { return 4; };
|
||||
if (k == TK_GE) { return 4; };
|
||||
if (k == TK_PIPE) { return 5; };
|
||||
if (k == TK_CARET) { return 6; };
|
||||
if (k == TK_AMP) { return 7; };
|
||||
if (k == TK_LSHIFT) { return 8; };
|
||||
if (k == TK_RSHIFT) { return 8; };
|
||||
if (k == TK_PLUS) { return 9; };
|
||||
if (k == TK_MINUS) { return 9; };
|
||||
if (k == TK_STAR) { return 10; };
|
||||
if (k == TK_SLASH) { return 10; };
|
||||
if (k == TK_PERCENT) { return 10; };
|
||||
return 0;
|
||||
};
|
||||
|
||||
fn isassignop(k: i32) bool = {
|
||||
if (k == TK_ASSIGN) { return true; };
|
||||
if (k == TK_PLUSEQ) { return true; };
|
||||
if (k == TK_MINUSEQ) { return true; };
|
||||
if (k == TK_STAREQ) { return true; };
|
||||
if (k == TK_SLASHEQ) { return true; };
|
||||
if (k == TK_PERCENTEQ) { return true; };
|
||||
if (k == TK_AMPEQ) { return true; };
|
||||
if (k == TK_PIPEEQ) { return true; };
|
||||
if (k == TK_CARETEQ) { return true; };
|
||||
if (k == TK_LSHIFTEQ) { return true; };
|
||||
if (k == TK_RSHIFTEQ) { return true; };
|
||||
return false;
|
||||
};
|
||||
|
||||
// Forward references between parseunary/parseexpr/parsebin/parsepostfix
|
||||
// are resolved by the two-pass checker — no body-less prototypes needed.
|
||||
|
||||
fn parseprimary(p: *parser) *node = {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
|
||||
if (p.cur_kind == TK_INT) {
|
||||
let n: *node = newnode(p.a, N_INTLIT, pf, pl, pc);
|
||||
n.uval = p.cur_uval;
|
||||
n.str = p.cur_text;
|
||||
advance(p);
|
||||
return n;
|
||||
};
|
||||
if (p.cur_kind == TK_STR) {
|
||||
let n: *node = newnode(p.a, N_STRLIT, pf, pl, pc);
|
||||
n.str = p.cur_text;
|
||||
advance(p);
|
||||
return n;
|
||||
};
|
||||
if (p.cur_kind == TK_RUNE) {
|
||||
let n: *node = newnode(p.a, N_RUNELIT, pf, pl, pc);
|
||||
n.uval = p.cur_uval;
|
||||
advance(p);
|
||||
return n;
|
||||
};
|
||||
if (p.cur_kind == TK_TRUE) {
|
||||
advance(p);
|
||||
return newnode(p.a, N_TRUE, pf, pl, pc);
|
||||
};
|
||||
if (p.cur_kind == TK_FALSE) {
|
||||
advance(p);
|
||||
return newnode(p.a, N_FALSE, pf, pl, pc);
|
||||
};
|
||||
if (p.cur_kind == TK_NIL) {
|
||||
advance(p);
|
||||
return newnode(p.a, N_NIL, pf, pl, pc);
|
||||
};
|
||||
if (p.cur_kind == TK_LPAREN) {
|
||||
advance(p);
|
||||
let e: *node = parseexpr(p);
|
||||
// Tuple literal: (a, b, ...)
|
||||
if (accept_tok(p, TK_COMMA)) {
|
||||
let t: *node = newnode(p.a, N_TUPLE, pf, pl, pc);
|
||||
t.list = e;
|
||||
let tail: *node = e;
|
||||
for (true) {
|
||||
if (p.cur_kind == TK_RPAREN) { break; };
|
||||
let en: *node = parseexpr(p);
|
||||
tail.next = en;
|
||||
tail = en;
|
||||
if (!accept_tok(p, TK_COMMA)) { break; };
|
||||
};
|
||||
expect_tok(p, TK_RPAREN, "expected ')' in tuple");
|
||||
return t;
|
||||
};
|
||||
expect_tok(p, TK_RPAREN, "expected ')'");
|
||||
return e;
|
||||
};
|
||||
if (p.cur_kind == TK_IDENT) {
|
||||
let n: *node = newnode(p.a, N_IDENT, pf, pl, pc);
|
||||
n.str = p.cur_text;
|
||||
advance(p);
|
||||
// `IDENT {` — struct literal. Disambiguate: only consume as a
|
||||
// struct lit when we're not in a context where '{' starts a
|
||||
// block (e.g. `if (cond) {`). The parser is called from
|
||||
// expressions, never directly from cond contexts that need a
|
||||
// block; in stmt parsing, the for/if drivers consume their
|
||||
// own paren/cond, so this is safe.
|
||||
if (p.cur_kind == TK_LBRACE) {
|
||||
advance(p);
|
||||
let s: *node = newnode(p.a, N_STRUCTLIT, pf, pl, pc);
|
||||
s.lhs = n;
|
||||
let head: *node = nil;
|
||||
let tail: *node = nil;
|
||||
for (p.cur_kind != TK_RBRACE) {
|
||||
if (p.cur_kind == TK_EOF) { break; };
|
||||
let fpf: str = p.cur_file;
|
||||
let fpl: i32 = p.cur_line;
|
||||
let fpc: i32 = p.cur_col;
|
||||
let id: str;
|
||||
expectident(p, &id);
|
||||
expect_tok(p, TK_ASSIGN, "expected '=' in struct lit field");
|
||||
let v: *node = parseexpr(p);
|
||||
let f: *node = newnode(p.a, N_FIELD, fpf, fpl, fpc);
|
||||
f.str = id;
|
||||
f.lhs = v;
|
||||
if (head == nil) { head = f; tail = f; }
|
||||
else { tail.next = f; tail = f; };
|
||||
if (!accept_tok(p, TK_COMMA)) { break; };
|
||||
};
|
||||
expect_tok(p, TK_RBRACE, "expected '}' after struct literal");
|
||||
s.list = head;
|
||||
return s;
|
||||
};
|
||||
return n;
|
||||
};
|
||||
if (p.cur_kind == TK_MATCH) {
|
||||
// match (e) { case let v: T => stmt; case T => stmt; case => stmt; };
|
||||
advance(p);
|
||||
expect_tok(p, TK_LPAREN, "expected '(' after match");
|
||||
let m: *node = newnode(p.a, N_MATCH, pf, pl, pc);
|
||||
m.lhs = parseexpr(p);
|
||||
expect_tok(p, TK_RPAREN, "expected ')' after match scrutinee");
|
||||
expect_tok(p, TK_LBRACE, "expected '{' to open match body");
|
||||
let head: *node = nil;
|
||||
let tail: *node = nil;
|
||||
for (p.cur_kind == TK_CASE) {
|
||||
let cf: str = p.cur_file;
|
||||
let cl: i32 = p.cur_line;
|
||||
let cc: i32 = p.cur_col;
|
||||
advance(p); // past `case`
|
||||
let mc: *node = newnode(p.a, N_MCASE, cf, cl, cc);
|
||||
if (p.cur_kind == TK_LET) {
|
||||
advance(p);
|
||||
let id: str;
|
||||
expectident(p, &id);
|
||||
mc.str = id;
|
||||
expect_tok(p, TK_COLON, "expected ':' after match binding");
|
||||
mc.lhs = parsetype(p);
|
||||
} else { if (p.cur_kind != TK_FATARROW) {
|
||||
mc.lhs = parsetype(p);
|
||||
};};
|
||||
expect_tok(p, TK_FATARROW, "expected '=>' in match arm");
|
||||
mc.body = parsestmt(p);
|
||||
if (head == nil) { head = mc; tail = mc; }
|
||||
else { tail.next = mc; tail = mc; };
|
||||
};
|
||||
expect_tok(p, TK_RBRACE, "expected '}' after match body");
|
||||
m.list = head;
|
||||
return m;
|
||||
};
|
||||
err_msg(p, "expected expression");
|
||||
advance(p);
|
||||
return newnode(p.a, N_NONE, pf, pl, pc);
|
||||
};
|
||||
|
||||
fn parsearglist(p: *parser, close_kind: i32, head_out: **node) void = {
|
||||
*head_out = nil;
|
||||
if (p.cur_kind == close_kind) { return; };
|
||||
let head: *node = nil;
|
||||
let tail: *node = nil;
|
||||
for (true) {
|
||||
let e: *node = parseexpr(p);
|
||||
if (head == nil) { head = e; tail = e; }
|
||||
else { tail.next = e; tail = e; };
|
||||
if (!accept_tok(p, TK_COMMA)) { break; };
|
||||
if (p.cur_kind == close_kind) { break; };
|
||||
};
|
||||
*head_out = head;
|
||||
};
|
||||
|
||||
fn parsepostfix(p: *parser, lhs: *node) *node = {
|
||||
let cur: *node = lhs;
|
||||
for (true) {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
if (p.cur_kind == TK_LPAREN) {
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_CALL, pf, pl, pc);
|
||||
n.lhs = cur;
|
||||
let arghead: *node = nil;
|
||||
parsearglist(p, TK_RPAREN, &arghead);
|
||||
n.list = arghead;
|
||||
expect_tok(p, TK_RPAREN, "expected ')' after args");
|
||||
cur = n;
|
||||
continue;
|
||||
};
|
||||
if (p.cur_kind == TK_LBRACK) {
|
||||
advance(p);
|
||||
// `[ : hi ]` — slice with implicit lo = 0.
|
||||
if (p.cur_kind == TK_COLON) {
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_SLICE, pf, pl, pc);
|
||||
n.lhs = cur;
|
||||
if (p.cur_kind != TK_RBRACK) {
|
||||
n.cond = parseexpr(p);
|
||||
};
|
||||
expect_tok(p, TK_RBRACK, "expected ']' in slice");
|
||||
cur = n;
|
||||
continue;
|
||||
};
|
||||
// Suppress cast inside `[...]` so ':' parses as slice
|
||||
// separator rather than the postfix cast operator.
|
||||
let prev: i32 = p.nocast;
|
||||
p.nocast = 1;
|
||||
let e: *node = parseexpr(p);
|
||||
p.nocast = prev;
|
||||
if (p.cur_kind == TK_COLON) {
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_SLICE, pf, pl, pc);
|
||||
n.lhs = cur;
|
||||
n.rhs = e;
|
||||
if (p.cur_kind != TK_RBRACK) {
|
||||
n.cond = parseexpr(p);
|
||||
};
|
||||
expect_tok(p, TK_RBRACK, "expected ']' in slice");
|
||||
cur = n;
|
||||
continue;
|
||||
};
|
||||
let n: *node = newnode(p.a, N_INDEX, pf, pl, pc);
|
||||
n.lhs = cur;
|
||||
n.rhs = e;
|
||||
expect_tok(p, TK_RBRACK, "expected ']' after index");
|
||||
cur = n;
|
||||
continue;
|
||||
};
|
||||
if (p.cur_kind == TK_DOT) {
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_DOT, pf, pl, pc);
|
||||
n.lhs = cur;
|
||||
let id: str;
|
||||
expectident(p, &id);
|
||||
n.str = id;
|
||||
cur = n;
|
||||
continue;
|
||||
};
|
||||
if (p.cur_kind == TK_COLON) {
|
||||
if (p.nocast != 0) {
|
||||
return cur;
|
||||
};
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_CAST, pf, pl, pc);
|
||||
n.lhs = cur;
|
||||
n.rhs = parsetype(p);
|
||||
cur = n;
|
||||
continue;
|
||||
};
|
||||
break;
|
||||
};
|
||||
return cur;
|
||||
};
|
||||
|
||||
fn parseunary(p: *parser) *node = {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
let k: i32 = p.cur_kind;
|
||||
if (k == TK_MINUS) {
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_UN, pf, pl, pc);
|
||||
n.op = TK_MINUS; n.lhs = parseunary(p);
|
||||
return n;
|
||||
};
|
||||
if (k == TK_PLUS) {
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_UN, pf, pl, pc);
|
||||
n.op = TK_PLUS; n.lhs = parseunary(p);
|
||||
return n;
|
||||
};
|
||||
if (k == TK_NOT) {
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_UN, pf, pl, pc);
|
||||
n.op = TK_NOT; n.lhs = parseunary(p);
|
||||
return n;
|
||||
};
|
||||
if (k == TK_TILDE) {
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_UN, pf, pl, pc);
|
||||
n.op = TK_TILDE; n.lhs = parseunary(p);
|
||||
return n;
|
||||
};
|
||||
if (k == TK_STAR) {
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_UN, pf, pl, pc);
|
||||
n.op = TK_STAR; n.lhs = parseunary(p);
|
||||
return n;
|
||||
};
|
||||
if (k == TK_AMP) {
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_UN, pf, pl, pc);
|
||||
n.op = TK_AMP; n.lhs = parseunary(p);
|
||||
return n;
|
||||
};
|
||||
return parsepostfix(p, parseprimary(p));
|
||||
};
|
||||
|
||||
fn parsebin(p: *parser, lhs: *node, minp: i32) *node = {
|
||||
let cur: *node = lhs;
|
||||
for (true) {
|
||||
let op: i32 = p.cur_kind;
|
||||
let pr: i32 = bprec(op);
|
||||
if (pr == 0) { return cur; };
|
||||
if (pr < minp) { return cur; };
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
advance(p);
|
||||
let rhs: *node = parseunary(p);
|
||||
for (true) {
|
||||
let np: i32 = bprec(p.cur_kind);
|
||||
if (np <= pr) { break; };
|
||||
rhs = parsebin(p, rhs, np);
|
||||
};
|
||||
let n: *node = newnode(p.a, N_BIN, pf, pl, pc);
|
||||
n.op = op; n.lhs = cur; n.rhs = rhs;
|
||||
cur = n;
|
||||
};
|
||||
return cur;
|
||||
};
|
||||
|
||||
fn parseexpr(p: *parser) *node = {
|
||||
let e: *node = parsebin(p, parseunary(p), 1);
|
||||
if (isassignop(p.cur_kind)) {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
let op: i32 = p.cur_kind;
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_ASSIGN, pf, pl, pc);
|
||||
n.op = op;
|
||||
n.lhs = e;
|
||||
n.rhs = parseexpr(p); // right-associative
|
||||
return n;
|
||||
};
|
||||
return e;
|
||||
};
|
||||
|
||||
// ---- statements ------------------------------------------------------
|
||||
//
|
||||
// Subset wired today: block, let, return, if (no else-if chain), for
|
||||
// (single-cond C-style), expr-stmt, defer, break, continue. Switch
|
||||
// and match arms are not yet wired; tuple-let / multi-let neither.
|
||||
|
||||
fn parselet_local(p: *parser) *node = {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
advance(p); // past `let`
|
||||
let n: *node = newnode(p.a, N_LET, pf, pl, pc);
|
||||
let id: str;
|
||||
expectident(p, &id);
|
||||
n.str = id;
|
||||
if (accept_tok(p, TK_COLON)) {
|
||||
n.lhs = parsetype(p);
|
||||
};
|
||||
if (accept_tok(p, TK_ASSIGN)) {
|
||||
n.rhs = parseexpr(p);
|
||||
};
|
||||
expect_tok(p, TK_SEMI, "expected ';' after let");
|
||||
return n;
|
||||
};
|
||||
|
||||
fn parseblock(p: *parser) *node = {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
expect_tok(p, TK_LBRACE, "expected '{' to open block");
|
||||
let blk: *node = newnode(p.a, N_BLOCK, pf, pl, pc);
|
||||
let head: *node = nil;
|
||||
let tail: *node = nil;
|
||||
for (p.cur_kind != TK_RBRACE) {
|
||||
if (p.cur_kind == TK_EOF) { break; };
|
||||
let s: *node = parsestmt(p);
|
||||
if (s != nil) {
|
||||
if (head == nil) { head = s; tail = s; }
|
||||
else { tail.next = s; tail = s; };
|
||||
};
|
||||
};
|
||||
expect_tok(p, TK_RBRACE, "expected '}' to close block");
|
||||
blk.list = head;
|
||||
return blk;
|
||||
};
|
||||
|
||||
fn parseif(p: *parser) *node = {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
advance(p); // past `if`
|
||||
expect_tok(p, TK_LPAREN, "expected '(' after if");
|
||||
let n: *node = newnode(p.a, N_IF, pf, pl, pc);
|
||||
n.cond = parseexpr(p);
|
||||
expect_tok(p, TK_RPAREN, "expected ')' after if condition");
|
||||
n.body = parseblock(p);
|
||||
if (accept_tok(p, TK_ELSE)) {
|
||||
if (p.cur_kind == TK_IF) {
|
||||
n.els = parseif(p);
|
||||
} else {
|
||||
n.els = parseblock(p);
|
||||
};
|
||||
};
|
||||
return n;
|
||||
};
|
||||
|
||||
fn parsefor(p: *parser) *node = {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
advance(p); // past `for`
|
||||
expect_tok(p, TK_LPAREN, "expected '(' after for");
|
||||
let n: *node = newnode(p.a, N_FOR, pf, pl, pc);
|
||||
// Three forms (matching C parser):
|
||||
// for (cond) — only cond
|
||||
// for (init; cond; post) — full
|
||||
// for (true) — infinite (cond is N_TRUE)
|
||||
// Distinguish by counting ';'. Look at first chunk: if it's a
|
||||
// `let` stmt that's the init. Otherwise, parse expr; if next is
|
||||
// ';' it was cond. If we see two ';' total after init, post is
|
||||
// next. Simpler: peek for `let` to decide init form.
|
||||
if (p.cur_kind == TK_LET) {
|
||||
n.lhs = parselet_local(p); // init (consumes its own ';')
|
||||
n.cond = parseexpr(p);
|
||||
expect_tok(p, TK_SEMI, "expected ';' after for cond");
|
||||
n.rhs = parseexpr(p);
|
||||
} else {
|
||||
// Parse one expr. If next is ';', it's a 3-clause without init.
|
||||
let first: *node = parseexpr(p);
|
||||
if (accept_tok(p, TK_SEMI)) {
|
||||
// cond ; post
|
||||
n.cond = first;
|
||||
n.rhs = parseexpr(p);
|
||||
} else {
|
||||
// just (cond)
|
||||
n.cond = first;
|
||||
};
|
||||
};
|
||||
expect_tok(p, TK_RPAREN, "expected ')' after for");
|
||||
n.body = parseblock(p);
|
||||
return n;
|
||||
};
|
||||
|
||||
fn parsestmt(p: *parser) *node = {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
|
||||
// `static` is allowed on local lets per Hare; we accept and skip
|
||||
// it (it doesn't change the AST shape).
|
||||
if (p.cur_kind == TK_STATIC) { advance(p); };
|
||||
|
||||
if (p.cur_kind == TK_LBRACE) {
|
||||
let b: *node = parseblock(p);
|
||||
expect_tok(p, TK_SEMI, "expected ';' after block");
|
||||
return b;
|
||||
};
|
||||
if (p.cur_kind == TK_LET) { return parselet_local(p); };
|
||||
if (p.cur_kind == TK_IF) {
|
||||
let n: *node = parseif(p);
|
||||
expect_tok(p, TK_SEMI, "expected ';' after if");
|
||||
return n;
|
||||
};
|
||||
if (p.cur_kind == TK_FOR) {
|
||||
let n: *node = parsefor(p);
|
||||
expect_tok(p, TK_SEMI, "expected ';' after for");
|
||||
return n;
|
||||
};
|
||||
if (p.cur_kind == TK_RETURN) {
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_RETURN, pf, pl, pc);
|
||||
if (p.cur_kind != TK_SEMI) {
|
||||
let first: *node = parseexpr(p);
|
||||
// Hare-style multi-value: `return a, b;` becomes a
|
||||
// tuple expression so codegen sees one rvalue.
|
||||
if (p.cur_kind == TK_COMMA) {
|
||||
let t: *node = newnode(p.a, N_TUPLE, pf, pl, pc);
|
||||
t.list = first;
|
||||
let tail: *node = first;
|
||||
for (accept_tok(p, TK_COMMA)) {
|
||||
let e: *node = parseexpr(p);
|
||||
tail.next = e;
|
||||
tail = e;
|
||||
};
|
||||
n.lhs = t;
|
||||
} else {
|
||||
n.lhs = first;
|
||||
};
|
||||
};
|
||||
expect_tok(p, TK_SEMI, "expected ';' after return");
|
||||
return n;
|
||||
};
|
||||
if (p.cur_kind == TK_DEFER) {
|
||||
advance(p);
|
||||
let n: *node = newnode(p.a, N_DEFER, pf, pl, pc);
|
||||
n.lhs = parseexpr(p);
|
||||
expect_tok(p, TK_SEMI, "expected ';' after defer");
|
||||
return n;
|
||||
};
|
||||
if (p.cur_kind == TK_BREAK) {
|
||||
advance(p);
|
||||
expect_tok(p, TK_SEMI, "expected ';' after break");
|
||||
return newnode(p.a, N_BREAK, pf, pl, pc);
|
||||
};
|
||||
if (p.cur_kind == TK_CONTINUE) {
|
||||
advance(p);
|
||||
expect_tok(p, TK_SEMI, "expected ';' after continue");
|
||||
return newnode(p.a, N_CONTINUE, pf, pl, pc);
|
||||
};
|
||||
// expression statement
|
||||
let n: *node = newnode(p.a, N_EXPRSTMT, pf, pl, pc);
|
||||
n.lhs = parseexpr(p);
|
||||
expect_tok(p, TK_SEMI, "expected ';' after expression statement");
|
||||
return n;
|
||||
};
|
||||
|
||||
// ---- top-level decl parsers ------------------------------------------
|
||||
|
||||
fn parseuse(p: *parser) *node = {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
advance(p); // past `use`
|
||||
let n: *node = newnode(p.a, N_USE, pf, pl, pc);
|
||||
let id: str;
|
||||
expectident(p, &id);
|
||||
n.str = id;
|
||||
expect_tok(p, TK_SEMI, "expected ';' after use");
|
||||
return n;
|
||||
};
|
||||
|
||||
fn parsedef(p: *parser, exported: i32) *node = {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
advance(p); // past `def`
|
||||
let n: *node = newnode(p.a, N_DEF, pf, pl, pc);
|
||||
let id: str;
|
||||
expectident(p, &id);
|
||||
n.str = id;
|
||||
expect_tok(p, TK_COLON, "expected ':' in def");
|
||||
n.lhs = parsetype(p);
|
||||
expect_tok(p, TK_ASSIGN, "expected '=' in def");
|
||||
n.rhs = parseexpr(p);
|
||||
expect_tok(p, TK_SEMI, "expected ';' after def");
|
||||
n.exported = exported;
|
||||
return n;
|
||||
};
|
||||
|
||||
fn parselet(p: *parser, exported: i32) *node = {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
advance(p); // past `let`
|
||||
let n: *node = newnode(p.a, N_LET, pf, pl, pc);
|
||||
let id: str;
|
||||
expectident(p, &id);
|
||||
n.str = id;
|
||||
if (accept_tok(p, TK_COLON)) {
|
||||
n.lhs = parsetype(p);
|
||||
};
|
||||
if (accept_tok(p, TK_ASSIGN)) {
|
||||
n.rhs = parseexpr(p);
|
||||
};
|
||||
expect_tok(p, TK_SEMI, "expected ';' after let");
|
||||
n.exported = exported;
|
||||
return n;
|
||||
};
|
||||
|
||||
fn parseattrs(p: *parser) *node = {
|
||||
let head: *node = nil;
|
||||
let tail: *node = nil;
|
||||
for (p.cur_kind == TK_AT) {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
advance(p);
|
||||
let a: *node = newnode(p.a, N_ATTR, pf, pl, pc);
|
||||
let id: str;
|
||||
expectident(p, &id);
|
||||
a.str = id;
|
||||
expect_tok(p, TK_LPAREN, "expected '(' after attribute name");
|
||||
let arghead: *node = nil;
|
||||
parsearglist(p, TK_RPAREN, &arghead);
|
||||
a.list = arghead;
|
||||
expect_tok(p, TK_RPAREN, "expected ')' after attribute args");
|
||||
if (head == nil) { head = a; tail = a; }
|
||||
else { tail.next = a; tail = a; };
|
||||
};
|
||||
return head;
|
||||
};
|
||||
|
||||
fn parseparams(p: *parser) *node = {
|
||||
if (p.cur_kind == TK_RPAREN) { return nil; };
|
||||
let head: *node = nil;
|
||||
let tail: *node = nil;
|
||||
for (true) {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
let n: *node = newnode(p.a, N_PARAM, pf, pl, pc);
|
||||
// Param form: IDENT ':' type. Anonymous-type-only params (used
|
||||
// in fn type expressions) aren't yet wired here.
|
||||
let id: str;
|
||||
expectident(p, &id);
|
||||
n.str = id;
|
||||
expect_tok(p, TK_COLON, "expected ':' in parameter");
|
||||
n.lhs = parsetype(p);
|
||||
if (head == nil) { head = n; tail = n; }
|
||||
else { tail.next = n; tail = n; };
|
||||
if (!accept_tok(p, TK_COMMA)) { break; };
|
||||
if (p.cur_kind == TK_RPAREN) { break; };
|
||||
};
|
||||
return head;
|
||||
};
|
||||
|
||||
fn parsefn(p: *parser, exported: i32, attrs: *node) *node = {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
advance(p); // past `fn`
|
||||
let n: *node = newnode(p.a, N_FNDECL, pf, pl, pc);
|
||||
let id: str;
|
||||
expectident(p, &id);
|
||||
n.str = id;
|
||||
expect_tok(p, TK_LPAREN, "expected '(' after fn name");
|
||||
n.list = parseparams(p);
|
||||
expect_tok(p, TK_RPAREN, "expected ')' after params");
|
||||
if (p.cur_kind != TK_ASSIGN) {
|
||||
if (p.cur_kind != TK_SEMI) {
|
||||
n.lhs = parsetype(p);
|
||||
};
|
||||
};
|
||||
if (accept_tok(p, TK_ASSIGN)) {
|
||||
n.body = parseblock(p);
|
||||
expect_tok(p, TK_SEMI, "expected ';' after fn body");
|
||||
} else {
|
||||
// Body-less fn: FFI declaration (`fn name(args) ret;`).
|
||||
expect_tok(p, TK_SEMI, "expected ';' after fn header");
|
||||
};
|
||||
n.exported = exported;
|
||||
n.attr = attrs;
|
||||
return n;
|
||||
};
|
||||
|
||||
fn parsetypedecl(p: *parser, exported: i32) *node = {
|
||||
let pf: str = p.cur_file;
|
||||
let pl: i32 = p.cur_line;
|
||||
let pc: i32 = p.cur_col;
|
||||
advance(p); // past `type`
|
||||
let n: *node = newnode(p.a, N_TYPEDECL, pf, pl, pc);
|
||||
let id: str;
|
||||
expectident(p, &id);
|
||||
n.str = id;
|
||||
expect_tok(p, TK_ASSIGN, "expected '=' in type decl");
|
||||
n.lhs = parsetype(p);
|
||||
expect_tok(p, TK_SEMI, "expected ';' after type decl");
|
||||
n.exported = exported;
|
||||
return n;
|
||||
};
|
||||
|
||||
// ---- file-level loop -------------------------------------------------
|
||||
|
||||
export fn parsefile(p: *parser) *node = {
|
||||
let f: *node = newnode(p.a, N_FILE, p.cur_file, p.cur_line, p.cur_col);
|
||||
let head: *node = nil;
|
||||
let tail: *node = nil;
|
||||
|
||||
for (p.cur_kind != TK_EOF) {
|
||||
let attrs: *node = parseattrs(p);
|
||||
let exported: i32 = 0;
|
||||
if (p.cur_kind == TK_EXPORT) { exported = 1; advance(p); };
|
||||
|
||||
let d: *node = nil;
|
||||
if (p.cur_kind == TK_USE) {
|
||||
d = parseuse(p);
|
||||
} else { if (p.cur_kind == TK_DEF) {
|
||||
d = parsedef(p, exported);
|
||||
} else { if (p.cur_kind == TK_TYPE) {
|
||||
d = parsetypedecl(p, exported);
|
||||
} else { if (p.cur_kind == TK_LET) {
|
||||
d = parselet(p, exported);
|
||||
} else { if (p.cur_kind == TK_FN) {
|
||||
d = parsefn(p, exported, attrs);
|
||||
} else {
|
||||
// Recovery: chew tokens until next ';' or EOF, balancing
|
||||
// '{' '}' pairs so internal ';'s in unfamiliar forms don't
|
||||
// derail us.
|
||||
for (p.cur_kind != TK_SEMI) {
|
||||
if (p.cur_kind == TK_EOF) { break; };
|
||||
if (p.cur_kind == TK_LBRACE) {
|
||||
let depth: i32 = 0;
|
||||
for (true) {
|
||||
if (p.cur_kind == TK_EOF) { break; };
|
||||
if (p.cur_kind == TK_LBRACE) { depth += 1; advance(p); continue; };
|
||||
if (p.cur_kind == TK_RBRACE) {
|
||||
depth -= 1;
|
||||
advance(p);
|
||||
if (depth == 0) { break; };
|
||||
continue;
|
||||
};
|
||||
advance(p);
|
||||
};
|
||||
continue;
|
||||
};
|
||||
advance(p);
|
||||
};
|
||||
if (p.cur_kind == TK_SEMI) { advance(p); };
|
||||
};};};};};
|
||||
|
||||
if (d != nil) {
|
||||
if (head == nil) {
|
||||
head = d;
|
||||
tail = d;
|
||||
} else {
|
||||
tail.next = d;
|
||||
tail = d;
|
||||
};
|
||||
};
|
||||
};
|
||||
f.list = head;
|
||||
return f;
|
||||
};
|
||||
113
selfhost/cmd/wwc/sym.ww
Normal file
113
selfhost/cmd/wwc/sym.ww
Normal file
@@ -0,0 +1,113 @@
|
||||
// selfhost/cmd/wwc/sym.ww — port of cmd/wwc/sym.c.
|
||||
//
|
||||
// Per-scope hashtable, chained to the parent. Lookup walks up.
|
||||
// Plan 9 / Hare flavoured. Duplicate definitions in the same scope
|
||||
// return nil; the caller flags the error.
|
||||
|
||||
use mem;
|
||||
use typ;
|
||||
use ast;
|
||||
|
||||
// Symbol kinds — must stay numerically aligned with cmd/wwc/ww.h Skind.
|
||||
def SK_NONE: i32 = 0;
|
||||
def SK_VAR: i32 = 1;
|
||||
def SK_PARAM: i32 = 2;
|
||||
def SK_DEF: i32 = 3;
|
||||
def SK_TYPE: i32 = 4;
|
||||
def SK_FN: i32 = 5;
|
||||
def SK_USE: i32 = 6;
|
||||
def SK_FIELD: i32 = 7;
|
||||
|
||||
type sym = struct {
|
||||
name: str,
|
||||
skind: i32,
|
||||
type_: *tinfo,
|
||||
decl: *node,
|
||||
exported: i32,
|
||||
snext: *sym, // iteration order
|
||||
hashnext: *sym, // hash bucket chain
|
||||
scope: *scope,
|
||||
};
|
||||
|
||||
def NBUCKETS: i32 = 16;
|
||||
|
||||
type scope = struct {
|
||||
parent: *scope,
|
||||
first: *sym,
|
||||
last: *sym,
|
||||
buckets: **sym, // length = NBUCKETS
|
||||
nbuckets: i32,
|
||||
a: *arena,
|
||||
};
|
||||
|
||||
// FNV-1a 64 — same hash the C side uses, so bucket distribution is
|
||||
// identical when both walk a scope in declaration order.
|
||||
fn hashstr(s: str) u64 = {
|
||||
let h: u64 = 14695981039346656037u64;
|
||||
let i: i32 = 0;
|
||||
for (i < s.len) {
|
||||
let c: u8 = s[i];
|
||||
h = h ^ (c: u64);
|
||||
h = h * 1099511628211u64;
|
||||
i += 1;
|
||||
};
|
||||
return h;
|
||||
};
|
||||
|
||||
export fn newscope(a: *arena, parent: *scope) *scope = {
|
||||
let s: *scope = amalloc(a, 64u64): *scope;
|
||||
s.parent = parent;
|
||||
s.a = a;
|
||||
s.nbuckets = NBUCKETS;
|
||||
s.buckets = amalloc(a, (NBUCKETS: u64) * 8u64): **sym;
|
||||
return s;
|
||||
};
|
||||
|
||||
export fn streq(a: str, b: str) bool = {
|
||||
if (a.len != b.len) { return false; };
|
||||
let i: i32 = 0;
|
||||
for (i < a.len) {
|
||||
if (a[i] != b[i]) { return false; };
|
||||
i += 1;
|
||||
};
|
||||
return true;
|
||||
};
|
||||
|
||||
export fn scope_lookup_local(s: *scope, name: str) *sym = {
|
||||
if (s == nil) { return nil; };
|
||||
let h: u64 = hashstr(name);
|
||||
let bi: i32 = (h % (s.nbuckets: u64)): i32;
|
||||
let b: *sym = s.buckets[bi];
|
||||
for (b != nil) {
|
||||
let bn: str = b.name;
|
||||
if (streq(bn, name)) { return b; };
|
||||
b = b.hashnext;
|
||||
};
|
||||
return nil;
|
||||
};
|
||||
|
||||
export fn scope_lookup(s: *scope, name: str) *sym = {
|
||||
for (s != nil) {
|
||||
let r: *sym = scope_lookup_local(s, name);
|
||||
if (r != nil) { return r; };
|
||||
s = s.parent;
|
||||
};
|
||||
return nil;
|
||||
};
|
||||
|
||||
export fn scope_define(s: *scope, name: str, k: i32, t: *tinfo, decl: *node) *sym = {
|
||||
if (scope_lookup_local(s, name) != nil) { return nil; };
|
||||
let sy: *sym = amalloc(s.a, 80u64): *sym;
|
||||
sy.name = name;
|
||||
sy.skind = k;
|
||||
sy.type_ = t;
|
||||
sy.decl = decl;
|
||||
sy.scope = s;
|
||||
let h: u64 = hashstr(name);
|
||||
let bi: i32 = (h % (s.nbuckets: u64)): i32;
|
||||
sy.hashnext = s.buckets[bi];
|
||||
s.buckets[bi] = sy;
|
||||
if (s.first == nil) { s.first = sy; } else { s.last.snext = sy; };
|
||||
s.last = sy;
|
||||
return sy;
|
||||
};
|
||||
394
selfhost/cmd/wwc/tok.ww
Normal file
394
selfhost/cmd/wwc/tok.ww
Normal file
@@ -0,0 +1,394 @@
|
||||
// selfhost/cmd/wwc/tok.ww — port of cmd/wwc/tok.c plus the Tkind /
|
||||
// Tok / Pos shapes from cmd/wwc/ww.h.
|
||||
//
|
||||
// Token kind values must stay numerically equal to the C side: the
|
||||
// 990_selfhost test diffs ww-side wwdump output against C-side
|
||||
// wwdump output, byte-for-byte. Reordering this list shifts the
|
||||
// integers and breaks the diff.
|
||||
//
|
||||
// Bottom of file: tokprint, which emits one token per line in a
|
||||
// format identical to cmd/wwc/tok.c:tokprint().
|
||||
|
||||
use os;
|
||||
use strconv;
|
||||
|
||||
// ---- Tkind ------------------------------------------------------------
|
||||
// Mirror of the C enum in cmd/wwc/ww.h. Don't reorder.
|
||||
|
||||
def TK_NONE: i32 = 0;
|
||||
def TK_EOF: i32 = 1;
|
||||
def TK_ERR: i32 = 2;
|
||||
def TK_IDENT: i32 = 3;
|
||||
def TK_INT: i32 = 4;
|
||||
def TK_FLOAT: i32 = 5;
|
||||
def TK_RUNE: i32 = 6;
|
||||
def TK_STR: i32 = 7;
|
||||
|
||||
def TK_FN: i32 = 8;
|
||||
def TK_LET: i32 = 9;
|
||||
def TK_DEF: i32 = 10;
|
||||
def TK_IF: i32 = 11;
|
||||
def TK_ELSE: i32 = 12;
|
||||
def TK_FOR: i32 = 13;
|
||||
def TK_SWITCH: i32 = 14;
|
||||
def TK_CASE: i32 = 15;
|
||||
def TK_RETURN: i32 = 16;
|
||||
def TK_USE: i32 = 17;
|
||||
def TK_TYPE: i32 = 18;
|
||||
def TK_STRUCT: i32 = 19;
|
||||
def TK_DEFER: i32 = 20;
|
||||
def TK_BREAK: i32 = 21;
|
||||
def TK_CONTINUE: i32 = 22;
|
||||
def TK_EXPORT: i32 = 23;
|
||||
def TK_PROC: i32 = 24;
|
||||
def TK_CHAN: i32 = 25;
|
||||
def TK_NIL: i32 = 26;
|
||||
def TK_TRUE: i32 = 27;
|
||||
def TK_FALSE: i32 = 28;
|
||||
def TK_AS: i32 = 29;
|
||||
def TK_STATIC: i32 = 30;
|
||||
def TK_MATCH: i32 = 31;
|
||||
|
||||
def TK_LPAREN: i32 = 32;
|
||||
def TK_RPAREN: i32 = 33;
|
||||
def TK_LBRACE: i32 = 34;
|
||||
def TK_RBRACE: i32 = 35;
|
||||
def TK_LBRACK: i32 = 36;
|
||||
def TK_RBRACK: i32 = 37;
|
||||
def TK_COMMA: i32 = 38;
|
||||
def TK_SEMI: i32 = 39;
|
||||
def TK_COLON: i32 = 40;
|
||||
def TK_DOT: i32 = 41;
|
||||
def TK_ELLIPSIS: i32 = 42;
|
||||
def TK_DOTDOT: i32 = 43;
|
||||
def TK_AT: i32 = 44;
|
||||
def TK_QUESTION: i32 = 45;
|
||||
|
||||
def TK_ASSIGN: i32 = 46;
|
||||
def TK_PLUSEQ: i32 = 47;
|
||||
def TK_MINUSEQ: i32 = 48;
|
||||
def TK_STAREQ: i32 = 49;
|
||||
def TK_SLASHEQ: i32 = 50;
|
||||
def TK_PERCENTEQ: i32 = 51;
|
||||
def TK_AMPEQ: i32 = 52;
|
||||
def TK_PIPEEQ: i32 = 53;
|
||||
def TK_CARETEQ: i32 = 54;
|
||||
def TK_LSHIFTEQ: i32 = 55;
|
||||
def TK_RSHIFTEQ: i32 = 56;
|
||||
|
||||
def TK_PLUS: i32 = 57;
|
||||
def TK_MINUS: i32 = 58;
|
||||
def TK_STAR: i32 = 59;
|
||||
def TK_SLASH: i32 = 60;
|
||||
def TK_PERCENT: i32 = 61;
|
||||
def TK_AMP: i32 = 62;
|
||||
def TK_PIPE: i32 = 63;
|
||||
def TK_CARET: i32 = 64;
|
||||
def TK_TILDE: i32 = 65;
|
||||
def TK_LSHIFT: i32 = 66;
|
||||
def TK_RSHIFT: i32 = 67;
|
||||
|
||||
def TK_EQ: i32 = 68;
|
||||
def TK_NEQ: i32 = 69;
|
||||
def TK_LT: i32 = 70;
|
||||
def TK_LE: i32 = 71;
|
||||
def TK_GT: i32 = 72;
|
||||
def TK_GE: i32 = 73;
|
||||
|
||||
def TK_AND: i32 = 74;
|
||||
def TK_OR: i32 = 75;
|
||||
def TK_NOT: i32 = 76;
|
||||
|
||||
def TK_LARROW: i32 = 77;
|
||||
def TK_ARROW: i32 = 78;
|
||||
def TK_FATARROW: i32 = 79;
|
||||
|
||||
def TK_LAST: i32 = 80;
|
||||
|
||||
// ---- Pos / Tok --------------------------------------------------------
|
||||
//
|
||||
// `pos` is used at error-reporting boundaries; we always pass it via
|
||||
// *pos so the value never gets struct-copied (6c can't yet copy a
|
||||
// 24-byte struct).
|
||||
//
|
||||
// `tok` is flat — file/line/col live directly on the token rather than
|
||||
// nested inside a `pos` field. Same reason: nested struct field
|
||||
// assignment isn't supported, and flat primitives are.
|
||||
|
||||
type pos = struct {
|
||||
file: str,
|
||||
line: i32,
|
||||
col: i32,
|
||||
};
|
||||
|
||||
type tok = struct {
|
||||
kind: i32,
|
||||
file: str, // path of the source the token came from
|
||||
line: i32,
|
||||
col: i32,
|
||||
text: str, // arena-owned token text (TK_IDENT, TK_STR, TK_ERR)
|
||||
uval: u64, // TK_INT, TK_RUNE
|
||||
fval: f64, // TK_FLOAT
|
||||
tsuffix: str, // typed numeric literal suffix or empty
|
||||
};
|
||||
|
||||
// ---- keyword lookup ---------------------------------------------------
|
||||
|
||||
fn streq_n(a: *u8, b: str, n: i32) bool = {
|
||||
if (b.len != n) { return false; };
|
||||
let i: i32 = 0;
|
||||
for (i < n) {
|
||||
if (a[i] != b[i]) { return false; };
|
||||
i += 1;
|
||||
};
|
||||
return true;
|
||||
};
|
||||
|
||||
// kwlookup — returns the matching TK_* keyword kind for a byte run,
|
||||
// or TK_NONE if it's an ordinary identifier. Linear search over a
|
||||
// small alphabetised list, matching cmd/wwc/tok.c.
|
||||
export fn kwlookup(p: *u8, n: i32) i32 = {
|
||||
if (streq_n(p, "as", n)) { return TK_AS; };
|
||||
if (streq_n(p, "break", n)) { return TK_BREAK; };
|
||||
if (streq_n(p, "case", n)) { return TK_CASE; };
|
||||
if (streq_n(p, "chan", n)) { return TK_CHAN; };
|
||||
if (streq_n(p, "continue", n)) { return TK_CONTINUE; };
|
||||
if (streq_n(p, "def", n)) { return TK_DEF; };
|
||||
if (streq_n(p, "defer", n)) { return TK_DEFER; };
|
||||
if (streq_n(p, "else", n)) { return TK_ELSE; };
|
||||
if (streq_n(p, "export", n)) { return TK_EXPORT; };
|
||||
if (streq_n(p, "false", n)) { return TK_FALSE; };
|
||||
if (streq_n(p, "fn", n)) { return TK_FN; };
|
||||
if (streq_n(p, "for", n)) { return TK_FOR; };
|
||||
if (streq_n(p, "if", n)) { return TK_IF; };
|
||||
if (streq_n(p, "let", n)) { return TK_LET; };
|
||||
if (streq_n(p, "match", n)) { return TK_MATCH; };
|
||||
if (streq_n(p, "nil", n)) { return TK_NIL; };
|
||||
if (streq_n(p, "proc", n)) { return TK_PROC; };
|
||||
if (streq_n(p, "return", n)) { return TK_RETURN; };
|
||||
if (streq_n(p, "static", n)) { return TK_STATIC; };
|
||||
if (streq_n(p, "struct", n)) { return TK_STRUCT; };
|
||||
if (streq_n(p, "switch", n)) { return TK_SWITCH; };
|
||||
if (streq_n(p, "true", n)) { return TK_TRUE; };
|
||||
if (streq_n(p, "type", n)) { return TK_TYPE; };
|
||||
if (streq_n(p, "use", n)) { return TK_USE; };
|
||||
return TK_NONE;
|
||||
};
|
||||
|
||||
// ---- tokname ----------------------------------------------------------
|
||||
//
|
||||
// Returns the canonical printable spelling for a token kind. Matches
|
||||
// the C tokname()'s output exactly so wwdump output diffs cleanly.
|
||||
|
||||
export fn tokname(k: i32) str = {
|
||||
if (k == TK_NONE) { return "<none>"; };
|
||||
if (k == TK_EOF) { return "EOF"; };
|
||||
if (k == TK_ERR) { return "ERR"; };
|
||||
if (k == TK_IDENT) { return "IDENT"; };
|
||||
if (k == TK_INT) { return "INT"; };
|
||||
if (k == TK_FLOAT) { return "FLOAT"; };
|
||||
if (k == TK_RUNE) { return "RUNE"; };
|
||||
if (k == TK_STR) { return "STR"; };
|
||||
|
||||
if (k == TK_FN) { return "fn"; };
|
||||
if (k == TK_LET) { return "let"; };
|
||||
if (k == TK_DEF) { return "def"; };
|
||||
if (k == TK_IF) { return "if"; };
|
||||
if (k == TK_ELSE) { return "else"; };
|
||||
if (k == TK_FOR) { return "for"; };
|
||||
if (k == TK_SWITCH) { return "switch"; };
|
||||
if (k == TK_CASE) { return "case"; };
|
||||
if (k == TK_RETURN) { return "return"; };
|
||||
if (k == TK_USE) { return "use"; };
|
||||
if (k == TK_TYPE) { return "type"; };
|
||||
if (k == TK_STRUCT) { return "struct"; };
|
||||
if (k == TK_DEFER) { return "defer"; };
|
||||
if (k == TK_BREAK) { return "break"; };
|
||||
if (k == TK_CONTINUE) { return "continue"; };
|
||||
if (k == TK_EXPORT) { return "export"; };
|
||||
if (k == TK_PROC) { return "proc"; };
|
||||
if (k == TK_CHAN) { return "chan"; };
|
||||
if (k == TK_NIL) { return "nil"; };
|
||||
if (k == TK_TRUE) { return "true"; };
|
||||
if (k == TK_FALSE) { return "false"; };
|
||||
if (k == TK_AS) { return "as"; };
|
||||
if (k == TK_STATIC) { return "static"; };
|
||||
if (k == TK_MATCH) { return "match"; };
|
||||
|
||||
if (k == TK_LPAREN) { return "("; };
|
||||
if (k == TK_RPAREN) { return ")"; };
|
||||
if (k == TK_LBRACE) { return "{"; };
|
||||
if (k == TK_RBRACE) { return "}"; };
|
||||
if (k == TK_LBRACK) { return "["; };
|
||||
if (k == TK_RBRACK) { return "]"; };
|
||||
if (k == TK_COMMA) { return ","; };
|
||||
if (k == TK_SEMI) { return ";"; };
|
||||
if (k == TK_COLON) { return ":"; };
|
||||
if (k == TK_DOT) { return "."; };
|
||||
if (k == TK_ELLIPSIS) { return "..."; };
|
||||
if (k == TK_DOTDOT) { return ".."; };
|
||||
if (k == TK_AT) { return "@"; };
|
||||
if (k == TK_QUESTION) { return "?"; };
|
||||
|
||||
if (k == TK_ASSIGN) { return "="; };
|
||||
if (k == TK_PLUSEQ) { return "+="; };
|
||||
if (k == TK_MINUSEQ) { return "-="; };
|
||||
if (k == TK_STAREQ) { return "*="; };
|
||||
if (k == TK_SLASHEQ) { return "/="; };
|
||||
if (k == TK_PERCENTEQ) { return "%="; };
|
||||
if (k == TK_AMPEQ) { return "&="; };
|
||||
if (k == TK_PIPEEQ) { return "|="; };
|
||||
if (k == TK_CARETEQ) { return "^="; };
|
||||
if (k == TK_LSHIFTEQ) { return "<<="; };
|
||||
if (k == TK_RSHIFTEQ) { return ">>="; };
|
||||
|
||||
if (k == TK_PLUS) { return "+"; };
|
||||
if (k == TK_MINUS) { return "-"; };
|
||||
if (k == TK_STAR) { return "*"; };
|
||||
if (k == TK_SLASH) { return "/"; };
|
||||
if (k == TK_PERCENT) { return "%"; };
|
||||
if (k == TK_AMP) { return "&"; };
|
||||
if (k == TK_PIPE) { return "|"; };
|
||||
if (k == TK_CARET) { return "^"; };
|
||||
if (k == TK_TILDE) { return "~"; };
|
||||
if (k == TK_LSHIFT) { return "<<"; };
|
||||
if (k == TK_RSHIFT) { return ">>"; };
|
||||
|
||||
if (k == TK_EQ) { return "=="; };
|
||||
if (k == TK_NEQ) { return "!="; };
|
||||
if (k == TK_LT) { return "<"; };
|
||||
if (k == TK_LE) { return "<="; };
|
||||
if (k == TK_GT) { return ">"; };
|
||||
if (k == TK_GE) { return ">="; };
|
||||
|
||||
if (k == TK_AND) { return "&&"; };
|
||||
if (k == TK_OR) { return "||"; };
|
||||
if (k == TK_NOT) { return "!"; };
|
||||
|
||||
if (k == TK_LARROW) { return "<-"; };
|
||||
if (k == TK_ARROW) { return "->"; };
|
||||
if (k == TK_FATARROW) { return "=>"; };
|
||||
|
||||
if (k == TK_LAST) { return "<last>"; };
|
||||
return "<?>";
|
||||
};
|
||||
|
||||
// ---- writer for tokprint ----------------------------------------------
|
||||
//
|
||||
// fputq mirrors cmd/wwc/tok.c:fputq — quote the string with C-style
|
||||
// escapes for \, ", \n, \t, \r and \xNN for other non-printables.
|
||||
|
||||
fn fputc_byte(fd: i32, b: u8) void = {
|
||||
let buf: [1]u8;
|
||||
buf[0] = b;
|
||||
os.write(fd, buf.ptr, 1u64);
|
||||
};
|
||||
|
||||
fn fputs_str(fd: i32, s: str) void = {
|
||||
os.write(fd, s.ptr, s.len: u64);
|
||||
};
|
||||
|
||||
fn hexchar(n: u8) u8 = {
|
||||
if (n < 10u8) { return n + 48u8; }; // '0'..'9'
|
||||
return (n - 10u8) + 97u8; // 'a'..'f'
|
||||
};
|
||||
|
||||
fn fputhex2(fd: i32, b: u8) void = {
|
||||
let out: [4]u8;
|
||||
out[0] = 92u8; // '\\'
|
||||
out[1] = 120u8; // 'x'
|
||||
out[2] = hexchar(b >> 4u8);
|
||||
out[3] = hexchar(b & 15u8);
|
||||
os.write(fd, out.ptr, 4u64);
|
||||
};
|
||||
|
||||
fn fputq(fd: i32, p: *u8, n: i32) void = {
|
||||
fputc_byte(fd, 34u8); // '"'
|
||||
let i: i32 = 0;
|
||||
for (i < n) {
|
||||
let c: u8 = p[i];
|
||||
if (c == 92u8) { // '\\'
|
||||
fputs_str(fd, "\\\\");
|
||||
} else {
|
||||
if (c == 34u8) { // '"'
|
||||
fputs_str(fd, "\\\"");
|
||||
} else {
|
||||
if (c == 10u8) { // '\n'
|
||||
fputs_str(fd, "\\n");
|
||||
} else {
|
||||
if (c == 9u8) { // '\t'
|
||||
fputs_str(fd, "\\t");
|
||||
} else {
|
||||
if (c == 13u8) { // '\r'
|
||||
fputs_str(fd, "\\r");
|
||||
} else {
|
||||
if (c < 32u8) {
|
||||
fputhex2(fd, c);
|
||||
} else {
|
||||
if (c == 127u8) {
|
||||
fputhex2(fd, c);
|
||||
} else {
|
||||
fputc_byte(fd, c);
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
i += 1;
|
||||
};
|
||||
fputc_byte(fd, 34u8);
|
||||
};
|
||||
|
||||
// tokprint — write one token line to fd. Format must match
|
||||
// cmd/wwc/tok.c:tokprint() byte-for-byte: that's the diff anchor.
|
||||
// "<file>:<line>:<col> <kindname>[ <value>]\n"
|
||||
//
|
||||
// Takes `t` by pointer because 6c can't yet pass a >16-byte struct
|
||||
// by value; the C version takes Tok by value.
|
||||
export fn tokprint(fd: i32, t: *tok) void = {
|
||||
// Chained-dot field reads (`t.x.y`) on str sub-fields aren't yet
|
||||
// reduced by 6c — `t.x.y` returns the whole str. Lift the str
|
||||
// fields into locals so we can use the str pseudo-field path.
|
||||
let tfile: str = t.file;
|
||||
let ttext: str = t.text;
|
||||
if (tfile.len > 0) {
|
||||
fputs_str(fd, tfile);
|
||||
} else {
|
||||
fputs_str(fd, "<none>");
|
||||
};
|
||||
fputc_byte(fd, 58u8); // ':'
|
||||
let buf: [32]u8;
|
||||
let n: i32 = strconv.i64toa(buf[0:32], t.line: i64);
|
||||
os.write(fd, buf.ptr, n: u64);
|
||||
fputc_byte(fd, 58u8);
|
||||
n = strconv.i64toa(buf[0:32], t.col: i64);
|
||||
os.write(fd, buf.ptr, n: u64);
|
||||
fputc_byte(fd, 32u8); // ' '
|
||||
fputs_str(fd, tokname(t.kind));
|
||||
|
||||
if (t.kind == TK_IDENT) {
|
||||
fputc_byte(fd, 32u8);
|
||||
fputq(fd, ttext.ptr, ttext.len);
|
||||
} else { if (t.kind == TK_STR) {
|
||||
fputc_byte(fd, 32u8);
|
||||
fputq(fd, ttext.ptr, ttext.len);
|
||||
} else { if (t.kind == TK_ERR) {
|
||||
fputc_byte(fd, 32u8);
|
||||
fputq(fd, ttext.ptr, ttext.len);
|
||||
} else { if (t.kind == TK_INT) {
|
||||
fputc_byte(fd, 32u8);
|
||||
n = strconv.u64toa(buf[0:32], t.uval);
|
||||
os.write(fd, buf.ptr, n: u64);
|
||||
} else { if (t.kind == TK_RUNE) {
|
||||
fputc_byte(fd, 32u8);
|
||||
n = strconv.u64toa(buf[0:32], t.uval);
|
||||
os.write(fd, buf.ptr, n: u64);
|
||||
};};};};};
|
||||
// TK_FLOAT is intentionally not handled here — %g formatting
|
||||
// won't byte-match across implementations. Diff fixtures must
|
||||
// be float-free until we implement a stable float formatter.
|
||||
|
||||
fputc_byte(fd, 10u8); // '\n'
|
||||
};
|
||||
329
selfhost/cmd/wwc/typ.ww
Normal file
329
selfhost/cmd/wwc/typ.ww
Normal file
@@ -0,0 +1,329 @@
|
||||
// selfhost/cmd/wwc/type.ww — port of cmd/wwc/type.c.
|
||||
//
|
||||
// Status: full structural port. The C version uses module-globals for
|
||||
// the primitive types (ty_void, ty_i32, …); ww doesn't have writable
|
||||
// global storage yet, so we bundle the primitives into a `tctx` that
|
||||
// the checker passes around explicitly. typesinit fills the tctx
|
||||
// once per arena.
|
||||
|
||||
use os;
|
||||
use mem;
|
||||
|
||||
// ---- TypeKind ---------------------------------------------------------
|
||||
// Numeric values must stay aligned with cmd/wwc/ww.h TypeKind so the
|
||||
// next diff signal (typed-AST printer / cgen) can compare across the
|
||||
// two implementations.
|
||||
|
||||
def TY_NONE: i32 = 0;
|
||||
def TY_VOID: i32 = 1;
|
||||
def TY_BOOL: i32 = 2;
|
||||
def TY_RUNE: i32 = 3;
|
||||
def TY_I8: i32 = 4;
|
||||
def TY_I16: i32 = 5;
|
||||
def TY_I32: i32 = 6;
|
||||
def TY_I64: i32 = 7;
|
||||
def TY_U8: i32 = 8;
|
||||
def TY_U16: i32 = 9;
|
||||
def TY_U32: i32 = 10;
|
||||
def TY_U64: i32 = 11;
|
||||
def TY_UINT: i32 = 12;
|
||||
def TY_INT: i32 = 13;
|
||||
def TY_UINTPTR: i32 = 14;
|
||||
def TY_F32: i32 = 15;
|
||||
def TY_F64: i32 = 16;
|
||||
def TY_STR: i32 = 17;
|
||||
def TY_PTR: i32 = 18;
|
||||
def TY_SLICE: i32 = 19;
|
||||
def TY_ARRAY: i32 = 20;
|
||||
def TY_STRUCT: i32 = 21;
|
||||
def TY_FN: i32 = 22;
|
||||
def TY_CHAN: i32 = 23;
|
||||
def TY_NAMED: i32 = 24;
|
||||
def TY_TUPLE: i32 = 25;
|
||||
def TY_TAGGED: i32 = 26;
|
||||
def TY_ERR: i32 = 27;
|
||||
def TY_UNTYPED_INT: i32 = 28;
|
||||
def TY_UNTYPED_FLOAT: i32 = 29;
|
||||
def TY_UNTYPED_STR: i32 = 30;
|
||||
def TY_UNTYPED_RUNE: i32 = 31;
|
||||
def TY_UNTYPED_BOOL: i32 = 32;
|
||||
def TY_UNTYPED_NIL: i32 = 33;
|
||||
|
||||
// ---- tinfo / tfield / tparam -----------------------------------------
|
||||
|
||||
type tfield = struct {
|
||||
name: str,
|
||||
type_: *tinfo,
|
||||
offset: u64,
|
||||
tnext: *tfield,
|
||||
};
|
||||
|
||||
type tparam = struct {
|
||||
name: str,
|
||||
type_: *tinfo,
|
||||
tnext: *tparam,
|
||||
};
|
||||
|
||||
type tinfo = struct {
|
||||
kind: i32,
|
||||
size: u64,
|
||||
align: u64,
|
||||
sub: *tinfo, // ptr/slice/array/chan element
|
||||
alen: u64,
|
||||
fields: *tfield,
|
||||
params: *tparam,
|
||||
ret: *tinfo,
|
||||
variadic: i32,
|
||||
name: str,
|
||||
under: *tinfo,
|
||||
};
|
||||
|
||||
// ---- tctx — the box of primitive types -------------------------------
|
||||
|
||||
type tctx = struct {
|
||||
a: *arena,
|
||||
ty_void: *tinfo,
|
||||
ty_bool: *tinfo,
|
||||
ty_rune: *tinfo,
|
||||
ty_i8: *tinfo,
|
||||
ty_i16: *tinfo,
|
||||
ty_i32: *tinfo,
|
||||
ty_i64: *tinfo,
|
||||
ty_u8: *tinfo,
|
||||
ty_u16: *tinfo,
|
||||
ty_u32: *tinfo,
|
||||
ty_u64: *tinfo,
|
||||
ty_int: *tinfo,
|
||||
ty_uint: *tinfo,
|
||||
ty_uintptr: *tinfo,
|
||||
ty_f32: *tinfo,
|
||||
ty_f64: *tinfo,
|
||||
ty_str: *tinfo,
|
||||
ty_err: *tinfo,
|
||||
ty_untyped_int: *tinfo,
|
||||
ty_untyped_float: *tinfo,
|
||||
ty_untyped_str: *tinfo,
|
||||
ty_untyped_rune: *tinfo,
|
||||
ty_untyped_bool: *tinfo,
|
||||
ty_untyped_nil: *tinfo,
|
||||
};
|
||||
|
||||
// ---- constructors -----------------------------------------------------
|
||||
|
||||
export fn newtype(a: *arena, k: i32) *tinfo = {
|
||||
let t: *tinfo = amalloc(a, 96u64): *tinfo;
|
||||
t.kind = k;
|
||||
return t;
|
||||
};
|
||||
|
||||
fn prim(a: *arena, k: i32, nm: str, sz: u64, al: u64) *tinfo = {
|
||||
let t: *tinfo = newtype(a, k);
|
||||
t.name = nm;
|
||||
t.size = sz;
|
||||
if (al > 0u64) { t.align = al; } else { t.align = sz; };
|
||||
return t;
|
||||
};
|
||||
|
||||
export fn typesinit(c: *tctx, a: *arena) void = {
|
||||
c.a = a;
|
||||
c.ty_void = prim(a, TY_VOID, "void", 0u64, 1u64);
|
||||
c.ty_bool = prim(a, TY_BOOL, "bool", 1u64, 1u64);
|
||||
c.ty_rune = prim(a, TY_RUNE, "rune", 4u64, 4u64);
|
||||
c.ty_i8 = prim(a, TY_I8, "i8", 1u64, 1u64);
|
||||
c.ty_i16 = prim(a, TY_I16, "i16", 2u64, 2u64);
|
||||
c.ty_i32 = prim(a, TY_I32, "i32", 4u64, 4u64);
|
||||
c.ty_i64 = prim(a, TY_I64, "i64", 8u64, 8u64);
|
||||
c.ty_u8 = prim(a, TY_U8, "u8", 1u64, 1u64);
|
||||
c.ty_u16 = prim(a, TY_U16, "u16", 2u64, 2u64);
|
||||
c.ty_u32 = prim(a, TY_U32, "u32", 4u64, 4u64);
|
||||
c.ty_u64 = prim(a, TY_U64, "u64", 8u64, 8u64);
|
||||
c.ty_int = prim(a, TY_INT, "int", 8u64, 8u64);
|
||||
c.ty_uint = prim(a, TY_UINT, "uint", 8u64, 8u64);
|
||||
c.ty_uintptr= prim(a, TY_UINTPTR, "uintptr", 8u64, 8u64);
|
||||
c.ty_f32 = prim(a, TY_F32, "f32", 4u64, 4u64);
|
||||
c.ty_f64 = prim(a, TY_F64, "f64", 8u64, 8u64);
|
||||
c.ty_str = prim(a, TY_STR, "str", 16u64, 8u64);
|
||||
c.ty_err = prim(a, TY_ERR, "<err>", 0u64, 1u64);
|
||||
|
||||
c.ty_untyped_int = prim(a, TY_UNTYPED_INT, "untyped_int", 0u64, 1u64);
|
||||
c.ty_untyped_float = prim(a, TY_UNTYPED_FLOAT, "untyped_float", 0u64, 1u64);
|
||||
c.ty_untyped_str = prim(a, TY_UNTYPED_STR, "untyped_str", 0u64, 1u64);
|
||||
c.ty_untyped_rune = prim(a, TY_UNTYPED_RUNE, "untyped_rune", 0u64, 1u64);
|
||||
c.ty_untyped_bool = prim(a, TY_UNTYPED_BOOL, "untyped_bool", 0u64, 1u64);
|
||||
c.ty_untyped_nil = prim(a, TY_UNTYPED_NIL, "untyped_nil", 0u64, 1u64);
|
||||
};
|
||||
|
||||
export fn type_ptr(a: *arena, sub: *tinfo) *tinfo = {
|
||||
let t: *tinfo = newtype(a, TY_PTR);
|
||||
t.sub = sub;
|
||||
t.size = 8u64;
|
||||
t.align = 8u64;
|
||||
return t;
|
||||
};
|
||||
|
||||
export fn type_slice(a: *arena, sub: *tinfo) *tinfo = {
|
||||
let t: *tinfo = newtype(a, TY_SLICE);
|
||||
t.sub = sub;
|
||||
t.size = 24u64;
|
||||
t.align = 8u64;
|
||||
return t;
|
||||
};
|
||||
|
||||
export fn type_array(a: *arena, sub: *tinfo, n: u64) *tinfo = {
|
||||
let t: *tinfo = newtype(a, TY_ARRAY);
|
||||
t.sub = sub;
|
||||
t.alen = n;
|
||||
if (sub != nil) {
|
||||
t.size = sub.size * n;
|
||||
t.align = sub.align;
|
||||
} else {
|
||||
t.align = 1u64;
|
||||
};
|
||||
return t;
|
||||
};
|
||||
|
||||
export fn type_chan(a: *arena, sub: *tinfo) *tinfo = {
|
||||
let t: *tinfo = newtype(a, TY_CHAN);
|
||||
t.sub = sub;
|
||||
t.size = 8u64;
|
||||
t.align = 8u64;
|
||||
return t;
|
||||
};
|
||||
|
||||
export fn type_named(a: *arena, name: str, under: *tinfo) *tinfo = {
|
||||
let t: *tinfo = newtype(a, TY_NAMED);
|
||||
t.name = name;
|
||||
t.under = under;
|
||||
if (under != nil) {
|
||||
t.size = under.size;
|
||||
t.align = under.align;
|
||||
};
|
||||
return t;
|
||||
};
|
||||
|
||||
// ---- predicates -------------------------------------------------------
|
||||
|
||||
export fn type_isint(t: *tinfo) bool = {
|
||||
if (t == nil) { return false; };
|
||||
let k: i32 = t.kind;
|
||||
if (k == TY_I8) { return true; };
|
||||
if (k == TY_I16) { return true; };
|
||||
if (k == TY_I32) { return true; };
|
||||
if (k == TY_I64) { return true; };
|
||||
if (k == TY_U8) { return true; };
|
||||
if (k == TY_U16) { return true; };
|
||||
if (k == TY_U32) { return true; };
|
||||
if (k == TY_U64) { return true; };
|
||||
if (k == TY_INT) { return true; };
|
||||
if (k == TY_UINT){ return true; };
|
||||
if (k == TY_UINTPTR) { return true; };
|
||||
if (k == TY_RUNE){ return true; };
|
||||
if (k == TY_UNTYPED_INT) { return true; };
|
||||
if (k == TY_UNTYPED_RUNE) { return true; };
|
||||
if (k == TY_NAMED) { return type_isint(t.under); };
|
||||
return false;
|
||||
};
|
||||
|
||||
export fn type_isfloat(t: *tinfo) bool = {
|
||||
if (t == nil) { return false; };
|
||||
let k: i32 = t.kind;
|
||||
if (k == TY_F32) { return true; };
|
||||
if (k == TY_F64) { return true; };
|
||||
if (k == TY_UNTYPED_FLOAT) { return true; };
|
||||
if (k == TY_NAMED) { return type_isfloat(t.under); };
|
||||
return false;
|
||||
};
|
||||
|
||||
export fn type_isnum(t: *tinfo) bool = {
|
||||
if (type_isint(t)) { return true; };
|
||||
return type_isfloat(t);
|
||||
};
|
||||
|
||||
export fn type_isunsigned(t: *tinfo) bool = {
|
||||
if (t == nil) { return false; };
|
||||
let k: i32 = t.kind;
|
||||
if (k == TY_U8) { return true; };
|
||||
if (k == TY_U16) { return true; };
|
||||
if (k == TY_U32) { return true; };
|
||||
if (k == TY_U64) { return true; };
|
||||
if (k == TY_UINT){ return true; };
|
||||
if (k == TY_UINTPTR) { return true; };
|
||||
if (k == TY_NAMED) { return type_isunsigned(t.under); };
|
||||
return false;
|
||||
};
|
||||
|
||||
export fn type_isuntyped(t: *tinfo) bool = {
|
||||
if (t == nil) { return false; };
|
||||
let k: i32 = t.kind;
|
||||
if (k == TY_UNTYPED_INT) { return true; };
|
||||
if (k == TY_UNTYPED_FLOAT) { return true; };
|
||||
if (k == TY_UNTYPED_STR) { return true; };
|
||||
if (k == TY_UNTYPED_RUNE) { return true; };
|
||||
if (k == TY_UNTYPED_BOOL) { return true; };
|
||||
if (k == TY_UNTYPED_NIL) { return true; };
|
||||
return false;
|
||||
};
|
||||
|
||||
// type_eq — structural equality. Named types compare nominally.
|
||||
export fn type_eq(a: *tinfo, b: *tinfo) bool = {
|
||||
if (a == b) { return true; };
|
||||
if (a == nil) { return false; };
|
||||
if (b == nil) { return false; };
|
||||
if (a.kind != b.kind) { return false; };
|
||||
let k: i32 = a.kind;
|
||||
if (k == TY_PTR) { return type_eq(a.sub, b.sub); };
|
||||
if (k == TY_SLICE) { return type_eq(a.sub, b.sub); };
|
||||
if (k == TY_CHAN) { return type_eq(a.sub, b.sub); };
|
||||
if (k == TY_ARRAY) {
|
||||
if (a.alen != b.alen) { return false; };
|
||||
return type_eq(a.sub, b.sub);
|
||||
};
|
||||
if (k == TY_FN) {
|
||||
if (a.variadic != b.variadic) { return false; };
|
||||
if (!type_eq(a.ret, b.ret)) { return false; };
|
||||
let pa: *tparam = a.params;
|
||||
let pb: *tparam = b.params;
|
||||
for (true) {
|
||||
if (pa == nil) { if (pb == nil) { return true; }; return false; };
|
||||
if (pb == nil) { return false; };
|
||||
if (!type_eq(pa.type_, pb.type_)) { return false; };
|
||||
pa = pa.tnext;
|
||||
pb = pb.tnext;
|
||||
};
|
||||
return true;
|
||||
};
|
||||
if (k == TY_STRUCT) {
|
||||
let fa: *tfield = a.fields;
|
||||
let fb: *tfield = b.fields;
|
||||
for (true) {
|
||||
if (fa == nil) { if (fb == nil) { return true; }; return false; };
|
||||
if (fb == nil) { return false; };
|
||||
let na: str = fa.name;
|
||||
let nb: str = fb.name;
|
||||
if (na.len != nb.len) { return false; };
|
||||
let i: i32 = 0;
|
||||
for (i < na.len) {
|
||||
if (na[i] != nb[i]) { return false; };
|
||||
i += 1;
|
||||
};
|
||||
if (!type_eq(fa.type_, fb.type_)) { return false; };
|
||||
fa = fa.tnext;
|
||||
fb = fb.tnext;
|
||||
};
|
||||
return true;
|
||||
};
|
||||
if (k == TY_NAMED) { return false; }; // nominal: only same ptr
|
||||
if (k == TY_TUPLE) {
|
||||
let pa: *tparam = a.params;
|
||||
let pb: *tparam = b.params;
|
||||
for (true) {
|
||||
if (pa == nil) { if (pb == nil) { return true; }; return false; };
|
||||
if (pb == nil) { return false; };
|
||||
if (!type_eq(pa.type_, pb.type_)) { return false; };
|
||||
pa = pa.tnext;
|
||||
pb = pb.tnext;
|
||||
};
|
||||
return true;
|
||||
};
|
||||
return true; // primitives match by kind alone
|
||||
};
|
||||
6559
selfhost/cmd/wwdump/main.combined.ww
Normal file
6559
selfhost/cmd/wwdump/main.combined.ww
Normal file
File diff suppressed because it is too large
Load Diff
156
selfhost/cmd/wwdump/main.ww
Normal file
156
selfhost/cmd/wwdump/main.ww
Normal file
@@ -0,0 +1,156 @@
|
||||
// selfhost/cmd/wwdump/main.ww — ww-side port of cmd/wwdump/main.c.
|
||||
//
|
||||
// Reads a .ww file, runs the ww-side lexer, prints tokens through
|
||||
// the ww-side tokprint. The 990_selfhost test diffs this output
|
||||
// byte-for-byte against the C-side wwdump on the same file. Any
|
||||
// divergence is a port bug in lex.ww or tok.ww.
|
||||
//
|
||||
// Modes:
|
||||
// wwdump -t file.ww tokens (default)
|
||||
// wwdump -a file.ww AST (not yet implemented; reserved)
|
||||
|
||||
use os;
|
||||
use mem;
|
||||
use tok;
|
||||
use lex;
|
||||
use ast;
|
||||
use parse;
|
||||
use typ;
|
||||
use sym;
|
||||
use check;
|
||||
use cgen;
|
||||
use strconv;
|
||||
|
||||
// ---- argv helpers -----------------------------------------------------
|
||||
|
||||
// argstrlen — strlen on a NUL-terminated *u8. argv strings are always
|
||||
// NUL-terminated (kernel-supplied) so this is safe.
|
||||
fn argstrlen(s: *u8) i32 = {
|
||||
let n: i32 = 0;
|
||||
for (s[n] != 0u8) { n += 1; };
|
||||
return n;
|
||||
};
|
||||
|
||||
fn argstr(p: *u8) str = {
|
||||
let s: str;
|
||||
s.ptr = p;
|
||||
s.len = argstrlen(p);
|
||||
return s;
|
||||
};
|
||||
|
||||
// streq_lit — compare a NUL-terminated argv entry to a string literal.
|
||||
fn streq_lit(p: *u8, lit: str) bool = {
|
||||
let i: i32 = 0;
|
||||
for (i < lit.len) {
|
||||
if (p[i] != lit[i]) { return false; };
|
||||
i += 1;
|
||||
};
|
||||
return p[i] == 0u8;
|
||||
};
|
||||
|
||||
// ---- main -------------------------------------------------------------
|
||||
|
||||
export fn main(argc: i32, argv: **u8) i32 = {
|
||||
let mode: i32 = 116; // 't'
|
||||
let path: *u8 = nil;
|
||||
let i: i32 = 1;
|
||||
for (i < argc) {
|
||||
let a: *u8 = argv[i];
|
||||
if (streq_lit(a, "-t")) {
|
||||
mode = 116;
|
||||
} else { if (streq_lit(a, "-a")) {
|
||||
mode = 97; // 'a'
|
||||
} else { if (streq_lit(a, "-r")) {
|
||||
mode = 114; // 'r' — resolve / name-check
|
||||
} else { if (streq_lit(a, "-c")) {
|
||||
mode = 99; // 'c' — codegen / emit asm
|
||||
} else { if (path == nil) {
|
||||
path = a;
|
||||
};};};};};
|
||||
i += 1;
|
||||
};
|
||||
if (path == nil) {
|
||||
os.write(2, "usage: wwdump [-t|-a] file.ww\n".ptr, 30u64);
|
||||
return 2;
|
||||
};
|
||||
|
||||
let fd_or_err: (i32 | str) = os.tryopen(path, os.O_RDONLY, 0i32);
|
||||
let fd: i32 = -1;
|
||||
match (fd_or_err) {
|
||||
case let v: i32 => fd = v;
|
||||
case let e: str => {
|
||||
os.write(2, "wwdump: cannot open ".ptr, 20u64);
|
||||
os.write(2, path, argstrlen(path): u64);
|
||||
os.write(2, "\n".ptr, 1u64);
|
||||
return 1;
|
||||
};
|
||||
};
|
||||
|
||||
let sz: i64 = os.filesize(fd);
|
||||
if (sz < 0i64) {
|
||||
os.write(2, "wwdump: filesize failed\n".ptr, 24u64);
|
||||
os.close(fd);
|
||||
return 1;
|
||||
};
|
||||
|
||||
let a: *arena = newarena();
|
||||
let buf: *u8 = amalloc(a, sz: u64): *u8;
|
||||
let r: i64 = os.readfull(fd, buf, sz: u64);
|
||||
os.close(fd);
|
||||
if (r != sz) {
|
||||
os.write(2, "wwdump: short read\n".ptr, 19u64);
|
||||
return 1;
|
||||
};
|
||||
|
||||
let l: lex;
|
||||
lexinit(&l, a, argstr(path), buf, sz: u64);
|
||||
|
||||
if (mode == 116) { // '-t'
|
||||
for (true) {
|
||||
let t: tok;
|
||||
lexnext(&l, &t);
|
||||
tokprint(1i32, &t);
|
||||
if (t.kind == TK_EOF) { break; };
|
||||
if (t.kind == TK_ERR) { break; };
|
||||
};
|
||||
} else { if (mode == 97) { // '-a'
|
||||
let ps: parser;
|
||||
parserinit(&ps, a, &l);
|
||||
let f: *node = parsefile(&ps);
|
||||
astprint(1i32, f);
|
||||
} else { if (mode == 114) { // '-r' — name resolve report
|
||||
let ps: parser;
|
||||
parserinit(&ps, a, &l);
|
||||
let f: *node = parsefile(&ps);
|
||||
let tc: tctx;
|
||||
typesinit(&tc, a);
|
||||
let ck: checker;
|
||||
check_init(&ck, a, &tc);
|
||||
// Quiet by default; flip to 1 when debugging missing names.
|
||||
ck.verbose = 0;
|
||||
check_file(&ck, f);
|
||||
// (close out the if-else chain — we'll close all braces below)
|
||||
// "<file>: <resolved>/<resolved+unresolved> resolved"
|
||||
os.write(1, argstr(path).ptr, argstrlen(path): u64);
|
||||
os.write(1, ": ".ptr, 2u64);
|
||||
let buf: [32]u8;
|
||||
let n: i32 = strconv.i64toa(buf[0:32], ck.nresolved: i64);
|
||||
os.write(1, buf.ptr, n: u64);
|
||||
os.write(1, "/".ptr, 1u64);
|
||||
let total: i32 = ck.nresolved + ck.nunresolved;
|
||||
n = strconv.i64toa(buf[0:32], total: i64);
|
||||
os.write(1, buf.ptr, n: u64);
|
||||
os.write(1, " resolved\n".ptr, 10u64);
|
||||
if (ck.nunresolved > 0) { return 1; };
|
||||
} else { if (mode == 99) { // '-c' — codegen / emit asm
|
||||
let ps: parser;
|
||||
parserinit(&ps, a, &l);
|
||||
let f: *node = parsefile(&ps);
|
||||
let cg: cgen;
|
||||
cgen_init(&cg, a);
|
||||
cg_file(&cg, f);
|
||||
};};};};
|
||||
|
||||
if (l.errs > 0) { return 1; };
|
||||
return 0;
|
||||
};
|
||||
549
selfhost/test/smoke.combined.ww
Normal file
549
selfhost/test/smoke.combined.ww
Normal file
@@ -0,0 +1,549 @@
|
||||
// os — process and filesystem facade. The body of each call lands
|
||||
// either in libwwrt.a (rt_syscall trampoline) or libc bindings,
|
||||
// depending on how the program was linked.
|
||||
|
||||
@symbol("rt_syscall") fn syscall0(num: i64) i64;
|
||||
@symbol("rt_syscall") fn syscall1(num: i64, a: i64) i64;
|
||||
@symbol("rt_syscall") fn syscall2(num: i64, a: i64, b: i64) i64;
|
||||
@symbol("rt_syscall") fn syscall3(num: i64, a: i64, b: i64, c: i64) i64;
|
||||
@symbol("rt_syscall") fn syscall4(num: i64, a: i64, b: i64, c: i64, d: i64) i64;
|
||||
|
||||
@symbol("rt_alloc") fn alloc(n: u64) *void;
|
||||
@symbol("rt_free") fn free(p: *void, n: u64) void;
|
||||
@symbol("rt_abort") fn abort(msg: str) void;
|
||||
|
||||
// Hare-style runtime check. Caller passes a message that's printed
|
||||
// to stderr before exit(1).
|
||||
export fn assert(cond: bool, msg: str) void = {
|
||||
if (!cond) { abort(msg); };
|
||||
};
|
||||
|
||||
def SYS_READ: i64 = 0;
|
||||
def SYS_WRITE: i64 = 1;
|
||||
def SYS_OPEN: i64 = 2;
|
||||
def SYS_CLOSE: i64 = 3;
|
||||
def SYS_LSEEK: i64 = 8;
|
||||
def SYS_ACCESS: i64 = 21;
|
||||
def SYS_GETPID: i64 = 39;
|
||||
def SYS_FORK: i64 = 57;
|
||||
def SYS_EXECVE: i64 = 59;
|
||||
def SYS_EXIT: i64 = 60;
|
||||
def SYS_WAIT4: i64 = 61;
|
||||
def SYS_UNLINK: i64 = 87;
|
||||
|
||||
// open(2) flags. Linux values, matching <fcntl.h>.
|
||||
def O_RDONLY: i32 = 0;
|
||||
def O_WRONLY: i32 = 1;
|
||||
def O_RDWR: i32 = 2;
|
||||
def O_CREAT: i32 = 64; // 0x40
|
||||
def O_TRUNC: i32 = 512; // 0x200
|
||||
|
||||
// lseek(2) whence.
|
||||
def SEEK_SET: i32 = 0;
|
||||
def SEEK_CUR: i32 = 1;
|
||||
def SEEK_END: i32 = 2;
|
||||
|
||||
export fn exit(code: i32) void = {
|
||||
syscall1(SYS_EXIT, code: i64);
|
||||
};
|
||||
|
||||
// Raw, non-fallible primitives. These return Linux's int conventions
|
||||
// (negative = -errno, non-negative = bytes/fd/etc). Callers wanting a
|
||||
// Hare-style fallible API use the wrappers below.
|
||||
export fn write(fd: i32, buf: *u8, n: u64) i64 = {
|
||||
return syscall3(SYS_WRITE, fd: i64, buf: i64, n: i64);
|
||||
};
|
||||
|
||||
export fn read(fd: i32, buf: *u8, n: u64) i64 = {
|
||||
return syscall3(SYS_READ, fd: i64, buf: i64, n: i64);
|
||||
};
|
||||
|
||||
export fn close(fd: i32) i32 = {
|
||||
return syscall1(SYS_CLOSE, fd: i64): i32;
|
||||
};
|
||||
|
||||
// Fallible wrappers. The error variant is a plain str (Plan 9 errstr
|
||||
// model, see lib/errors); the sum type makes success/failure explicit
|
||||
// without overloading length-zero.
|
||||
export fn tryread(fd: i32, buf: *u8, n: u64) (i64 | str) = {
|
||||
let r: i64 = read(fd, buf, n);
|
||||
if (r < 0) { return "read failed"; };
|
||||
return r;
|
||||
};
|
||||
|
||||
export fn trywrite(fd: i32, buf: *u8, n: u64) (i64 | str) = {
|
||||
let r: i64 = write(fd, buf, n);
|
||||
if (r < 0) { return "write failed"; };
|
||||
return r;
|
||||
};
|
||||
|
||||
// open — Linux open(2). Path must be NUL-terminated; callers using ww
|
||||
// `str` must ensure the bytes are followed by a 0 byte (literals are,
|
||||
// arena-copied paths usually are by construction). Returns -errno on
|
||||
// failure, fd otherwise. Higher-level callers prefer `tryopen`.
|
||||
export fn open(path: *u8, flags: i32, mode: i32) i32 = {
|
||||
return syscall3(SYS_OPEN, path: i64, flags: i64, mode: i64): i32;
|
||||
};
|
||||
|
||||
export fn tryopen(path: *u8, flags: i32, mode: i32) (i32 | str) = {
|
||||
let fd: i32 = open(path, flags, mode);
|
||||
if (fd < 0) { return "open failed"; };
|
||||
return fd;
|
||||
};
|
||||
|
||||
// lseek — set/inspect the fd's position. Returns the new offset or
|
||||
// a negative errno. We use this for fstat-free file-size discovery
|
||||
// (open ⇒ lseek to end ⇒ lseek back).
|
||||
export fn lseek(fd: i32, off: i64, whence: i32) i64 = {
|
||||
return syscall3(SYS_LSEEK, fd: i64, off, whence: i64);
|
||||
};
|
||||
|
||||
// filesize — convenience: returns the byte length of an open fd by
|
||||
// seeking to the end and back. -1 on error.
|
||||
export fn filesize(fd: i32) i64 = {
|
||||
let end: i64 = lseek(fd, 0i64, SEEK_END);
|
||||
if (end < 0) { return -1i64; };
|
||||
let r: i64 = lseek(fd, 0i64, SEEK_SET);
|
||||
if (r < 0) { return -1i64; };
|
||||
return end;
|
||||
};
|
||||
|
||||
// readfull — keep reading until `n` bytes have arrived or the fd
|
||||
// closes early. Returns bytes read (0..=n) or -1 on read error.
|
||||
export fn readfull(fd: i32, buf: *u8, n: u64) i64 = {
|
||||
let got: u64 = 0u64;
|
||||
for (got < n) {
|
||||
let r: i64 = read(fd, buf + got, n - got);
|
||||
if (r < 0) { return -1i64; };
|
||||
if (r == 0) { return got: i64; }; // short read: caller decides
|
||||
got += r: u64;
|
||||
};
|
||||
return got: i64;
|
||||
};
|
||||
|
||||
// writefull — keep writing until `n` bytes have been accepted or the
|
||||
// fd refuses progress. Returns bytes written or -1.
|
||||
export fn writefull(fd: i32, buf: *u8, n: u64) i64 = {
|
||||
let sent: u64 = 0u64;
|
||||
for (sent < n) {
|
||||
let r: i64 = write(fd, buf + sent, n - sent);
|
||||
if (r < 0) { return -1i64; };
|
||||
if (r == 0) { return sent: i64; };
|
||||
sent += r: u64;
|
||||
};
|
||||
return sent: i64;
|
||||
};
|
||||
|
||||
// ---- process and filesystem helpers used by the `ww` driver ----------
|
||||
|
||||
// access(2): returns 0 if the file is reachable, negative errno
|
||||
// otherwise. mode is the bitset described in <unistd.h> (F_OK=0).
|
||||
export fn access(path: *u8, mode: i32) i32 = {
|
||||
return syscall2(SYS_ACCESS, path: i64, mode: i64): i32;
|
||||
};
|
||||
|
||||
// unlink(2).
|
||||
export fn unlink(path: *u8) i32 = {
|
||||
return syscall1(SYS_UNLINK, path: i64): i32;
|
||||
};
|
||||
|
||||
// getpid(2). Used by the driver to mint unique scratch paths.
|
||||
export fn getpid() i32 = {
|
||||
return syscall0(SYS_GETPID): i32;
|
||||
};
|
||||
|
||||
// fork(2): 0 in the child, child pid in the parent, negative errno
|
||||
// on failure.
|
||||
export fn fork() i32 = {
|
||||
return syscall0(SYS_FORK): i32;
|
||||
};
|
||||
|
||||
// execve(2): on success, does not return.
|
||||
export fn execve(path: *u8, argv: **u8, envp: **u8) i32 = {
|
||||
return syscall3(SYS_EXECVE, path: i64, argv: i64, envp: i64): i32;
|
||||
};
|
||||
|
||||
// wait4(2): wait for `pid` (or any child if -1), store status in
|
||||
// `*status_out`, return the pid that ended (or negative errno).
|
||||
export fn wait4(pid: i32, status_out: *i32, options: i32, rusage: *void) i32 = {
|
||||
return syscall4(SYS_WAIT4, pid: i64, status_out: i64,
|
||||
options: i64, rusage: i64): i32;
|
||||
};
|
||||
|
||||
// strconv — number↔string conversions. Decimal i64 to/from a fixed
|
||||
// buffer. Two error idioms ship side by side:
|
||||
// - Plan 9 style (atoi64): tuple `(value, ok)`. Pre-dates the
|
||||
// tagged-union work; kept for callers that already use it.
|
||||
// - Hare style (parse64/parseu64): `(value | str)`. The error
|
||||
// variant carries a short, allocation-free message describing
|
||||
// why the parse failed. Prefer this for new code.
|
||||
|
||||
// u64toa — write `v` in decimal into `buf` and return the byte count.
|
||||
// Unsigned-only so callers don't have to think about wraparound when
|
||||
// printing a u64 that happens to have the high bit set.
|
||||
export fn u64toa(buf: []u8, v: u64) i32 = {
|
||||
let tmp: [32]u8;
|
||||
let i: i32 = 0;
|
||||
let n: u64 = v;
|
||||
for (n > 0u64) {
|
||||
tmp[i] = ((n % 10u64) + 48u64): u8;
|
||||
n = n / 10u64;
|
||||
i += 1;
|
||||
};
|
||||
if (i == 0) {
|
||||
tmp[0] = 48u8;
|
||||
i = 1;
|
||||
};
|
||||
let out: i32 = 0;
|
||||
for (i > 0) {
|
||||
i -= 1;
|
||||
buf[out] = tmp[i];
|
||||
out += 1;
|
||||
};
|
||||
return out;
|
||||
};
|
||||
|
||||
export fn i64toa(buf: []u8, v: i64) i32 = {
|
||||
let neg: bool = false;
|
||||
let n: i64 = v;
|
||||
if (n < 0) {
|
||||
neg = true;
|
||||
n = -n;
|
||||
};
|
||||
let tmp: [32]u8;
|
||||
let i: i32 = 0;
|
||||
for (n > 0) {
|
||||
tmp[i] = ((n % 10) + 48): u8;
|
||||
n = n / 10;
|
||||
i += 1;
|
||||
};
|
||||
if (i == 0) {
|
||||
tmp[0] = 48u8;
|
||||
i = 1;
|
||||
};
|
||||
let out: i32 = 0;
|
||||
if (neg) {
|
||||
buf[out] = 45u8; // '-'
|
||||
out += 1;
|
||||
};
|
||||
for (i > 0) {
|
||||
i -= 1;
|
||||
buf[out] = tmp[i];
|
||||
out += 1;
|
||||
};
|
||||
return out;
|
||||
};
|
||||
|
||||
export fn atoi64(s: str) (i64, bool) = {
|
||||
let v: i64 = 0;
|
||||
let i: i32 = 0;
|
||||
let neg: bool = false;
|
||||
if (s.len > 0) {
|
||||
if (s[0] == 45u8) { neg = true; i = 1; };
|
||||
};
|
||||
if (i >= s.len) { return 0, false; };
|
||||
for (i < s.len) {
|
||||
let c: u8 = s[i];
|
||||
if (c < 48u8) { return 0, false; };
|
||||
if (c > 57u8) { return 0, false; };
|
||||
v = v * 10 + ((c: i64) - 48);
|
||||
i += 1;
|
||||
};
|
||||
if (neg) { v = -v; };
|
||||
return v, true;
|
||||
};
|
||||
|
||||
// parse64 — Hare-style fallible signed decimal parser. The value
|
||||
// variant is i64; the error variant is a short str describing the
|
||||
// reason. No locale, no whitespace, no underscores: a leading '-' is
|
||||
// the only non-digit accepted, and only at position 0.
|
||||
export fn parse64(s: str) (i64 | str) = {
|
||||
if (s.len == 0) { return "parse: empty"; };
|
||||
let i: i32 = 0;
|
||||
let neg: bool = false;
|
||||
if (s[0] == 45u8) { neg = true; i = 1; };
|
||||
if (i >= s.len) { return "parse: lone sign"; };
|
||||
let v: i64 = 0;
|
||||
for (i < s.len) {
|
||||
let c: u8 = s[i];
|
||||
if (c < 48u8) { return "parse: invalid digit"; };
|
||||
if (c > 57u8) { return "parse: invalid digit"; };
|
||||
v = v * 10 + ((c: i64) - 48);
|
||||
i += 1;
|
||||
};
|
||||
if (neg) { v = -v; };
|
||||
return v;
|
||||
};
|
||||
|
||||
// parseu64 — fallible unsigned decimal parser. No leading sign.
|
||||
export fn parseu64(s: str) (u64 | str) = {
|
||||
if (s.len == 0) { return "parse: empty"; };
|
||||
let v: u64 = 0u64;
|
||||
let i: i32 = 0;
|
||||
for (i < s.len) {
|
||||
let c: u8 = s[i];
|
||||
if (c < 48u8) { return "parse: invalid digit"; };
|
||||
if (c > 57u8) { return "parse: invalid digit"; };
|
||||
v = v * 10u64 + ((c: u64) - 48u64);
|
||||
i += 1;
|
||||
};
|
||||
return v;
|
||||
};
|
||||
|
||||
// ascii — byte-class predicates and case folding for the ASCII range.
|
||||
// Matches Hare's ascii::isdigit family. Bytes outside 0..127 always
|
||||
// answer `false`. The lexer hot path uses these inline; they are
|
||||
// expected to inline to a couple of compares.
|
||||
|
||||
export fn isdigit(c: u8) bool = {
|
||||
if (c < 48u8) { return false; };
|
||||
if (c > 57u8) { return false; };
|
||||
return true;
|
||||
};
|
||||
|
||||
export fn isupper(c: u8) bool = {
|
||||
if (c < 65u8) { return false; };
|
||||
if (c > 90u8) { return false; };
|
||||
return true;
|
||||
};
|
||||
|
||||
export fn islower(c: u8) bool = {
|
||||
if (c < 97u8) { return false; };
|
||||
if (c > 122u8) { return false; };
|
||||
return true;
|
||||
};
|
||||
|
||||
export fn isalpha(c: u8) bool = {
|
||||
if (isupper(c)) { return true; };
|
||||
return islower(c);
|
||||
};
|
||||
|
||||
export fn isalnum(c: u8) bool = {
|
||||
if (isalpha(c)) { return true; };
|
||||
return isdigit(c);
|
||||
};
|
||||
|
||||
// isspace — the C/Hare set: space, tab, NL, VT, FF, CR.
|
||||
export fn isspace(c: u8) bool = {
|
||||
if (c == 32u8) { return true; }; // ' '
|
||||
if (c == 9u8) { return true; }; // '\t'
|
||||
if (c == 10u8) { return true; }; // '\n'
|
||||
if (c == 11u8) { return true; }; // '\v'
|
||||
if (c == 12u8) { return true; }; // '\f'
|
||||
if (c == 13u8) { return true; }; // '\r'
|
||||
return false;
|
||||
};
|
||||
|
||||
export fn ishex(c: u8) bool = {
|
||||
if (isdigit(c)) { return true; };
|
||||
if (c >= 65u8) {
|
||||
if (c <= 70u8) { return true; }; // 'A'..'F'
|
||||
};
|
||||
if (c >= 97u8) {
|
||||
if (c <= 102u8) { return true; }; // 'a'..'f'
|
||||
};
|
||||
return false;
|
||||
};
|
||||
|
||||
// digitval — value of `c` as a hex/decimal digit, or -1 if not one.
|
||||
// Useful when scanning numeric literals.
|
||||
export fn digitval(c: u8) i32 = {
|
||||
if (isdigit(c)) { return (c - 48u8): i32; };
|
||||
if (c >= 65u8) {
|
||||
if (c <= 70u8) { return ((c - 65u8) + 10u8): i32; };
|
||||
};
|
||||
if (c >= 97u8) {
|
||||
if (c <= 102u8) { return ((c - 97u8) + 10u8): i32; };
|
||||
};
|
||||
return -1;
|
||||
};
|
||||
|
||||
// isidstart / isidpart — identifier classes used by the lexer.
|
||||
// Alpha or '_' starts; alnum or '_' continues.
|
||||
export fn isidstart(c: u8) bool = {
|
||||
if (isalpha(c)) { return true; };
|
||||
if (c == 95u8) { return true; }; // '_'
|
||||
return false;
|
||||
};
|
||||
|
||||
export fn isidpart(c: u8) bool = {
|
||||
if (isalnum(c)) { return true; };
|
||||
if (c == 95u8) { return true; };
|
||||
return false;
|
||||
};
|
||||
|
||||
// tolower / toupper — fold ASCII case. Non-letters pass through.
|
||||
export fn tolower(c: u8) u8 = {
|
||||
if (isupper(c)) { return c + 32u8; };
|
||||
return c;
|
||||
};
|
||||
|
||||
export fn toupper(c: u8) u8 = {
|
||||
if (islower(c)) { return c - 32u8; };
|
||||
return c;
|
||||
};
|
||||
|
||||
// selfhost/test/smoke.ww — end-to-end smoke for the selfhost path.
|
||||
//
|
||||
// Exercises the patterns the real ww-side compiler port will use:
|
||||
// - bump arena allocator (mem.ww shape)
|
||||
// - error idiom (T | str)
|
||||
// - struct of fn pointers + ctx pointer (the io.stream-style
|
||||
// polymorphism we use instead of interfaces)
|
||||
// - byte-level scanning that mirrors the hot path inside lex.ww
|
||||
// - strconv round-trip via the real stdlib
|
||||
//
|
||||
// `main` returns 42 when every check passes, 1..N on failure
|
||||
// indicating which probe broke. The 990_selfhost test asserts 42.
|
||||
//
|
||||
// Note: only stack-local mutable state. Top-level `let` mutation
|
||||
// requires a writable .data segment in 6l, which is a separate
|
||||
// task; until then we exercise polymorphism via ctx pointers, which
|
||||
// is what the real port wants anyway.
|
||||
|
||||
use os;
|
||||
use strconv;
|
||||
use ascii;
|
||||
|
||||
// --- bump arena ---------------------------------------------------------
|
||||
|
||||
type arena = struct {
|
||||
buf: *u8,
|
||||
off: u64,
|
||||
cap: u64,
|
||||
};
|
||||
|
||||
// In-place init. Returning a 24-byte struct by value isn't yet
|
||||
// supported in 6c (SysV requires a hidden return-slot pointer for
|
||||
// structs >16 bytes), so we initialize through a pointer like the
|
||||
// real compiler does today.
|
||||
fn arena_init(a: *arena, buf: *u8, cap: u64) void = {
|
||||
a.buf = buf;
|
||||
a.off = 0u64;
|
||||
a.cap = cap;
|
||||
};
|
||||
|
||||
fn arena_alloc(a: *arena, n: u64) *u8 = {
|
||||
if (n > a.cap - a.off) { return nil; };
|
||||
let p: *u8 = a.buf + a.off;
|
||||
a.off += n;
|
||||
return p;
|
||||
};
|
||||
|
||||
// --- (i32 | str) error idiom -------------------------------------------
|
||||
|
||||
fn checked_div(num: i32, den: i32) (i32 | str) = {
|
||||
if (den == 0) { return "div by zero"; };
|
||||
return num / den;
|
||||
};
|
||||
|
||||
// --- struct-of-fn-pointer polymorphism ---------------------------------
|
||||
//
|
||||
// A trivial "writer" abstraction: a function pointer plus a context.
|
||||
// This mirrors how io.stream / Plan 9 Bio work. The ctx pointer lets
|
||||
// the implementation own its own state without a global.
|
||||
|
||||
type counter = struct {
|
||||
n: i32,
|
||||
};
|
||||
|
||||
type writer = struct {
|
||||
ctx: *void,
|
||||
emit: fn(ctx: *void, b: u8) void,
|
||||
};
|
||||
|
||||
fn count_emit(ctx: *void, b: u8) void = {
|
||||
let c: *counter = ctx: *counter;
|
||||
c.n += 1;
|
||||
};
|
||||
|
||||
// --- byte scanner like lex.ww's hot path -------------------------------
|
||||
|
||||
fn count_digits(s: str) i32 = {
|
||||
let i: i32 = 0;
|
||||
let n: i32 = 0;
|
||||
for (i < s.len) {
|
||||
let c: u8 = s[i];
|
||||
if (c >= 48u8) {
|
||||
if (c <= 57u8) { n += 1; };
|
||||
};
|
||||
i += 1;
|
||||
};
|
||||
return n;
|
||||
};
|
||||
|
||||
// --- entry --------------------------------------------------------------
|
||||
|
||||
export fn main() i32 = {
|
||||
// Probe 1 — arena hands out distinct pointers, refuses oversize.
|
||||
let buf: [256]u8;
|
||||
let a: arena;
|
||||
arena_init(&a, buf.ptr, 256u64);
|
||||
let p1: *u8 = arena_alloc(&a, 32u64);
|
||||
let p2: *u8 = arena_alloc(&a, 32u64);
|
||||
if (p1 == nil) { return 1; };
|
||||
if (p2 == nil) { return 2; };
|
||||
if (p1 == p2) { return 3; };
|
||||
let p3: *u8 = arena_alloc(&a, 1024u64);
|
||||
if (p3 != nil) { return 4; };
|
||||
|
||||
// Probe 2 — error union both ways.
|
||||
let r_ok: (i32 | str) = checked_div(84, 2);
|
||||
let r_bad: (i32 | str) = checked_div(1, 0);
|
||||
let acc: i32 = 0;
|
||||
match (r_ok) {
|
||||
case let v: i32 => acc = v;
|
||||
case let e: str => return 5;
|
||||
};
|
||||
if (acc != 42) { return 6; };
|
||||
match (r_bad) {
|
||||
case let v: i32 => return 7;
|
||||
case let e: str => acc = e.len: i32;
|
||||
};
|
||||
if (acc != 11) { return 8; }; // len("div by zero") == 11
|
||||
|
||||
// Probe 3 — struct-of-fn-pointer dispatch via ctx pointer.
|
||||
let c: counter = counter { n = 0 };
|
||||
let w: writer = writer { ctx = (&c): *void, emit = count_emit };
|
||||
w.emit(w.ctx, 65u8);
|
||||
w.emit(w.ctx, 66u8);
|
||||
w.emit(w.ctx, 67u8);
|
||||
if (c.n != 3) { return 9; };
|
||||
|
||||
// Probe 4 — byte scan over a literal.
|
||||
let dn: i32 = count_digits("ww123abc");
|
||||
if (dn != 3) { return 10; };
|
||||
|
||||
// Probe 5 — strconv round-trip via the real stdlib.
|
||||
let outbuf: [32]u8;
|
||||
let nb: i32 = strconv.i64toa(outbuf[0:32], 4242i64);
|
||||
if (nb != 4) { return 11; };
|
||||
if (outbuf[0] != 52u8) { return 12; }; // '4'
|
||||
if (outbuf[3] != 50u8) { return 13; }; // '2'
|
||||
|
||||
// Probe 6 — ascii classifications.
|
||||
if (!ascii.isdigit(53u8)) { return 14; }; // '5'
|
||||
if (ascii.isdigit(65u8)) { return 15; }; // 'A' is not a digit
|
||||
if (!ascii.isalpha(122u8)) { return 16; }; // 'z'
|
||||
if (!ascii.isidstart(95u8)) { return 17; }; // '_'
|
||||
if (!ascii.isidpart(48u8)) { return 18; }; // '0' is part
|
||||
if (ascii.digitval(70u8) != 15) { return 19; }; // 'F' = 15
|
||||
if (ascii.tolower(65u8) != 97u8) { return 20; }; // 'A' -> 'a'
|
||||
|
||||
// Probe 7 — file open/read via the new os APIs. /proc/self/cmdline
|
||||
// always exists on Linux, no write side, and is non-empty.
|
||||
let path: str = "/proc/self/cmdline";
|
||||
let fd_or_err: (i32 | str) = os.tryopen(path.ptr, os.O_RDONLY, 0i32);
|
||||
let fd: i32 = 0;
|
||||
match (fd_or_err) {
|
||||
case let v: i32 => fd = v;
|
||||
case let e: str => return 21;
|
||||
};
|
||||
let rbuf: [128]u8;
|
||||
let n: i64 = os.readfull(fd, rbuf.ptr, 128u64);
|
||||
os.close(fd);
|
||||
if (n <= 0i64) { return 22; };
|
||||
|
||||
return 42;
|
||||
};
|
||||
|
||||
163
selfhost/test/smoke.ww
Normal file
163
selfhost/test/smoke.ww
Normal file
@@ -0,0 +1,163 @@
|
||||
// selfhost/test/smoke.ww — end-to-end smoke for the selfhost path.
|
||||
//
|
||||
// Exercises the patterns the real ww-side compiler port will use:
|
||||
// - bump arena allocator (mem.ww shape)
|
||||
// - error idiom (T | str)
|
||||
// - struct of fn pointers + ctx pointer (the io.stream-style
|
||||
// polymorphism we use instead of interfaces)
|
||||
// - byte-level scanning that mirrors the hot path inside lex.ww
|
||||
// - strconv round-trip via the real stdlib
|
||||
//
|
||||
// `main` returns 42 when every check passes, 1..N on failure
|
||||
// indicating which probe broke. The 990_selfhost test asserts 42.
|
||||
//
|
||||
// Note: only stack-local mutable state. Top-level `let` mutation
|
||||
// requires a writable .data segment in 6l, which is a separate
|
||||
// task; until then we exercise polymorphism via ctx pointers, which
|
||||
// is what the real port wants anyway.
|
||||
|
||||
use os;
|
||||
use strconv;
|
||||
use ascii;
|
||||
|
||||
// --- bump arena ---------------------------------------------------------
|
||||
|
||||
type arena = struct {
|
||||
buf: *u8,
|
||||
off: u64,
|
||||
cap: u64,
|
||||
};
|
||||
|
||||
// In-place init. Returning a 24-byte struct by value isn't yet
|
||||
// supported in 6c (SysV requires a hidden return-slot pointer for
|
||||
// structs >16 bytes), so we initialize through a pointer like the
|
||||
// real compiler does today.
|
||||
fn arena_init(a: *arena, buf: *u8, cap: u64) void = {
|
||||
a.buf = buf;
|
||||
a.off = 0u64;
|
||||
a.cap = cap;
|
||||
};
|
||||
|
||||
fn arena_alloc(a: *arena, n: u64) *u8 = {
|
||||
if (n > a.cap - a.off) { return nil; };
|
||||
let p: *u8 = a.buf + a.off;
|
||||
a.off += n;
|
||||
return p;
|
||||
};
|
||||
|
||||
// --- (i32 | str) error idiom -------------------------------------------
|
||||
|
||||
fn checked_div(num: i32, den: i32) (i32 | str) = {
|
||||
if (den == 0) { return "div by zero"; };
|
||||
return num / den;
|
||||
};
|
||||
|
||||
// --- struct-of-fn-pointer polymorphism ---------------------------------
|
||||
//
|
||||
// A trivial "writer" abstraction: a function pointer plus a context.
|
||||
// This mirrors how io.stream / Plan 9 Bio work. The ctx pointer lets
|
||||
// the implementation own its own state without a global.
|
||||
|
||||
type counter = struct {
|
||||
n: i32,
|
||||
};
|
||||
|
||||
type writer = struct {
|
||||
ctx: *void,
|
||||
emit: fn(ctx: *void, b: u8) void,
|
||||
};
|
||||
|
||||
fn count_emit(ctx: *void, b: u8) void = {
|
||||
let c: *counter = ctx: *counter;
|
||||
c.n += 1;
|
||||
};
|
||||
|
||||
// --- byte scanner like lex.ww's hot path -------------------------------
|
||||
|
||||
fn count_digits(s: str) i32 = {
|
||||
let i: i32 = 0;
|
||||
let n: i32 = 0;
|
||||
for (i < s.len) {
|
||||
let c: u8 = s[i];
|
||||
if (c >= 48u8) {
|
||||
if (c <= 57u8) { n += 1; };
|
||||
};
|
||||
i += 1;
|
||||
};
|
||||
return n;
|
||||
};
|
||||
|
||||
// --- entry --------------------------------------------------------------
|
||||
|
||||
export fn main() i32 = {
|
||||
// Probe 1 — arena hands out distinct pointers, refuses oversize.
|
||||
let buf: [256]u8;
|
||||
let a: arena;
|
||||
arena_init(&a, buf.ptr, 256u64);
|
||||
let p1: *u8 = arena_alloc(&a, 32u64);
|
||||
let p2: *u8 = arena_alloc(&a, 32u64);
|
||||
if (p1 == nil) { return 1; };
|
||||
if (p2 == nil) { return 2; };
|
||||
if (p1 == p2) { return 3; };
|
||||
let p3: *u8 = arena_alloc(&a, 1024u64);
|
||||
if (p3 != nil) { return 4; };
|
||||
|
||||
// Probe 2 — error union both ways.
|
||||
let r_ok: (i32 | str) = checked_div(84, 2);
|
||||
let r_bad: (i32 | str) = checked_div(1, 0);
|
||||
let acc: i32 = 0;
|
||||
match (r_ok) {
|
||||
case let v: i32 => acc = v;
|
||||
case let e: str => return 5;
|
||||
};
|
||||
if (acc != 42) { return 6; };
|
||||
match (r_bad) {
|
||||
case let v: i32 => return 7;
|
||||
case let e: str => acc = e.len: i32;
|
||||
};
|
||||
if (acc != 11) { return 8; }; // len("div by zero") == 11
|
||||
|
||||
// Probe 3 — struct-of-fn-pointer dispatch via ctx pointer.
|
||||
let c: counter = counter { n = 0 };
|
||||
let w: writer = writer { ctx = (&c): *void, emit = count_emit };
|
||||
w.emit(w.ctx, 65u8);
|
||||
w.emit(w.ctx, 66u8);
|
||||
w.emit(w.ctx, 67u8);
|
||||
if (c.n != 3) { return 9; };
|
||||
|
||||
// Probe 4 — byte scan over a literal.
|
||||
let dn: i32 = count_digits("ww123abc");
|
||||
if (dn != 3) { return 10; };
|
||||
|
||||
// Probe 5 — strconv round-trip via the real stdlib.
|
||||
let outbuf: [32]u8;
|
||||
let nb: i32 = strconv.i64toa(outbuf[0:32], 4242i64);
|
||||
if (nb != 4) { return 11; };
|
||||
if (outbuf[0] != 52u8) { return 12; }; // '4'
|
||||
if (outbuf[3] != 50u8) { return 13; }; // '2'
|
||||
|
||||
// Probe 6 — ascii classifications.
|
||||
if (!ascii.isdigit(53u8)) { return 14; }; // '5'
|
||||
if (ascii.isdigit(65u8)) { return 15; }; // 'A' is not a digit
|
||||
if (!ascii.isalpha(122u8)) { return 16; }; // 'z'
|
||||
if (!ascii.isidstart(95u8)) { return 17; }; // '_'
|
||||
if (!ascii.isidpart(48u8)) { return 18; }; // '0' is part
|
||||
if (ascii.digitval(70u8) != 15) { return 19; }; // 'F' = 15
|
||||
if (ascii.tolower(65u8) != 97u8) { return 20; }; // 'A' -> 'a'
|
||||
|
||||
// Probe 7 — file open/read via the new os APIs. /proc/self/cmdline
|
||||
// always exists on Linux, no write side, and is non-empty.
|
||||
let path: str = "/proc/self/cmdline";
|
||||
let fd_or_err: (i32 | str) = os.tryopen(path.ptr, os.O_RDONLY, 0i32);
|
||||
let fd: i32 = 0;
|
||||
match (fd_or_err) {
|
||||
case let v: i32 => fd = v;
|
||||
case let e: str => return 21;
|
||||
};
|
||||
let rbuf: [128]u8;
|
||||
let n: i64 = os.readfull(fd, rbuf.ptr, 128u64);
|
||||
os.close(fd);
|
||||
if (n <= 0i64) { return 22; };
|
||||
|
||||
return 42;
|
||||
};
|
||||
45
selfhost/test/sym_link.ww
Normal file
45
selfhost/test/sym_link.ww
Normal file
@@ -0,0 +1,45 @@
|
||||
// selfhost/test/sym_link.ww — link-and-run probe for the ww-cgen
|
||||
// against the sym/typ/ast/mem dep stack. Exercises arena (mem),
|
||||
// hashtable scope (sym), and pulls in typ/ast as type carriers.
|
||||
// Returns 42 on success; smaller values name the probe that broke.
|
||||
|
||||
use mem;
|
||||
use typ;
|
||||
use ast;
|
||||
use sym;
|
||||
|
||||
export fn main() i32 = {
|
||||
let a: *arena = newarena();
|
||||
if (a == nil) { return 1; };
|
||||
|
||||
let s: *scope = newscope(a, nil);
|
||||
if (s == nil) { return 2; };
|
||||
|
||||
let n1: str = "foo";
|
||||
let r1: *sym = scope_define(s, n1, SK_VAR, nil, nil);
|
||||
if (r1 == nil) { return 3; };
|
||||
|
||||
let n2: str = "bar";
|
||||
let r2: *sym = scope_define(s, n2, SK_TYPE, nil, nil);
|
||||
if (r2 == nil) { return 4; };
|
||||
|
||||
// Duplicate define in same scope must fail.
|
||||
let r3: *sym = scope_define(s, n1, SK_VAR, nil, nil);
|
||||
if (r3 != nil) { return 5; };
|
||||
|
||||
let l1: *sym = scope_lookup(s, n1);
|
||||
if (l1 == nil) { return 6; };
|
||||
if (l1.skind != SK_VAR) { return 7; };
|
||||
|
||||
let l2: *sym = scope_lookup(s, n2);
|
||||
if (l2 == nil) { return 8; };
|
||||
if (l2.skind != SK_TYPE) { return 9; };
|
||||
|
||||
// Not-found lookup returns nil.
|
||||
let n3: str = "baz";
|
||||
let l3: *sym = scope_lookup(s, n3);
|
||||
if (l3 != nil) { return 10; };
|
||||
|
||||
freearena(a);
|
||||
return 42;
|
||||
};
|
||||
29
selfhost/test/uses.ww
Normal file
29
selfhost/test/uses.ww
Normal file
@@ -0,0 +1,29 @@
|
||||
// selfhost/test/uses.ww — AST-diff fixture. Grows as parse.ww does.
|
||||
// Currently exercises: `use IDENT;`, `def NAME: TYPE = LIT;`,
|
||||
// `type NAME = TYPE;` (alias + struct), top-level `let NAME: TYPE = LIT;`.
|
||||
//
|
||||
// Function declarations are still recovered past — the body parser
|
||||
// is the next major chunk. See selfhost/cmd/wwc/parse.ww header.
|
||||
|
||||
use os;
|
||||
use mem;
|
||||
use fmt;
|
||||
|
||||
def MAX_LINE: i32 = 4096;
|
||||
def NAME: str = "ww";
|
||||
def READY: bool = true;
|
||||
|
||||
type byte = u8;
|
||||
type rune = i32;
|
||||
type pos = struct {
|
||||
file: str,
|
||||
line: i32,
|
||||
col: i32,
|
||||
};
|
||||
type buffer = [4096]u8;
|
||||
type bytes = []u8;
|
||||
type linkptr = *byte;
|
||||
|
||||
let nerrors: i32 = 0;
|
||||
let nwarnings: i32 = 0;
|
||||
let prog_name: str = "ww";
|
||||
Reference in New Issue
Block a user