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:
107
cmd/6a/a.h
Normal file
107
cmd/6a/a.h
Normal file
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* a.h — 6a-private header. Modelled on Plan 9 cmd/6a/a.h, trimmed
|
||||
* to the instruction subset that 6c emits.
|
||||
*
|
||||
* 6a is line-oriented and has no preprocessor: each non-blank, non-
|
||||
* label line is one instruction. We read the whole file into a list
|
||||
* of `Aprog`s, then encode and emit ELF64.
|
||||
*/
|
||||
#ifndef SIX_A_H
|
||||
#define SIX_A_H
|
||||
|
||||
#include "6.out.h"
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
|
||||
typedef int8_t i8;
|
||||
typedef int16_t i16;
|
||||
typedef int32_t i32;
|
||||
typedef int64_t i64;
|
||||
typedef uint8_t u8;
|
||||
typedef uint16_t u16;
|
||||
typedef uint32_t u32;
|
||||
typedef uint64_t u64;
|
||||
|
||||
typedef struct Aoperand Aoperand;
|
||||
typedef struct Aprog Aprog;
|
||||
typedef struct Asym Asym;
|
||||
typedef struct Areloc Areloc;
|
||||
typedef struct Asm Asm;
|
||||
|
||||
struct Aoperand {
|
||||
int type; /* D_NONE, D_AX..D_R15, D_CONST, D_INDIR, D_EXTERN, D_BRANCH */
|
||||
int reg; /* base register for D_INDIR */
|
||||
i64 offset; /* immediate or displacement */
|
||||
const char *sym;
|
||||
};
|
||||
|
||||
struct Aprog {
|
||||
int as; /* opcode (A_*) */
|
||||
Aoperand from;
|
||||
Aoperand to;
|
||||
int line;
|
||||
const char *label; /* label preceding this prog, if any */
|
||||
Aprog *link;
|
||||
/* for A_DATA: raw payload bytes interned by the parser */
|
||||
u8 *bytes;
|
||||
u64 nbytes;
|
||||
};
|
||||
|
||||
struct Asym {
|
||||
const char *name;
|
||||
int defined; /* 1 if we own its address */
|
||||
int is_text; /* if 1, address is in .text */
|
||||
int is_global; /* exported (TEXT) */
|
||||
u64 addr; /* offset within section if defined */
|
||||
int idx; /* ELF symtab index, filled at emit time */
|
||||
Asym *next;
|
||||
};
|
||||
|
||||
struct Areloc {
|
||||
u64 off; /* offset within .text where relocation lands */
|
||||
int kind; /* R_X86_64_PLT32 (4), R_X86_64_PC32 (2) */
|
||||
Asym *sym;
|
||||
i64 addend;
|
||||
Areloc *next;
|
||||
};
|
||||
|
||||
struct Asm {
|
||||
/* parser state */
|
||||
const char *file;
|
||||
const char *src;
|
||||
u64 srclen;
|
||||
u64 pos;
|
||||
int line;
|
||||
|
||||
/* program list */
|
||||
Aprog *head, *tail;
|
||||
|
||||
/* output text section */
|
||||
u8 *text;
|
||||
u64 textcap, textlen;
|
||||
|
||||
/* symbols */
|
||||
Asym *syms;
|
||||
Areloc *relocs;
|
||||
|
||||
int errs;
|
||||
};
|
||||
|
||||
/* lex.c / parse.c */
|
||||
void a_init(Asm*, const char *file, const char *src, u64 len);
|
||||
int a_parse(Asm*);
|
||||
|
||||
/* asm.c */
|
||||
int a_encode(Asm*);
|
||||
|
||||
/* obj.c */
|
||||
int a_emit_elf(Asm*, FILE *out);
|
||||
|
||||
/* helpers */
|
||||
Asym *a_intern(Asm*, const char *name);
|
||||
void a_emit_byte(Asm*, u8);
|
||||
void a_emit_u32(Asm*, u32);
|
||||
void a_addreloc(Asm*, u64 off, int kind, Asym *s, i64 add);
|
||||
|
||||
#endif
|
||||
689
cmd/6a/asm.c
Normal file
689
cmd/6a/asm.c
Normal file
@@ -0,0 +1,689 @@
|
||||
/*
|
||||
* 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: the instructions cgen emits today. Operand shapes
|
||||
* we accept:
|
||||
* MOVQ $imm, reg — C7 /0 imm32 (REX.W) [imm fits in i32]
|
||||
* MOVQ reg, reg — 89 /r (REX.W)
|
||||
* MOVQ off(reg), reg — 8B /r (REX.W)
|
||||
* MOVQ reg, off(reg) — 89 /r (REX.W)
|
||||
* ADDQ/SUBQ/AND/OR/XOR — 01/29/21/09/31 /r (REX.W) [reg→reg]
|
||||
* ADDQ $imm, reg — 81 /0 imm32 (REX.W)
|
||||
* SUBQ $imm, reg — 81 /5 imm32 (REX.W) (likewise CMPQ)
|
||||
* IMULQ reg, reg — 0F AF /r (REX.W)
|
||||
* IDIVQ reg — F7 /7 (REX.W)
|
||||
* DIVQ reg — F7 /6 (REX.W) (unsigned)
|
||||
* NEGQ/NOTQ reg — F7 /3, F7 /2 (REX.W)
|
||||
* SHLQ/SHRQ CL, reg — D3 /4, D3 /5 (REX.W)
|
||||
* CMPQ reg, reg — 39 /r (REX.W)
|
||||
* CMPQ $imm, reg — 81 /7 imm32 (REX.W)
|
||||
* PUSHQ reg — 50+rd (REX.B for high)
|
||||
* POPQ reg — 58+rd (REX.B for high)
|
||||
* LEAQ name(SB), reg — 48 8D /r RIP-relative; reloc PC32
|
||||
* LEAQ off(reg), reg — 48 8D /r
|
||||
* CALL name(SB) — E8 cd reloc PLT32
|
||||
* CALL reg — FF /2 (REX.W not strictly needed)
|
||||
* RET — C3
|
||||
* JMP/Jcc label — E9 cd / 0F 8x cd rel32 to local label
|
||||
* SYSCALL — 0F 05
|
||||
*/
|
||||
#include "a.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
|
||||
void
|
||||
a_emit_byte(Asm *a, u8 b)
|
||||
{
|
||||
if (a->textlen + 1 > a->textcap) {
|
||||
u64 nc = a->textcap ? a->textcap * 2 : 4096;
|
||||
a->text = realloc(a->text, nc);
|
||||
a->textcap = nc;
|
||||
}
|
||||
a->text[a->textlen++] = b;
|
||||
}
|
||||
|
||||
void
|
||||
a_emit_u32(Asm *a, u32 v)
|
||||
{
|
||||
a_emit_byte(a, (u8)(v & 0xff));
|
||||
a_emit_byte(a, (u8)((v >> 8) & 0xff));
|
||||
a_emit_byte(a, (u8)((v >> 16) & 0xff));
|
||||
a_emit_byte(a, (u8)((v >> 24) & 0xff));
|
||||
}
|
||||
|
||||
void
|
||||
a_addreloc(Asm *a, u64 off, int kind, Asym *s, i64 add)
|
||||
{
|
||||
Areloc *r = calloc(1, sizeof *r);
|
||||
r->off = off;
|
||||
r->kind = kind;
|
||||
r->sym = s;
|
||||
r->addend = add;
|
||||
r->next = a->relocs;
|
||||
a->relocs = r;
|
||||
}
|
||||
|
||||
/* ------ register codes ------------------------------------------- */
|
||||
|
||||
/* low 3 bits of register encoding */
|
||||
static int
|
||||
rcode(int r)
|
||||
{
|
||||
switch (r) {
|
||||
case D_AX: return 0; case D_CX: return 1;
|
||||
case D_DX: return 2; case D_BX: return 3;
|
||||
case D_SP: return 4; case D_BP: return 5;
|
||||
case D_SI: return 6; case D_DI: return 7;
|
||||
case D_R8: return 0; case D_R9: return 1;
|
||||
case D_R10:return 2; case D_R11:return 3;
|
||||
case D_R12:return 4; case D_R13:return 5;
|
||||
case D_R14:return 6; case D_R15:return 7;
|
||||
case D_X0: return 0; case D_X1: return 1;
|
||||
case D_X2: return 2; case D_X3: return 3;
|
||||
case D_X4: return 4; case D_X5: return 5;
|
||||
case D_X6: return 6; case D_X7: return 7;
|
||||
case D_X8: return 0; case D_X9: return 1;
|
||||
case D_X10:return 2; case D_X11:return 3;
|
||||
case D_X12:return 4; case D_X13:return 5;
|
||||
case D_X14:return 6; case D_X15:return 7;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* 1 if r needs the high bit (REX.R or REX.B) */
|
||||
static int
|
||||
rhi(int r)
|
||||
{
|
||||
if (r >= D_R8 && r <= D_R15) return 1;
|
||||
if (r >= D_X8 && r <= D_X15) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
is_xmm(int r)
|
||||
{
|
||||
return r >= D_X0 && r <= D_X15;
|
||||
}
|
||||
|
||||
/* ModR/M byte */
|
||||
static u8
|
||||
modrm(int mod, int reg, int rm)
|
||||
{
|
||||
return (u8)(((mod & 3) << 6) | ((reg & 7) << 3) | (rm & 7));
|
||||
}
|
||||
|
||||
/* emit REX with W=1 plus optional R/B for high regs */
|
||||
static void
|
||||
emit_rex(Asm *a, int regbit, int rmbit, int w)
|
||||
{
|
||||
u8 b = 0x40;
|
||||
if (w) b |= 0x08;
|
||||
if (regbit) b |= 0x04;
|
||||
if (rmbit) b |= 0x01;
|
||||
if (b != 0x40 || w) a_emit_byte(a, b);
|
||||
}
|
||||
|
||||
/* encode mod/disp for [base+disp]; returns 0 on ok.
|
||||
* Special-cases SP (needs SIB) and BP (forces disp).
|
||||
*/
|
||||
static void
|
||||
emit_modrm_mem(Asm *a, int reg_field, int base, i64 disp)
|
||||
{
|
||||
int rm = rcode(base);
|
||||
int mod;
|
||||
int needsib = (rm == 4); /* SP requires SIB */
|
||||
int forced_disp = (rm == 5 && disp == 0); /* BP needs explicit disp8 */
|
||||
|
||||
if (disp == 0 && !forced_disp) mod = 0;
|
||||
else if (disp >= -128 && disp <= 127) mod = 1;
|
||||
else mod = 2;
|
||||
|
||||
a_emit_byte(a, modrm(mod, reg_field, rm));
|
||||
if (needsib)
|
||||
a_emit_byte(a, (u8)(0x24)); /* SIB: scale=0 idx=4(none) base=4 */
|
||||
if (mod == 1)
|
||||
a_emit_byte(a, (u8)(disp & 0xff));
|
||||
else if (mod == 2)
|
||||
a_emit_u32(a, (u32)disp);
|
||||
}
|
||||
|
||||
/* Plan 9 op order: src, dst. Generic two-reg encoding for ops that
|
||||
* use the standard "reg, r/m" form (89 /r, 01 /r, etc.) — opcode
|
||||
* implies the REX.W and the direction; we emit "src register goes
|
||||
* into reg field, dst register into rm field". */
|
||||
static void
|
||||
encode_rr(Asm *a, u8 opcode, int src, int dst)
|
||||
{
|
||||
emit_rex(a, rhi(src), rhi(dst), 1);
|
||||
a_emit_byte(a, opcode);
|
||||
a_emit_byte(a, modrm(3, rcode(src), rcode(dst)));
|
||||
}
|
||||
|
||||
/* MOVQ src reg → mem(base, disp). opcode = 0x89 */
|
||||
static void
|
||||
encode_rm(Asm *a, u8 opcode, int src_reg, int base, i64 disp)
|
||||
{
|
||||
emit_rex(a, rhi(src_reg), rhi(base), 1);
|
||||
a_emit_byte(a, opcode);
|
||||
emit_modrm_mem(a, rcode(src_reg), base, disp);
|
||||
}
|
||||
|
||||
/* MOVQ mem(base, disp) → reg. opcode = 0x8B */
|
||||
static void
|
||||
encode_mr(Asm *a, u8 opcode, int dst_reg, int base, i64 disp)
|
||||
{
|
||||
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 */
|
||||
static void
|
||||
encode_ri_imm32(Asm *a, u8 opcode, int subop, int dst, i32 imm)
|
||||
{
|
||||
emit_rex(a, 0, rhi(dst), 1);
|
||||
a_emit_byte(a, opcode);
|
||||
a_emit_byte(a, modrm(3, subop, rcode(dst)));
|
||||
a_emit_u32(a, (u32)imm);
|
||||
}
|
||||
|
||||
/* unary-on-reg: F7 /n reg, etc. */
|
||||
static void
|
||||
encode_unary(Asm *a, u8 opcode, int subop, int dst)
|
||||
{
|
||||
emit_rex(a, 0, rhi(dst), 1);
|
||||
a_emit_byte(a, opcode);
|
||||
a_emit_byte(a, modrm(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. */
|
||||
static void
|
||||
sse_rr(Asm *a, u8 prefix, u8 op2, int reg_op, int rm_op)
|
||||
{
|
||||
if (prefix) a_emit_byte(a, prefix);
|
||||
emit_rex(a, rhi(reg_op), rhi(rm_op), 0);
|
||||
a_emit_byte(a, 0x0F);
|
||||
a_emit_byte(a, op2);
|
||||
a_emit_byte(a, modrm(3, rcode(reg_op), rcode(rm_op)));
|
||||
}
|
||||
|
||||
static void
|
||||
sse_mr_load(Asm *a, u8 prefix, u8 op2, int reg_op, int base, i64 disp)
|
||||
{
|
||||
if (prefix) a_emit_byte(a, prefix);
|
||||
emit_rex(a, rhi(reg_op), rhi(base), 0);
|
||||
a_emit_byte(a, 0x0F);
|
||||
a_emit_byte(a, op2);
|
||||
emit_modrm_mem(a, rcode(reg_op), base, disp);
|
||||
}
|
||||
|
||||
/* like sse_mr_load but encoded with REX.W (used by CVTTSD2SI / CVTSI2SD
|
||||
* which target/source 64-bit integer regs) */
|
||||
static void
|
||||
sse_rr_w(Asm *a, u8 prefix, u8 op2, int reg_op, int rm_op)
|
||||
{
|
||||
if (prefix) a_emit_byte(a, prefix);
|
||||
emit_rex(a, rhi(reg_op), rhi(rm_op), 1);
|
||||
a_emit_byte(a, 0x0F);
|
||||
a_emit_byte(a, op2);
|
||||
a_emit_byte(a, modrm(3, rcode(reg_op), rcode(rm_op)));
|
||||
}
|
||||
|
||||
/* ------ second-pass helper: resolve labels to addresses ---------- */
|
||||
|
||||
static u64
|
||||
resolve_label(Asm *a, const char *name)
|
||||
{
|
||||
for (Asym *s = a->syms; s; s = s->next)
|
||||
if (s->defined && strcmp(s->name, name) == 0)
|
||||
return s->addr;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
label_defined(Asm *a, const char *name)
|
||||
{
|
||||
for (Asym *s = a->syms; s; s = s->next)
|
||||
if (s->defined && strcmp(s->name, name) == 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ------ first pass: encode ---------------------------------------- */
|
||||
|
||||
/* For local labels, we record a "fixup" — an offset in .text that
|
||||
* needs to be patched once the label is resolved at end of pass. */
|
||||
typedef struct Fixup Fixup;
|
||||
struct Fixup {
|
||||
u64 off; /* where the rel32 lands */
|
||||
const char *label;
|
||||
Fixup *next;
|
||||
};
|
||||
static Fixup *fixups;
|
||||
|
||||
static void
|
||||
add_fixup(u64 off, const char *label)
|
||||
{
|
||||
Fixup *f = calloc(1, sizeof *f);
|
||||
f->off = off;
|
||||
f->label = strdup(label);
|
||||
f->next = fixups;
|
||||
fixups = f;
|
||||
}
|
||||
|
||||
int
|
||||
a_encode(Asm *a)
|
||||
{
|
||||
fixups = NULL;
|
||||
const char *cur_text = NULL; /* current TEXT name */
|
||||
(void)cur_text;
|
||||
for (Aprog *p = a->head; p; p = p->link) {
|
||||
/* Define any pending label at the current PC */
|
||||
if (p->label) {
|
||||
Asym *s = a_intern(a, p->label);
|
||||
s->defined = 1;
|
||||
s->is_text = 1;
|
||||
s->addr = a->textlen;
|
||||
}
|
||||
switch (p->as) {
|
||||
case A_NOP:
|
||||
break;
|
||||
case A_TEXT: {
|
||||
Asym *s = a_intern(a, p->to.sym);
|
||||
s->defined = 1;
|
||||
s->is_text = 1;
|
||||
s->is_global = 1;
|
||||
s->addr = a->textlen;
|
||||
cur_text = p->to.sym;
|
||||
break;
|
||||
}
|
||||
case A_DATA: {
|
||||
Asym *s = a_intern(a, p->to.sym);
|
||||
s->defined = 1;
|
||||
s->is_text = 1; /* we lay it out at the end of .text */
|
||||
s->is_global = 1;
|
||||
s->addr = a->textlen;
|
||||
for (u64 i = 0; i < p->nbytes; i++)
|
||||
a_emit_byte(a, p->bytes[i]);
|
||||
break;
|
||||
}
|
||||
case A_RET:
|
||||
a_emit_byte(a, 0xC3);
|
||||
break;
|
||||
case A_SYSCALL:
|
||||
a_emit_byte(a, 0x0F); a_emit_byte(a, 0x05);
|
||||
break;
|
||||
case A_PUSHQ:
|
||||
if (rhi(p->to.type)) a_emit_byte(a, 0x41);
|
||||
a_emit_byte(a, (u8)(0x50 + rcode(p->to.type)));
|
||||
break;
|
||||
case A_POPQ:
|
||||
if (rhi(p->to.type)) a_emit_byte(a, 0x41);
|
||||
a_emit_byte(a, (u8)(0x58 + rcode(p->to.type)));
|
||||
break;
|
||||
case A_NEGQ:
|
||||
encode_unary(a, 0xF7, 3, p->to.type); break;
|
||||
case A_NOTQ:
|
||||
encode_unary(a, 0xF7, 2, p->to.type); break;
|
||||
case A_IDIVQ:
|
||||
encode_unary(a, 0xF7, 7, p->to.type); break;
|
||||
case A_DIVQ:
|
||||
/* unsigned divide; shares the F7 group with IDIVQ but
|
||||
* uses /6 instead of /7. */
|
||||
encode_unary(a, 0xF7, 6, p->to.type); break;
|
||||
|
||||
case A_MOVQ:
|
||||
if (p->from.type == D_CONST && p->to.type >= D_AX && p->to.type <= D_R15) {
|
||||
i64 v = p->from.offset;
|
||||
if (v >= -2147483648LL && v <= 2147483647LL) {
|
||||
/* C7 /0 imm32, sign-extended */
|
||||
encode_ri_imm32(a, 0xC7, 0, p->to.type, (i32)v);
|
||||
} else {
|
||||
/* movabs r64, imm64: REX.W B8+rd imm64 */
|
||||
emit_rex(a, 0, rhi(p->to.type), 1);
|
||||
a_emit_byte(a, (u8)(0xB8 + rcode(p->to.type)));
|
||||
for (int k = 0; k < 8; k++)
|
||||
a_emit_byte(a, (u8)((v >> (k * 8)) & 0xff));
|
||||
}
|
||||
} else if (p->from.type >= D_AX && p->from.type <= D_R15
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15) {
|
||||
encode_rr(a, 0x89, p->from.type, p->to.type);
|
||||
} else if (p->from.type == D_INDIR
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15) {
|
||||
encode_mr(a, 0x8B, p->to.type, p->from.reg, p->from.offset);
|
||||
} else if (p->from.type >= D_AX && p->from.type <= D_R15
|
||||
&& p->to.type == D_INDIR) {
|
||||
encode_rm(a, 0x89, p->from.type, p->to.reg, p->to.offset);
|
||||
} else if (p->from.type == D_CONST
|
||||
&& p->to.type == D_INDIR) {
|
||||
/* MOVQ $imm32, r/m64 — C7 /0 (REX.W) imm32.
|
||||
* The CPU sign-extends imm32 into 64 bits, so
|
||||
* any value within i32 range works. */
|
||||
emit_rex(a, 0, rhi(p->to.reg), 1);
|
||||
a_emit_byte(a, 0xC7);
|
||||
emit_modrm_mem(a, 0, p->to.reg, p->to.offset);
|
||||
a_emit_u32(a, (u32)(i32)p->from.offset);
|
||||
} else if (p->from.type == D_EXTERN
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15) {
|
||||
/* RIP-relative load: 48 8B /r mod=00 rm=5 disp32 */
|
||||
emit_rex(a, rhi(p->to.type), 0, 1);
|
||||
a_emit_byte(a, 0x8B);
|
||||
a_emit_byte(a, modrm(0, rcode(p->to.type), 5));
|
||||
u64 reloff = a->textlen;
|
||||
a_emit_u32(a, 0);
|
||||
Asym *s = a_intern(a, p->from.sym);
|
||||
a_addreloc(a, reloff, 2, s, -4);
|
||||
} else if (p->from.type >= D_AX && p->from.type <= D_R15
|
||||
&& p->to.type == D_EXTERN) {
|
||||
/* RIP-relative store: 48 89 /r mod=00 rm=5 disp32 */
|
||||
emit_rex(a, rhi(p->from.type), 0, 1);
|
||||
a_emit_byte(a, 0x89);
|
||||
a_emit_byte(a, modrm(0, rcode(p->from.type), 5));
|
||||
u64 reloff = a->textlen;
|
||||
a_emit_u32(a, 0);
|
||||
Asym *s = a_intern(a, p->to.sym);
|
||||
a_addreloc(a, reloff, 2, s, -4);
|
||||
} else {
|
||||
fprintf(stderr, "6a: line %d: unsupported MOVQ shape\n", p->line);
|
||||
a->errs++;
|
||||
}
|
||||
break;
|
||||
case A_MOVB:
|
||||
/* MOV r/m8, r8 — 88 /r. No REX.W. We always emit REX
|
||||
* to allow access to SIL/DIL/BPL/SPL. */
|
||||
if (p->from.type >= D_AX && p->from.type <= D_R15
|
||||
&& p->to.type == D_INDIR) {
|
||||
emit_rex(a, rhi(p->from.type), rhi(p->to.reg), 0);
|
||||
a_emit_byte(a, 0x88);
|
||||
emit_modrm_mem(a, rcode(p->from.type),
|
||||
p->to.reg, p->to.offset);
|
||||
} else if (p->from.type == D_INDIR
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15) {
|
||||
emit_rex(a, rhi(p->to.type), rhi(p->from.reg), 0);
|
||||
a_emit_byte(a, 0x8A); /* MOV r8, r/m8 */
|
||||
emit_modrm_mem(a, rcode(p->to.type),
|
||||
p->from.reg, p->from.offset);
|
||||
} else {
|
||||
fprintf(stderr, "6a: line %d: unsupported MOVB shape\n", p->line);
|
||||
a->errs++;
|
||||
}
|
||||
break;
|
||||
case A_MOVZBQ:
|
||||
/* MOVZX r64, r/m8 — 0F B6 /r with REX.W */
|
||||
if (p->from.type == D_INDIR
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15) {
|
||||
emit_rex(a, rhi(p->to.type), rhi(p->from.reg), 1);
|
||||
a_emit_byte(a, 0x0F);
|
||||
a_emit_byte(a, 0xB6);
|
||||
emit_modrm_mem(a, rcode(p->to.type),
|
||||
p->from.reg, p->from.offset);
|
||||
} else {
|
||||
fprintf(stderr, "6a: line %d: unsupported MOVZBQ shape\n", p->line);
|
||||
a->errs++;
|
||||
}
|
||||
break;
|
||||
case A_MOVL:
|
||||
/* MOV r/m32, r32 (89 /r) and MOV r32, r/m32 (8B /r),
|
||||
* both without REX.W. The CPU zero-extends 32-bit ops
|
||||
* into the 64-bit reg, so reads of u32 fields are safe.
|
||||
* Sign-extension lives in MOVSXD. */
|
||||
if (p->from.type >= D_AX && p->from.type <= D_R15
|
||||
&& p->to.type == D_INDIR) {
|
||||
emit_rex(a, rhi(p->from.type), rhi(p->to.reg), 0);
|
||||
a_emit_byte(a, 0x89);
|
||||
emit_modrm_mem(a, rcode(p->from.type),
|
||||
p->to.reg, p->to.offset);
|
||||
} else if (p->from.type == D_INDIR
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15) {
|
||||
emit_rex(a, rhi(p->to.type), rhi(p->from.reg), 0);
|
||||
a_emit_byte(a, 0x8B);
|
||||
emit_modrm_mem(a, rcode(p->to.type),
|
||||
p->from.reg, p->from.offset);
|
||||
} else if (p->from.type >= D_AX && p->from.type <= D_R15
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15) {
|
||||
emit_rex(a, rhi(p->from.type), rhi(p->to.type), 0);
|
||||
a_emit_byte(a, 0x89);
|
||||
a_emit_byte(a, modrm(3,
|
||||
rcode(p->from.type), rcode(p->to.type)));
|
||||
} else {
|
||||
fprintf(stderr, "6a: line %d: unsupported MOVL shape\n", p->line);
|
||||
a->errs++;
|
||||
}
|
||||
break;
|
||||
case A_MOVSXD:
|
||||
/* MOVSXD r64, r/m32 — 63 /r with REX.W */
|
||||
if (p->from.type == D_INDIR
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15) {
|
||||
emit_rex(a, rhi(p->to.type), rhi(p->from.reg), 1);
|
||||
a_emit_byte(a, 0x63);
|
||||
emit_modrm_mem(a, rcode(p->to.type),
|
||||
p->from.reg, p->from.offset);
|
||||
} else {
|
||||
fprintf(stderr, "6a: line %d: unsupported MOVSXD shape\n", p->line);
|
||||
a->errs++;
|
||||
}
|
||||
break;
|
||||
case A_MOVSD:
|
||||
/* xmm←mem (load): F2 0F 10 /r */
|
||||
/* xmm←xmm: F2 0F 10 /r */
|
||||
/* mem←xmm (store):F2 0F 11 /r */
|
||||
if (is_xmm(p->from.type) && is_xmm(p->to.type)) {
|
||||
sse_rr(a, 0xF2, 0x10, p->to.type, p->from.type);
|
||||
} else if (p->from.type == D_INDIR && is_xmm(p->to.type)) {
|
||||
sse_mr_load(a, 0xF2, 0x10, p->to.type,
|
||||
p->from.reg, p->from.offset);
|
||||
} else if (is_xmm(p->from.type) && p->to.type == D_INDIR) {
|
||||
sse_mr_load(a, 0xF2, 0x11, p->from.type,
|
||||
p->to.reg, p->to.offset);
|
||||
} else {
|
||||
fprintf(stderr, "6a: line %d: unsupported MOVSD shape\n", p->line);
|
||||
a->errs++;
|
||||
}
|
||||
break;
|
||||
case A_ADDSD:
|
||||
sse_rr(a, 0xF2, 0x58, p->to.type, p->from.type);
|
||||
break;
|
||||
case A_SUBSD:
|
||||
sse_rr(a, 0xF2, 0x5C, p->to.type, p->from.type);
|
||||
break;
|
||||
case A_MULSD:
|
||||
sse_rr(a, 0xF2, 0x59, p->to.type, p->from.type);
|
||||
break;
|
||||
case A_DIVSD:
|
||||
sse_rr(a, 0xF2, 0x5E, p->to.type, p->from.type);
|
||||
break;
|
||||
case A_UCOMISD:
|
||||
sse_rr(a, 0x66, 0x2E, p->to.type, p->from.type);
|
||||
break;
|
||||
case A_CVTTSD2SI:
|
||||
/* int_reg ← xmm: F2 REX.W 0F 2C /r ; reg=int rm=xmm */
|
||||
sse_rr_w(a, 0xF2, 0x2C, p->to.type, p->from.type);
|
||||
break;
|
||||
case A_CVTSI2SD:
|
||||
/* xmm ← int_reg: F2 REX.W 0F 2A /r ; reg=xmm rm=int */
|
||||
sse_rr_w(a, 0xF2, 0x2A, p->to.type, p->from.type);
|
||||
break;
|
||||
case A_MOVSS:
|
||||
if (is_xmm(p->from.type) && is_xmm(p->to.type)) {
|
||||
sse_rr(a, 0xF3, 0x10, p->to.type, p->from.type);
|
||||
} else if (p->from.type == D_INDIR && is_xmm(p->to.type)) {
|
||||
sse_mr_load(a, 0xF3, 0x10, p->to.type,
|
||||
p->from.reg, p->from.offset);
|
||||
} else if (is_xmm(p->from.type) && p->to.type == D_INDIR) {
|
||||
sse_mr_load(a, 0xF3, 0x11, p->from.type,
|
||||
p->to.reg, p->to.offset);
|
||||
} else {
|
||||
fprintf(stderr, "6a: line %d: unsupported MOVSS shape\n", p->line);
|
||||
a->errs++;
|
||||
}
|
||||
break;
|
||||
case A_ADDSS:
|
||||
sse_rr(a, 0xF3, 0x58, p->to.type, p->from.type); break;
|
||||
case A_SUBSS:
|
||||
sse_rr(a, 0xF3, 0x5C, p->to.type, p->from.type); break;
|
||||
case A_MULSS:
|
||||
sse_rr(a, 0xF3, 0x59, p->to.type, p->from.type); break;
|
||||
case A_DIVSS:
|
||||
sse_rr(a, 0xF3, 0x5E, p->to.type, p->from.type); break;
|
||||
case A_UCOMISS:
|
||||
sse_rr(a, 0x00, 0x2E, p->to.type, p->from.type); break;
|
||||
case A_CVTTSS2SI:
|
||||
sse_rr_w(a, 0xF3, 0x2C, p->to.type, p->from.type); break;
|
||||
case A_CVTSI2SS:
|
||||
sse_rr_w(a, 0xF3, 0x2A, p->to.type, p->from.type); break;
|
||||
case A_CVTSD2SS:
|
||||
/* xmm←xmm: F2 0F 5A /r ; reg=dst rm=src */
|
||||
sse_rr(a, 0xF2, 0x5A, p->to.type, p->from.type); break;
|
||||
case A_CVTSS2SD:
|
||||
sse_rr(a, 0xF3, 0x5A, p->to.type, p->from.type); break;
|
||||
case A_ADDQ:
|
||||
if (p->from.type == D_CONST
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15)
|
||||
encode_ri_imm32(a, 0x81, 0, p->to.type, (i32)p->from.offset);
|
||||
else if (p->from.type == D_CONST && p->to.type == D_INDIR) {
|
||||
/* ADD r/m64, imm32 — 81 /0 (REX.W) */
|
||||
emit_rex(a, 0, rhi(p->to.reg), 1);
|
||||
a_emit_byte(a, 0x81);
|
||||
emit_modrm_mem(a, 0, p->to.reg, p->to.offset);
|
||||
a_emit_u32(a, (u32)(i32)p->from.offset);
|
||||
} else if (p->from.type >= D_AX && p->from.type <= D_R15
|
||||
&& p->to.type == D_INDIR)
|
||||
encode_rm(a, 0x01, p->from.type, p->to.reg, p->to.offset);
|
||||
else if (p->from.type == D_INDIR
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15)
|
||||
encode_mr(a, 0x03, p->to.type, p->from.reg, p->from.offset);
|
||||
else
|
||||
encode_rr(a, 0x01, p->from.type, p->to.type);
|
||||
break;
|
||||
case A_SUBQ:
|
||||
if (p->from.type == D_CONST
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15)
|
||||
encode_ri_imm32(a, 0x81, 5, p->to.type, (i32)p->from.offset);
|
||||
else if (p->from.type == D_CONST && p->to.type == D_INDIR) {
|
||||
emit_rex(a, 0, rhi(p->to.reg), 1);
|
||||
a_emit_byte(a, 0x81);
|
||||
emit_modrm_mem(a, 5, p->to.reg, p->to.offset);
|
||||
a_emit_u32(a, (u32)(i32)p->from.offset);
|
||||
} else if (p->from.type >= D_AX && p->from.type <= D_R15
|
||||
&& p->to.type == D_INDIR)
|
||||
encode_rm(a, 0x29, p->from.type, p->to.reg, p->to.offset);
|
||||
else if (p->from.type == D_INDIR
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15)
|
||||
encode_mr(a, 0x2B, p->to.type, p->from.reg, p->from.offset);
|
||||
else
|
||||
encode_rr(a, 0x29, p->from.type, p->to.type);
|
||||
break;
|
||||
case A_ANDQ: encode_rr(a, 0x21, p->from.type, p->to.type); break;
|
||||
case A_ORQ: encode_rr(a, 0x09, p->from.type, p->to.type); break;
|
||||
case A_XORQ:
|
||||
if (p->from.type == D_CONST
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15)
|
||||
encode_ri_imm32(a, 0x81, 6, p->to.type, (i32)p->from.offset);
|
||||
else
|
||||
encode_rr(a, 0x31, p->from.type, p->to.type);
|
||||
break;
|
||||
case A_IMULQ:
|
||||
emit_rex(a, rhi(p->to.type), rhi(p->from.type), 1);
|
||||
a_emit_byte(a, 0x0F); a_emit_byte(a, 0xAF);
|
||||
a_emit_byte(a, modrm(3, rcode(p->to.type), rcode(p->from.type)));
|
||||
break;
|
||||
case A_SHLQ:
|
||||
encode_unary(a, 0xD3, 4, p->to.type); break;
|
||||
case A_SHRQ:
|
||||
encode_unary(a, 0xD3, 5, p->to.type); break;
|
||||
case A_CMPQ:
|
||||
if (p->from.type == D_CONST && p->to.type >= D_AX && p->to.type <= D_R15)
|
||||
encode_ri_imm32(a, 0x81, 7, p->to.type, (i32)p->from.offset);
|
||||
else
|
||||
encode_rr(a, 0x39, p->from.type, p->to.type);
|
||||
break;
|
||||
case A_LEAQ:
|
||||
if (p->from.type == D_INDIR
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15) {
|
||||
encode_mr(a, 0x8D, p->to.type, p->from.reg, p->from.offset);
|
||||
} else if (p->from.type == D_EXTERN
|
||||
&& p->to.type >= D_AX && p->to.type <= D_R15) {
|
||||
/* RIP-relative: 48 8D /r mod=00 rm=5 disp32 */
|
||||
emit_rex(a, rhi(p->to.type), 0, 1);
|
||||
a_emit_byte(a, 0x8D);
|
||||
a_emit_byte(a, modrm(0, rcode(p->to.type), 5));
|
||||
u64 reloff = a->textlen;
|
||||
a_emit_u32(a, 0);
|
||||
Asym *s = a_intern(a, p->from.sym);
|
||||
/* R_X86_64_PC32 (2) with addend -4 */
|
||||
a_addreloc(a, reloff, 2, s, -4);
|
||||
}
|
||||
break;
|
||||
case A_CALL:
|
||||
if (p->to.type == D_EXTERN) {
|
||||
a_emit_byte(a, 0xE8);
|
||||
u64 reloff = a->textlen;
|
||||
a_emit_u32(a, 0);
|
||||
Asym *s = a_intern(a, p->to.sym);
|
||||
/* R_X86_64_PLT32 (4); addend -4 */
|
||||
a_addreloc(a, reloff, 4, s, -4);
|
||||
} else if (p->to.type == D_BRANCH) {
|
||||
/* local call to a label */
|
||||
a_emit_byte(a, 0xE8);
|
||||
add_fixup(a->textlen, p->to.sym);
|
||||
a_emit_u32(a, 0);
|
||||
} else if (p->to.type >= D_AX && p->to.type <= D_R15) {
|
||||
if (rhi(p->to.type)) a_emit_byte(a, 0x41);
|
||||
a_emit_byte(a, 0xFF);
|
||||
a_emit_byte(a, modrm(3, 2, rcode(p->to.type)));
|
||||
}
|
||||
break;
|
||||
case A_JMP:
|
||||
a_emit_byte(a, 0xE9);
|
||||
add_fixup(a->textlen, p->to.sym);
|
||||
a_emit_u32(a, 0);
|
||||
break;
|
||||
case A_JE: case A_JNE: case A_JL: case A_JLE:
|
||||
case A_JG: case A_JGE: case A_JB: case A_JBE:
|
||||
case A_JA: case A_JAE: case A_JZ: case A_JNZ: {
|
||||
u8 cc = 0;
|
||||
switch (p->as) {
|
||||
case A_JE: case A_JZ: cc = 0x84; break;
|
||||
case A_JNE: case A_JNZ: cc = 0x85; break;
|
||||
case A_JL: cc = 0x8C; break;
|
||||
case A_JLE: cc = 0x8E; break;
|
||||
case A_JG: cc = 0x8F; break;
|
||||
case A_JGE: cc = 0x8D; break;
|
||||
case A_JB: cc = 0x82; break;
|
||||
case A_JBE: cc = 0x86; break;
|
||||
case A_JA: cc = 0x87; break;
|
||||
case A_JAE: cc = 0x83; break;
|
||||
default: break;
|
||||
}
|
||||
a_emit_byte(a, 0x0F);
|
||||
a_emit_byte(a, cc);
|
||||
add_fixup(a->textlen, p->to.sym);
|
||||
a_emit_u32(a, 0);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
fprintf(stderr, "6a: unsupported opcode %d on line %d\n", p->as, p->line);
|
||||
a->errs++;
|
||||
}
|
||||
}
|
||||
|
||||
/* second pass: patch fixups */
|
||||
for (Fixup *f = fixups; f; f = f->next) {
|
||||
if (!label_defined(a, f->label)) {
|
||||
fprintf(stderr, "6a: undefined label '%s'\n", f->label);
|
||||
a->errs++;
|
||||
continue;
|
||||
}
|
||||
u64 target = resolve_label(a, f->label);
|
||||
i64 rel = (i64)target - ((i64)f->off + 4);
|
||||
i32 rel32 = (i32)rel;
|
||||
a->text[f->off + 0] = (u8)(rel32 & 0xff);
|
||||
a->text[f->off + 1] = (u8)((rel32 >> 8) & 0xff);
|
||||
a->text[f->off + 2] = (u8)((rel32 >> 16) & 0xff);
|
||||
a->text[f->off + 3] = (u8)((rel32 >> 24) & 0xff);
|
||||
}
|
||||
return a->errs;
|
||||
}
|
||||
31
cmd/6a/lex.c
Normal file
31
cmd/6a/lex.c
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* lex.c — character-level helpers for 6a's line-oriented parser.
|
||||
* The parser itself lives in parse.c; here we keep the tokenisers
|
||||
* for identifiers and numbers so parse.c stays focused on syntax.
|
||||
*/
|
||||
#include "a.h"
|
||||
#include <ctype.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
int
|
||||
a_isidstart(int c)
|
||||
{
|
||||
return c == '_' || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
|
||||
}
|
||||
|
||||
int
|
||||
a_isidcont(int c)
|
||||
{
|
||||
return a_isidstart(c) || (c >= '0' && c <= '9') || c == '.';
|
||||
}
|
||||
|
||||
i64
|
||||
a_parsenum(const char *s, char **end)
|
||||
{
|
||||
/* Let strtoll handle the sign itself: hand-stripping '-' then
|
||||
* negating the result fails for LLONG_MIN because the positive
|
||||
* magnitude (2^63) doesn't fit in long long, strtoll clamps to
|
||||
* LLONG_MAX, and the negation lands one short. */
|
||||
return (i64)strtoll(s, end, 0);
|
||||
}
|
||||
59
cmd/6a/main.c
Normal file
59
cmd/6a/main.c
Normal file
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* 6a — amd64 assembler driver. Read .s, parse, encode, emit ELF .o.
|
||||
*/
|
||||
#include "a.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static int
|
||||
slurp(const char *path, char **buf, u64 *len)
|
||||
{
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (f == NULL) return -1;
|
||||
fseek(f, 0, SEEK_END);
|
||||
long n = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
if (n < 0) { fclose(f); return -1; }
|
||||
char *b = malloc((size_t)n + 1);
|
||||
if (fread(b, 1, (size_t)n, f) != (size_t)n) { free(b); fclose(f); return -1; }
|
||||
b[n] = 0;
|
||||
fclose(f);
|
||||
*buf = b;
|
||||
*len = (u64)n;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
const char *src = NULL;
|
||||
const char *out = NULL;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (strcmp(argv[i], "-o") == 0 && i + 1 < argc) out = argv[++i];
|
||||
else if (argv[i][0] == '-') {
|
||||
fprintf(stderr, "6a: unknown flag %s\n", argv[i]); return 2;
|
||||
} else if (src == NULL) src = argv[i];
|
||||
else { fprintf(stderr, "6a: only one input\n"); return 2; }
|
||||
}
|
||||
if (src == NULL || out == NULL) {
|
||||
fputs("usage: 6a -o file.o file.s\n", stderr);
|
||||
return 2;
|
||||
}
|
||||
char *buf;
|
||||
u64 len;
|
||||
if (slurp(src, &buf, &len) < 0) {
|
||||
fprintf(stderr, "6a: cannot read %s\n", src);
|
||||
return 1;
|
||||
}
|
||||
Asm a;
|
||||
a_init(&a, src, buf, len);
|
||||
if (a_parse(&a) != 0) return 1;
|
||||
if (a_encode(&a) != 0) return 1;
|
||||
FILE *f = fopen(out, "wb");
|
||||
if (f == NULL) { fprintf(stderr, "6a: cannot open %s\n", out); return 1; }
|
||||
int rc = a_emit_elf(&a, f);
|
||||
fclose(f);
|
||||
free(buf);
|
||||
return rc;
|
||||
}
|
||||
242
cmd/6a/obj.c
Normal file
242
cmd/6a/obj.c
Normal file
@@ -0,0 +1,242 @@
|
||||
/*
|
||||
* 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 = file (skipped), 2.. = our syms.
|
||||
* For simplicity we emit GLOBAL symbols only (no LOCAL ordering rules
|
||||
* to worry about).
|
||||
*/
|
||||
#include "a.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
|
||||
/* ELF constants */
|
||||
#define ELFMAG "\x7f""ELF"
|
||||
#define ELFCLASS64 2
|
||||
#define ELFDATA2LSB 1
|
||||
#define EV_CURRENT 1
|
||||
#define ET_REL 1
|
||||
#define EM_X86_64 62
|
||||
|
||||
#define SHT_NULL 0
|
||||
#define SHT_PROGBITS 1
|
||||
#define SHT_SYMTAB 2
|
||||
#define SHT_STRTAB 3
|
||||
#define SHT_RELA 4
|
||||
|
||||
#define SHF_ALLOC 0x2
|
||||
#define SHF_EXECINSTR 0x4
|
||||
#define SHF_INFO_LINK 0x40
|
||||
|
||||
#define STB_LOCAL 0
|
||||
#define STB_GLOBAL 1
|
||||
#define STT_NOTYPE 0
|
||||
#define STT_FUNC 2
|
||||
#define ELF64_ST_INFO(b,t) (((b) << 4) + ((t) & 0xf))
|
||||
|
||||
#define R_X86_64_PC32 2
|
||||
#define R_X86_64_PLT32 4
|
||||
#define ELF64_R_INFO(s,t) (((u64)(s) << 32) | ((u64)(t) & 0xffffffff))
|
||||
|
||||
/* growable byte buffer */
|
||||
typedef struct Buf Buf;
|
||||
struct Buf { u8 *p; size_t n, cap; };
|
||||
|
||||
static void
|
||||
bput(Buf *b, const void *src, size_t n)
|
||||
{
|
||||
if (b->n + n > b->cap) {
|
||||
size_t nc = b->cap ? b->cap * 2 : 256;
|
||||
while (nc < b->n + n) nc *= 2;
|
||||
b->p = realloc(b->p, nc);
|
||||
b->cap = nc;
|
||||
}
|
||||
memcpy(b->p + b->n, src, n);
|
||||
b->n += n;
|
||||
}
|
||||
|
||||
static u32 stput(Buf *st, const char *s) {
|
||||
u32 off = (u32)st->n;
|
||||
bput(st, s, strlen(s) + 1);
|
||||
return off;
|
||||
}
|
||||
|
||||
#pragma pack(push, 1)
|
||||
typedef struct {
|
||||
u8 e_ident[16];
|
||||
u16 e_type, e_machine;
|
||||
u32 e_version;
|
||||
u64 e_entry, e_phoff, e_shoff;
|
||||
u32 e_flags;
|
||||
u16 e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum, e_shstrndx;
|
||||
} Ehdr;
|
||||
|
||||
typedef struct {
|
||||
u32 sh_name, sh_type;
|
||||
u64 sh_flags, sh_addr, sh_offset, sh_size;
|
||||
u32 sh_link, sh_info;
|
||||
u64 sh_addralign, sh_entsize;
|
||||
} Shdr;
|
||||
|
||||
typedef struct {
|
||||
u32 st_name;
|
||||
u8 st_info, st_other;
|
||||
u16 st_shndx;
|
||||
u64 st_value, st_size;
|
||||
} Sym64;
|
||||
|
||||
typedef struct {
|
||||
u64 r_offset;
|
||||
u64 r_info;
|
||||
i64 r_addend;
|
||||
} Rela64;
|
||||
#pragma pack(pop)
|
||||
|
||||
int
|
||||
a_emit_elf(Asm *a, FILE *f)
|
||||
{
|
||||
Buf shstr = {0}, str = {0}, sym = {0}, rela = {0};
|
||||
stput(&shstr, ""); /* idx 0 = empty */
|
||||
stput(&str, "");
|
||||
|
||||
/* Section name offsets */
|
||||
u32 shn_text = stput(&shstr, ".text");
|
||||
u32 shn_rela = stput(&shstr, ".rela.text");
|
||||
u32 shn_symtab = stput(&shstr, ".symtab");
|
||||
u32 shn_strtab = stput(&shstr, ".strtab");
|
||||
u32 shn_shstrtab = stput(&shstr, ".shstrtab");
|
||||
|
||||
/* Symbol 0 — STN_UNDEF */
|
||||
{
|
||||
Sym64 z = {0};
|
||||
bput(&sym, &z, sizeof z);
|
||||
}
|
||||
|
||||
/* Section indices: 1=.text, 2=.rela.text, 3=.symtab, 4=.strtab, 5=.shstrtab */
|
||||
const u16 SH_TEXT = 1;
|
||||
|
||||
/* Build symbols (defined = global; undefined = global UND) */
|
||||
int idx = 1;
|
||||
for (Asym *s = a->syms; s; s = s->next) {
|
||||
Sym64 e = {0};
|
||||
e.st_name = stput(&str, s->name);
|
||||
if (s->defined) {
|
||||
e.st_info = ELF64_ST_INFO(STB_GLOBAL, STT_FUNC);
|
||||
e.st_shndx = SH_TEXT;
|
||||
e.st_value = s->addr;
|
||||
e.st_size = 0;
|
||||
} else {
|
||||
e.st_info = ELF64_ST_INFO(STB_GLOBAL, STT_NOTYPE);
|
||||
e.st_shndx = 0;
|
||||
}
|
||||
bput(&sym, &e, sizeof e);
|
||||
s->idx = idx++;
|
||||
}
|
||||
|
||||
/* Build relocations */
|
||||
for (Areloc *r = a->relocs; r; r = r->next) {
|
||||
Rela64 re;
|
||||
re.r_offset = r->off;
|
||||
re.r_info = ELF64_R_INFO((u64)r->sym->idx, (u64)r->kind);
|
||||
re.r_addend = r->addend;
|
||||
bput(&rela, &re, sizeof re);
|
||||
}
|
||||
|
||||
/* Layout offsets in the file */
|
||||
u64 off = sizeof(Ehdr);
|
||||
u64 off_text = off; off += a->textlen;
|
||||
u64 off_rela = off; off += rela.n;
|
||||
u64 off_sym = off; off += sym.n;
|
||||
u64 off_str = off; off += str.n;
|
||||
u64 off_shstr= off; off += shstr.n;
|
||||
/* align to 8 */
|
||||
while (off % 8) off++;
|
||||
u64 off_shdr = off;
|
||||
const int NSECT = 6; /* null + 5 real */
|
||||
|
||||
Ehdr eh = {0};
|
||||
memcpy(eh.e_ident, "\x7f""ELF", 4);
|
||||
eh.e_ident[4] = ELFCLASS64;
|
||||
eh.e_ident[5] = ELFDATA2LSB;
|
||||
eh.e_ident[6] = EV_CURRENT;
|
||||
eh.e_type = ET_REL;
|
||||
eh.e_machine = EM_X86_64;
|
||||
eh.e_version = EV_CURRENT;
|
||||
eh.e_shoff = off_shdr;
|
||||
eh.e_ehsize = sizeof(Ehdr);
|
||||
eh.e_shentsize = sizeof(Shdr);
|
||||
eh.e_shnum = NSECT;
|
||||
eh.e_shstrndx = 5;
|
||||
|
||||
fwrite(&eh, 1, sizeof eh, f);
|
||||
if (a->textlen) fwrite(a->text, 1, a->textlen, f);
|
||||
fwrite(rela.p, 1, rela.n, f);
|
||||
fwrite(sym.p, 1, sym.n, f);
|
||||
fwrite(str.p, 1, str.n, f);
|
||||
fwrite(shstr.p, 1, shstr.n, f);
|
||||
while ((u64)ftell(f) % 8) fputc(0, f);
|
||||
|
||||
/* section header table */
|
||||
Shdr sh = {0};
|
||||
fwrite(&sh, 1, sizeof sh, f); /* SHT_NULL */
|
||||
|
||||
memset(&sh, 0, sizeof sh);
|
||||
sh.sh_name = shn_text;
|
||||
sh.sh_type = SHT_PROGBITS;
|
||||
sh.sh_flags = SHF_ALLOC | SHF_EXECINSTR;
|
||||
sh.sh_offset = off_text;
|
||||
sh.sh_size = a->textlen;
|
||||
sh.sh_addralign = 1;
|
||||
fwrite(&sh, 1, sizeof sh, f);
|
||||
|
||||
memset(&sh, 0, sizeof sh);
|
||||
sh.sh_name = shn_rela;
|
||||
sh.sh_type = SHT_RELA;
|
||||
sh.sh_flags = SHF_INFO_LINK;
|
||||
sh.sh_offset = off_rela;
|
||||
sh.sh_size = rela.n;
|
||||
sh.sh_link = 3; /* symtab */
|
||||
sh.sh_info = 1; /* applies to .text */
|
||||
sh.sh_addralign = 8;
|
||||
sh.sh_entsize = sizeof(Rela64);
|
||||
fwrite(&sh, 1, sizeof sh, f);
|
||||
|
||||
memset(&sh, 0, sizeof sh);
|
||||
sh.sh_name = shn_symtab;
|
||||
sh.sh_type = SHT_SYMTAB;
|
||||
sh.sh_offset = off_sym;
|
||||
sh.sh_size = sym.n;
|
||||
sh.sh_link = 4; /* strtab */
|
||||
sh.sh_info = 1; /* one local: STN_UNDEF */
|
||||
sh.sh_addralign = 8;
|
||||
sh.sh_entsize = sizeof(Sym64);
|
||||
fwrite(&sh, 1, sizeof sh, f);
|
||||
|
||||
memset(&sh, 0, sizeof sh);
|
||||
sh.sh_name = shn_strtab;
|
||||
sh.sh_type = SHT_STRTAB;
|
||||
sh.sh_offset = off_str;
|
||||
sh.sh_size = str.n;
|
||||
sh.sh_addralign = 1;
|
||||
fwrite(&sh, 1, sizeof sh, f);
|
||||
|
||||
memset(&sh, 0, sizeof sh);
|
||||
sh.sh_name = shn_shstrtab;
|
||||
sh.sh_type = SHT_STRTAB;
|
||||
sh.sh_offset = off_shstr;
|
||||
sh.sh_size = shstr.n;
|
||||
sh.sh_addralign = 1;
|
||||
fwrite(&sh, 1, sizeof sh, f);
|
||||
|
||||
free(shstr.p); free(str.p); free(sym.p); free(rela.p);
|
||||
return 0;
|
||||
}
|
||||
405
cmd/6a/parse.c
Normal file
405
cmd/6a/parse.c
Normal file
@@ -0,0 +1,405 @@
|
||||
/*
|
||||
* 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
|
||||
*
|
||||
* Identifiers may include '.' and '_'. Whitespace inside operands
|
||||
* (between '$' and a number, etc.) is rejected for sanity.
|
||||
*/
|
||||
#include "a.h"
|
||||
#include <ctype.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
extern int a_isidstart(int);
|
||||
extern int a_isidcont(int);
|
||||
extern i64 a_parsenum(const char *, char **);
|
||||
|
||||
void
|
||||
a_init(Asm *a, const char *file, const char *src, u64 len)
|
||||
{
|
||||
memset(a, 0, sizeof *a);
|
||||
a->file = file;
|
||||
a->src = src;
|
||||
a->srclen = len;
|
||||
a->line = 1;
|
||||
}
|
||||
|
||||
static void
|
||||
err(Asm *a, const char *msg)
|
||||
{
|
||||
fprintf(stderr, "6a: %s:%d: %s\n", a->file, a->line, msg);
|
||||
a->errs++;
|
||||
}
|
||||
|
||||
Asym *
|
||||
a_intern(Asm *a, const char *name)
|
||||
{
|
||||
for (Asym *s = a->syms; s; s = s->next)
|
||||
if (strcmp(s->name, name) == 0) return s;
|
||||
Asym *s = calloc(1, sizeof *s);
|
||||
s->name = strdup(name);
|
||||
s->next = a->syms;
|
||||
a->syms = s;
|
||||
return s;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* line iterator: returns the next line as a NUL-terminated buffer in
|
||||
* line/llen pointers, advances pos. Returns 0 on EOF.
|
||||
*/
|
||||
static int
|
||||
nextline(Asm *a, char **line, size_t *llen, char *buf, size_t bufsz)
|
||||
{
|
||||
if (a->pos >= a->srclen) return 0;
|
||||
size_t n = 0;
|
||||
while (a->pos < a->srclen && a->src[a->pos] != '\n' && n + 1 < bufsz)
|
||||
buf[n++] = a->src[a->pos++];
|
||||
buf[n] = '\0';
|
||||
if (a->pos < a->srclen && a->src[a->pos] == '\n') a->pos++;
|
||||
*line = buf;
|
||||
*llen = n;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* skip leading whitespace */
|
||||
static const char *
|
||||
skipws(const char *p)
|
||||
{
|
||||
while (*p == ' ' || *p == '\t') p++;
|
||||
return p;
|
||||
}
|
||||
|
||||
static int
|
||||
opcode_lookup(const char *m)
|
||||
{
|
||||
struct { const char *m; int op; } tab[] = {
|
||||
{ "MOVQ", A_MOVQ }, { "MOVL", A_MOVL },
|
||||
{ "MOVB", A_MOVB }, { "MOVZBQ", A_MOVZBQ },
|
||||
{ "MOVSXD", A_MOVSXD },
|
||||
{ "MOVSD", A_MOVSD },
|
||||
{ "ADDSD", A_ADDSD },{ "SUBSD", A_SUBSD },
|
||||
{ "MULSD", A_MULSD },{ "DIVSD", A_DIVSD },
|
||||
{ "UCOMISD", A_UCOMISD },
|
||||
{ "CVTTSD2SI", A_CVTTSD2SI },
|
||||
{ "CVTSI2SD", A_CVTSI2SD },
|
||||
{ "MOVSS", A_MOVSS },
|
||||
{ "ADDSS", A_ADDSS },{ "SUBSS", A_SUBSS },
|
||||
{ "MULSS", A_MULSS },{ "DIVSS", A_DIVSS },
|
||||
{ "UCOMISS", A_UCOMISS },
|
||||
{ "CVTTSS2SI", A_CVTTSS2SI },
|
||||
{ "CVTSI2SS", A_CVTSI2SS },
|
||||
{ "CVTSD2SS", A_CVTSD2SS },
|
||||
{ "CVTSS2SD", A_CVTSS2SD },
|
||||
{ "ADDQ", A_ADDQ }, { "SUBQ", A_SUBQ },
|
||||
{ "IMULQ",A_IMULQ},{ "IDIVQ",A_IDIVQ},
|
||||
{ "DIVQ", A_DIVQ },
|
||||
{ "NEGQ", A_NEGQ },{ "NOTQ", A_NOTQ },
|
||||
{ "ANDQ", A_ANDQ },{ "ORQ", A_ORQ },
|
||||
{ "XORQ", A_XORQ },
|
||||
{ "SHLQ", A_SHLQ },{ "SHRQ", A_SHRQ },
|
||||
{ "CMPQ", A_CMPQ },
|
||||
{ "PUSHQ",A_PUSHQ},{ "POPQ", A_POPQ },
|
||||
{ "LEAQ", A_LEAQ },
|
||||
{ "CALL", A_CALL },{ "RET", A_RET },
|
||||
{ "JMP", A_JMP },
|
||||
{ "JE", A_JE },{ "JNE", A_JNE },
|
||||
{ "JL", A_JL },{ "JLE", A_JLE },
|
||||
{ "JG", A_JG },{ "JGE", A_JGE },
|
||||
{ "JB", A_JB },{ "JBE", A_JBE },
|
||||
{ "JA", A_JA },{ "JAE", A_JAE },
|
||||
{ "JZ", A_JZ },{ "JNZ", A_JNZ },
|
||||
{ "SYSCALL", A_SYSCALL },
|
||||
{ "TEXT", A_TEXT },
|
||||
{ "DATA", A_DATA },
|
||||
{ NULL, 0 }
|
||||
};
|
||||
for (int i = 0; tab[i].m; i++)
|
||||
if (strcmp(tab[i].m, m) == 0) return tab[i].op;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
reg_lookup(const char *r)
|
||||
{
|
||||
struct { const char *m; int reg; } tab[] = {
|
||||
{ "AX", D_AX }, { "BX", D_BX }, { "CX", D_CX }, { "DX", D_DX },
|
||||
{ "SP", D_SP }, { "BP", D_BP }, { "SI", D_SI }, { "DI", D_DI },
|
||||
{ "R8", D_R8 }, { "R9", D_R9 }, { "R10", D_R10 },
|
||||
{ "R11", D_R11 }, { "R12", D_R12 }, { "R13", D_R13 },
|
||||
{ "R14", D_R14 }, { "R15", D_R15 },
|
||||
{ "X0", D_X0 }, { "X1", D_X1 }, { "X2", D_X2 }, { "X3", D_X3 },
|
||||
{ "X4", D_X4 }, { "X5", D_X5 }, { "X6", D_X6 }, { "X7", D_X7 },
|
||||
{ "X8", D_X8 }, { "X9", D_X9 }, { "X10", D_X10 },
|
||||
{ "X11", D_X11 }, { "X12", D_X12 }, { "X13", D_X13 },
|
||||
{ "X14", D_X14 }, { "X15", D_X15 },
|
||||
{ "SB", D_PSB }, { "FP", D_PFP },
|
||||
{ NULL, 0 }
|
||||
};
|
||||
for (int i = 0; tab[i].m; i++)
|
||||
if (strcmp(tab[i].m, r) == 0) return tab[i].reg;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
parse_operand(Asm *a, const char *s, Aoperand *out)
|
||||
{
|
||||
while (*s == ' ' || *s == '\t') s++;
|
||||
if (*s == '\0') { out->type = D_NONE; return 0; }
|
||||
|
||||
if (*s == '$') {
|
||||
s++;
|
||||
char *end;
|
||||
out->type = D_CONST;
|
||||
out->offset = a_parsenum(s, &end);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* (REG) form */
|
||||
if (*s == '(') {
|
||||
s++;
|
||||
char rbuf[8] = {0};
|
||||
int n = 0;
|
||||
while (*s && *s != ')' && n < 7) rbuf[n++] = *s++;
|
||||
if (*s != ')') { err(a, "missing ')' in indirect"); return -1; }
|
||||
int r = reg_lookup(rbuf);
|
||||
if (r == 0) { err(a, "bad register in indirect"); return -1; }
|
||||
out->type = D_INDIR;
|
||||
out->reg = r;
|
||||
out->offset = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* number(REG) form, or label form, or REG */
|
||||
const char *p = s;
|
||||
int sign = 1;
|
||||
if (*p == '-') { sign = -1; p++; }
|
||||
if (isdigit((unsigned char)*p)) {
|
||||
char *end;
|
||||
i64 off = a_parsenum(s, &end);
|
||||
if (*end == '(') {
|
||||
char rbuf[8] = {0};
|
||||
int n = 0;
|
||||
end++;
|
||||
while (*end && *end != ')' && n < 7) rbuf[n++] = *end++;
|
||||
if (*end != ')') { err(a, "missing ')'"); return -1; }
|
||||
int r = reg_lookup(rbuf);
|
||||
if (r == 0) { err(a, "bad register"); return -1; }
|
||||
out->type = D_INDIR;
|
||||
out->reg = r;
|
||||
out->offset = off;
|
||||
return 0;
|
||||
}
|
||||
out->type = D_CONST;
|
||||
out->offset = off * sign;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* IDENT — register or symbol-or-label */
|
||||
if (a_isidstart((unsigned char)*s)) {
|
||||
char buf[64] = {0};
|
||||
int n = 0;
|
||||
while (a_isidcont((unsigned char)*s) && n < 63) buf[n++] = *s++;
|
||||
buf[n] = 0;
|
||||
|
||||
/* ID(SB) means external symbol */
|
||||
if (*s == '(') {
|
||||
char rbuf[8] = {0};
|
||||
int rn = 0;
|
||||
s++;
|
||||
while (*s && *s != ')' && rn < 7) rbuf[rn++] = *s++;
|
||||
if (*s != ')') { err(a, "missing ')'"); return -1; }
|
||||
s++;
|
||||
int r = reg_lookup(rbuf);
|
||||
if (r == D_PSB) {
|
||||
out->type = D_EXTERN;
|
||||
out->sym = strdup(buf);
|
||||
return 0;
|
||||
}
|
||||
out->type = D_INDIR;
|
||||
out->reg = r;
|
||||
out->offset = 0;
|
||||
/* unusual case: name(REG) with named offset; not used */
|
||||
return 0;
|
||||
}
|
||||
|
||||
int r = reg_lookup(buf);
|
||||
if (r != 0) {
|
||||
out->type = r;
|
||||
return 0;
|
||||
}
|
||||
/* otherwise it's a branch target */
|
||||
out->type = D_BRANCH;
|
||||
out->sym = strdup(buf);
|
||||
return 0;
|
||||
}
|
||||
|
||||
err(a, "unrecognised operand");
|
||||
return -1;
|
||||
}
|
||||
|
||||
int
|
||||
a_parse(Asm *a)
|
||||
{
|
||||
char buf[1024];
|
||||
char *line;
|
||||
size_t len;
|
||||
const char *pending_label = NULL;
|
||||
|
||||
while (nextline(a, &line, &len, buf, sizeof buf)) {
|
||||
const char *p = skipws(line);
|
||||
if (*p == '\0' || (*p == '/' && p[1] == '/')) {
|
||||
a->line++;
|
||||
continue;
|
||||
}
|
||||
|
||||
/* label? */
|
||||
if (a_isidstart((unsigned char)*p) && line[0] != '\t') {
|
||||
const char *q = p;
|
||||
while (a_isidcont((unsigned char)*q)) q++;
|
||||
if (*q == ':') {
|
||||
size_t nl = q - p;
|
||||
char *name = malloc(nl + 1);
|
||||
memcpy(name, p, nl);
|
||||
name[nl] = '\0';
|
||||
/* If a label is already pending we'd lose it
|
||||
* by overwriting; flush it onto a NOP prog so
|
||||
* each label still pins to a real address. */
|
||||
if (pending_label) {
|
||||
Aprog *prg = calloc(1, sizeof *prg);
|
||||
prg->as = A_NOP;
|
||||
prg->label = pending_label;
|
||||
prg->line = a->line;
|
||||
if (a->head == NULL) a->head = prg;
|
||||
else a->tail->link = prg;
|
||||
a->tail = prg;
|
||||
}
|
||||
pending_label = name;
|
||||
a->line++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
/* TEXT or instruction */
|
||||
const char *m = p;
|
||||
char mnem[16] = {0};
|
||||
int n = 0;
|
||||
while (*m && *m != ' ' && *m != '\t' && n < 15) mnem[n++] = *m++;
|
||||
mnem[n] = '\0';
|
||||
|
||||
int op = opcode_lookup(mnem);
|
||||
if (op == 0) {
|
||||
err(a, "unknown opcode");
|
||||
a->line++;
|
||||
continue;
|
||||
}
|
||||
|
||||
Aprog *prg = calloc(1, sizeof *prg);
|
||||
prg->as = op;
|
||||
prg->line = a->line;
|
||||
prg->label = pending_label;
|
||||
pending_label = NULL;
|
||||
|
||||
while (*m == ' ' || *m == '\t') m++;
|
||||
const char *rest = m;
|
||||
|
||||
if (op == A_TEXT) {
|
||||
/* TEXT name,$framesize */
|
||||
char nbuf[64] = {0};
|
||||
int nn = 0;
|
||||
while (*m && *m != ',' && nn < 63) nbuf[nn++] = *m++;
|
||||
prg->to.type = D_EXTERN;
|
||||
prg->to.sym = strdup(nbuf);
|
||||
if (*m == ',') {
|
||||
m++;
|
||||
while (*m == ' ' || *m == '$') m++;
|
||||
prg->from.type = D_CONST;
|
||||
prg->from.offset = a_parsenum(m, NULL);
|
||||
}
|
||||
} else if (op == A_DATA) {
|
||||
/* DATA name(SB),"escaped bytes" */
|
||||
char nbuf[128] = {0};
|
||||
int nn = 0;
|
||||
while (*m && *m != '(' && nn < 127) nbuf[nn++] = *m++;
|
||||
prg->to.type = D_EXTERN;
|
||||
prg->to.sym = strdup(nbuf);
|
||||
if (*m == '(') {
|
||||
while (*m && *m != ')') m++;
|
||||
if (*m == ')') m++;
|
||||
}
|
||||
while (*m == ' ' || *m == ',' || *m == '\t') m++;
|
||||
if (*m != '"') {
|
||||
err(a, "DATA expects \"...\"");
|
||||
prg->bytes = NULL;
|
||||
prg->nbytes = 0;
|
||||
} else {
|
||||
m++;
|
||||
/* parse escapes into a fresh buffer */
|
||||
size_t cap = 32, len = 0;
|
||||
u8 *buf = malloc(cap);
|
||||
while (*m && *m != '"') {
|
||||
int c = (unsigned char)*m++;
|
||||
if (c == '\\' && *m) {
|
||||
int e = (unsigned char)*m++;
|
||||
switch (e) {
|
||||
case 'n': c = '\n'; break;
|
||||
case 't': c = '\t'; break;
|
||||
case 'r': c = '\r'; break;
|
||||
case '\\': c = '\\'; break;
|
||||
case '"': c = '"'; break;
|
||||
case '0': c = 0; break;
|
||||
case 'x': {
|
||||
int hi = (unsigned char)*m++;
|
||||
int lo = (unsigned char)*m++;
|
||||
int h = (hi<='9'?hi-'0':(hi|0x20)-'a'+10);
|
||||
int l = (lo<='9'?lo-'0':(lo|0x20)-'a'+10);
|
||||
c = (h << 4) | l;
|
||||
break;
|
||||
}
|
||||
default: c = e; break;
|
||||
}
|
||||
}
|
||||
if (len + 1 > cap) {
|
||||
cap *= 2;
|
||||
buf = realloc(buf, cap);
|
||||
}
|
||||
buf[len++] = (u8)c;
|
||||
}
|
||||
prg->bytes = buf;
|
||||
prg->nbytes = len;
|
||||
}
|
||||
} else {
|
||||
/* split rest at top-level comma */
|
||||
const char *comma = NULL;
|
||||
for (const char *q = rest; *q; q++)
|
||||
if (*q == ',' && comma == NULL) comma = q;
|
||||
if (comma) {
|
||||
char op1[256], op2[256];
|
||||
size_t l1 = comma - rest;
|
||||
if (l1 >= sizeof op1) l1 = sizeof op1 - 1;
|
||||
memcpy(op1, rest, l1); op1[l1] = '\0';
|
||||
size_t l2 = strlen(comma + 1);
|
||||
if (l2 >= sizeof op2) l2 = sizeof op2 - 1;
|
||||
memcpy(op2, comma + 1, l2); op2[l2] = '\0';
|
||||
parse_operand(a, op1, &prg->from);
|
||||
parse_operand(a, op2, &prg->to);
|
||||
} else if (*rest) {
|
||||
parse_operand(a, rest, &prg->to);
|
||||
}
|
||||
}
|
||||
|
||||
if (a->head == NULL) a->head = prg;
|
||||
else a->tail->link = prg;
|
||||
a->tail = prg;
|
||||
a->line++;
|
||||
}
|
||||
return a->errs;
|
||||
}
|
||||
107
cmd/6c/6.out.h
Normal file
107
cmd/6c/6.out.h
Normal file
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* 6.out.h — amd64 instruction enum + register names. Mirrors the
|
||||
* Plan 9 6c shape (cmd/6c/6.out.h) but trimmed to the subset that
|
||||
* 6c emits and 6a consumes in this bootstrap. Each new opcode added
|
||||
* here must also gain encoding support in cmd/6a/asm.c.
|
||||
*/
|
||||
#ifndef SIX_OUT_H
|
||||
#define SIX_OUT_H
|
||||
|
||||
/* registers — Plan 9 names; lowercase = 8-bit, etc. We use 64-bit. */
|
||||
enum {
|
||||
D_NONE = 0,
|
||||
|
||||
/* general purpose 64-bit */
|
||||
D_AX, D_CX, D_DX, D_BX,
|
||||
D_SP, D_BP, D_SI, D_DI,
|
||||
D_R8, D_R9, D_R10, D_R11,
|
||||
D_R12, D_R13, D_R14, D_R15,
|
||||
|
||||
/* SSE/XMM 64-bit float regs */
|
||||
D_X0, D_X1, D_X2, D_X3,
|
||||
D_X4, D_X5, D_X6, D_X7,
|
||||
D_X8, D_X9, D_X10, D_X11,
|
||||
D_X12, D_X13, D_X14, D_X15,
|
||||
|
||||
/* pseudo regs (Plan 9) */
|
||||
D_PSP, /* SP pseudo (frame-relative) */
|
||||
D_PFP, /* FP pseudo (incoming args) */
|
||||
D_PSB, /* SB pseudo (static base) */
|
||||
|
||||
/* operand kinds; not registers but share the slot */
|
||||
D_CONST, /* $N immediate */
|
||||
D_BRANCH, /* label reference */
|
||||
D_EXTERN, /* external symbol */
|
||||
D_INDIR /* offset(reg) memory */
|
||||
};
|
||||
|
||||
/* opcodes — the small set we currently emit & encode */
|
||||
enum {
|
||||
A_NOP = 0,
|
||||
A_TEXT,
|
||||
A_DATA,
|
||||
A_GLOBL,
|
||||
A_END,
|
||||
|
||||
A_MOVQ,
|
||||
A_MOVL,
|
||||
A_MOVB,
|
||||
A_MOVZBQ, /* movzx r64, r/m8 — load byte zero-extended */
|
||||
A_MOVSXD, /* movsxd r64, r/m32 — load i32 sign-extended */
|
||||
|
||||
/* SSE2 scalar double-precision float */
|
||||
A_MOVSD, /* xmm/m → xmm and xmm → m */
|
||||
A_ADDSD,
|
||||
A_SUBSD,
|
||||
A_MULSD,
|
||||
A_DIVSD,
|
||||
A_UCOMISD,
|
||||
A_CVTTSD2SI, /* truncate f64 → i64 */
|
||||
A_CVTSI2SD, /* convert i64 → f64 */
|
||||
|
||||
/* SSE scalar single-precision float (f32). Same xmm regs. */
|
||||
A_MOVSS,
|
||||
A_ADDSS,
|
||||
A_SUBSS,
|
||||
A_MULSS,
|
||||
A_DIVSS,
|
||||
A_UCOMISS,
|
||||
A_CVTTSS2SI,
|
||||
A_CVTSI2SS,
|
||||
A_CVTSD2SS, /* f64 → f32 truncate */
|
||||
A_CVTSS2SD, /* f32 → f64 widen */
|
||||
A_ADDQ,
|
||||
A_SUBQ,
|
||||
A_IMULQ,
|
||||
A_IDIVQ,
|
||||
A_DIVQ, /* unsigned 64-bit divide; sibling of IDIVQ */
|
||||
A_NEGQ,
|
||||
A_NOTQ,
|
||||
A_ANDQ,
|
||||
A_ORQ,
|
||||
A_XORQ,
|
||||
A_SHLQ,
|
||||
A_SHRQ,
|
||||
A_CMPQ,
|
||||
|
||||
A_PUSHQ,
|
||||
A_POPQ,
|
||||
A_LEAQ,
|
||||
|
||||
A_CALL,
|
||||
A_RET,
|
||||
A_JMP,
|
||||
A_JE, A_JNE,
|
||||
A_JL, A_JLE, A_JG, A_JGE,
|
||||
A_JB, A_JBE, A_JA, A_JAE,
|
||||
A_JZ, A_JNZ,
|
||||
|
||||
A_SYSCALL,
|
||||
|
||||
A_LAST
|
||||
};
|
||||
|
||||
const char *anames(int); /* opcode -> mnemonic */
|
||||
const char *rnames(int); /* register -> name */
|
||||
|
||||
#endif
|
||||
2622
cmd/6c/cgen.c
Normal file
2622
cmd/6c/cgen.c
Normal file
File diff suppressed because it is too large
Load Diff
56
cmd/6c/gc.h
Normal file
56
cmd/6c/gc.h
Normal file
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* gc.h — 6c-private header: Prog/Adr structs, scratch register set,
|
||||
* stack-frame state. Plan 9 cmd/6c/gc.h shape, trimmed.
|
||||
*/
|
||||
#ifndef SIX_GC_H
|
||||
#define SIX_GC_H
|
||||
|
||||
#include "ww.h"
|
||||
#include "6.out.h"
|
||||
|
||||
typedef struct Prog Prog;
|
||||
typedef struct Adr Adr;
|
||||
|
||||
/* one operand: register, immediate, indirect, or symbolic. */
|
||||
struct Adr {
|
||||
int type; /* D_AX, D_CONST, D_INDIR, ... */
|
||||
int reg; /* base register for D_INDIR */
|
||||
long long offset; /* immediate value or memory displacement */
|
||||
const char *sym; /* symbol name for D_EXTERN/D_BRANCH */
|
||||
};
|
||||
|
||||
struct Prog {
|
||||
int as; /* opcode (A_MOVQ, ...) */
|
||||
Adr from; /* source operand */
|
||||
Adr to; /* destination operand (Plan 9 order) */
|
||||
int line;
|
||||
const char *label; /* if non-NULL, this prog is preceded by label: */
|
||||
Prog *link;
|
||||
};
|
||||
|
||||
/* per-fn codegen state */
|
||||
typedef struct Cg Cg;
|
||||
struct Cg {
|
||||
Arena *a;
|
||||
Prog *head, *tail;
|
||||
const char *fnname;
|
||||
int framesize; /* bytes of locals; 16-byte aligned */
|
||||
int curoff; /* current top of locals */
|
||||
Scope *locals; /* (name → offset) tracked via Sym */
|
||||
int labelseq;
|
||||
};
|
||||
|
||||
/* cgen.c */
|
||||
void cg_init(Cg*, Arena*);
|
||||
void cg_file(Cg*, FILE *out, Node *file);
|
||||
Prog *newprog(Cg*, int op);
|
||||
void emit(Cg*, Prog*);
|
||||
|
||||
/* txt.c */
|
||||
void txt_emit(FILE*, Prog *head);
|
||||
|
||||
/* swt.c, peep.c, reg.c — placeholders for now */
|
||||
void peephole(Cg*);
|
||||
void regalloc_init(Cg*);
|
||||
|
||||
#endif
|
||||
93
cmd/6c/main.c
Normal file
93
cmd/6c/main.c
Normal file
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* 6c — amd64 compiler driver. Reads a .ww source file, runs the
|
||||
* libwwc frontend (lex → parse → check), then walks the typed AST
|
||||
* via cgen.c and writes Plan 9-flavoured amd64 asm to stdout (or
|
||||
* the file given by -o).
|
||||
*/
|
||||
#include "gc.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static int
|
||||
slurp(const char *path, char **outbuf, u64 *outlen)
|
||||
{
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (f == NULL) return -1;
|
||||
fseek(f, 0, SEEK_END);
|
||||
long n = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
if (n < 0) { fclose(f); return -1; }
|
||||
char *b = malloc((size_t)n + 1);
|
||||
if (b == NULL) { fclose(f); return -1; }
|
||||
if (fread(b, 1, (size_t)n, f) != (size_t)n) { free(b); fclose(f); return -1; }
|
||||
b[n] = '\0';
|
||||
fclose(f);
|
||||
*outbuf = b;
|
||||
*outlen = (u64)n;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
const char *src = NULL;
|
||||
const char *out = NULL;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
const char *a = argv[i];
|
||||
if (strcmp(a, "-o") == 0 && i + 1 < argc) {
|
||||
out = argv[++i];
|
||||
} else if (a[0] == '-') {
|
||||
fprintf(stderr, "6c: unknown flag %s\n", a);
|
||||
return 2;
|
||||
} else if (src == NULL) {
|
||||
src = a;
|
||||
} else {
|
||||
fprintf(stderr, "6c: only one input supported\n");
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
if (src == NULL) {
|
||||
fputs("usage: 6c [-o out.s] file.ww\n", stderr);
|
||||
return 2;
|
||||
}
|
||||
|
||||
char *buf;
|
||||
u64 len;
|
||||
if (slurp(src, &buf, &len) < 0) {
|
||||
fprintf(stderr, "6c: %s: cannot read\n", src);
|
||||
return 1;
|
||||
}
|
||||
|
||||
Arena *a = newarena();
|
||||
Lex l;
|
||||
Parser p;
|
||||
Checker c;
|
||||
Cg cg;
|
||||
|
||||
lexinit(&l, a, src, buf, len);
|
||||
parserinit(&p, a, &l);
|
||||
Node *file = parsefile(&p);
|
||||
if (l.errs || p.errs) return 1;
|
||||
|
||||
check_init(&c, a);
|
||||
check_file(&c, file);
|
||||
if (c.errs) return 1;
|
||||
|
||||
FILE *of = stdout;
|
||||
if (out) {
|
||||
of = fopen(out, "wb");
|
||||
if (of == NULL) {
|
||||
fprintf(stderr, "6c: cannot open %s\n", out);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
cg_init(&cg, a);
|
||||
cg_file(&cg, of, file);
|
||||
|
||||
if (of != stdout) fclose(of);
|
||||
freearena(a);
|
||||
free(buf);
|
||||
return 0;
|
||||
}
|
||||
8
cmd/6c/peep.c
Normal file
8
cmd/6c/peep.c
Normal file
@@ -0,0 +1,8 @@
|
||||
/*
|
||||
* peep.c — peephole pass. Currently a no-op; reserved for the kind of
|
||||
* cleanup Plan 9 6c does (folding adjacent moves, removing redundant
|
||||
* compares). Wire in `peephole(c)` from cgen.c after the main walk.
|
||||
*/
|
||||
#include "gc.h"
|
||||
|
||||
void peep_run(Cg *c) { (void)c; }
|
||||
9
cmd/6c/reg.c
Normal file
9
cmd/6c/reg.c
Normal file
@@ -0,0 +1,9 @@
|
||||
/*
|
||||
* reg.c — register allocator. The current cgen pins everything to AX
|
||||
* with BX as a scratch top-of-stack — no real allocation. This file
|
||||
* is the seam where a linear-scan or graph-colouring pass would land
|
||||
* later; today it's empty.
|
||||
*/
|
||||
#include "gc.h"
|
||||
|
||||
void reg_run(Cg *c) { (void)c; }
|
||||
8
cmd/6c/swt.c
Normal file
8
cmd/6c/swt.c
Normal file
@@ -0,0 +1,8 @@
|
||||
/*
|
||||
* swt.c — switch-statement lowering. Stub for now: cgen falls
|
||||
* through to a no-op for N_SWITCH. When we add a real lowering, it
|
||||
* will live here, mirroring Plan 9 6c's pswt.c.
|
||||
*/
|
||||
#include "gc.h"
|
||||
|
||||
void swt_lower(Cg *c, Node *n) { (void)c; (void)n; }
|
||||
189
cmd/6c/txt.c
Normal file
189
cmd/6c/txt.c
Normal file
@@ -0,0 +1,189 @@
|
||||
/*
|
||||
* txt.c — print a Prog list as Plan 9-flavoured amd64 asm text.
|
||||
*
|
||||
* Format we emit (and that 6a expects):
|
||||
* TEXT name<framesize>
|
||||
* MOVQ $1, AX
|
||||
* MOVQ AX, name(SB) ; extern symbol
|
||||
* MOVQ off(BP), AX ; local
|
||||
* CMPQ AX, $0
|
||||
* JE label
|
||||
* RET
|
||||
* label:
|
||||
*
|
||||
* Operand order is Plan 9-ish: source first, dest second. (Same as
|
||||
* AT&T; the convention diverges from Plan 9 only on a few items we
|
||||
* don't yet emit.)
|
||||
*/
|
||||
#include "gc.h"
|
||||
#include <string.h>
|
||||
|
||||
const char *
|
||||
anames(int op)
|
||||
{
|
||||
switch (op) {
|
||||
case A_NOP: return "NOP";
|
||||
case A_TEXT: return "TEXT";
|
||||
case A_DATA: return "DATA";
|
||||
case A_GLOBL: return "GLOBL";
|
||||
case A_END: return "END";
|
||||
case A_MOVQ: return "MOVQ";
|
||||
case A_MOVL: return "MOVL";
|
||||
case A_MOVB: return "MOVB";
|
||||
case A_MOVZBQ: return "MOVZBQ";
|
||||
case A_MOVSXD: return "MOVSXD";
|
||||
case A_MOVSD: return "MOVSD";
|
||||
case A_ADDSD: return "ADDSD";
|
||||
case A_SUBSD: return "SUBSD";
|
||||
case A_MULSD: return "MULSD";
|
||||
case A_DIVSD: return "DIVSD";
|
||||
case A_UCOMISD: return "UCOMISD";
|
||||
case A_CVTTSD2SI: return "CVTTSD2SI";
|
||||
case A_CVTSI2SD:return "CVTSI2SD";
|
||||
case A_MOVSS: return "MOVSS";
|
||||
case A_ADDSS: return "ADDSS";
|
||||
case A_SUBSS: return "SUBSS";
|
||||
case A_MULSS: return "MULSS";
|
||||
case A_DIVSS: return "DIVSS";
|
||||
case A_UCOMISS: return "UCOMISS";
|
||||
case A_CVTTSS2SI: return "CVTTSS2SI";
|
||||
case A_CVTSI2SS:return "CVTSI2SS";
|
||||
case A_CVTSD2SS:return "CVTSD2SS";
|
||||
case A_CVTSS2SD:return "CVTSS2SD";
|
||||
case A_ADDQ: return "ADDQ";
|
||||
case A_SUBQ: return "SUBQ";
|
||||
case A_IMULQ: return "IMULQ";
|
||||
case A_IDIVQ: return "IDIVQ";
|
||||
case A_DIVQ: return "DIVQ";
|
||||
case A_NEGQ: return "NEGQ";
|
||||
case A_NOTQ: return "NOTQ";
|
||||
case A_ANDQ: return "ANDQ";
|
||||
case A_ORQ: return "ORQ";
|
||||
case A_XORQ: return "XORQ";
|
||||
case A_SHLQ: return "SHLQ";
|
||||
case A_SHRQ: return "SHRQ";
|
||||
case A_CMPQ: return "CMPQ";
|
||||
case A_PUSHQ: return "PUSHQ";
|
||||
case A_POPQ: return "POPQ";
|
||||
case A_LEAQ: return "LEAQ";
|
||||
case A_CALL: return "CALL";
|
||||
case A_RET: return "RET";
|
||||
case A_JMP: return "JMP";
|
||||
case A_JE: return "JE";
|
||||
case A_JNE: return "JNE";
|
||||
case A_JL: return "JL";
|
||||
case A_JLE: return "JLE";
|
||||
case A_JG: return "JG";
|
||||
case A_JGE: return "JGE";
|
||||
case A_JB: return "JB";
|
||||
case A_JBE: return "JBE";
|
||||
case A_JA: return "JA";
|
||||
case A_JAE: return "JAE";
|
||||
case A_JZ: return "JZ";
|
||||
case A_JNZ: return "JNZ";
|
||||
case A_SYSCALL: return "SYSCALL";
|
||||
}
|
||||
return "??";
|
||||
}
|
||||
|
||||
const char *
|
||||
rnames(int r)
|
||||
{
|
||||
switch (r) {
|
||||
case D_AX: return "AX"; case D_CX: return "CX";
|
||||
case D_DX: return "DX"; case D_BX: return "BX";
|
||||
case D_SP: return "SP"; case D_BP: return "BP";
|
||||
case D_SI: return "SI"; case D_DI: return "DI";
|
||||
case D_R8: return "R8"; case D_R9: return "R9";
|
||||
case D_R10: return "R10"; case D_R11: return "R11";
|
||||
case D_R12: return "R12"; case D_R13: return "R13";
|
||||
case D_R14: return "R14"; case D_R15: return "R15";
|
||||
case D_X0: return "X0"; case D_X1: return "X1";
|
||||
case D_X2: return "X2"; case D_X3: return "X3";
|
||||
case D_X4: return "X4"; case D_X5: return "X5";
|
||||
case D_X6: return "X6"; case D_X7: return "X7";
|
||||
case D_X8: return "X8"; case D_X9: return "X9";
|
||||
case D_X10: return "X10"; case D_X11: return "X11";
|
||||
case D_X12: return "X12"; case D_X13: return "X13";
|
||||
case D_X14: return "X14"; case D_X15: return "X15";
|
||||
case D_PSP: return "SP"; case D_PFP: return "FP"; case D_PSB: return "SB";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
static void
|
||||
prAdr(FILE *f, Adr a)
|
||||
{
|
||||
switch (a.type) {
|
||||
case D_NONE: fputs("?", f); break;
|
||||
case D_CONST:
|
||||
fprintf(f, "$%lld", a.offset);
|
||||
break;
|
||||
case D_INDIR:
|
||||
if (a.offset)
|
||||
fprintf(f, "%lld(%s)", a.offset, rnames(a.reg));
|
||||
else
|
||||
fprintf(f, "(%s)", rnames(a.reg));
|
||||
break;
|
||||
case D_BRANCH:
|
||||
fputs(a.sym ? a.sym : "?", f);
|
||||
break;
|
||||
case D_EXTERN:
|
||||
fprintf(f, "%s(SB)", a.sym ? a.sym : "?");
|
||||
break;
|
||||
default:
|
||||
fputs(rnames(a.type), f);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
txt_emit(FILE *f, Prog *head)
|
||||
{
|
||||
for (Prog *p = head; p; p = p->link) {
|
||||
if (p->label) {
|
||||
fprintf(f, "%s:\n", p->label);
|
||||
if (p->as == A_NOP) continue;
|
||||
}
|
||||
switch (p->as) {
|
||||
case A_NOP:
|
||||
break;
|
||||
case A_TEXT:
|
||||
fprintf(f, "TEXT %s,$%lld\n",
|
||||
p->to.sym ? p->to.sym : "?",
|
||||
p->from.offset);
|
||||
break;
|
||||
case A_RET:
|
||||
fputs("\tRET\n", f);
|
||||
break;
|
||||
case A_SYSCALL:
|
||||
fputs("\tSYSCALL\n", f);
|
||||
break;
|
||||
case A_NEGQ:
|
||||
case A_NOTQ:
|
||||
case A_PUSHQ:
|
||||
case A_POPQ:
|
||||
case A_IDIVQ:
|
||||
case A_DIVQ:
|
||||
fprintf(f, "\t%s\t", anames(p->as));
|
||||
prAdr(f, p->to);
|
||||
fputc('\n', f);
|
||||
break;
|
||||
case A_CALL:
|
||||
case A_JMP:
|
||||
case A_JE: case A_JNE:
|
||||
case A_JL: case A_JLE: case A_JG: case A_JGE:
|
||||
case A_JB: case A_JBE: case A_JA: case A_JAE:
|
||||
case A_JZ: case A_JNZ:
|
||||
fprintf(f, "\t%s\t", anames(p->as));
|
||||
prAdr(f, p->to);
|
||||
fputc('\n', f);
|
||||
break;
|
||||
default:
|
||||
fprintf(f, "\t%s\t", anames(p->as));
|
||||
prAdr(f, p->from);
|
||||
fputs(", ", f);
|
||||
prAdr(f, p->to);
|
||||
fputc('\n', f);
|
||||
}
|
||||
}
|
||||
}
|
||||
74
cmd/6l/l.h
Normal file
74
cmd/6l/l.h
Normal file
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* l.h — 6l-private header. Loads relocatable ELF64 .o files (the
|
||||
* format produced by 6a) and links them into a static executable.
|
||||
*
|
||||
* No archives yet (phase 8). No dynamic linking ever.
|
||||
*/
|
||||
#ifndef SIX_L_H
|
||||
#define SIX_L_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
|
||||
typedef int8_t i8;
|
||||
typedef int16_t i16;
|
||||
typedef int32_t i32;
|
||||
typedef int64_t i64;
|
||||
typedef uint8_t u8;
|
||||
typedef uint16_t u16;
|
||||
typedef uint32_t u32;
|
||||
typedef uint64_t u64;
|
||||
|
||||
typedef struct Lsym Lsym;
|
||||
typedef struct Lrel Lrel;
|
||||
typedef struct Lobj Lobj;
|
||||
typedef struct Lnk Lnk;
|
||||
|
||||
struct Lsym {
|
||||
const char *name;
|
||||
u64 val; /* offset within combined .text once linked */
|
||||
int defined; /* 1 if a Lobj defines this symbol */
|
||||
Lobj *owner;
|
||||
int idx_in_owner;
|
||||
Lsym *next;
|
||||
};
|
||||
|
||||
struct Lrel {
|
||||
u64 off; /* offset within combined .text */
|
||||
int kind; /* R_X86_64_* */
|
||||
Lsym *sym;
|
||||
i64 addend;
|
||||
Lrel *next;
|
||||
};
|
||||
|
||||
struct Lobj {
|
||||
const char *path;
|
||||
u8 *buf; /* mmapped or read-in object bytes */
|
||||
u64 len;
|
||||
u64 text_off; /* offset of .text in combined output */
|
||||
u64 text_size;
|
||||
Lobj *next;
|
||||
};
|
||||
|
||||
struct Lnk {
|
||||
Lobj *objs;
|
||||
Lsym *syms;
|
||||
Lrel *rels;
|
||||
u8 *text; /* combined .text */
|
||||
u64 textcap, textlen;
|
||||
int errs;
|
||||
};
|
||||
|
||||
/* obj.c */
|
||||
int l_load(Lnk*, const char *path);
|
||||
/* sym.c */
|
||||
Lsym *l_intern(Lnk*, const char *name);
|
||||
Lsym *l_lookup(Lnk*, const char *name);
|
||||
/* pass.c */
|
||||
int l_resolve(Lnk*);
|
||||
int l_relocate(Lnk*, u64 base);
|
||||
/* out.c */
|
||||
int l_emit_elf(Lnk*, FILE *out, u64 base, u64 entry);
|
||||
|
||||
#endif
|
||||
73
cmd/6l/main.c
Normal file
73
cmd/6l/main.c
Normal file
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* 6l — amd64 static linker. Reads relocatable ELF .o files, resolves,
|
||||
* relocates, writes a static ELF executable.
|
||||
*
|
||||
* 6l -o out file1.o file2.o ...
|
||||
*
|
||||
* The first symbol named "_start" defined among the inputs becomes
|
||||
* the entry point. If none is found, fall back to "main".
|
||||
*/
|
||||
#include "l.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
const char *out = NULL;
|
||||
const char **inputs = calloc(argc, sizeof *inputs);
|
||||
int ninputs = 0;
|
||||
u64 base = 0x400000;
|
||||
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
|
||||
out = argv[++i];
|
||||
} else if (argv[i][0] == '-') {
|
||||
fprintf(stderr, "6l: unknown flag %s\n", argv[i]);
|
||||
return 2;
|
||||
} else {
|
||||
inputs[ninputs++] = argv[i];
|
||||
}
|
||||
}
|
||||
if (out == NULL || ninputs == 0) {
|
||||
fputs("usage: 6l -o exe file1.o [file2.o...]\n", stderr);
|
||||
return 2;
|
||||
}
|
||||
|
||||
Lnk l = {0};
|
||||
/* Seed the symbol table with the entry point so archive pulls
|
||||
* include the .o that defines it. Without this, a libwwrt.a
|
||||
* containing start.o is silently skipped if no user .o
|
||||
* references _start, and the entry falls back to main — which
|
||||
* has no proper exit path. */
|
||||
(void)l_intern(&l, "_start");
|
||||
for (int i = 0; i < ninputs; i++) {
|
||||
if (l_load(&l, inputs[i]) != 0) return 1;
|
||||
}
|
||||
if (l_resolve(&l) != 0) return 1;
|
||||
if (l_relocate(&l, base + 0x1000) != 0) return 1;
|
||||
|
||||
Lsym *entry = l_lookup(&l, "_start");
|
||||
if (entry == NULL || !entry->defined) entry = l_lookup(&l, "main");
|
||||
if (entry == NULL || !entry->defined) {
|
||||
fprintf(stderr, "6l: no _start or main symbol defined\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
FILE *f = fopen(out, "wb");
|
||||
if (f == NULL) {
|
||||
fprintf(stderr, "6l: cannot open %s\n", out);
|
||||
return 1;
|
||||
}
|
||||
int rc = l_emit_elf(&l, f, base, base + 0x1000 + entry->val);
|
||||
fclose(f);
|
||||
if (rc == 0) {
|
||||
/* chmod +x */
|
||||
char cmd[1024];
|
||||
snprintf(cmd, sizeof cmd, "chmod +x %s", out);
|
||||
(void)system(cmd);
|
||||
}
|
||||
free(inputs);
|
||||
return rc;
|
||||
}
|
||||
324
cmd/6l/obj.c
Normal file
324
cmd/6l/obj.c
Normal file
@@ -0,0 +1,324 @@
|
||||
/*
|
||||
* obj.c — load an ELF64 relocatable object emitted by 6a, append its
|
||||
* .text bytes to the combined image, and pull its symbols and
|
||||
* relocations into the global tables (with offsets adjusted to the
|
||||
* combined section).
|
||||
*/
|
||||
#include "l.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define ET_REL 1
|
||||
#define EM_X86_64 62
|
||||
|
||||
#define SHT_PROGBITS 1
|
||||
#define SHT_SYMTAB 2
|
||||
#define SHT_STRTAB 3
|
||||
#define SHT_RELA 4
|
||||
|
||||
#pragma pack(push, 1)
|
||||
typedef struct {
|
||||
u8 e_ident[16];
|
||||
u16 e_type, e_machine;
|
||||
u32 e_version;
|
||||
u64 e_entry, e_phoff, e_shoff;
|
||||
u32 e_flags;
|
||||
u16 e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum, e_shstrndx;
|
||||
} Ehdr;
|
||||
|
||||
typedef struct {
|
||||
u32 sh_name, sh_type;
|
||||
u64 sh_flags, sh_addr, sh_offset, sh_size;
|
||||
u32 sh_link, sh_info;
|
||||
u64 sh_addralign, sh_entsize;
|
||||
} Shdr;
|
||||
|
||||
typedef struct {
|
||||
u32 st_name;
|
||||
u8 st_info, st_other;
|
||||
u16 st_shndx;
|
||||
u64 st_value, st_size;
|
||||
} Sym64;
|
||||
|
||||
typedef struct {
|
||||
u64 r_offset;
|
||||
u64 r_info;
|
||||
i64 r_addend;
|
||||
} Rela64;
|
||||
#pragma pack(pop)
|
||||
|
||||
#define ELF64_R_SYM(i) ((u32)((i) >> 32))
|
||||
#define ELF64_R_TYPE(i) ((u32)((i) & 0xffffffff))
|
||||
#define ELF64_ST_TYPE(i) ((i) & 0xf)
|
||||
#define ELF64_ST_BIND(i) ((i) >> 4)
|
||||
|
||||
static int
|
||||
read_all(const char *path, u8 **out, u64 *len)
|
||||
{
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (f == NULL) return -1;
|
||||
fseek(f, 0, SEEK_END);
|
||||
long n = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
if (n < 0) { fclose(f); return -1; }
|
||||
u8 *b = malloc((size_t)n);
|
||||
if (fread(b, 1, (size_t)n, f) != (size_t)n) { free(b); fclose(f); return -1; }
|
||||
fclose(f);
|
||||
*out = b;
|
||||
*len = (u64)n;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
emit_text(Lnk *l, const u8 *src, u64 n)
|
||||
{
|
||||
if (l->textlen + n > l->textcap) {
|
||||
u64 nc = l->textcap ? l->textcap * 2 : 4096;
|
||||
while (nc < l->textlen + n) nc *= 2;
|
||||
l->text = realloc(l->text, nc);
|
||||
l->textcap = nc;
|
||||
}
|
||||
memcpy(l->text + l->textlen, src, n);
|
||||
l->textlen += n;
|
||||
}
|
||||
|
||||
/* Internal: load a single ELF .o image already in memory. The caller
|
||||
* gives us the bytes (we own them) and a path tag for diagnostics.
|
||||
* If the bytes look like an archive (magic "!<arch>\n") we recurse
|
||||
* over each member instead.
|
||||
*/
|
||||
static int load_image(Lnk *l, const char *path, u8 *buf, u64 len);
|
||||
|
||||
static u64
|
||||
ar_field(const u8 *p, int n)
|
||||
{
|
||||
/* decimal field, space-padded */
|
||||
u64 v = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (p[i] >= '0' && p[i] <= '9') v = v * 10 + (p[i] - '0');
|
||||
else if (p[i] == ' ') break;
|
||||
else if (p[i] == 0) break;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
/* Read an ELF .o image's globally-defined symbol names without
|
||||
* actually appending it to the link. Returns a heap-allocated
|
||||
* NULL-terminated array; caller frees the array (not the strings,
|
||||
* which point into the .o image and must remain alive).
|
||||
*/
|
||||
static char **
|
||||
elf_globals(const u8 *buf, u64 len)
|
||||
{
|
||||
if (len < sizeof(Ehdr)) return NULL;
|
||||
Ehdr *eh = (Ehdr *)buf;
|
||||
if (memcmp(eh->e_ident, "\x7f""ELF", 4) != 0) return NULL;
|
||||
Shdr *sh = (Shdr *)(buf + eh->e_shoff);
|
||||
int idx_text = -1, idx_symtab = -1;
|
||||
const char *shstr = (const char *)(buf + sh[eh->e_shstrndx].sh_offset);
|
||||
for (u16 i = 0; i < eh->e_shnum; i++) {
|
||||
if (sh[i].sh_type == SHT_PROGBITS &&
|
||||
strcmp(shstr + sh[i].sh_name, ".text") == 0)
|
||||
idx_text = i;
|
||||
else if (sh[i].sh_type == SHT_SYMTAB)
|
||||
idx_symtab = i;
|
||||
}
|
||||
if (idx_text < 0 || idx_symtab < 0) return NULL;
|
||||
int idx_strtab = sh[idx_symtab].sh_link;
|
||||
Sym64 *symtab = (Sym64 *)(buf + sh[idx_symtab].sh_offset);
|
||||
u64 nsyms = sh[idx_symtab].sh_size / sizeof(Sym64);
|
||||
const char *str = (const char *)(buf + sh[idx_strtab].sh_offset);
|
||||
|
||||
char **out = calloc(nsyms + 1, sizeof *out);
|
||||
int n = 0;
|
||||
for (u64 i = 1; i < nsyms; i++) {
|
||||
if (symtab[i].st_shndx == 0) continue;
|
||||
if ((symtab[i].st_info >> 4) != 1) continue; /* STB_GLOBAL */
|
||||
if ((int)symtab[i].st_shndx != idx_text) continue;
|
||||
out[n++] = strdup(str + symtab[i].st_name);
|
||||
}
|
||||
out[n] = NULL;
|
||||
return out;
|
||||
}
|
||||
|
||||
typedef struct ArMember ArMember;
|
||||
struct ArMember {
|
||||
u8 *data; /* heap copy; freed if never loaded */
|
||||
u64 size;
|
||||
char **defs; /* NULL-terminated list of defined globals */
|
||||
int loaded;
|
||||
ArMember *next;
|
||||
};
|
||||
|
||||
static int
|
||||
member_defines_undef(Lnk *l, ArMember *m)
|
||||
{
|
||||
if (m->defs == NULL) return 0;
|
||||
for (int i = 0; m->defs[i]; i++) {
|
||||
Lsym *s = l_lookup(l, m->defs[i]);
|
||||
if (s != NULL && !s->defined) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
load_archive(Lnk *l, const char *path, u8 *buf, u64 len)
|
||||
{
|
||||
/* Pass 1: index members. We copy each member's bytes (cheap; few
|
||||
* tens of KB per stdlib module) so the archive buffer can be
|
||||
* freed once we're done indexing. */
|
||||
ArMember *head = NULL, *tail = NULL;
|
||||
u64 pos = 8; /* past "!<arch>\n" */
|
||||
while (pos + 60 <= len) {
|
||||
const u8 *hdr = buf + pos;
|
||||
u64 size = ar_field(hdr + 48, 10);
|
||||
u64 hdr_end = pos + 60;
|
||||
if (hdr_end + size > len) break;
|
||||
if (hdr[0] != '/' && hdr[0] != 0 && hdr[0] != ' ') {
|
||||
ArMember *m = calloc(1, sizeof *m);
|
||||
m->size = size;
|
||||
m->data = malloc((size_t)size);
|
||||
memcpy(m->data, buf + hdr_end, (size_t)size);
|
||||
m->defs = elf_globals(m->data, size);
|
||||
if (head == NULL) head = m;
|
||||
else tail->next = m;
|
||||
tail = m;
|
||||
}
|
||||
pos = hdr_end + size;
|
||||
if (size & 1) pos++;
|
||||
}
|
||||
free(buf);
|
||||
|
||||
/* Pass 2: iteratively pull members that define a currently-
|
||||
* undefined symbol. Each pull may introduce new undefs, so loop. */
|
||||
int changed = 1;
|
||||
while (changed) {
|
||||
changed = 0;
|
||||
for (ArMember *m = head; m; m = m->next) {
|
||||
if (m->loaded) continue;
|
||||
if (!member_defines_undef(l, m)) continue;
|
||||
u8 *copy = malloc((size_t)m->size);
|
||||
memcpy(copy, m->data, m->size);
|
||||
if (load_image(l, path, copy, m->size) == 0) {
|
||||
m->loaded = 1;
|
||||
changed = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Free unloaded members; loaded ones had their bytes consumed
|
||||
* by load_image (which took the copy). */
|
||||
while (head) {
|
||||
ArMember *next = head->next;
|
||||
free(head->data);
|
||||
if (head->defs) {
|
||||
for (int i = 0; head->defs[i]; i++) free(head->defs[i]);
|
||||
free(head->defs);
|
||||
}
|
||||
free(head);
|
||||
head = next;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
l_load(Lnk *l, const char *path)
|
||||
{
|
||||
u8 *buf;
|
||||
u64 len;
|
||||
if (read_all(path, &buf, &len) < 0) return -1;
|
||||
if (len >= 8 && memcmp(buf, "!<arch>\n", 8) == 0)
|
||||
return load_archive(l, path, buf, len);
|
||||
return load_image(l, path, buf, len);
|
||||
}
|
||||
|
||||
static int
|
||||
load_image(Lnk *l, const char *path, u8 *buf, u64 len)
|
||||
{
|
||||
if (len < sizeof(Ehdr)) { free(buf); return -1; }
|
||||
Ehdr *eh = (Ehdr *)buf;
|
||||
if (memcmp(eh->e_ident, "\x7f""ELF", 4) != 0 || eh->e_ident[4] != 2
|
||||
|| eh->e_machine != EM_X86_64 || eh->e_type != ET_REL) {
|
||||
fprintf(stderr, "6l: %s: not an amd64 ELF64 relocatable\n", path);
|
||||
free(buf);
|
||||
return -1;
|
||||
}
|
||||
Shdr *sh = (Shdr *)(buf + eh->e_shoff);
|
||||
if (eh->e_shstrndx >= eh->e_shnum) { free(buf); return -1; }
|
||||
const char *shstr = (const char *)(buf + sh[eh->e_shstrndx].sh_offset);
|
||||
|
||||
/* find .text, .symtab, .strtab, .rela.text */
|
||||
int idx_text = -1, idx_symtab = -1, idx_strtab = -1, idx_rela = -1;
|
||||
for (u16 i = 0; i < eh->e_shnum; i++) {
|
||||
const char *nm = shstr + sh[i].sh_name;
|
||||
if (sh[i].sh_type == SHT_PROGBITS && strcmp(nm, ".text") == 0)
|
||||
idx_text = i;
|
||||
else if (sh[i].sh_type == SHT_SYMTAB)
|
||||
idx_symtab = i;
|
||||
else if (sh[i].sh_type == SHT_RELA && strcmp(nm, ".rela.text") == 0)
|
||||
idx_rela = i;
|
||||
}
|
||||
if (idx_text < 0 || idx_symtab < 0) {
|
||||
fprintf(stderr, "6l: %s: missing .text or .symtab\n", path);
|
||||
free(buf);
|
||||
return -1;
|
||||
}
|
||||
idx_strtab = sh[idx_symtab].sh_link;
|
||||
|
||||
Lobj *ob = calloc(1, sizeof *ob);
|
||||
ob->path = strdup(path);
|
||||
ob->buf = buf;
|
||||
ob->len = len;
|
||||
ob->text_off = l->textlen;
|
||||
ob->text_size = sh[idx_text].sh_size;
|
||||
ob->next = l->objs;
|
||||
l->objs = ob;
|
||||
|
||||
/* append .text */
|
||||
emit_text(l, buf + sh[idx_text].sh_offset, sh[idx_text].sh_size);
|
||||
|
||||
/* per-object: load symbols */
|
||||
Sym64 *symtab = (Sym64 *)(buf + sh[idx_symtab].sh_offset);
|
||||
u64 nsyms = sh[idx_symtab].sh_size / sizeof(Sym64);
|
||||
const char *str = (const char *)(buf + sh[idx_strtab].sh_offset);
|
||||
|
||||
/* map per-object sym index → global Lsym */
|
||||
Lsym **map = calloc(nsyms, sizeof *map);
|
||||
for (u64 i = 1; i < nsyms; i++) {
|
||||
const char *nm = str + symtab[i].st_name;
|
||||
if (nm[0] == '\0') continue;
|
||||
Lsym *gs = l_intern(l, nm);
|
||||
if (symtab[i].st_shndx != 0 /* SHN_UNDEF */
|
||||
&& symtab[i].st_shndx == idx_text) {
|
||||
if (gs->defined) {
|
||||
fprintf(stderr, "6l: %s: duplicate symbol %s\n",
|
||||
path, nm);
|
||||
l->errs++;
|
||||
} else {
|
||||
gs->defined = 1;
|
||||
gs->owner = ob;
|
||||
gs->idx_in_owner = (int)i;
|
||||
gs->val = ob->text_off + symtab[i].st_value;
|
||||
}
|
||||
}
|
||||
map[i] = gs;
|
||||
}
|
||||
|
||||
/* per-object: collect relocations */
|
||||
if (idx_rela >= 0) {
|
||||
Rela64 *rt = (Rela64 *)(buf + sh[idx_rela].sh_offset);
|
||||
u64 nrel = sh[idx_rela].sh_size / sizeof(Rela64);
|
||||
for (u64 i = 0; i < nrel; i++) {
|
||||
Lrel *r = calloc(1, sizeof *r);
|
||||
r->off = ob->text_off + rt[i].r_offset;
|
||||
r->kind = (int)ELF64_R_TYPE(rt[i].r_info);
|
||||
u32 sidx = ELF64_R_SYM(rt[i].r_info);
|
||||
r->sym = (sidx < nsyms) ? map[sidx] : NULL;
|
||||
r->addend = rt[i].r_addend;
|
||||
r->next = l->rels;
|
||||
l->rels = r;
|
||||
}
|
||||
}
|
||||
free(map);
|
||||
return 0;
|
||||
}
|
||||
89
cmd/6l/out.c
Normal file
89
cmd/6l/out.c
Normal file
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* out.c — emit a static ELF64 executable.
|
||||
*
|
||||
* Layout (file order):
|
||||
* [0..64) ELF header
|
||||
* [64..120) program header (one PT_LOAD)
|
||||
* [120..0x1000) zero pad
|
||||
* [0x1000..) .text bytes
|
||||
*
|
||||
* The single PT_LOAD covers the whole file, R+X. No interpreter,
|
||||
* no dynamic, no .bss yet. Entry point is the address of the
|
||||
* symbol named "_start" (or whatever main supplies via -e).
|
||||
*/
|
||||
#include "l.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define ET_EXEC 2
|
||||
#define EM_X86_64 62
|
||||
#define EV_CURRENT 1
|
||||
#define ELFCLASS64 2
|
||||
#define ELFDATA2LSB 1
|
||||
|
||||
#define PT_LOAD 1
|
||||
#define PF_X 1
|
||||
#define PF_W 2
|
||||
#define PF_R 4
|
||||
|
||||
#pragma pack(push, 1)
|
||||
typedef struct {
|
||||
u8 e_ident[16];
|
||||
u16 e_type, e_machine;
|
||||
u32 e_version;
|
||||
u64 e_entry, e_phoff, e_shoff;
|
||||
u32 e_flags;
|
||||
u16 e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum, e_shstrndx;
|
||||
} Ehdr;
|
||||
|
||||
typedef struct {
|
||||
u32 p_type, p_flags;
|
||||
u64 p_offset, p_vaddr, p_paddr;
|
||||
u64 p_filesz, p_memsz, p_align;
|
||||
} Phdr;
|
||||
#pragma pack(pop)
|
||||
|
||||
int
|
||||
l_emit_elf(Lnk *l, FILE *f, u64 base, u64 entry)
|
||||
{
|
||||
const u64 text_off = 0x1000;
|
||||
const u64 text_va = base + text_off;
|
||||
const u64 filesz = text_off + l->textlen;
|
||||
|
||||
Ehdr eh = {0};
|
||||
memcpy(eh.e_ident, "\x7f""ELF", 4);
|
||||
eh.e_ident[4] = ELFCLASS64;
|
||||
eh.e_ident[5] = ELFDATA2LSB;
|
||||
eh.e_ident[6] = EV_CURRENT;
|
||||
eh.e_type = ET_EXEC;
|
||||
eh.e_machine = EM_X86_64;
|
||||
eh.e_version = EV_CURRENT;
|
||||
eh.e_entry = entry;
|
||||
eh.e_phoff = sizeof(Ehdr);
|
||||
eh.e_ehsize = sizeof(Ehdr);
|
||||
eh.e_phentsize = sizeof(Phdr);
|
||||
eh.e_phnum = 1;
|
||||
(void)text_va;
|
||||
|
||||
Phdr ph = {0};
|
||||
ph.p_type = PT_LOAD;
|
||||
ph.p_flags = PF_R | PF_X;
|
||||
ph.p_offset = 0;
|
||||
ph.p_vaddr = base;
|
||||
ph.p_paddr = base;
|
||||
ph.p_filesz = filesz;
|
||||
ph.p_memsz = filesz;
|
||||
ph.p_align = 0x1000;
|
||||
|
||||
fwrite(&eh, 1, sizeof eh, f);
|
||||
fwrite(&ph, 1, sizeof ph, f);
|
||||
|
||||
/* pad to text_off */
|
||||
long here = ftell(f);
|
||||
for (long i = here; i < (long)text_off; i++) fputc(0, f);
|
||||
|
||||
if (l->textlen) fwrite(l->text, 1, l->textlen, f);
|
||||
|
||||
return 0;
|
||||
}
|
||||
63
cmd/6l/pass.c
Normal file
63
cmd/6l/pass.c
Normal file
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* pass.c — resolution + relocation. After all objects are loaded:
|
||||
*
|
||||
* l_resolve : check that every symbol referenced by a relocation
|
||||
* is defined somewhere. Errors get logged.
|
||||
* l_relocate: with the final virtual base address known, walk the
|
||||
* relocation list and patch the .text bytes in place.
|
||||
*
|
||||
* Supported relocation kinds: PC32 (2), PLT32 (4). Both are PC-relative
|
||||
* 32-bit displacements; for static linking PLT32 collapses to PC32.
|
||||
*/
|
||||
#include "l.h"
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define R_X86_64_PC32 2
|
||||
#define R_X86_64_PLT32 4
|
||||
|
||||
int
|
||||
l_resolve(Lnk *l)
|
||||
{
|
||||
for (Lrel *r = l->rels; r; r = r->next) {
|
||||
if (r->sym == NULL) continue;
|
||||
if (!r->sym->defined) {
|
||||
fprintf(stderr, "6l: undefined reference to '%s'\n",
|
||||
r->sym->name);
|
||||
l->errs++;
|
||||
}
|
||||
}
|
||||
return l->errs;
|
||||
}
|
||||
|
||||
static void
|
||||
patch_u32(u8 *p, u32 v)
|
||||
{
|
||||
p[0] = (u8)(v & 0xff);
|
||||
p[1] = (u8)((v >> 8) & 0xff);
|
||||
p[2] = (u8)((v >> 16) & 0xff);
|
||||
p[3] = (u8)((v >> 24) & 0xff);
|
||||
}
|
||||
|
||||
int
|
||||
l_relocate(Lnk *l, u64 base)
|
||||
{
|
||||
for (Lrel *r = l->rels; r; r = r->next) {
|
||||
if (r->sym == NULL || !r->sym->defined) continue;
|
||||
switch (r->kind) {
|
||||
case R_X86_64_PC32:
|
||||
case R_X86_64_PLT32: {
|
||||
u64 site = base + r->off;
|
||||
i64 target = (i64)(base + r->sym->val);
|
||||
i64 rel = target - (i64)site + r->addend;
|
||||
patch_u32(l->text + r->off, (u32)(i32)rel);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
fprintf(stderr, "6l: unsupported reloc kind %d\n",
|
||||
r->kind);
|
||||
l->errs++;
|
||||
}
|
||||
}
|
||||
return l->errs;
|
||||
}
|
||||
27
cmd/6l/sym.c
Normal file
27
cmd/6l/sym.c
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* sym.c — global symbol table for the linker. Plain singly-linked
|
||||
* list; usually a few hundred entries, hashing isn't worth it yet.
|
||||
*/
|
||||
#include "l.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
Lsym *
|
||||
l_intern(Lnk *l, const char *name)
|
||||
{
|
||||
for (Lsym *s = l->syms; s; s = s->next)
|
||||
if (strcmp(s->name, name) == 0) return s;
|
||||
Lsym *s = calloc(1, sizeof *s);
|
||||
s->name = strdup(name);
|
||||
s->next = l->syms;
|
||||
l->syms = s;
|
||||
return s;
|
||||
}
|
||||
|
||||
Lsym *
|
||||
l_lookup(Lnk *l, const char *name)
|
||||
{
|
||||
for (Lsym *s = l->syms; s; s = s->next)
|
||||
if (strcmp(s->name, name) == 0) return s;
|
||||
return NULL;
|
||||
}
|
||||
349
cmd/ww/main.c
Normal file
349
cmd/ww/main.c
Normal file
@@ -0,0 +1,349 @@
|
||||
/*
|
||||
* ww — the user-facing driver. Plan 9 cc(1) / Hare hare(1) analogue.
|
||||
*
|
||||
* Pipeline:
|
||||
* ww build foo.ww → 6c foo.ww > foo.s ; 6a foo.s > foo.o ;
|
||||
* 6l -o foo foo.o <runtime.o>
|
||||
* ww run foo.ww → build then exec ./foo
|
||||
*
|
||||
* Tool paths default to siblings of $0 (so a fresh build runs out of
|
||||
* out/bin/), and can be overridden with WW_6C / WW_6A / WW_6L.
|
||||
*/
|
||||
#include "ww.h"
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/wait.h>
|
||||
#include <libgen.h>
|
||||
|
||||
static const char *usage =
|
||||
"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"
|
||||
" test <path> build and run module tests\n"
|
||||
" fmt <path> reformat ww source\n"
|
||||
" version print version and exit\n";
|
||||
|
||||
static char *self_dir; /* directory containing this binary */
|
||||
|
||||
static const char *
|
||||
toolpath(const char *envvar, const char *name)
|
||||
{
|
||||
const char *p = getenv(envvar);
|
||||
if (p && p[0]) return p;
|
||||
static char buf[1024];
|
||||
snprintf(buf, sizeof buf, "%s/%s", self_dir, name);
|
||||
return strdup(buf);
|
||||
}
|
||||
|
||||
static int
|
||||
run(const char *cmd)
|
||||
{
|
||||
int rc = system(cmd);
|
||||
if (rc == -1) return -1;
|
||||
if (WIFEXITED(rc)) return WEXITSTATUS(rc);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Set of imported module paths, kept on the heap. Used to break
|
||||
* cycles in `use` resolution. Linear because typical imports are
|
||||
* a handful per build. */
|
||||
struct ImportSet {
|
||||
char **paths;
|
||||
int n, cap;
|
||||
};
|
||||
|
||||
static int
|
||||
import_seen(struct ImportSet *s, const char *path)
|
||||
{
|
||||
for (int i = 0; i < s->n; i++)
|
||||
if (strcmp(s->paths[i], path) == 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
import_add(struct ImportSet *s, const char *path)
|
||||
{
|
||||
if (s->n + 1 > s->cap) {
|
||||
s->cap = s->cap ? s->cap * 2 : 8;
|
||||
s->paths = realloc(s->paths, s->cap * sizeof *s->paths);
|
||||
}
|
||||
s->paths[s->n++] = strdup(path);
|
||||
}
|
||||
|
||||
/* try <dir>/X.ww then <dir>/X/X.ww; return resolved path in `out` or 0. */
|
||||
static int
|
||||
locate_import_in(const char *dir, const char *name, char *out, size_t outsz)
|
||||
{
|
||||
snprintf(out, outsz, "%s/%s.ww", dir, name);
|
||||
if (access(out, 0) == 0) return 1;
|
||||
snprintf(out, outsz, "%s/%s/%s.ww", dir, name, name);
|
||||
if (access(out, 0) == 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Walk a colon-separated dirlist trying to resolve `name`. Returns 1
|
||||
* on the first hit. */
|
||||
static int
|
||||
locate_import(const char *dirs, const char *name, char *out, size_t outsz)
|
||||
{
|
||||
const char *p = dirs;
|
||||
while (*p) {
|
||||
const char *e = strchr(p, ':');
|
||||
size_t n = e ? (size_t)(e - p) : strlen(p);
|
||||
if (n > 0 && n < outsz) {
|
||||
char dir[1024];
|
||||
if (n >= sizeof dir) n = sizeof dir - 1;
|
||||
memcpy(dir, p, n);
|
||||
dir[n] = '\0';
|
||||
if (locate_import_in(dir, name, out, outsz)) return 1;
|
||||
}
|
||||
if (!e) break;
|
||||
p = e + 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Recursively expand `path`: for each top-level `use IDENT;` we find,
|
||||
* resolve the import and expand it first, then append our own bytes.
|
||||
* Already-visited paths are skipped. */
|
||||
static void
|
||||
expand(FILE *out, const char *path, struct ImportSet *visited,
|
||||
const char *libdir)
|
||||
{
|
||||
/* Use the path as-is for cycle detection. Different syntactic
|
||||
* paths to the same file would re-import, which is harmless given
|
||||
* our flat-scope concatenation (duplicate decls would fail at
|
||||
* check time, surfacing the issue). */
|
||||
if (import_seen(visited, path)) return;
|
||||
import_add(visited, path);
|
||||
|
||||
FILE *in = fopen(path, "rb");
|
||||
if (in == NULL) {
|
||||
fprintf(stderr, "ww: cannot read %s\n", path);
|
||||
return;
|
||||
}
|
||||
/* Scan once for `use X;` clauses, expand each. We keep the line
|
||||
* format simple — leading whitespace + "use" + IDENT + optional
|
||||
* dotted suffix + ";". Inside-comment occurrences would slip
|
||||
* through, but ww source rarely puts that pattern in a comment. */
|
||||
char line[2048];
|
||||
while (fgets(line, sizeof line, in)) {
|
||||
const char *p = line;
|
||||
while (*p == ' ' || *p == '\t') p++;
|
||||
if (strncmp(p, "use ", 4) != 0 && strncmp(p, "use\t", 4) != 0)
|
||||
continue;
|
||||
p += 4;
|
||||
while (*p == ' ' || *p == '\t') p++;
|
||||
char name[256] = {0};
|
||||
int j = 0;
|
||||
while ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z')
|
||||
|| *p == '_' || *p == '.' || (*p >= '0' && *p <= '9'))
|
||||
if (j + 1 < (int)sizeof name) name[j++] = *p++;
|
||||
if (j == 0) continue;
|
||||
char ipath[1024];
|
||||
if (!locate_import(libdir, name, ipath, sizeof ipath))
|
||||
continue; /* silently skip if not found */
|
||||
expand(out, ipath, visited, libdir);
|
||||
}
|
||||
|
||||
rewind(in);
|
||||
int ch;
|
||||
while ((ch = fgetc(in)) != EOF) fputc(ch, out);
|
||||
fputc('\n', out);
|
||||
fclose(in);
|
||||
}
|
||||
|
||||
static int
|
||||
build_one(const char *src, const char *out, const char *extra_includes)
|
||||
{
|
||||
const char *c6 = toolpath("WW_6C", "6c");
|
||||
const char *a6 = toolpath("WW_6A", "6a");
|
||||
const char *l6 = toolpath("WW_6L", "6l");
|
||||
const char *libdir = getenv("WW_LIB");
|
||||
if (libdir == NULL || libdir[0] == 0) {
|
||||
static char libbuf[1024];
|
||||
snprintf(libbuf, sizeof libbuf, "%s/../lib", self_dir);
|
||||
libdir = libbuf;
|
||||
}
|
||||
const char *srcdir = getenv("WW_SRCLIB");
|
||||
static char srcbuf[1024];
|
||||
if (srcdir == NULL || srcdir[0] == 0) {
|
||||
/* in-tree default: ../../lib relative to bin/ */
|
||||
snprintf(srcbuf, sizeof srcbuf, "%s/../../lib", self_dir);
|
||||
if (access(srcbuf, 0) == 0) srcdir = srcbuf;
|
||||
else if (access("lib", 0) == 0) srcdir = "lib";
|
||||
else srcdir = libdir;
|
||||
}
|
||||
|
||||
/* Compose the search path: any -I dirs first, then srcdir.
|
||||
* locate_import walks them left-to-right. */
|
||||
static char searchpath[4096];
|
||||
if (extra_includes && extra_includes[0])
|
||||
snprintf(searchpath, sizeof searchpath, "%s:%s", extra_includes, srcdir);
|
||||
else
|
||||
snprintf(searchpath, sizeof searchpath, "%s", srcdir);
|
||||
srcdir = searchpath;
|
||||
|
||||
/* Strip extension to derive a stem; e.g. /tmp/foo.ww → /tmp/foo */
|
||||
char stem[1024];
|
||||
snprintf(stem, sizeof stem, "%s", src);
|
||||
char *dot = strrchr(stem, '.');
|
||||
if (dot && strcmp(dot, ".ww") == 0) *dot = '\0';
|
||||
|
||||
char asmf[1024], obj[1024], combined[1024];
|
||||
snprintf(asmf, sizeof asmf, "%s.s", stem);
|
||||
snprintf(obj, sizeof obj, "%s.o", stem);
|
||||
snprintf(combined, sizeof combined, "%s.combined.ww", stem);
|
||||
|
||||
/* Resolve `use X;` imports by concatenating sources into a temp
|
||||
* file. The compiler then sees one flat source. */
|
||||
{
|
||||
FILE *cf = fopen(combined, "wb");
|
||||
if (cf == NULL) {
|
||||
fprintf(stderr, "ww: cannot open %s\n", combined);
|
||||
return 1;
|
||||
}
|
||||
struct ImportSet visited = {0};
|
||||
expand(cf, src, &visited, srcdir);
|
||||
fclose(cf);
|
||||
for (int i = 0; i < visited.n; i++) free(visited.paths[i]);
|
||||
free(visited.paths);
|
||||
}
|
||||
|
||||
char cmd[4096];
|
||||
snprintf(cmd, sizeof cmd, "%s -o %s %s", c6, asmf, combined);
|
||||
if (run(cmd) != 0) {
|
||||
fprintf(stderr, "ww: 6c failed\n");
|
||||
return 1;
|
||||
}
|
||||
snprintf(cmd, sizeof cmd, "%s -o %s %s", a6, obj, asmf);
|
||||
if (run(cmd) != 0) {
|
||||
fprintf(stderr, "ww: 6a failed\n");
|
||||
return 1;
|
||||
}
|
||||
/* Link runtime: prefer libwwrt.a (selective archive pull) but
|
||||
* fall back to start.o + syscall.o in the in-tree obj/ dir if
|
||||
* we're running uninstalled. */
|
||||
char rtargs[2048] = {0};
|
||||
char path[1024];
|
||||
snprintf(path, sizeof path, "%s/libwwrt.a", libdir);
|
||||
if (access(path, 0) == 0) {
|
||||
snprintf(rtargs, sizeof rtargs, "%s", path);
|
||||
} else {
|
||||
char a1[1024], a2[1024];
|
||||
snprintf(a1, sizeof a1, "%s/../obj/rt/start.o", self_dir);
|
||||
snprintf(a2, sizeof a2, "%s/../obj/rt/syscall.o", self_dir);
|
||||
snprintf(rtargs, sizeof rtargs, "%s %s", a1, a2);
|
||||
}
|
||||
snprintf(cmd, sizeof cmd, "%s -o %s %s %s", l6, out, obj, rtargs);
|
||||
if (run(cmd) != 0) {
|
||||
fprintf(stderr, "ww: 6l failed\n");
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
do_version(void)
|
||||
{
|
||||
printf("ww %s\n", WW_VERSION);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
do_build(int argc, char **argv)
|
||||
{
|
||||
const char *src = NULL;
|
||||
char libs[2048] = {0};
|
||||
char incs[2048] = {0};
|
||||
for (int i = 0; i < argc; i++) {
|
||||
if (strncmp(argv[i], "-l", 2) == 0 && argv[i][2]) {
|
||||
char libpath[512];
|
||||
const char *libdir = getenv("WW_LIB");
|
||||
if (libdir == NULL) {
|
||||
static char def[1024];
|
||||
snprintf(def, sizeof def, "%s/../lib", self_dir);
|
||||
libdir = def;
|
||||
}
|
||||
snprintf(libpath, sizeof libpath, "%s/lib%s.a",
|
||||
libdir, argv[i] + 2);
|
||||
size_t n = strlen(libs);
|
||||
snprintf(libs + n, sizeof libs - n, " %s", libpath);
|
||||
} else if (strcmp(argv[i], "-I") == 0 && i + 1 < argc) {
|
||||
size_t n = strlen(incs);
|
||||
snprintf(incs + n, sizeof incs - n,
|
||||
"%s%s", n ? ":" : "", argv[++i]);
|
||||
} else if (strncmp(argv[i], "-I", 2) == 0 && argv[i][2]) {
|
||||
size_t n = strlen(incs);
|
||||
snprintf(incs + n, sizeof incs - n,
|
||||
"%s%s", n ? ":" : "", argv[i] + 2);
|
||||
} else if (src == NULL) {
|
||||
src = argv[i];
|
||||
}
|
||||
}
|
||||
if (src == NULL) { fputs("ww build: missing source\n", stderr); return 2; }
|
||||
char out[1024];
|
||||
const char *base = strrchr(src, '/');
|
||||
base = base ? base + 1 : src;
|
||||
snprintf(out, sizeof out, "%s", base);
|
||||
char *dot = strrchr(out, '.');
|
||||
if (dot && strcmp(dot, ".ww") == 0) *dot = '\0';
|
||||
(void)libs; /* libs string is gathered; build_one currently
|
||||
* always links libwwrt.a; -l support pending more
|
||||
* glue between driver and 6l invocation. */
|
||||
return build_one(src, out, incs);
|
||||
}
|
||||
|
||||
static int
|
||||
do_run(int argc, char **argv)
|
||||
{
|
||||
if (argc < 1) { fputs("ww run: missing source\n", stderr); return 2; }
|
||||
char tmp[1024];
|
||||
snprintf(tmp, sizeof tmp, "/tmp/ww_run_%d", getpid());
|
||||
if (build_one(argv[0], tmp, "") != 0) return 1;
|
||||
int rc = run(tmp);
|
||||
unlink(tmp);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
do_test(int argc, char **argv)
|
||||
{
|
||||
(void)argc; (void)argv;
|
||||
fputs("ww: test: not implemented in this phase\n", stderr);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int
|
||||
do_fmt(int argc, char **argv)
|
||||
{
|
||||
(void)argc; (void)argv;
|
||||
fputs("ww: fmt: not implemented in this phase\n", stderr);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
if (argc >= 1) {
|
||||
char buf[1024];
|
||||
snprintf(buf, sizeof buf, "%s", argv[0]);
|
||||
self_dir = strdup(dirname(buf));
|
||||
}
|
||||
if (argc < 2) { fputs(usage, stderr); return 2; }
|
||||
const char *cmd = argv[1];
|
||||
if (strcmp(cmd, "-V") == 0 || strcmp(cmd, "version") == 0)
|
||||
return do_version();
|
||||
if (strcmp(cmd, "-h") == 0 || strcmp(cmd, "--help") == 0) {
|
||||
fputs(usage, stdout); return 0;
|
||||
}
|
||||
if (strcmp(cmd, "build") == 0) return do_build(argc - 2, argv + 2);
|
||||
if (strcmp(cmd, "run") == 0) return do_run(argc - 2, argv + 2);
|
||||
if (strcmp(cmd, "test") == 0) return do_test(argc - 2, argv + 2);
|
||||
if (strcmp(cmd, "fmt") == 0) return do_fmt(argc - 2, argv + 2);
|
||||
fprintf(stderr, "ww: unknown subcommand: %s\n", cmd);
|
||||
fputs(usage, stderr);
|
||||
return 2;
|
||||
}
|
||||
189
cmd/wwc/ast.c
Normal file
189
cmd/wwc/ast.c
Normal file
@@ -0,0 +1,189 @@
|
||||
/*
|
||||
* ast.c — Node constructor + s-expression printer.
|
||||
*
|
||||
* Constructor zeroes everything past kind/pos. Printer is rigid and
|
||||
* deterministic so golden tests can diff. One node per logical line,
|
||||
* children indented by 2 spaces.
|
||||
*/
|
||||
#include "ww.h"
|
||||
#include <string.h>
|
||||
|
||||
Node *
|
||||
newnode(Arena *a, Nkind k, Pos p)
|
||||
{
|
||||
Node *n = amalloc(a, sizeof *n);
|
||||
n->kind = k;
|
||||
n->pos = p;
|
||||
return n;
|
||||
}
|
||||
|
||||
static const char *
|
||||
nkname(Nkind k)
|
||||
{
|
||||
switch (k) {
|
||||
case N_NONE: return "none";
|
||||
case N_INTLIT: return "int";
|
||||
case N_FLOATLIT: return "float";
|
||||
case N_STRLIT: return "str";
|
||||
case N_RUNELIT: return "rune";
|
||||
case N_TRUE: return "true";
|
||||
case N_FALSE: return "false";
|
||||
case N_NIL: return "nil";
|
||||
case N_IDENT: return "id";
|
||||
case N_BIN: return "bin";
|
||||
case N_UN: return "un";
|
||||
case N_CALL: return "call";
|
||||
case N_INDEX: return "index";
|
||||
case N_DOT: return "dot";
|
||||
case N_CAST: return "cast";
|
||||
case N_STRUCTLIT: return "structlit";
|
||||
case N_ARRLIT: return "arrlit";
|
||||
case N_FIELD: return "field";
|
||||
case N_ASSIGN: return "assign";
|
||||
case N_ALLOC: return "alloc";
|
||||
case N_FREE: return "free";
|
||||
case N_RECV: return "recv";
|
||||
case N_SLICE: return "slice";
|
||||
case N_SPREAD: return "spread";
|
||||
case N_BLOCK: return "block";
|
||||
case N_EXPRSTMT: return "exprstmt";
|
||||
case N_LET: return "let";
|
||||
case N_RETURN: return "return";
|
||||
case N_IF: return "if";
|
||||
case N_FOR: return "for";
|
||||
case N_FORRANGE: return "forrange";
|
||||
case N_DEFER: return "defer";
|
||||
case N_BREAK: return "break";
|
||||
case N_CONTINUE: return "continue";
|
||||
case N_SWITCH: return "switch";
|
||||
case N_CASE: return "case";
|
||||
case N_FILE: return "file";
|
||||
case N_USE: return "use";
|
||||
case N_DEF: return "def";
|
||||
case N_TYPEDECL: return "typedecl";
|
||||
case N_FNDECL: return "fn";
|
||||
case N_PARAM: return "param";
|
||||
case N_TNAME: return "tname";
|
||||
case N_TPTR: return "tptr";
|
||||
case N_TSLICE: return "tslice";
|
||||
case N_TARRAY: return "tarray";
|
||||
case N_TFN: return "tfn";
|
||||
case N_TSTRUCT: return "tstruct";
|
||||
case N_TFIELD: return "tfield";
|
||||
case N_TCHAN: return "tchan";
|
||||
case N_ATTR: return "attr";
|
||||
case N_TTUPLE: return "ttuple";
|
||||
case N_TTAGGED: return "ttagged";
|
||||
case N_TUPLE: return "tuple";
|
||||
case N_MATCH: return "match";
|
||||
case N_MCASE: return "mcase";
|
||||
case N_TRYPROP: return "tryprop";
|
||||
case N_TRYUNW: return "tryunw";
|
||||
case N_MLET: return "mlet";
|
||||
case N_MASSIGN: return "massign";
|
||||
case N_LAST: return "last";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
static void
|
||||
indent(FILE *f, int d)
|
||||
{
|
||||
for (int i = 0; i < d; i++) fputs(" ", f);
|
||||
}
|
||||
|
||||
static void
|
||||
printq(FILE *f, const char *s)
|
||||
{
|
||||
fputc('"', f);
|
||||
for (; *s; s++) {
|
||||
unsigned char c = (unsigned char)*s;
|
||||
switch (c) {
|
||||
case '"': fputs("\\\"", f); break;
|
||||
case '\\': fputs("\\\\", f); break;
|
||||
case '\n': fputs("\\n", f); break;
|
||||
case '\t': fputs("\\t", f); break;
|
||||
default:
|
||||
if (c < 0x20) fprintf(f, "\\x%02x", c);
|
||||
else fputc(c, f);
|
||||
}
|
||||
}
|
||||
fputc('"', f);
|
||||
}
|
||||
|
||||
static void pr(FILE*, Node*, int);
|
||||
|
||||
static void
|
||||
prlist(FILE *f, const char *tag, Node *head, int d)
|
||||
{
|
||||
indent(f, d);
|
||||
fprintf(f, "(%s\n", tag);
|
||||
for (Node *n = head; n; n = n->next)
|
||||
pr(f, n, d + 1);
|
||||
indent(f, d);
|
||||
fputs(")\n", f);
|
||||
}
|
||||
|
||||
static void
|
||||
pr(FILE *f, Node *n, int d)
|
||||
{
|
||||
if (n == NULL) {
|
||||
indent(f, d); fputs("()\n", f); return;
|
||||
}
|
||||
indent(f, d);
|
||||
fprintf(f, "(%s", nkname(n->kind));
|
||||
switch (n->kind) {
|
||||
case N_INTLIT:
|
||||
fprintf(f, " %llu", (unsigned long long)n->uval);
|
||||
break;
|
||||
case N_FLOATLIT:
|
||||
fprintf(f, " %g", n->fval);
|
||||
break;
|
||||
case N_RUNELIT:
|
||||
fprintf(f, " %llu", (unsigned long long)n->uval);
|
||||
break;
|
||||
case N_STRLIT:
|
||||
case N_IDENT:
|
||||
case N_USE:
|
||||
case N_DOT:
|
||||
case N_DEF:
|
||||
case N_TYPEDECL:
|
||||
case N_FNDECL:
|
||||
case N_PARAM:
|
||||
case N_LET:
|
||||
case N_TNAME:
|
||||
case N_TFIELD:
|
||||
case N_FIELD:
|
||||
case N_ATTR:
|
||||
if (n->str) { fputc(' ', f); printq(f, n->str); }
|
||||
break;
|
||||
case N_BIN:
|
||||
case N_UN:
|
||||
case N_ASSIGN:
|
||||
fprintf(f, " %s", tokname(n->op));
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
if (n->kind == N_FNDECL && n->export)
|
||||
fputs(" export", f);
|
||||
if (n->kind == N_DEF && n->export)
|
||||
fputs(" export", f);
|
||||
if (n->kind == N_TYPEDECL && n->export)
|
||||
fputs(" export", f);
|
||||
fputc('\n', f);
|
||||
if (n->attr)
|
||||
prlist(f, "@", n->attr, d + 1);
|
||||
if (n->lhs) pr(f, n->lhs, d + 1);
|
||||
if (n->rhs) pr(f, n->rhs, d + 1);
|
||||
if (n->cond) pr(f, n->cond, d + 1);
|
||||
if (n->body) pr(f, n->body, d + 1);
|
||||
if (n->els) pr(f, n->els, d + 1);
|
||||
if (n->list) prlist(f, "list", n->list, d + 1);
|
||||
indent(f, d); fputs(")\n", f);
|
||||
}
|
||||
|
||||
void
|
||||
astprint(FILE *f, Node *n)
|
||||
{
|
||||
pr(f, n, 0);
|
||||
}
|
||||
945
cmd/wwc/check.c
Normal file
945
cmd/wwc/check.c
Normal file
@@ -0,0 +1,945 @@
|
||||
/*
|
||||
* check.c — name resolution + type checking pass.
|
||||
*
|
||||
* Two-stage:
|
||||
* 1) collect: walk top-level decls and install Syms with stub types.
|
||||
* 2) resolve: expand types, check fn bodies and def initialisers.
|
||||
*
|
||||
* Errors do not stop the walk — we keep going so the user gets many
|
||||
* diagnostics from one run. Nodes get their resolved Type attached.
|
||||
*/
|
||||
#include "ww.h"
|
||||
#include <string.h>
|
||||
|
||||
static void cstmt(Checker*, Node*);
|
||||
static Type *cexpr(Checker*, Node*);
|
||||
static Type *resolve_type(Checker*, Node*);
|
||||
|
||||
static Type *
|
||||
err(Checker *c, Pos p, const char *fmt, ...)
|
||||
{
|
||||
(void)c;
|
||||
va_list ap;
|
||||
fprintf(errout ? errout : stderr,
|
||||
"%s:%d:%d: error: ", p.file ? p.file : "?", p.line, p.col);
|
||||
va_start(ap, fmt);
|
||||
vfprintf(errout ? errout : stderr, fmt, ap);
|
||||
va_end(ap);
|
||||
fputc('\n', errout ? errout : stderr);
|
||||
c->errs++;
|
||||
return ty_err;
|
||||
}
|
||||
|
||||
static Type *
|
||||
lookup_builtin(const char *name)
|
||||
{
|
||||
if (strcmp(name, "void") == 0) return ty_void;
|
||||
if (strcmp(name, "bool") == 0) return ty_bool;
|
||||
if (strcmp(name, "rune") == 0) return ty_rune;
|
||||
if (strcmp(name, "i8") == 0) return ty_i8;
|
||||
if (strcmp(name, "i16") == 0) return ty_i16;
|
||||
if (strcmp(name, "i32") == 0) return ty_i32;
|
||||
if (strcmp(name, "i64") == 0) return ty_i64;
|
||||
if (strcmp(name, "u8") == 0) return ty_u8;
|
||||
if (strcmp(name, "u16") == 0) return ty_u16;
|
||||
if (strcmp(name, "u32") == 0) return ty_u32;
|
||||
if (strcmp(name, "u64") == 0) return ty_u64;
|
||||
if (strcmp(name, "int") == 0) return ty_int;
|
||||
if (strcmp(name, "uint") == 0) return ty_uint;
|
||||
if (strcmp(name, "uintptr") == 0) return ty_uintptr;
|
||||
if (strcmp(name, "f32") == 0) return ty_f32;
|
||||
if (strcmp(name, "f64") == 0) return ty_f64;
|
||||
if (strcmp(name, "str") == 0) return ty_str;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static Type *
|
||||
resolve_typename(Checker *c, Node *n)
|
||||
{
|
||||
const char *nm = n->str;
|
||||
Type *bi = lookup_builtin(nm);
|
||||
if (bi) return bi;
|
||||
Sym *s = scope_lookup(c->cur, nm);
|
||||
if (s == NULL && nm) {
|
||||
/* module-qualified: io.stream → strip the last dot prefix
|
||||
* and look up the leaf if `io` is a `use`-imported name. */
|
||||
const char *dot = strrchr(nm, '.');
|
||||
if (dot) {
|
||||
char head[128] = {0};
|
||||
size_t hl = (size_t)(dot - nm);
|
||||
if (hl < sizeof head) memcpy(head, nm, hl);
|
||||
Sym *m = scope_lookup(c->cur, head);
|
||||
if (m && m->kind == SK_USE)
|
||||
s = scope_lookup(c->cur, dot + 1);
|
||||
}
|
||||
}
|
||||
if (s == NULL || s->kind != SK_TYPE)
|
||||
return err(c, n->pos, "unknown type '%s'", nm);
|
||||
return s->type;
|
||||
}
|
||||
|
||||
static Type *
|
||||
resolve_type(Checker *c, Node *n)
|
||||
{
|
||||
if (n == NULL) return ty_void;
|
||||
switch (n->kind) {
|
||||
case N_TNAME:
|
||||
return resolve_typename(c, n);
|
||||
case N_TPTR:
|
||||
return type_ptr(c->a, resolve_type(c, n->lhs));
|
||||
case N_TSLICE:
|
||||
return type_slice(c->a, resolve_type(c, n->lhs));
|
||||
case N_TARRAY: {
|
||||
u64 len = 0;
|
||||
if (n->rhs && n->rhs->kind == N_INTLIT)
|
||||
len = n->rhs->uval;
|
||||
else
|
||||
err(c, n->pos, "array length must be an integer literal");
|
||||
return type_array(c->a, resolve_type(c, n->lhs), len);
|
||||
}
|
||||
case N_TCHAN:
|
||||
return type_chan(c->a, resolve_type(c, n->lhs));
|
||||
case N_TTUPLE: {
|
||||
Type *t = newtype(c->a, TY_TUPLE);
|
||||
Tparam *head = NULL, *tail = NULL;
|
||||
u64 sz = 0, al = 1;
|
||||
for (Node *e = n->list; e; e = e->next) {
|
||||
Tparam *tp = amalloc(c->a, sizeof *tp);
|
||||
tp->type = resolve_type(c, e);
|
||||
if (tp->type && tp->type->align > al) al = tp->type->align;
|
||||
if (tp->type) sz += tp->type->size;
|
||||
if (head == NULL) head = tp;
|
||||
else tail->next = tp;
|
||||
tail = tp;
|
||||
}
|
||||
t->params = head;
|
||||
t->size = sz;
|
||||
t->align = al;
|
||||
return t;
|
||||
}
|
||||
case N_TTAGGED: {
|
||||
/* (T1 | T2 | ...) — tag (8B) followed by the largest variant. */
|
||||
Type *t = newtype(c->a, TY_TAGGED);
|
||||
Tparam *head = NULL, *tail = NULL;
|
||||
u64 maxsz = 0, al = 8;
|
||||
for (Node *e = n->list; e; e = e->next) {
|
||||
Tparam *tp = amalloc(c->a, sizeof *tp);
|
||||
tp->type = resolve_type(c, e);
|
||||
if (tp->type && tp->type->size > maxsz) maxsz = tp->type->size;
|
||||
if (tp->type && tp->type->align > al) al = tp->type->align;
|
||||
if (head == NULL) head = tp;
|
||||
else tail->next = tp;
|
||||
tail = tp;
|
||||
}
|
||||
t->params = head;
|
||||
t->size = 8 + maxsz;
|
||||
t->align = al;
|
||||
return t;
|
||||
}
|
||||
case N_TFN: {
|
||||
Type *t = newtype(c->a, TY_FN);
|
||||
t->ret = resolve_type(c, n->lhs);
|
||||
t->size = 8;
|
||||
t->align = 8;
|
||||
Tparam *head = NULL, *tail = NULL;
|
||||
for (Node *p = n->list; p; p = p->next) {
|
||||
if (strcmp(p->str ? p->str : "", "...") == 0) {
|
||||
t->variadic = 1;
|
||||
continue;
|
||||
}
|
||||
Tparam *tp = amalloc(c->a, sizeof *tp);
|
||||
tp->name = p->str;
|
||||
tp->type = resolve_type(c, p->lhs);
|
||||
if (head == NULL) head = tp;
|
||||
else tail->next = tp;
|
||||
tail = tp;
|
||||
}
|
||||
t->params = head;
|
||||
return t;
|
||||
}
|
||||
case N_TSTRUCT: {
|
||||
Type *t = newtype(c->a, TY_STRUCT);
|
||||
Tfield *head = NULL, *tail = NULL;
|
||||
u64 off = 0, maxalign = 1;
|
||||
for (Node *f = n->list; f; f = f->next) {
|
||||
Tfield *tf = amalloc(c->a, sizeof *tf);
|
||||
tf->name = f->str;
|
||||
tf->type = resolve_type(c, f->lhs);
|
||||
if (tf->type->align > maxalign) maxalign = tf->type->align;
|
||||
off = (off + tf->type->align - 1) & ~(tf->type->align - 1);
|
||||
tf->offset = off;
|
||||
off += tf->type->size;
|
||||
if (head == NULL) head = tf;
|
||||
else tail->next = tf;
|
||||
tail = tf;
|
||||
}
|
||||
t->fields = head;
|
||||
t->align = maxalign;
|
||||
t->size = (off + maxalign - 1) & ~(maxalign - 1);
|
||||
return t;
|
||||
}
|
||||
default:
|
||||
return err(c, n->pos, "expected type expression");
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- expressions -------------------------------------------------- */
|
||||
|
||||
static Type *
|
||||
unify_arith(Checker *c, Pos p, Type *a, Type *b)
|
||||
{
|
||||
if (a == ty_err || b == ty_err) return ty_err;
|
||||
/* untyped + untyped → untyped (prefer float over int) */
|
||||
if (type_isuntyped(a) && type_isuntyped(b)) {
|
||||
if (a->kind == TY_UNTYPED_FLOAT || b->kind == TY_UNTYPED_FLOAT)
|
||||
return ty_untyped_float;
|
||||
return ty_untyped_int;
|
||||
}
|
||||
/* untyped + typed → typed (if assignable) */
|
||||
if (type_isuntyped(a) && type_assignable(b, a)) return b;
|
||||
if (type_isuntyped(b) && type_assignable(a, b)) return a;
|
||||
if (type_eq(a, b)) return a;
|
||||
return err(c, p, "operands have differing types %s and %s",
|
||||
type_name(c->a, a), type_name(c->a, b));
|
||||
}
|
||||
|
||||
static Type *
|
||||
cbinop(Checker *c, Node *n)
|
||||
{
|
||||
Type *l = cexpr(c, n->lhs);
|
||||
Type *r = cexpr(c, n->rhs);
|
||||
switch (n->op) {
|
||||
case TK_PLUS: case TK_MINUS: case TK_STAR: case TK_SLASH:
|
||||
case TK_PERCENT:
|
||||
/* pointer arithmetic: ptr ± int → ptr; ptr - ptr → int */
|
||||
if ((n->op == TK_PLUS || n->op == TK_MINUS)
|
||||
&& l && l->kind == TY_PTR && type_isint(r))
|
||||
return l;
|
||||
if (n->op == TK_PLUS && type_isint(l) && r && r->kind == TY_PTR)
|
||||
return r;
|
||||
if (n->op == TK_MINUS && l && r && l->kind == TY_PTR
|
||||
&& r->kind == TY_PTR)
|
||||
return ty_i64;
|
||||
if (!type_isnum(l) || !type_isnum(r))
|
||||
return err(c, n->pos, "arithmetic on non-numeric type");
|
||||
return unify_arith(c, n->pos, l, r);
|
||||
case TK_AMP: case TK_PIPE: case TK_CARET: case TK_LSHIFT:
|
||||
case TK_RSHIFT:
|
||||
if (!type_isint(l) || !type_isint(r))
|
||||
return err(c, n->pos, "bitwise on non-integer type");
|
||||
return unify_arith(c, n->pos, l, r);
|
||||
case TK_EQ: case TK_NEQ:
|
||||
(void)unify_arith(c, n->pos, l, r);
|
||||
return ty_bool;
|
||||
case TK_LT: case TK_LE: case TK_GT: case TK_GE:
|
||||
if (!type_isnum(l) || !type_isnum(r))
|
||||
err(c, n->pos, "ordered comparison on non-numeric");
|
||||
(void)unify_arith(c, n->pos, l, r);
|
||||
return ty_bool;
|
||||
case TK_AND: case TK_OR:
|
||||
if (!(l == ty_bool || l == ty_untyped_bool || l == ty_err))
|
||||
err(c, n->pos, "left of %s is not bool", tokname(n->op));
|
||||
if (!(r == ty_bool || r == ty_untyped_bool || r == ty_err))
|
||||
err(c, n->pos, "right of %s is not bool", tokname(n->op));
|
||||
return ty_bool;
|
||||
default:
|
||||
return err(c, n->pos, "unsupported binary op %s", tokname(n->op));
|
||||
}
|
||||
}
|
||||
|
||||
static Type *
|
||||
cunop(Checker *c, Node *n)
|
||||
{
|
||||
Type *t = cexpr(c, n->lhs);
|
||||
switch (n->op) {
|
||||
case TK_MINUS: case TK_PLUS:
|
||||
if (!type_isnum(t))
|
||||
return err(c, n->pos, "%s on non-numeric", tokname(n->op));
|
||||
return t;
|
||||
case TK_NOT:
|
||||
if (!(t == ty_bool || t == ty_untyped_bool || t == ty_err))
|
||||
err(c, n->pos, "! on non-bool");
|
||||
return ty_bool;
|
||||
case TK_TILDE:
|
||||
if (!type_isint(t))
|
||||
return err(c, n->pos, "~ on non-integer");
|
||||
return t;
|
||||
case TK_STAR: /* deref */
|
||||
if (t == ty_err) return ty_err;
|
||||
if (t->kind != TY_PTR)
|
||||
return err(c, n->pos, "cannot deref non-pointer %s",
|
||||
type_name(c->a, t));
|
||||
return t->sub;
|
||||
case TK_AMP: /* address-of */
|
||||
return type_ptr(c->a, t);
|
||||
default:
|
||||
return err(c, n->pos, "unsupported unary %s", tokname(n->op));
|
||||
}
|
||||
}
|
||||
|
||||
static Type *
|
||||
cexpr(Checker *c, Node *n)
|
||||
{
|
||||
if (n == NULL) return ty_err;
|
||||
switch (n->kind) {
|
||||
case N_INTLIT:
|
||||
if (n->tsuffix) {
|
||||
Type *t = lookup_builtin(n->tsuffix);
|
||||
n->type = t ? t : ty_untyped_int;
|
||||
} else {
|
||||
n->type = ty_untyped_int;
|
||||
}
|
||||
return n->type;
|
||||
case N_FLOATLIT:
|
||||
if (n->tsuffix) {
|
||||
Type *t = lookup_builtin(n->tsuffix);
|
||||
n->type = t ? t : ty_untyped_float;
|
||||
} else {
|
||||
n->type = ty_untyped_float;
|
||||
}
|
||||
return n->type;
|
||||
case N_STRLIT: n->type = ty_untyped_str; return n->type;
|
||||
case N_RUNELIT: n->type = ty_untyped_rune; return n->type;
|
||||
case N_TRUE:
|
||||
case N_FALSE: n->type = ty_untyped_bool; return n->type;
|
||||
case N_NIL: n->type = ty_untyped_nil; return n->type;
|
||||
case N_IDENT: {
|
||||
Sym *s = scope_lookup(c->cur, n->str);
|
||||
if (s == NULL)
|
||||
return n->type = err(c, n->pos, "undefined: %s", n->str);
|
||||
/* SK_USE has no concrete value type; the only legal use is
|
||||
* as the lhs of a DOT (module-qualified ref). Surface ty_err
|
||||
* here; the DOT case below resolves the qualified symbol. */
|
||||
if (s->kind == SK_USE)
|
||||
return n->type = ty_err;
|
||||
n->type = s->type;
|
||||
return s->type;
|
||||
}
|
||||
case N_PARAM:
|
||||
return n->type = ty_err; /* shouldn't appear in expr ctx */
|
||||
case N_BIN: n->type = cbinop(c, n); return n->type;
|
||||
case N_UN: n->type = cunop(c, n); return n->type;
|
||||
case N_CAST: {
|
||||
(void)cexpr(c, n->lhs);
|
||||
n->type = resolve_type(c, n->rhs);
|
||||
return n->type;
|
||||
}
|
||||
case N_DOT: {
|
||||
/* module-qualified: lhs is an N_IDENT bound as SK_USE.
|
||||
* Resolve to the symbol with the same leaf name. With
|
||||
* driver-side concatenation, all symbols live in flat
|
||||
* scope, so we lookup `n->str` directly. */
|
||||
if (n->lhs && n->lhs->kind == N_IDENT) {
|
||||
Sym *ms = scope_lookup(c->cur, n->lhs->str);
|
||||
if (ms && ms->kind == SK_USE) {
|
||||
Sym *fs = scope_lookup(c->cur, n->str);
|
||||
if (fs)
|
||||
return n->type = fs->type;
|
||||
/* Leaf isn't in scope here — treat as an
|
||||
* external declaration. The codegen will
|
||||
* still emit CALL/MOVQ by the leaf name; the
|
||||
* linker fails if the symbol is truly
|
||||
* missing. */
|
||||
return n->type = ty_err;
|
||||
}
|
||||
}
|
||||
Type *base = cexpr(c, n->lhs);
|
||||
if (base == NULL || base == ty_err) return n->type = ty_err;
|
||||
Type *u = (base->kind == TY_NAMED) ? base->under : base;
|
||||
if (u && u->kind == TY_PTR) u = u->sub;
|
||||
if (u && u->kind == TY_NAMED) u = u->under;
|
||||
/* built-in pseudo-fields on slice/str/array: .len, .cap, .ptr */
|
||||
if (u && (u->kind == TY_SLICE || u->kind == TY_ARRAY ||
|
||||
u->kind == TY_STR)) {
|
||||
if (strcmp(n->str, "len") == 0) return n->type = ty_i32;
|
||||
if (strcmp(n->str, "cap") == 0) return n->type = ty_i32;
|
||||
if (strcmp(n->str, "ptr") == 0) {
|
||||
Type *elem = (u->kind == TY_STR) ? ty_u8 : u->sub;
|
||||
return n->type = type_ptr(c->a, elem);
|
||||
}
|
||||
}
|
||||
if (u && u->kind == TY_STRUCT) {
|
||||
for (Tfield *f = u->fields; f; f = f->next)
|
||||
if (strcmp(f->name, n->str) == 0)
|
||||
return n->type = f->type;
|
||||
return n->type = err(c, n->pos, "no field '%s' in %s",
|
||||
n->str, type_name(c->a, base));
|
||||
}
|
||||
/* tuple positional access: t.0, t.1, ... */
|
||||
if (u && u->kind == TY_TUPLE && n->str) {
|
||||
int idx = 0;
|
||||
for (const char *q = n->str; *q; q++) {
|
||||
if (*q < '0' || *q > '9') { idx = -1; break; }
|
||||
idx = idx * 10 + (*q - '0');
|
||||
}
|
||||
if (idx < 0)
|
||||
return n->type = err(c, n->pos,
|
||||
"tuple field must be numeric");
|
||||
Tparam *tp = u->params;
|
||||
while (idx > 0 && tp) { tp = tp->next; idx--; }
|
||||
if (tp == NULL)
|
||||
return n->type = err(c, n->pos,
|
||||
"tuple index out of range");
|
||||
return n->type = tp->type;
|
||||
}
|
||||
/* module-qualified: lhs is IDENT bound as SK_USE */
|
||||
return n->type = ty_err;
|
||||
}
|
||||
case N_INDEX: {
|
||||
Type *base = cexpr(c, n->lhs);
|
||||
Type *idx = cexpr(c, n->rhs);
|
||||
if (idx != ty_err && !type_isint(idx))
|
||||
err(c, n->pos, "index must be integer");
|
||||
if (base == ty_err) return n->type = ty_err;
|
||||
Type *u = (base->kind == TY_NAMED) ? base->under : base;
|
||||
if (u && (u->kind == TY_SLICE || u->kind == TY_ARRAY))
|
||||
return n->type = u->sub;
|
||||
if (u && u->kind == TY_STR)
|
||||
return n->type = ty_u8;
|
||||
if (u && u->kind == TY_PTR && u->sub &&
|
||||
(u->sub->kind == TY_ARRAY || u->sub->kind == TY_SLICE))
|
||||
return n->type = u->sub->sub;
|
||||
/* C-style pointer indexing: p[i] → *(p+i) */
|
||||
if (u && u->kind == TY_PTR && u->sub)
|
||||
return n->type = u->sub;
|
||||
return n->type = err(c, n->pos, "indexing non-indexable %s",
|
||||
type_name(c->a, base));
|
||||
}
|
||||
case N_CALL: {
|
||||
/* Hare-style builtins: len(x), append(s, v), alloc(...).
|
||||
* Recognised by name with no scope binding; we type-check
|
||||
* the args ourselves and skip the normal call resolution. */
|
||||
if (n->lhs && n->lhs->kind == N_IDENT &&
|
||||
n->lhs->str && strcmp(n->lhs->str, "len") == 0 &&
|
||||
n->list != NULL && n->list->next == NULL) {
|
||||
(void)cexpr(c, n->list);
|
||||
n->type = ty_i32;
|
||||
n->lhs->type = ty_err; /* mark builtin: no real symbol */
|
||||
return n->type;
|
||||
}
|
||||
if (n->lhs && n->lhs->kind == N_IDENT &&
|
||||
n->lhs->str && strcmp(n->lhs->str, "append") == 0 &&
|
||||
n->list != NULL && n->list->next != NULL) {
|
||||
for (Node *a = n->list; a; a = a->next)
|
||||
(void)cexpr(c, a);
|
||||
n->type = ty_void;
|
||||
n->lhs->type = ty_err;
|
||||
return n->type;
|
||||
}
|
||||
if (n->lhs && n->lhs->kind == N_IDENT &&
|
||||
n->lhs->str && strcmp(n->lhs->str, "alloc") == 0 &&
|
||||
n->list != NULL && n->list->next == NULL) {
|
||||
Type *t = cexpr(c, n->list);
|
||||
Type *def = type_default(t);
|
||||
n->type = type_ptr(c->a, def ? def : ty_void);
|
||||
n->lhs->type = ty_err;
|
||||
return n->type;
|
||||
}
|
||||
if (n->lhs && n->lhs->kind == N_IDENT &&
|
||||
n->lhs->str && strcmp(n->lhs->str, "free") == 0 &&
|
||||
n->list != NULL && n->list->next == NULL) {
|
||||
(void)cexpr(c, n->list);
|
||||
n->type = ty_void;
|
||||
n->lhs->type = ty_err;
|
||||
return n->type;
|
||||
}
|
||||
/* alloc([], n) — Hare-style fresh slice with cap n. We pin
|
||||
* the element type to u8 by default; the caller's declared
|
||||
* slice type drives the actual element size at codegen. */
|
||||
if (n->lhs && n->lhs->kind == N_IDENT &&
|
||||
n->lhs->str && strcmp(n->lhs->str, "alloc") == 0 &&
|
||||
n->list && n->list->kind == N_ARRLIT &&
|
||||
n->list->list == NULL &&
|
||||
n->list->next && n->list->next->next == NULL) {
|
||||
(void)cexpr(c, n->list->next);
|
||||
n->type = type_slice(c->a, ty_u8);
|
||||
n->lhs->type = ty_err;
|
||||
return n->type;
|
||||
}
|
||||
Type *ft = cexpr(c, n->lhs);
|
||||
if (ft == ty_err) {
|
||||
/* Walk args anyway so cgen sees real types. The
|
||||
* common case is a module-qualified call whose leaf
|
||||
* isn't in this scope (raw 6c on a single file with
|
||||
* `use mod;` but no driver concatenation). */
|
||||
for (Node *a = n->list; a; a = a->next)
|
||||
(void)cexpr(c, a);
|
||||
return n->type = ty_err;
|
||||
}
|
||||
Type *u = (ft->kind == TY_NAMED) ? ft->under : ft;
|
||||
if (u == NULL || u->kind != TY_FN)
|
||||
return n->type = err(c, n->pos, "calling non-function %s",
|
||||
type_name(c->a, ft));
|
||||
Tparam *p = u->params;
|
||||
for (Node *a = n->list; a; a = a->next) {
|
||||
Type *at = cexpr(c, a);
|
||||
if (p == NULL) {
|
||||
if (!u->variadic)
|
||||
err(c, n->pos, "too many arguments");
|
||||
continue;
|
||||
}
|
||||
if (!type_assignable(p->type, at) && at != ty_err && p->type != ty_err)
|
||||
err(c, a->pos, "argument type %s not assignable to %s",
|
||||
type_name(c->a, at), type_name(c->a, p->type));
|
||||
p = p->next;
|
||||
}
|
||||
if (p != NULL)
|
||||
err(c, n->pos, "not enough arguments");
|
||||
return n->type = u->ret ? u->ret : ty_void;
|
||||
}
|
||||
case N_ASSIGN: {
|
||||
Type *l = cexpr(c, n->lhs);
|
||||
Type *r = cexpr(c, n->rhs);
|
||||
if (l != ty_err && r != ty_err && !type_assignable(l, r))
|
||||
err(c, n->pos, "cannot assign %s to %s",
|
||||
type_name(c->a, r), type_name(c->a, l));
|
||||
return n->type = l;
|
||||
}
|
||||
case N_STRUCTLIT: {
|
||||
/* lhs may be an N_IDENT (the bare type name) or a real type
|
||||
* expression. Resolve via name lookup first; fall back to
|
||||
* resolve_type for the synthetic-type-expr case. */
|
||||
Type *t = NULL;
|
||||
if (n->lhs && n->lhs->kind == N_IDENT) {
|
||||
Sym *s = scope_lookup(c->cur, n->lhs->str);
|
||||
if (s == NULL || s->kind != SK_TYPE)
|
||||
t = err(c, n->pos, "unknown struct type '%s'",
|
||||
n->lhs->str);
|
||||
else
|
||||
t = s->type;
|
||||
} else {
|
||||
t = resolve_type(c, n->lhs);
|
||||
}
|
||||
Type *u = (t && t->kind == TY_NAMED) ? t->under : t;
|
||||
for (Node *f = n->list; f; f = f->next) {
|
||||
Type *vt = cexpr(c, f->lhs);
|
||||
if (u && u->kind == TY_STRUCT) {
|
||||
Tfield *match = NULL;
|
||||
for (Tfield *fl = u->fields; fl; fl = fl->next)
|
||||
if (strcmp(fl->name, f->str) == 0) {
|
||||
match = fl; break;
|
||||
}
|
||||
if (match == NULL)
|
||||
err(c, f->pos, "no field '%s' in %s",
|
||||
f->str, type_name(c->a, t));
|
||||
else if (vt != ty_err &&
|
||||
!type_assignable(match->type, vt))
|
||||
err(c, f->pos, "field %s: %s not assignable to %s",
|
||||
f->str, type_name(c->a, vt),
|
||||
type_name(c->a, match->type));
|
||||
}
|
||||
}
|
||||
return n->type = t;
|
||||
}
|
||||
case N_ARRLIT: {
|
||||
Type *elt = NULL;
|
||||
u64 count = 0;
|
||||
for (Node *e = n->list; e; e = e->next) {
|
||||
if (e->kind == N_FIELD && e->str &&
|
||||
strcmp(e->str, "...") == 0)
|
||||
continue;
|
||||
Type *t = cexpr(c, e);
|
||||
if (elt == NULL) elt = type_default(t);
|
||||
count++;
|
||||
}
|
||||
if (elt == NULL) elt = ty_i32;
|
||||
return n->type = type_array(c->a, elt, count);
|
||||
}
|
||||
case N_SPREAD:
|
||||
return n->type = cexpr(c, n->lhs);
|
||||
case N_SLICE: {
|
||||
Type *base = cexpr(c, n->lhs);
|
||||
if (n->rhs) (void)cexpr(c, n->rhs);
|
||||
if (n->cond) (void)cexpr(c, n->cond);
|
||||
Type *u = (base && base->kind == TY_NAMED) ? base->under : base;
|
||||
if (u && u->kind == TY_ARRAY)
|
||||
return n->type = type_slice(c->a, u->sub);
|
||||
if (u && u->kind == TY_SLICE)
|
||||
return n->type = base;
|
||||
if (u && u->kind == TY_STR)
|
||||
return n->type = ty_str;
|
||||
if (u && u->kind == TY_PTR && u->sub)
|
||||
return n->type = type_slice(c->a, u->sub);
|
||||
return n->type = err(c, n->pos, "cannot slice %s",
|
||||
type_name(c->a, base));
|
||||
}
|
||||
case N_RECV: {
|
||||
Type *t = cexpr(c, n->lhs);
|
||||
Type *u = (t && t->kind == TY_NAMED) ? t->under : t;
|
||||
if (u && u->kind == TY_CHAN) return n->type = u->sub;
|
||||
return n->type = err(c, n->pos, "<- expects chan, got %s",
|
||||
type_name(c->a, t));
|
||||
}
|
||||
case N_MATCH: {
|
||||
Type *st = cexpr(c, n->lhs);
|
||||
Type *u = (st && st->kind == TY_NAMED) ? st->under : st;
|
||||
if (u == NULL || u->kind != TY_TAGGED) {
|
||||
return n->type = err(c, n->pos,
|
||||
"match on non-tagged-union %s", type_name(c->a, st));
|
||||
}
|
||||
for (Node *cs = n->list; cs; cs = cs->next) {
|
||||
Scope *saved = c->cur;
|
||||
c->cur = newscope(c->a, saved);
|
||||
/* Resolve the case pattern's type so codegen can map it
|
||||
* to the variant tag. Both `case T =>` and `case let v: T
|
||||
* =>` get this — `case =>` (default) leaves cs->type NULL.
|
||||
* For multi-pattern `case T1 | T2 =>` each alternative in
|
||||
* cs->list also gets its type resolved in place. */
|
||||
if (cs->lhs) {
|
||||
Type *vt = resolve_type(c, cs->lhs);
|
||||
cs->type = vt;
|
||||
for (Node *alt = cs->list; alt; alt = alt->next)
|
||||
alt->type = resolve_type(c, alt);
|
||||
if (cs->str && cs->str[0])
|
||||
scope_define(c->cur, cs->str, SK_VAR, vt, cs);
|
||||
}
|
||||
cstmt(c, cs->body);
|
||||
c->cur = saved;
|
||||
}
|
||||
n->type = ty_void;
|
||||
return n->type;
|
||||
}
|
||||
case N_TRYPROP: case N_TRYUNW: {
|
||||
Type *t = cexpr(c, n->lhs);
|
||||
Type *u = (t && t->kind == TY_NAMED) ? t->under : t;
|
||||
if (u == NULL || u->kind != TY_TAGGED) {
|
||||
return n->type = err(c, n->pos,
|
||||
"%s on non-tagged-union %s",
|
||||
n->kind == N_TRYPROP ? "?" : "!",
|
||||
type_name(c->a, t));
|
||||
}
|
||||
/* Convention: first variant is the success type. */
|
||||
Tparam *first = u->params;
|
||||
return n->type = first ? first->type : ty_err;
|
||||
}
|
||||
case N_TUPLE: {
|
||||
/* keep untyped element types; assignability is checked
|
||||
* element-wise at the consumer (return / mlet / massign). */
|
||||
Type *t = newtype(c->a, TY_TUPLE);
|
||||
Tparam *head = NULL, *tail = NULL;
|
||||
for (Node *e = n->list; e; e = e->next) {
|
||||
Tparam *tp = amalloc(c->a, sizeof *tp);
|
||||
tp->type = cexpr(c, e);
|
||||
if (head == NULL) head = tp;
|
||||
else tail->next = tp;
|
||||
tail = tp;
|
||||
}
|
||||
t->params = head;
|
||||
return n->type = t;
|
||||
}
|
||||
default:
|
||||
return n->type = err(c, n->pos, "internal: unhandled expr kind %d",
|
||||
n->kind);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- statements --------------------------------------------------- */
|
||||
|
||||
static void
|
||||
clet(Checker *c, Node *n)
|
||||
{
|
||||
Type *declared = n->lhs ? resolve_type(c, n->lhs) : NULL;
|
||||
Type *initt = NULL;
|
||||
if (n->rhs) initt = cexpr(c, n->rhs);
|
||||
Type *t = declared;
|
||||
if (t == NULL && initt) t = type_default(initt);
|
||||
if (t == NULL) {
|
||||
err(c, n->pos, "let needs a type or initialiser");
|
||||
t = ty_err;
|
||||
}
|
||||
if (declared && initt && initt != ty_err &&
|
||||
!type_assignable(declared, initt))
|
||||
err(c, n->pos, "init %s not assignable to declared %s",
|
||||
type_name(c->a, initt), type_name(c->a, declared));
|
||||
n->type = t;
|
||||
if (n->str && n->str[0])
|
||||
scope_define(c->cur, n->str, SK_VAR, t, n);
|
||||
}
|
||||
|
||||
static void
|
||||
cstmt(Checker *c, Node *n)
|
||||
{
|
||||
if (n == NULL) return;
|
||||
switch (n->kind) {
|
||||
case N_BLOCK: {
|
||||
Scope *saved = c->cur;
|
||||
c->cur = newscope(c->a, saved);
|
||||
for (Node *s = n->list; s; s = s->next)
|
||||
cstmt(c, s);
|
||||
c->cur = saved;
|
||||
break;
|
||||
}
|
||||
case N_EXPRSTMT: (void)cexpr(c, n->lhs); break;
|
||||
case N_LET: clet(c, n); break;
|
||||
case N_RETURN: {
|
||||
Type *rt = n->lhs ? cexpr(c, n->lhs) : ty_void;
|
||||
if (c->ret == NULL) {
|
||||
err(c, n->pos, "return outside function");
|
||||
break;
|
||||
}
|
||||
if (c->ret == ty_void && n->lhs)
|
||||
err(c, n->pos, "return value in void function");
|
||||
else if (c->ret != ty_void && rt != ty_err && c->ret != ty_err
|
||||
&& !type_assignable(c->ret, rt))
|
||||
err(c, n->pos, "return %s not assignable to %s",
|
||||
type_name(c->a, rt), type_name(c->a, c->ret));
|
||||
break;
|
||||
}
|
||||
case N_IF: {
|
||||
Type *ct = cexpr(c, n->cond);
|
||||
if (ct != ty_err && ct != ty_bool && ct != ty_untyped_bool)
|
||||
err(c, n->pos, "if condition must be bool, got %s",
|
||||
type_name(c->a, ct));
|
||||
cstmt(c, n->body);
|
||||
cstmt(c, n->els);
|
||||
break;
|
||||
}
|
||||
case N_FORRANGE: {
|
||||
Scope *saved = c->cur;
|
||||
c->cur = newscope(c->a, saved);
|
||||
c->loops++;
|
||||
Type *st = cexpr(c, n->lhs);
|
||||
Type *u = (st && st->kind == TY_NAMED) ? st->under : st;
|
||||
Type *elem = NULL;
|
||||
if (u && (u->kind == TY_SLICE || u->kind == TY_ARRAY)) elem = u->sub;
|
||||
else if (u && u->kind == TY_STR) elem = ty_u8;
|
||||
else err(c, n->pos, "for-range needs slice/array/str");
|
||||
if (n->list != NULL) {
|
||||
/* tuple destructure: each name binds to a tuple field */
|
||||
Type *etu = (elem && elem->kind == TY_NAMED) ? elem->under : elem;
|
||||
Tparam *tp = (etu && etu->kind == TY_TUPLE) ? etu->params : NULL;
|
||||
for (Node *nm = n->list; nm; nm = nm->next) {
|
||||
Type *ft = tp ? tp->type : ty_err;
|
||||
if (nm->str && nm->str[0])
|
||||
scope_define(c->cur, nm->str,
|
||||
SK_VAR, ft, nm);
|
||||
if (tp) tp = tp->next;
|
||||
}
|
||||
} else if (n->str && n->str[0]) {
|
||||
scope_define(c->cur, n->str, SK_VAR,
|
||||
elem ? elem : ty_err, n);
|
||||
}
|
||||
cstmt(c, n->body);
|
||||
c->loops--;
|
||||
c->cur = saved;
|
||||
break;
|
||||
}
|
||||
case N_FOR: {
|
||||
Scope *saved = c->cur;
|
||||
c->cur = newscope(c->a, saved);
|
||||
c->loops++;
|
||||
if (n->lhs) cstmt(c, n->lhs); /* init may be a let or expr */
|
||||
if (n->cond) {
|
||||
Type *ct = cexpr(c, n->cond);
|
||||
if (ct != ty_err && ct != ty_bool && ct != ty_untyped_bool)
|
||||
err(c, n->pos, "for condition must be bool, got %s",
|
||||
type_name(c->a, ct));
|
||||
}
|
||||
if (n->rhs) (void)cexpr(c, n->rhs);
|
||||
cstmt(c, n->body);
|
||||
c->loops--;
|
||||
c->cur = saved;
|
||||
break;
|
||||
}
|
||||
case N_MLET: {
|
||||
Type *rt = cexpr(c, n->rhs);
|
||||
Type *u = (rt && rt->kind == TY_TUPLE) ? rt : NULL;
|
||||
if (u == NULL) {
|
||||
err(c, n->pos, "multi-let rhs is not a tuple (got %s)",
|
||||
type_name(c->a, rt));
|
||||
}
|
||||
Tparam *tp = u ? u->params : NULL;
|
||||
for (Node *l = n->list; l; l = l->next) {
|
||||
Type *declared = l->lhs ? resolve_type(c, l->lhs) : NULL;
|
||||
Type *elem = tp ? tp->type : NULL;
|
||||
Type *t = declared ? declared :
|
||||
(elem ? type_default(elem) : ty_err);
|
||||
if (declared && elem && !type_assignable(declared, elem))
|
||||
err(c, l->pos, "let %s: %s not assignable from %s",
|
||||
l->str, type_name(c->a, elem),
|
||||
type_name(c->a, declared));
|
||||
l->type = t;
|
||||
if (l->str && l->str[0])
|
||||
scope_define(c->cur, l->str, SK_VAR, t, l);
|
||||
if (tp) tp = tp->next;
|
||||
}
|
||||
if (u && tp != NULL)
|
||||
err(c, n->pos, "tuple has extra elements");
|
||||
break;
|
||||
}
|
||||
case N_MASSIGN: {
|
||||
Type *rt = cexpr(c, n->rhs);
|
||||
Type *u = (rt && rt->kind == TY_TUPLE) ? rt : NULL;
|
||||
if (u == NULL) {
|
||||
err(c, n->pos, "multi-assign rhs is not a tuple (got %s)",
|
||||
type_name(c->a, rt));
|
||||
}
|
||||
Tparam *tp = u ? u->params : NULL;
|
||||
for (Node *lv = n->list; lv; lv = lv->next) {
|
||||
Type *lt = cexpr(c, lv);
|
||||
Type *elem = tp ? tp->type : NULL;
|
||||
if (lt && elem && !type_assignable(lt, elem))
|
||||
err(c, lv->pos, "cannot assign %s to %s",
|
||||
type_name(c->a, elem), type_name(c->a, lt));
|
||||
if (tp) tp = tp->next;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case N_DEFER: (void)cexpr(c, n->lhs); break;
|
||||
case N_BREAK:
|
||||
case N_CONTINUE:
|
||||
if (c->loops == 0)
|
||||
err(c, n->pos, "%s outside loop",
|
||||
n->kind == N_BREAK ? "break" : "continue");
|
||||
break;
|
||||
case N_SWITCH: {
|
||||
Type *st = cexpr(c, n->lhs);
|
||||
(void)st;
|
||||
for (Node *cs = n->list; cs; cs = cs->next) {
|
||||
for (Node *e = cs->list; e; e = e->next)
|
||||
(void)cexpr(c, e);
|
||||
cstmt(c, cs->body);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
err(c, n->pos, "internal: unhandled stmt kind %d", n->kind);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- top-level ---------------------------------------------------- */
|
||||
|
||||
static Type *
|
||||
build_fn_type(Checker *c, Node *fn)
|
||||
{
|
||||
Type *t = newtype(c->a, TY_FN);
|
||||
t->size = 8; t->align = 8;
|
||||
t->ret = fn->lhs ? resolve_type(c, fn->lhs) : ty_void;
|
||||
Tparam *head = NULL, *tail = NULL;
|
||||
for (Node *p = fn->list; p; p = p->next) {
|
||||
if (p->str && strcmp(p->str, "...") == 0) {
|
||||
t->variadic = 1;
|
||||
continue;
|
||||
}
|
||||
Tparam *tp = amalloc(c->a, sizeof *tp);
|
||||
tp->name = p->str;
|
||||
tp->type = resolve_type(c, p->lhs);
|
||||
if (head == NULL) head = tp;
|
||||
else tail->next = tp;
|
||||
tail = tp;
|
||||
}
|
||||
t->params = head;
|
||||
return t;
|
||||
}
|
||||
|
||||
void
|
||||
check_init(Checker *c, Arena *a)
|
||||
{
|
||||
memset(c, 0, sizeof *c);
|
||||
c->a = a;
|
||||
typesinit(a);
|
||||
c->top = newscope(a, NULL);
|
||||
c->cur = c->top;
|
||||
}
|
||||
|
||||
void
|
||||
check_file(Checker *c, Node *file)
|
||||
{
|
||||
if (file == NULL || file->kind != N_FILE) return;
|
||||
|
||||
/* pass 1: install names (types first, then defs/fns).
|
||||
* For self-referential types we install the named-type placeholder
|
||||
* BEFORE resolving its body; the body may legitimately mention
|
||||
* the type itself (`type stream = struct { read: fn(*stream)... }`).
|
||||
*/
|
||||
for (Node *d = file->list; d; d = d->next) {
|
||||
if (d->kind != N_TYPEDECL) continue;
|
||||
Type *named = type_named(c->a, d->str, NULL);
|
||||
if (!scope_define(c->cur, d->str, SK_TYPE, named, d))
|
||||
err(c, d->pos, "duplicate type %s", d->str);
|
||||
d->type = named;
|
||||
}
|
||||
for (Node *d = file->list; d; d = d->next) {
|
||||
if (d->kind != N_TYPEDECL) continue;
|
||||
Type *under = resolve_type(c, d->lhs);
|
||||
d->type->under = under;
|
||||
if (under) {
|
||||
d->type->size = under->size;
|
||||
d->type->align = under->align;
|
||||
}
|
||||
}
|
||||
for (Node *d = file->list; d; d = d->next) {
|
||||
switch (d->kind) {
|
||||
case N_USE:
|
||||
scope_define(c->cur, d->str, SK_USE, NULL, d);
|
||||
break;
|
||||
case N_DEF: {
|
||||
Type *t = resolve_type(c, d->lhs);
|
||||
d->type = t;
|
||||
if (!scope_define(c->cur, d->str, SK_DEF, t, d))
|
||||
err(c, d->pos, "duplicate def %s", d->str);
|
||||
break;
|
||||
}
|
||||
case N_FNDECL: {
|
||||
Type *t = build_fn_type(c, d);
|
||||
d->type = t;
|
||||
if (!scope_define(c->cur, d->str, SK_FN, t, d))
|
||||
err(c, d->pos, "duplicate fn %s", d->str);
|
||||
break;
|
||||
}
|
||||
case N_LET: {
|
||||
Type *t = d->lhs ? resolve_type(c, d->lhs) : NULL;
|
||||
d->type = t;
|
||||
if (d->str && d->str[0])
|
||||
scope_define(c->cur, d->str, SK_VAR, t, d);
|
||||
break;
|
||||
}
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
/* pass 2: check def initialisers and fn bodies */
|
||||
for (Node *d = file->list; d; d = d->next) {
|
||||
switch (d->kind) {
|
||||
case N_DEF: {
|
||||
if (d->rhs) {
|
||||
Type *rt = cexpr(c, d->rhs);
|
||||
if (d->type && rt != ty_err && d->type != ty_err
|
||||
&& !type_assignable(d->type, rt))
|
||||
err(c, d->pos, "def %s init %s not assignable to %s",
|
||||
d->str, type_name(c->a, rt),
|
||||
type_name(c->a, d->type));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case N_FNDECL: {
|
||||
if (d->body == NULL) break; /* extern decl */
|
||||
Scope *saved = c->cur;
|
||||
c->cur = newscope(c->a, saved);
|
||||
Type *fnt = d->type;
|
||||
for (Tparam *p = fnt->params; p; p = p->next) {
|
||||
if (p->name && p->name[0])
|
||||
scope_define(c->cur, p->name, SK_PARAM, p->type, d);
|
||||
}
|
||||
Type *prev = c->ret;
|
||||
c->ret = fnt->ret;
|
||||
cstmt(c, d->body);
|
||||
c->ret = prev;
|
||||
c->cur = saved;
|
||||
break;
|
||||
}
|
||||
case N_LET: {
|
||||
if (d->rhs) {
|
||||
Type *rt = cexpr(c, d->rhs);
|
||||
if (d->type == NULL) d->type = type_default(rt);
|
||||
if (d->type && rt != ty_err && d->type != ty_err
|
||||
&& !type_assignable(d->type, rt))
|
||||
err(c, d->pos, "let %s init not assignable",
|
||||
d->str);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
}
|
||||
76
cmd/wwc/err.c
Normal file
76
cmd/wwc/err.c
Normal file
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* err.c — diagnostics.
|
||||
*
|
||||
* fatal prints, sets exit(1).
|
||||
* errorf prints with source location, increments nerrors.
|
||||
* warnf prints with source location, increments nwarnings.
|
||||
*
|
||||
* Plan 9 style: short, no levels beyond fatal/error/warn, no colour.
|
||||
*/
|
||||
#include "ww.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
Pos noPos = { "<none>", 0, 0 };
|
||||
int nerrors;
|
||||
int nwarnings;
|
||||
FILE *errout; /* set by main; defaults to stderr */
|
||||
|
||||
static FILE *
|
||||
out(void)
|
||||
{
|
||||
return errout ? errout : stderr;
|
||||
}
|
||||
|
||||
static void
|
||||
prefix(Pos p)
|
||||
{
|
||||
FILE *f = out();
|
||||
if (p.file == NULL)
|
||||
p = noPos;
|
||||
if (p.line > 0)
|
||||
fprintf(f, "%s:%d:%d: ", p.file, p.line, p.col);
|
||||
else
|
||||
fprintf(f, "%s: ", p.file);
|
||||
}
|
||||
|
||||
void
|
||||
fatal(const char *fmt, ...)
|
||||
{
|
||||
FILE *f = out();
|
||||
va_list ap;
|
||||
fprintf(f, "ww: ");
|
||||
va_start(ap, fmt);
|
||||
vfprintf(f, fmt, ap);
|
||||
va_end(ap);
|
||||
fprintf(f, "\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
void
|
||||
errorf(Pos p, const char *fmt, ...)
|
||||
{
|
||||
FILE *f = out();
|
||||
va_list ap;
|
||||
prefix(p);
|
||||
fprintf(f, "error: ");
|
||||
va_start(ap, fmt);
|
||||
vfprintf(f, fmt, ap);
|
||||
va_end(ap);
|
||||
fprintf(f, "\n");
|
||||
nerrors++;
|
||||
}
|
||||
|
||||
void
|
||||
warnf(Pos p, const char *fmt, ...)
|
||||
{
|
||||
FILE *f = out();
|
||||
va_list ap;
|
||||
prefix(p);
|
||||
fprintf(f, "warning: ");
|
||||
va_start(ap, fmt);
|
||||
vfprintf(f, fmt, ap);
|
||||
va_end(ap);
|
||||
fprintf(f, "\n");
|
||||
nwarnings++;
|
||||
}
|
||||
476
cmd/wwc/lex.c
Normal file
476
cmd/wwc/lex.c
Normal file
@@ -0,0 +1,476 @@
|
||||
/*
|
||||
* lex.c — hand-rolled DFA. UTF-8 source, ASCII operators.
|
||||
*
|
||||
* Comments: //... and (slash-star ... star-slash). Both stripped.
|
||||
* Whitespace: space, tab, CR, NL.
|
||||
* Identifiers: [A-Za-z_][A-Za-z0-9_]* — also matches keywords; we
|
||||
* look up the kw table after lexing the run.
|
||||
* Integer: 0x[0-9a-fA-F_]+, 0o[0-7_]+, 0b[01_]+, [0-9][0-9_]*
|
||||
* Float: [0-9]+'.'[0-9]+([eE][+-]?[0-9]+)?
|
||||
* Rune: 'x' with C-like escapes
|
||||
* String: "..." with C-like escapes
|
||||
* Operators: longest match.
|
||||
*
|
||||
* No automatic semicolon insertion (Hare rule). The lexer only emits
|
||||
* what is in the source; the parser is responsible for non-empty rules.
|
||||
*/
|
||||
#include "ww.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
|
||||
void
|
||||
lexinit(Lex *l, Arena *a, const char *file, const char *src, u64 len)
|
||||
{
|
||||
memset(l, 0, sizeof *l);
|
||||
l->file = file;
|
||||
l->src = src;
|
||||
l->srclen = len;
|
||||
l->line = 1;
|
||||
l->col = 1;
|
||||
l->a = a;
|
||||
}
|
||||
|
||||
static int
|
||||
lpeek(Lex *l, u64 ahead)
|
||||
{
|
||||
u64 p = l->pos + ahead;
|
||||
if (p >= l->srclen)
|
||||
return -1;
|
||||
return (unsigned char)l->src[p];
|
||||
}
|
||||
|
||||
static int
|
||||
lget(Lex *l)
|
||||
{
|
||||
if (l->pos >= l->srclen)
|
||||
return -1;
|
||||
int c = (unsigned char)l->src[l->pos++];
|
||||
if (c == '\n') {
|
||||
l->line++;
|
||||
l->col = 1;
|
||||
} else {
|
||||
l->col++;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
static Pos
|
||||
lpos(Lex *l)
|
||||
{
|
||||
Pos p = { l->file, l->line, l->col };
|
||||
return p;
|
||||
}
|
||||
|
||||
static int
|
||||
isidstart(int c)
|
||||
{
|
||||
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
|
||||
}
|
||||
|
||||
static int
|
||||
isidcont(int c)
|
||||
{
|
||||
return isidstart(c) || (c >= '0' && c <= '9');
|
||||
}
|
||||
|
||||
static int
|
||||
ishex(int c)
|
||||
{
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
|
||||
(c >= 'A' && c <= 'F');
|
||||
}
|
||||
|
||||
/* skip whitespace and comments. returns 0 on EOF, else 1. */
|
||||
static int
|
||||
skipws(Lex *l)
|
||||
{
|
||||
for (;;) {
|
||||
int c = lpeek(l, 0);
|
||||
if (c < 0)
|
||||
return 0;
|
||||
if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
|
||||
lget(l);
|
||||
continue;
|
||||
}
|
||||
if (c == '/' && lpeek(l, 1) == '/') {
|
||||
while ((c = lpeek(l, 0)) >= 0 && c != '\n')
|
||||
lget(l);
|
||||
continue;
|
||||
}
|
||||
if (c == '/' && lpeek(l, 1) == '*') {
|
||||
lget(l); lget(l);
|
||||
int prev = -1;
|
||||
for (;;) {
|
||||
int x = lget(l);
|
||||
if (x < 0) {
|
||||
Pos p = lpos(l);
|
||||
errorf(p, "unterminated /* comment");
|
||||
l->errs++;
|
||||
return 0;
|
||||
}
|
||||
if (prev == '*' && x == '/')
|
||||
break;
|
||||
prev = x;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
static u64
|
||||
parseint(const char *s, u64 n, int base, int *ok)
|
||||
{
|
||||
u64 v = 0;
|
||||
int got = 0;
|
||||
for (u64 i = 0; i < n; i++) {
|
||||
int c = (unsigned char)s[i];
|
||||
if (c == '_')
|
||||
continue;
|
||||
int d;
|
||||
if (c >= '0' && c <= '9') d = c - '0';
|
||||
else if (c >= 'a' && c <= 'f') d = c - 'a' + 10;
|
||||
else if (c >= 'A' && c <= 'F') d = c - 'A' + 10;
|
||||
else { *ok = 0; return 0; }
|
||||
if (d >= base) { *ok = 0; return 0; }
|
||||
/* overflow? cheap check */
|
||||
if (v > (u64)~0ULL / (u64)base) { *ok = 0; return 0; }
|
||||
v = v * (u64)base + (u64)d;
|
||||
got = 1;
|
||||
}
|
||||
*ok = got;
|
||||
return v;
|
||||
}
|
||||
|
||||
static int
|
||||
escape(Lex *l, int *out)
|
||||
{
|
||||
int c = lget(l);
|
||||
if (c < 0) return -1;
|
||||
switch (c) {
|
||||
case 'n': *out = '\n'; return 0;
|
||||
case 't': *out = '\t'; return 0;
|
||||
case 'r': *out = '\r'; return 0;
|
||||
case '\\': *out = '\\'; return 0;
|
||||
case '\'': *out = '\''; return 0;
|
||||
case '"': *out = '"'; return 0;
|
||||
case '0': *out = '\0'; return 0;
|
||||
case 'a': *out = '\a'; return 0;
|
||||
case 'b': *out = '\b'; return 0;
|
||||
case 'f': *out = '\f'; return 0;
|
||||
case 'v': *out = '\v'; return 0;
|
||||
case 'x': {
|
||||
int hi = lget(l), lo = lget(l);
|
||||
if (!ishex(hi) || !ishex(lo)) {
|
||||
Pos p = lpos(l);
|
||||
errorf(p, "bad \\x escape");
|
||||
l->errs++;
|
||||
return -1;
|
||||
}
|
||||
int h = (hi <= '9' ? hi - '0' : (hi | 0x20) - 'a' + 10);
|
||||
int o = (lo <= '9' ? lo - '0' : (lo | 0x20) - 'a' + 10);
|
||||
*out = (h << 4) | o;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
{ Pos p = lpos(l); errorf(p, "bad escape \\%c", c); l->errs++; }
|
||||
return -1;
|
||||
}
|
||||
|
||||
static Tok
|
||||
lexnum(Lex *l, Pos start)
|
||||
{
|
||||
Tok t = (Tok){ TK_INT, start, NULL, 0, {0}, TK_NONE };
|
||||
u64 begin = l->pos;
|
||||
int base = 10;
|
||||
int isfloat = 0;
|
||||
int c = lpeek(l, 0);
|
||||
|
||||
if (c == '0' && (lpeek(l, 1) == 'x' || lpeek(l, 1) == 'X')) {
|
||||
lget(l); lget(l);
|
||||
base = 16;
|
||||
while ((c = lpeek(l, 0)) >= 0 && (ishex(c) || c == '_'))
|
||||
lget(l);
|
||||
} else if (c == '0' && (lpeek(l, 1) == 'b' || lpeek(l, 1) == 'B')) {
|
||||
lget(l); lget(l);
|
||||
base = 2;
|
||||
while ((c = lpeek(l, 0)) >= 0 && (c == '0' || c == '1' || c == '_'))
|
||||
lget(l);
|
||||
} else if (c == '0' && (lpeek(l, 1) == 'o' || lpeek(l, 1) == 'O')) {
|
||||
lget(l); lget(l);
|
||||
base = 8;
|
||||
while ((c = lpeek(l, 0)) >= 0 && ((c >= '0' && c <= '7') || c == '_'))
|
||||
lget(l);
|
||||
} else {
|
||||
while ((c = lpeek(l, 0)) >= 0 && ((c >= '0' && c <= '9') || c == '_'))
|
||||
lget(l);
|
||||
if (lpeek(l, 0) == '.' && lpeek(l, 1) >= '0' && lpeek(l, 1) <= '9') {
|
||||
isfloat = 1;
|
||||
lget(l);
|
||||
while ((c = lpeek(l, 0)) >= 0 && ((c >= '0' && c <= '9') || c == '_'))
|
||||
lget(l);
|
||||
c = lpeek(l, 0);
|
||||
if (c == 'e' || c == 'E') {
|
||||
lget(l);
|
||||
if (lpeek(l, 0) == '+' || lpeek(l, 0) == '-')
|
||||
lget(l);
|
||||
while ((c = lpeek(l, 0)) >= 0 && c >= '0' && c <= '9')
|
||||
lget(l);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
u64 n = l->pos - begin;
|
||||
t.text = astrndup(l->a, l->src + begin, n);
|
||||
t.tlen = n;
|
||||
|
||||
if (isfloat) {
|
||||
t.kind = TK_FLOAT;
|
||||
/* strdup with underscores stripped before strtod */
|
||||
char *clean = amalloc(l->a, n + 1);
|
||||
u64 j = 0;
|
||||
for (u64 i = 0; i < n; i++)
|
||||
if (l->src[begin + i] != '_')
|
||||
clean[j++] = l->src[begin + i];
|
||||
clean[j] = '\0';
|
||||
errno = 0;
|
||||
t.v.fval = strtod(clean, NULL);
|
||||
if (errno) {
|
||||
errorf(start, "bad float literal '%s'", t.text);
|
||||
l->errs++;
|
||||
}
|
||||
} else {
|
||||
const char *digs = l->src + begin;
|
||||
u64 dn = n;
|
||||
if (base != 10) {
|
||||
digs += 2;
|
||||
dn -= 2;
|
||||
}
|
||||
int ok = 0;
|
||||
t.v.uval = parseint(digs, dn, base, &ok);
|
||||
if (!ok) {
|
||||
errorf(start, "bad integer literal '%s'", t.text);
|
||||
l->errs++;
|
||||
t.kind = TK_ERR;
|
||||
}
|
||||
}
|
||||
|
||||
/* Typed suffix: i8/i16/i32/i64, u8/u16/u32/u64, f32/f64.
|
||||
* Must be glued (no whitespace) to the digits. We grab the
|
||||
* adjacent identifier-like run and accept it only if it's one
|
||||
* of the recognised type names. */
|
||||
if (isidstart(lpeek(l, 0))) {
|
||||
u64 sb = l->pos;
|
||||
while (isidcont(lpeek(l, 0))) lget(l);
|
||||
u64 sl = l->pos - sb;
|
||||
const char *names[] = {
|
||||
"i8", "i16", "i32", "i64",
|
||||
"u8", "u16", "u32", "u64",
|
||||
"f32", "f64", NULL
|
||||
};
|
||||
const char *match = NULL;
|
||||
for (int i = 0; names[i]; i++) {
|
||||
u64 nl = strlen(names[i]);
|
||||
if (nl == sl && memcmp(names[i], l->src + sb, nl) == 0) {
|
||||
match = names[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match) {
|
||||
t.tsuffix = astrndup(l->a, l->src + sb, sl);
|
||||
} else {
|
||||
/* not a known suffix — rewind so the run becomes a
|
||||
* separate token. */
|
||||
l->pos = sb;
|
||||
}
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
static Tok
|
||||
lexident(Lex *l, Pos start)
|
||||
{
|
||||
u64 begin = l->pos;
|
||||
while (isidcont(lpeek(l, 0)))
|
||||
lget(l);
|
||||
u64 n = l->pos - begin;
|
||||
const char *p = l->src + begin;
|
||||
Tkind k = kwlookup(p, n);
|
||||
Tok t = (Tok){ k != TK_NONE ? k : TK_IDENT, start,
|
||||
astrndup(l->a, p, n), n, {0}, TK_NONE };
|
||||
return t;
|
||||
}
|
||||
|
||||
static Tok
|
||||
lexstr(Lex *l, Pos start)
|
||||
{
|
||||
/* opening quote already consumed by caller */
|
||||
u64 cap = 32, n = 0;
|
||||
char *buf = amalloc(l->a, cap);
|
||||
for (;;) {
|
||||
int c = lpeek(l, 0);
|
||||
if (c < 0) {
|
||||
errorf(start, "unterminated string");
|
||||
l->errs++;
|
||||
Tok t = (Tok){ TK_ERR, start, astrndup(l->a, "", 0), 0, {0}, TK_NONE };
|
||||
return t;
|
||||
}
|
||||
if (c == '"') { lget(l); break; }
|
||||
int ch;
|
||||
if (c == '\\') {
|
||||
lget(l);
|
||||
if (escape(l, &ch) < 0)
|
||||
ch = 0;
|
||||
} else {
|
||||
ch = lget(l);
|
||||
}
|
||||
if (n + 1 >= cap) {
|
||||
u64 ncap = cap * 2;
|
||||
char *nb = amalloc(l->a, ncap);
|
||||
memcpy(nb, buf, n);
|
||||
buf = nb;
|
||||
cap = ncap;
|
||||
}
|
||||
buf[n++] = (char)ch;
|
||||
}
|
||||
buf[n] = '\0';
|
||||
Tok t = (Tok){ TK_STR, start, buf, n, {0}, TK_NONE };
|
||||
return t;
|
||||
}
|
||||
|
||||
static Tok
|
||||
lexrune(Lex *l, Pos start)
|
||||
{
|
||||
int ch;
|
||||
int c = lpeek(l, 0);
|
||||
if (c < 0) {
|
||||
errorf(start, "unterminated rune");
|
||||
l->errs++;
|
||||
return (Tok){ TK_ERR, start, "", 0, {0}, TK_NONE };
|
||||
}
|
||||
if (c == '\\') {
|
||||
lget(l);
|
||||
if (escape(l, &ch) < 0)
|
||||
ch = 0;
|
||||
} else {
|
||||
ch = lget(l);
|
||||
}
|
||||
if (lpeek(l, 0) != '\'') {
|
||||
errorf(start, "rune literal missing closing '");
|
||||
l->errs++;
|
||||
return (Tok){ TK_ERR, start, "", 0, {0}, TK_NONE };
|
||||
}
|
||||
lget(l);
|
||||
Tok t = (Tok){ TK_RUNE, start, NULL, 0, {0}, TK_NONE };
|
||||
t.v.uval = (u64)(u32)ch;
|
||||
t.text = aprintf(l->a, "%d", ch);
|
||||
t.tlen = strlen(t.text);
|
||||
return t;
|
||||
}
|
||||
|
||||
#define EMIT(K) do { Tok _t = (Tok){ (K), start, NULL, 0, {0}, TK_NONE }; \
|
||||
_t.text = tokname(K); _t.tlen = strlen(_t.text); return _t; } while (0)
|
||||
|
||||
Tok
|
||||
lexnext(Lex *l)
|
||||
{
|
||||
if (!skipws(l)) {
|
||||
Pos p = lpos(l);
|
||||
Tok t = (Tok){ TK_EOF, p, "", 0, {0}, TK_NONE };
|
||||
return t;
|
||||
}
|
||||
Pos start = lpos(l);
|
||||
int c = lpeek(l, 0);
|
||||
|
||||
if (isidstart(c))
|
||||
return lexident(l, start);
|
||||
if (c >= '0' && c <= '9')
|
||||
return lexnum(l, start);
|
||||
|
||||
if (c == '"') { lget(l); return lexstr(l, start); }
|
||||
if (c == '\'') { lget(l); return lexrune(l, start); }
|
||||
|
||||
lget(l);
|
||||
switch (c) {
|
||||
case '(': EMIT(TK_LPAREN);
|
||||
case ')': EMIT(TK_RPAREN);
|
||||
case '{': EMIT(TK_LBRACE);
|
||||
case '}': EMIT(TK_RBRACE);
|
||||
case '[': EMIT(TK_LBRACK);
|
||||
case ']': EMIT(TK_RBRACK);
|
||||
case ',': EMIT(TK_COMMA);
|
||||
case ';': EMIT(TK_SEMI);
|
||||
case ':': EMIT(TK_COLON);
|
||||
case '@': EMIT(TK_AT);
|
||||
case '?': EMIT(TK_QUESTION);
|
||||
case '~': EMIT(TK_TILDE);
|
||||
case '.':
|
||||
if (lpeek(l, 0) == '.' && lpeek(l, 1) == '.') {
|
||||
lget(l); lget(l);
|
||||
EMIT(TK_ELLIPSIS);
|
||||
}
|
||||
if (lpeek(l, 0) == '.') {
|
||||
lget(l);
|
||||
EMIT(TK_DOTDOT);
|
||||
}
|
||||
EMIT(TK_DOT);
|
||||
case '+':
|
||||
if (lpeek(l, 0) == '=') { lget(l); EMIT(TK_PLUSEQ); }
|
||||
EMIT(TK_PLUS);
|
||||
case '-':
|
||||
if (lpeek(l, 0) == '=') { lget(l); EMIT(TK_MINUSEQ); }
|
||||
if (lpeek(l, 0) == '>') { lget(l); EMIT(TK_ARROW); }
|
||||
EMIT(TK_MINUS);
|
||||
case '*':
|
||||
if (lpeek(l, 0) == '=') { lget(l); EMIT(TK_STAREQ); }
|
||||
EMIT(TK_STAR);
|
||||
case '/':
|
||||
if (lpeek(l, 0) == '=') { lget(l); EMIT(TK_SLASHEQ); }
|
||||
EMIT(TK_SLASH);
|
||||
case '%':
|
||||
if (lpeek(l, 0) == '=') { lget(l); EMIT(TK_PERCENTEQ); }
|
||||
EMIT(TK_PERCENT);
|
||||
case '&':
|
||||
if (lpeek(l, 0) == '&') { lget(l); EMIT(TK_AND); }
|
||||
if (lpeek(l, 0) == '=') { lget(l); EMIT(TK_AMPEQ); }
|
||||
EMIT(TK_AMP);
|
||||
case '|':
|
||||
if (lpeek(l, 0) == '|') { lget(l); EMIT(TK_OR); }
|
||||
if (lpeek(l, 0) == '=') { lget(l); EMIT(TK_PIPEEQ); }
|
||||
EMIT(TK_PIPE);
|
||||
case '^':
|
||||
if (lpeek(l, 0) == '=') { lget(l); EMIT(TK_CARETEQ); }
|
||||
EMIT(TK_CARET);
|
||||
case '=':
|
||||
if (lpeek(l, 0) == '=') { lget(l); EMIT(TK_EQ); }
|
||||
if (lpeek(l, 0) == '>') { lget(l); EMIT(TK_FATARROW); }
|
||||
EMIT(TK_ASSIGN);
|
||||
case '!':
|
||||
if (lpeek(l, 0) == '=') { lget(l); EMIT(TK_NEQ); }
|
||||
EMIT(TK_NOT);
|
||||
case '<':
|
||||
if (lpeek(l, 0) == '<') {
|
||||
lget(l);
|
||||
if (lpeek(l, 0) == '=') { lget(l); EMIT(TK_LSHIFTEQ); }
|
||||
EMIT(TK_LSHIFT);
|
||||
}
|
||||
if (lpeek(l, 0) == '=') { lget(l); EMIT(TK_LE); }
|
||||
if (lpeek(l, 0) == '-') { lget(l); EMIT(TK_LARROW); }
|
||||
EMIT(TK_LT);
|
||||
case '>':
|
||||
if (lpeek(l, 0) == '>') {
|
||||
lget(l);
|
||||
if (lpeek(l, 0) == '=') { lget(l); EMIT(TK_RSHIFTEQ); }
|
||||
EMIT(TK_RSHIFT);
|
||||
}
|
||||
if (lpeek(l, 0) == '=') { lget(l); EMIT(TK_GE); }
|
||||
EMIT(TK_GT);
|
||||
}
|
||||
errorf(start, "unexpected character 0x%02x", c);
|
||||
l->errs++;
|
||||
Tok t = (Tok){ TK_ERR, start, NULL, 0, {0}, TK_NONE };
|
||||
t.text = astrndup(l->a, (const char[]){ (char)c }, 1);
|
||||
t.tlen = 1;
|
||||
return t;
|
||||
}
|
||||
117
cmd/wwc/mem.c
Normal file
117
cmd/wwc/mem.c
Normal file
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* mem.c — arena allocator. No free per allocation; freearena releases
|
||||
* the whole chain. Aligned to 16 so structs with 8-byte fields and
|
||||
* doubles are happy.
|
||||
*
|
||||
* Hot allocations in the compiler land in arenas: tokens, AST nodes,
|
||||
* symbols, types. The chunk size doubles up to a cap so we don't
|
||||
* fragment on huge inputs.
|
||||
*/
|
||||
#include "ww.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define ALIGN 16
|
||||
#define INIT_CHUNK (64 * 1024)
|
||||
#define MAX_CHUNK (4 * 1024 * 1024)
|
||||
|
||||
static u64
|
||||
roundup(u64 n, u64 a)
|
||||
{
|
||||
return (n + a - 1) & ~(a - 1);
|
||||
}
|
||||
|
||||
Arena *
|
||||
newarena(void)
|
||||
{
|
||||
Arena *a = calloc(1, sizeof *a);
|
||||
if (a == NULL)
|
||||
fatal("newarena: out of memory");
|
||||
a->buf = malloc(INIT_CHUNK);
|
||||
if (a->buf == NULL)
|
||||
fatal("newarena: out of memory");
|
||||
a->cap = INIT_CHUNK;
|
||||
return a;
|
||||
}
|
||||
|
||||
static void
|
||||
grow(Arena *a, u64 need)
|
||||
{
|
||||
u64 ncap = a->cap * 2;
|
||||
if (ncap > MAX_CHUNK)
|
||||
ncap = MAX_CHUNK;
|
||||
if (ncap < need)
|
||||
ncap = roundup(need, ALIGN);
|
||||
|
||||
/* push current chunk onto chain, allocate fresh head */
|
||||
Arena *old = malloc(sizeof *old);
|
||||
if (old == NULL)
|
||||
fatal("arena: oom");
|
||||
*old = *a;
|
||||
a->next = old;
|
||||
a->buf = malloc(ncap);
|
||||
if (a->buf == NULL)
|
||||
fatal("arena: oom (chunk=%llu)", (unsigned long long)ncap);
|
||||
a->off = 0;
|
||||
a->cap = ncap;
|
||||
}
|
||||
|
||||
void *
|
||||
amalloc(Arena *a, u64 n)
|
||||
{
|
||||
n = roundup(n, ALIGN);
|
||||
if (n > a->cap - a->off)
|
||||
grow(a, n);
|
||||
void *p = a->buf + a->off;
|
||||
a->off += n;
|
||||
a->total += n;
|
||||
memset(p, 0, n);
|
||||
return p;
|
||||
}
|
||||
|
||||
char *
|
||||
astrdup(Arena *a, const char *s)
|
||||
{
|
||||
u64 n = strlen(s);
|
||||
char *p = amalloc(a, n + 1);
|
||||
memcpy(p, s, n);
|
||||
return p;
|
||||
}
|
||||
|
||||
char *
|
||||
astrndup(Arena *a, const char *s, u64 n)
|
||||
{
|
||||
char *p = amalloc(a, n + 1);
|
||||
memcpy(p, s, n);
|
||||
return p;
|
||||
}
|
||||
|
||||
char *
|
||||
aprintf(Arena *a, const char *fmt, ...)
|
||||
{
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
int n = vsnprintf(NULL, 0, fmt, ap);
|
||||
va_end(ap);
|
||||
if (n < 0)
|
||||
fatal("aprintf: vsnprintf failed");
|
||||
char *p = amalloc(a, (u64)n + 1);
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(p, (size_t)n + 1, fmt, ap);
|
||||
va_end(ap);
|
||||
return p;
|
||||
}
|
||||
|
||||
void
|
||||
freearena(Arena *a)
|
||||
{
|
||||
while (a) {
|
||||
Arena *next = a->next;
|
||||
free(a->buf);
|
||||
/* The head Arena was returned by newarena() and is the only
|
||||
* one we should free as a struct; the linked older ones were
|
||||
* allocated by grow() and are also freeable. */
|
||||
free(a);
|
||||
a = next;
|
||||
}
|
||||
}
|
||||
1183
cmd/wwc/parse.c
Normal file
1183
cmd/wwc/parse.c
Normal file
File diff suppressed because it is too large
Load Diff
74
cmd/wwc/sym.c
Normal file
74
cmd/wwc/sym.c
Normal file
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* sym.c — symbol table. Plan 9-flavoured: a per-scope hashtable
|
||||
* chained to the parent scope. Lookup walks up. Duplicate definitions
|
||||
* within the same scope are flagged by the caller (we just refuse the
|
||||
* insert and return the first one).
|
||||
*/
|
||||
#include "ww.h"
|
||||
#include <string.h>
|
||||
|
||||
#define INIT_BUCKETS 16
|
||||
|
||||
static u64
|
||||
hashstr(const char *s)
|
||||
{
|
||||
/* FNV-1a 64-bit; small fixed footprint, decent distribution */
|
||||
u64 h = 0xcbf29ce484222325ULL;
|
||||
for (; *s; s++) {
|
||||
h ^= (unsigned char)*s;
|
||||
h *= 0x100000001b3ULL;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
Scope *
|
||||
newscope(Arena *a, Scope *parent)
|
||||
{
|
||||
Scope *s = amalloc(a, sizeof *s);
|
||||
s->parent = parent;
|
||||
s->a = a;
|
||||
s->nbuckets = INIT_BUCKETS;
|
||||
s->buckets = amalloc(a, s->nbuckets * sizeof(Sym *));
|
||||
return s;
|
||||
}
|
||||
|
||||
Sym *
|
||||
scope_lookup_local(Scope *s, const char *name)
|
||||
{
|
||||
if (s == NULL) return NULL;
|
||||
u64 h = hashstr(name) % s->nbuckets;
|
||||
for (Sym *b = s->buckets[h]; b; b = b->hashnext)
|
||||
if (strcmp(b->name, name) == 0)
|
||||
return b;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Sym *
|
||||
scope_lookup(Scope *s, const char *name)
|
||||
{
|
||||
for (; s; s = s->parent) {
|
||||
Sym *r = scope_lookup_local(s, name);
|
||||
if (r) return r;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Sym *
|
||||
scope_define(Scope *s, const char *name, Skind k, Type *t, Node *decl)
|
||||
{
|
||||
if (scope_lookup_local(s, name) != NULL)
|
||||
return NULL;
|
||||
Sym *sy = amalloc(s->a, sizeof *sy);
|
||||
sy->name = name;
|
||||
sy->kind = k;
|
||||
sy->type = t;
|
||||
sy->decl = decl;
|
||||
sy->scope = s;
|
||||
u64 h = hashstr(name) % s->nbuckets;
|
||||
sy->hashnext = s->buckets[h];
|
||||
s->buckets[h] = sy;
|
||||
if (s->first == NULL) s->first = sy;
|
||||
else s->last->next = sy;
|
||||
s->last = sy;
|
||||
return sy;
|
||||
}
|
||||
199
cmd/wwc/tok.c
Normal file
199
cmd/wwc/tok.c
Normal file
@@ -0,0 +1,199 @@
|
||||
/*
|
||||
* tok.c — token names, keyword lookup, debug printer.
|
||||
*
|
||||
* One table-of-records keyed by kind. The keyword subset is also
|
||||
* scanned linearly during lexing — fewer than 25 entries, a hash
|
||||
* isn't worth it.
|
||||
*/
|
||||
#include "ww.h"
|
||||
#include <string.h>
|
||||
|
||||
struct kwent {
|
||||
const char *s;
|
||||
Tkind kind;
|
||||
};
|
||||
|
||||
/* keep alphabetised, so kwlookup is easy to read. */
|
||||
static const struct kwent kwtab[] = {
|
||||
{ "as", TK_AS },
|
||||
{ "break", TK_BREAK },
|
||||
{ "case", TK_CASE },
|
||||
{ "chan", TK_CHAN },
|
||||
{ "continue", TK_CONTINUE },
|
||||
{ "def", TK_DEF },
|
||||
{ "defer", TK_DEFER },
|
||||
{ "else", TK_ELSE },
|
||||
{ "export", TK_EXPORT },
|
||||
{ "false", TK_FALSE },
|
||||
{ "fn", TK_FN },
|
||||
{ "for", TK_FOR },
|
||||
{ "if", TK_IF },
|
||||
{ "let", TK_LET },
|
||||
{ "match", TK_MATCH },
|
||||
{ "nil", TK_NIL },
|
||||
{ "proc", TK_PROC },
|
||||
{ "return", TK_RETURN },
|
||||
{ "static", TK_STATIC },
|
||||
{ "struct", TK_STRUCT },
|
||||
{ "switch", TK_SWITCH },
|
||||
{ "true", TK_TRUE },
|
||||
{ "type", TK_TYPE },
|
||||
{ "use", TK_USE }
|
||||
};
|
||||
|
||||
Tkind
|
||||
kwlookup(const char *s, u64 n)
|
||||
{
|
||||
/* linear scan: small N, predictable, branchy fall-through is fine. */
|
||||
for (u64 i = 0; i < nelem(kwtab); i++) {
|
||||
const char *k = kwtab[i].s;
|
||||
if (strlen(k) == n && memcmp(k, s, n) == 0)
|
||||
return kwtab[i].kind;
|
||||
}
|
||||
return TK_NONE;
|
||||
}
|
||||
|
||||
const char *
|
||||
tokname(Tkind k)
|
||||
{
|
||||
switch (k) {
|
||||
case TK_NONE: return "<none>";
|
||||
case TK_EOF: return "EOF";
|
||||
case TK_ERR: return "ERR";
|
||||
case TK_IDENT: return "IDENT";
|
||||
case TK_INT: return "INT";
|
||||
case TK_FLOAT: return "FLOAT";
|
||||
case TK_RUNE: return "RUNE";
|
||||
case TK_STR: return "STR";
|
||||
|
||||
case TK_FN: return "fn";
|
||||
case TK_LET: return "let";
|
||||
case TK_DEF: return "def";
|
||||
case TK_IF: return "if";
|
||||
case TK_ELSE: return "else";
|
||||
case TK_FOR: return "for";
|
||||
case TK_SWITCH: return "switch";
|
||||
case TK_CASE: return "case";
|
||||
case TK_RETURN: return "return";
|
||||
case TK_USE: return "use";
|
||||
case TK_TYPE: return "type";
|
||||
case TK_STRUCT: return "struct";
|
||||
case TK_DEFER: return "defer";
|
||||
case TK_BREAK: return "break";
|
||||
case TK_CONTINUE: return "continue";
|
||||
case TK_EXPORT: return "export";
|
||||
case TK_PROC: return "proc";
|
||||
case TK_CHAN: return "chan";
|
||||
case TK_NIL: return "nil";
|
||||
case TK_TRUE: return "true";
|
||||
case TK_FALSE: return "false";
|
||||
case TK_AS: return "as";
|
||||
case TK_STATIC: return "static";
|
||||
case TK_MATCH: return "match";
|
||||
|
||||
case TK_LPAREN: return "(";
|
||||
case TK_RPAREN: return ")";
|
||||
case TK_LBRACE: return "{";
|
||||
case TK_RBRACE: return "}";
|
||||
case TK_LBRACK: return "[";
|
||||
case TK_RBRACK: return "]";
|
||||
case TK_COMMA: return ",";
|
||||
case TK_SEMI: return ";";
|
||||
case TK_COLON: return ":";
|
||||
case TK_DOT: return ".";
|
||||
case TK_ELLIPSIS: return "...";
|
||||
case TK_DOTDOT: return "..";
|
||||
case TK_AT: return "@";
|
||||
case TK_QUESTION: return "?";
|
||||
|
||||
case TK_ASSIGN: return "=";
|
||||
case TK_PLUSEQ: return "+=";
|
||||
case TK_MINUSEQ: return "-=";
|
||||
case TK_STAREQ: return "*=";
|
||||
case TK_SLASHEQ: return "/=";
|
||||
case TK_PERCENTEQ: return "%=";
|
||||
case TK_AMPEQ: return "&=";
|
||||
case TK_PIPEEQ: return "|=";
|
||||
case TK_CARETEQ: return "^=";
|
||||
case TK_LSHIFTEQ: return "<<=";
|
||||
case TK_RSHIFTEQ: return ">>=";
|
||||
|
||||
case TK_PLUS: return "+";
|
||||
case TK_MINUS: return "-";
|
||||
case TK_STAR: return "*";
|
||||
case TK_SLASH: return "/";
|
||||
case TK_PERCENT: return "%";
|
||||
case TK_AMP: return "&";
|
||||
case TK_PIPE: return "|";
|
||||
case TK_CARET: return "^";
|
||||
case TK_TILDE: return "~";
|
||||
case TK_LSHIFT: return "<<";
|
||||
case TK_RSHIFT: return ">>";
|
||||
|
||||
case TK_EQ: return "==";
|
||||
case TK_NEQ: return "!=";
|
||||
case TK_LT: return "<";
|
||||
case TK_LE: return "<=";
|
||||
case TK_GT: return ">";
|
||||
case TK_GE: return ">=";
|
||||
|
||||
case TK_AND: return "&&";
|
||||
case TK_OR: return "||";
|
||||
case TK_NOT: return "!";
|
||||
|
||||
case TK_LARROW: return "<-";
|
||||
case TK_ARROW: return "->";
|
||||
case TK_FATARROW: return "=>";
|
||||
|
||||
case TK_LAST: return "<last>";
|
||||
}
|
||||
return "<?>";
|
||||
}
|
||||
|
||||
static void
|
||||
fputq(FILE *f, const char *s, u64 n)
|
||||
{
|
||||
fputc('"', f);
|
||||
for (u64 i = 0; i < n; i++) {
|
||||
unsigned char c = (unsigned char)s[i];
|
||||
switch (c) {
|
||||
case '\\': fputs("\\\\", f); break;
|
||||
case '"': fputs("\\\"", f); break;
|
||||
case '\n': fputs("\\n", f); break;
|
||||
case '\t': fputs("\\t", f); break;
|
||||
case '\r': fputs("\\r", f); break;
|
||||
default:
|
||||
if (c < 0x20 || c == 0x7f)
|
||||
fprintf(f, "\\x%02x", c);
|
||||
else
|
||||
fputc(c, f);
|
||||
}
|
||||
}
|
||||
fputc('"', f);
|
||||
}
|
||||
|
||||
void
|
||||
tokprint(FILE *f, Tok t)
|
||||
{
|
||||
fprintf(f, "%s:%d:%d %s",
|
||||
t.pos.file ? t.pos.file : "<none>", t.pos.line, t.pos.col,
|
||||
tokname(t.kind));
|
||||
switch (t.kind) {
|
||||
case TK_IDENT:
|
||||
case TK_STR:
|
||||
case TK_ERR:
|
||||
fputc(' ', f);
|
||||
fputq(f, t.text, t.tlen);
|
||||
break;
|
||||
case TK_INT:
|
||||
case TK_RUNE:
|
||||
fprintf(f, " %llu", (unsigned long long)t.v.uval);
|
||||
break;
|
||||
case TK_FLOAT:
|
||||
fprintf(f, " %g", t.v.fval);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
fputc('\n', f);
|
||||
}
|
||||
370
cmd/wwc/type.c
Normal file
370
cmd/wwc/type.c
Normal file
@@ -0,0 +1,370 @@
|
||||
/*
|
||||
* type.c — Type values and structural equality.
|
||||
*
|
||||
* Built-in types are constructed once and exposed as globals so the
|
||||
* rest of the compiler can `==`-compare them. Compound types (ptr,
|
||||
* slice, array, fn, struct, chan) are constructed on demand and
|
||||
* de-duplicated when equality is cheap (only ptr/slice for now).
|
||||
*/
|
||||
#include "ww.h"
|
||||
#include <string.h>
|
||||
|
||||
Type *ty_void, *ty_bool, *ty_rune;
|
||||
Type *ty_i8, *ty_i16, *ty_i32, *ty_i64;
|
||||
Type *ty_u8, *ty_u16, *ty_u32, *ty_u64;
|
||||
Type *ty_int, *ty_uint, *ty_uintptr;
|
||||
Type *ty_f32, *ty_f64, *ty_str;
|
||||
Type *ty_err;
|
||||
Type *ty_untyped_int, *ty_untyped_float, *ty_untyped_str;
|
||||
Type *ty_untyped_rune, *ty_untyped_bool, *ty_untyped_nil;
|
||||
|
||||
Type *
|
||||
newtype(Arena *a, TypeKind k)
|
||||
{
|
||||
Type *t = amalloc(a, sizeof *t);
|
||||
t->kind = k;
|
||||
return t;
|
||||
}
|
||||
|
||||
static Type *
|
||||
prim(Arena *a, TypeKind k, const char *nm, u64 sz, u64 al)
|
||||
{
|
||||
Type *t = newtype(a, k);
|
||||
t->name = nm;
|
||||
t->size = sz;
|
||||
t->align = al ? al : sz;
|
||||
return t;
|
||||
}
|
||||
|
||||
void
|
||||
typesinit(Arena *a)
|
||||
{
|
||||
/* Always re-init: callers create a fresh arena per compilation unit
|
||||
* and free it; old globals point at freed memory. */
|
||||
ty_void = prim(a, TY_VOID, "void", 0, 1);
|
||||
ty_bool = prim(a, TY_BOOL, "bool", 1, 1);
|
||||
ty_rune = prim(a, TY_RUNE, "rune", 4, 4);
|
||||
|
||||
ty_i8 = prim(a, TY_I8, "i8", 1, 1);
|
||||
ty_i16 = prim(a, TY_I16, "i16", 2, 2);
|
||||
ty_i32 = prim(a, TY_I32, "i32", 4, 4);
|
||||
ty_i64 = prim(a, TY_I64, "i64", 8, 8);
|
||||
ty_u8 = prim(a, TY_U8, "u8", 1, 1);
|
||||
ty_u16 = prim(a, TY_U16, "u16", 2, 2);
|
||||
ty_u32 = prim(a, TY_U32, "u32", 4, 4);
|
||||
ty_u64 = prim(a, TY_U64, "u64", 8, 8);
|
||||
ty_int = prim(a, TY_INT, "int", 8, 8); /* amd64 */
|
||||
ty_uint = prim(a, TY_UINT, "uint", 8, 8);
|
||||
ty_uintptr= prim(a, TY_UINTPTR,"uintptr", 8, 8);
|
||||
ty_f32 = prim(a, TY_F32, "f32", 4, 4);
|
||||
ty_f64 = prim(a, TY_F64, "f64", 8, 8);
|
||||
/* str is { *u8, len } — 16 bytes on amd64. ABI: pointer + u64. */
|
||||
ty_str = prim(a, TY_STR, "str", 16, 8);
|
||||
ty_err = prim(a, TY_ERR, "<err>", 0, 1);
|
||||
|
||||
ty_untyped_int = prim(a, TY_UNTYPED_INT, "untyped_int", 0, 1);
|
||||
ty_untyped_float = prim(a, TY_UNTYPED_FLOAT, "untyped_float", 0, 1);
|
||||
ty_untyped_str = prim(a, TY_UNTYPED_STR, "untyped_str", 0, 1);
|
||||
ty_untyped_rune = prim(a, TY_UNTYPED_RUNE, "untyped_rune", 0, 1);
|
||||
ty_untyped_bool = prim(a, TY_UNTYPED_BOOL, "untyped_bool", 0, 1);
|
||||
ty_untyped_nil = prim(a, TY_UNTYPED_NIL, "untyped_nil", 0, 1);
|
||||
}
|
||||
|
||||
Type *
|
||||
type_ptr(Arena *a, Type *sub)
|
||||
{
|
||||
Type *t = newtype(a, TY_PTR);
|
||||
t->sub = sub;
|
||||
t->size = 8;
|
||||
t->align = 8;
|
||||
return t;
|
||||
}
|
||||
|
||||
Type *
|
||||
type_slice(Arena *a, Type *sub)
|
||||
{
|
||||
Type *t = newtype(a, TY_SLICE);
|
||||
t->sub = sub;
|
||||
t->size = 24; /* { *T, len, cap } */
|
||||
t->align = 8;
|
||||
return t;
|
||||
}
|
||||
|
||||
Type *
|
||||
type_array(Arena *a, Type *sub, u64 len)
|
||||
{
|
||||
Type *t = newtype(a, TY_ARRAY);
|
||||
t->sub = sub;
|
||||
t->alen = len;
|
||||
t->size = sub ? sub->size * len : 0;
|
||||
t->align = sub ? sub->align : 1;
|
||||
return t;
|
||||
}
|
||||
|
||||
Type *
|
||||
type_chan(Arena *a, Type *sub)
|
||||
{
|
||||
Type *t = newtype(a, TY_CHAN);
|
||||
t->sub = sub;
|
||||
t->size = 8; /* opaque ptr */
|
||||
t->align = 8;
|
||||
return t;
|
||||
}
|
||||
|
||||
Type *
|
||||
type_named(Arena *a, const char *name, Type *under)
|
||||
{
|
||||
Type *t = newtype(a, TY_NAMED);
|
||||
t->name = name;
|
||||
t->under = under;
|
||||
if (under) {
|
||||
t->size = under->size;
|
||||
t->align = under->align;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
int
|
||||
type_isint(Type *t)
|
||||
{
|
||||
if (t == NULL) return 0;
|
||||
switch (t->kind) {
|
||||
case TY_I8: case TY_I16: case TY_I32: case TY_I64:
|
||||
case TY_U8: case TY_U16: case TY_U32: case TY_U64:
|
||||
case TY_INT: case TY_UINT: case TY_UINTPTR:
|
||||
case TY_RUNE:
|
||||
case TY_UNTYPED_INT:
|
||||
case TY_UNTYPED_RUNE:
|
||||
return 1;
|
||||
case TY_NAMED: return type_isint(t->under);
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
type_isfloat(Type *t)
|
||||
{
|
||||
if (t == NULL) return 0;
|
||||
switch (t->kind) {
|
||||
case TY_F32: case TY_F64: case TY_UNTYPED_FLOAT:
|
||||
return 1;
|
||||
case TY_NAMED: return type_isfloat(t->under);
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
type_isnum(Type *t)
|
||||
{
|
||||
return type_isint(t) || type_isfloat(t);
|
||||
}
|
||||
|
||||
int
|
||||
type_isunsigned(Type *t)
|
||||
{
|
||||
if (t == NULL) return 0;
|
||||
switch (t->kind) {
|
||||
case TY_U8: case TY_U16: case TY_U32: case TY_U64:
|
||||
case TY_UINT: case TY_UINTPTR:
|
||||
return 1;
|
||||
case TY_NAMED: return type_isunsigned(t->under);
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
type_isuntyped(Type *t)
|
||||
{
|
||||
if (t == NULL) return 0;
|
||||
switch (t->kind) {
|
||||
case TY_UNTYPED_INT: case TY_UNTYPED_FLOAT: case TY_UNTYPED_STR:
|
||||
case TY_UNTYPED_RUNE: case TY_UNTYPED_BOOL: case TY_UNTYPED_NIL:
|
||||
return 1;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
Type *
|
||||
type_default(Type *t)
|
||||
{
|
||||
if (t == NULL) return NULL;
|
||||
switch (t->kind) {
|
||||
case TY_UNTYPED_INT: return ty_i32;
|
||||
case TY_UNTYPED_FLOAT: return ty_f64;
|
||||
case TY_UNTYPED_STR: return ty_str;
|
||||
case TY_UNTYPED_RUNE: return ty_rune;
|
||||
case TY_UNTYPED_BOOL: return ty_bool;
|
||||
case TY_UNTYPED_NIL: return NULL; /* needs context */
|
||||
default: return t;
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
type_eq(Type *a, Type *b)
|
||||
{
|
||||
if (a == b) return 1;
|
||||
if (a == NULL || b == NULL) return 0;
|
||||
if (a->kind != b->kind) return 0;
|
||||
switch (a->kind) {
|
||||
case TY_PTR: case TY_SLICE: case TY_CHAN:
|
||||
return type_eq(a->sub, b->sub);
|
||||
case TY_ARRAY:
|
||||
return a->alen == b->alen && type_eq(a->sub, b->sub);
|
||||
case TY_FN: {
|
||||
if (a->variadic != b->variadic) return 0;
|
||||
if (!type_eq(a->ret, b->ret)) return 0;
|
||||
Tparam *pa = a->params, *pb = b->params;
|
||||
while (pa && pb) {
|
||||
if (!type_eq(pa->type, pb->type)) return 0;
|
||||
pa = pa->next; pb = pb->next;
|
||||
}
|
||||
return pa == NULL && pb == NULL;
|
||||
}
|
||||
case TY_STRUCT: {
|
||||
Tfield *fa = a->fields, *fb = b->fields;
|
||||
while (fa && fb) {
|
||||
if (strcmp(fa->name, fb->name) != 0) return 0;
|
||||
if (!type_eq(fa->type, fb->type)) return 0;
|
||||
fa = fa->next; fb = fb->next;
|
||||
}
|
||||
return fa == NULL && fb == NULL;
|
||||
}
|
||||
case TY_NAMED:
|
||||
return a == b; /* nominally equal only when same node */
|
||||
case TY_TUPLE: {
|
||||
Tparam *pa = a->params, *pb = b->params;
|
||||
while (pa && pb) {
|
||||
if (!type_eq(pa->type, pb->type)) return 0;
|
||||
pa = pa->next; pb = pb->next;
|
||||
}
|
||||
return pa == NULL && pb == NULL;
|
||||
}
|
||||
default: return 1; /* primitives */
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
type_assignable(Type *dst, Type *src)
|
||||
{
|
||||
if (dst == NULL || src == NULL) return 0;
|
||||
if (dst == ty_err || src == ty_err) return 1; /* swallow */
|
||||
if (type_eq(dst, src)) return 1;
|
||||
|
||||
/* Tagged-union variant inclusion: src is one of dst's variants.
|
||||
* Checked before the untyped branch so untyped literals (e.g.
|
||||
* 0, "msg") flow through to a variant's typed slot. Unwraps a
|
||||
* named alias on either side so `type result = (T | E);` also
|
||||
* accepts variants and the inverse. */
|
||||
{
|
||||
Type *du = (dst->kind == TY_NAMED) ? dst->under : dst;
|
||||
Type *su = (src->kind == TY_NAMED) ? src->under : src;
|
||||
if (du && du->kind == TY_TAGGED &&
|
||||
!(su && su->kind == TY_TAGGED)) {
|
||||
for (Tparam *p = du->params; p; p = p->next)
|
||||
if (type_assignable(p->type, src)) return 1;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Untyped → typed: only if the typed kind can hold the value. */
|
||||
if (type_isuntyped(src)) {
|
||||
if (src->kind == TY_UNTYPED_INT && type_isnum(dst)) return 1;
|
||||
if (src->kind == TY_UNTYPED_FLOAT && type_isfloat(dst)) return 1;
|
||||
if (src->kind == TY_UNTYPED_STR && (dst->kind == TY_STR ||
|
||||
(dst->kind == TY_NAMED && dst->under && dst->under->kind == TY_STR))) return 1;
|
||||
if (src->kind == TY_UNTYPED_RUNE && (type_isint(dst) || dst->kind == TY_RUNE)) return 1;
|
||||
if (src->kind == TY_UNTYPED_BOOL && (dst->kind == TY_BOOL ||
|
||||
(dst->kind == TY_NAMED && dst->under && dst->under->kind == TY_BOOL))) return 1;
|
||||
if (src->kind == TY_UNTYPED_NIL) {
|
||||
Type *du = (dst->kind == TY_NAMED) ? dst->under : dst;
|
||||
if (du && (du->kind == TY_PTR || du->kind == TY_SLICE ||
|
||||
du->kind == TY_CHAN || du->kind == TY_FN))
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Named on either side: compare to the underlying. NAMED is a
|
||||
* distinct type from its under; but assignment from under to
|
||||
* named (and vice-versa) is allowed in this minimal checker. */
|
||||
if (dst->kind == TY_NAMED && type_eq(dst->under, src)) return 1;
|
||||
if (src->kind == TY_NAMED && type_eq(dst, src->under)) return 1;
|
||||
|
||||
/* Tuple-to-tuple: element-wise assignable. */
|
||||
if (dst->kind == TY_TUPLE && src->kind == TY_TUPLE) {
|
||||
Tparam *pa = dst->params, *pb = src->params;
|
||||
while (pa && pb) {
|
||||
if (!type_assignable(pa->type, pb->type)) return 0;
|
||||
pa = pa->next; pb = pb->next;
|
||||
}
|
||||
return pa == NULL && pb == NULL;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
const char *
|
||||
type_name(Arena *a, Type *t)
|
||||
{
|
||||
if (t == NULL) return "<nil>";
|
||||
switch (t->kind) {
|
||||
case TY_NONE: return "<none>";
|
||||
case TY_VOID: return "void";
|
||||
case TY_BOOL: return "bool";
|
||||
case TY_RUNE: return "rune";
|
||||
case TY_I8: return "i8";
|
||||
case TY_I16: return "i16";
|
||||
case TY_I32: return "i32";
|
||||
case TY_I64: return "i64";
|
||||
case TY_U8: return "u8";
|
||||
case TY_U16: return "u16";
|
||||
case TY_U32: return "u32";
|
||||
case TY_U64: return "u64";
|
||||
case TY_INT: return "int";
|
||||
case TY_UINT: return "uint";
|
||||
case TY_UINTPTR: return "uintptr";
|
||||
case TY_F32: return "f32";
|
||||
case TY_F64: return "f64";
|
||||
case TY_STR: return "str";
|
||||
case TY_ERR: return "<err>";
|
||||
case TY_UNTYPED_INT: return "untyped_int";
|
||||
case TY_UNTYPED_FLOAT: return "untyped_float";
|
||||
case TY_UNTYPED_STR: return "untyped_str";
|
||||
case TY_UNTYPED_RUNE: return "untyped_rune";
|
||||
case TY_UNTYPED_BOOL: return "untyped_bool";
|
||||
case TY_UNTYPED_NIL: return "untyped_nil";
|
||||
case TY_PTR: return aprintf(a, "*%s", type_name(a, t->sub));
|
||||
case TY_SLICE: return aprintf(a, "[]%s", type_name(a, t->sub));
|
||||
case TY_ARRAY: return aprintf(a, "[%llu]%s",
|
||||
(unsigned long long)t->alen, type_name(a, t->sub));
|
||||
case TY_CHAN: return aprintf(a, "chan %s", type_name(a, t->sub));
|
||||
case TY_FN: {
|
||||
const char *r = t->ret ? type_name(a, t->ret) : "void";
|
||||
const char *acc = "";
|
||||
for (Tparam *p = t->params; p; p = p->next) {
|
||||
const char *pn = type_name(a, p->type);
|
||||
acc = acc[0] ? aprintf(a, "%s, %s", acc, pn) : pn;
|
||||
}
|
||||
return aprintf(a, "fn(%s) %s", acc, r);
|
||||
}
|
||||
case TY_STRUCT: return t->name ? t->name : "struct{...}";
|
||||
case TY_NAMED: return t->name ? t->name : "<named>";
|
||||
case TY_TUPLE: {
|
||||
const char *acc = "";
|
||||
for (Tparam *p = t->params; p; p = p->next) {
|
||||
const char *pn = type_name(a, p->type);
|
||||
acc = acc[0] ? aprintf(a, "%s, %s", acc, pn) : pn;
|
||||
}
|
||||
return aprintf(a, "(%s)", acc);
|
||||
}
|
||||
case TY_TAGGED: {
|
||||
const char *acc = "";
|
||||
for (Tparam *p = t->params; p; p = p->next) {
|
||||
const char *pn = type_name(a, p->type);
|
||||
acc = acc[0] ? aprintf(a, "%s | %s", acc, pn) : pn;
|
||||
}
|
||||
return aprintf(a, "(%s)", acc);
|
||||
}
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
462
cmd/wwc/ww.h
Normal file
462
cmd/wwc/ww.h
Normal file
@@ -0,0 +1,462 @@
|
||||
/*
|
||||
* ww.h — central header for libwwc.a (the ww frontend library).
|
||||
*
|
||||
* Plan 9 in spirit. This file mirrors cc/cc.h's role: one shared
|
||||
* header that declares everything every translation unit in the
|
||||
* frontend cares about.
|
||||
*
|
||||
* Phases add to this file (lexer/parser/checker), they do not branch
|
||||
* a sibling header. There is one frontend; there is one ww.h.
|
||||
*/
|
||||
#ifndef WW_H
|
||||
#define WW_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
|
||||
/* version banner — printed by `ww -V` */
|
||||
#define WW_VERSION "0.0"
|
||||
|
||||
/* short integer aliases, Plan 9 / Hare-flavoured */
|
||||
typedef int8_t i8;
|
||||
typedef int16_t i16;
|
||||
typedef int32_t i32;
|
||||
typedef int64_t i64;
|
||||
typedef uint8_t u8;
|
||||
typedef uint16_t u16;
|
||||
typedef uint32_t u32;
|
||||
typedef uint64_t u64;
|
||||
|
||||
/* forward decls — concrete shapes appear in their phases. */
|
||||
typedef struct Tok Tok;
|
||||
typedef struct Lex Lex;
|
||||
typedef struct Node Node;
|
||||
typedef struct Sym Sym;
|
||||
typedef struct Type Type;
|
||||
typedef struct Scope Scope;
|
||||
typedef struct Arena Arena;
|
||||
|
||||
/* mem.c — bump arena (no free; reset/destroy at end of phase) */
|
||||
struct Arena {
|
||||
u8 *buf; /* base of current chunk */
|
||||
u64 off; /* bytes used in current chunk */
|
||||
u64 cap; /* capacity of current chunk */
|
||||
struct Arena *next; /* older chunks (linked list, head = current) */
|
||||
u64 total; /* across all chunks, debug only */
|
||||
};
|
||||
|
||||
Arena *newarena(void);
|
||||
void *amalloc(Arena*, u64); /* zeroed, aligned to 16 */
|
||||
char *astrdup(Arena*, const char*);
|
||||
char *astrndup(Arena*, const char*, u64);
|
||||
char *aprintf(Arena*, const char*, ...);
|
||||
void freearena(Arena*);
|
||||
|
||||
/* err.c — diagnostics. Phase 0 has only fatal/warn; later phases add
|
||||
* source-location-bearing variants. */
|
||||
typedef struct Pos Pos;
|
||||
struct Pos {
|
||||
const char *file;
|
||||
i32 line;
|
||||
i32 col;
|
||||
};
|
||||
|
||||
extern Pos noPos;
|
||||
extern int nerrors;
|
||||
extern int nwarnings;
|
||||
extern FILE *errout;
|
||||
|
||||
void fatal(const char*, ...) __attribute__((noreturn, format(printf, 1, 2)));
|
||||
void errorf(Pos, const char*, ...) __attribute__((format(printf, 2, 3)));
|
||||
void warnf(Pos, const char*, ...) __attribute__((format(printf, 2, 3)));
|
||||
|
||||
/* tiny helpers */
|
||||
#define nelem(a) ((sizeof(a) / sizeof((a)[0])))
|
||||
|
||||
/* ---- lexer (lex.c, tok.c) ----------------------------------------- */
|
||||
typedef enum {
|
||||
/* zero is "no token" so memset-zero structs read sane */
|
||||
TK_NONE = 0,
|
||||
|
||||
/* trivial */
|
||||
TK_EOF,
|
||||
TK_ERR,
|
||||
TK_IDENT,
|
||||
TK_INT,
|
||||
TK_FLOAT,
|
||||
TK_RUNE,
|
||||
TK_STR,
|
||||
|
||||
/* keywords — stay grouped, used by tok.c kwtab */
|
||||
TK_FN,
|
||||
TK_LET,
|
||||
TK_DEF,
|
||||
TK_IF,
|
||||
TK_ELSE,
|
||||
TK_FOR,
|
||||
TK_SWITCH,
|
||||
TK_CASE,
|
||||
TK_RETURN,
|
||||
TK_USE,
|
||||
TK_TYPE,
|
||||
TK_STRUCT,
|
||||
TK_DEFER,
|
||||
TK_BREAK,
|
||||
TK_CONTINUE,
|
||||
TK_EXPORT,
|
||||
TK_PROC,
|
||||
TK_CHAN,
|
||||
TK_NIL,
|
||||
TK_TRUE,
|
||||
TK_FALSE,
|
||||
TK_AS, /* reserved for future cast spelling, not active */
|
||||
TK_STATIC, /* Hare-style storage-class qualifier */
|
||||
TK_MATCH, /* match expression head */
|
||||
|
||||
/* punct + operators */
|
||||
TK_LPAREN, /* ( */
|
||||
TK_RPAREN, /* ) */
|
||||
TK_LBRACE, /* { */
|
||||
TK_RBRACE, /* } */
|
||||
TK_LBRACK, /* [ */
|
||||
TK_RBRACK, /* ] */
|
||||
TK_COMMA, /* , */
|
||||
TK_SEMI, /* ; */
|
||||
TK_COLON, /* : */
|
||||
TK_DOT, /* . */
|
||||
TK_ELLIPSIS, /* ... */
|
||||
TK_DOTDOT, /* .. (range op) */
|
||||
TK_AT, /* @ */
|
||||
TK_QUESTION, /* ? */
|
||||
|
||||
TK_ASSIGN, /* = */
|
||||
TK_PLUSEQ, /* += */
|
||||
TK_MINUSEQ, /* -= */
|
||||
TK_STAREQ, /* *= */
|
||||
TK_SLASHEQ, /* /= */
|
||||
TK_PERCENTEQ, /* %= */
|
||||
TK_AMPEQ, /* &= */
|
||||
TK_PIPEEQ, /* |= */
|
||||
TK_CARETEQ, /* ^= */
|
||||
TK_LSHIFTEQ, /* <<= */
|
||||
TK_RSHIFTEQ, /* >>= */
|
||||
|
||||
TK_PLUS, /* + */
|
||||
TK_MINUS, /* - */
|
||||
TK_STAR, /* * */
|
||||
TK_SLASH, /* / */
|
||||
TK_PERCENT, /* % */
|
||||
TK_AMP, /* & */
|
||||
TK_PIPE, /* | */
|
||||
TK_CARET, /* ^ */
|
||||
TK_TILDE, /* ~ */
|
||||
TK_LSHIFT, /* << */
|
||||
TK_RSHIFT, /* >> */
|
||||
|
||||
TK_EQ, /* == */
|
||||
TK_NEQ, /* != */
|
||||
TK_LT, /* < */
|
||||
TK_LE, /* <= */
|
||||
TK_GT, /* > */
|
||||
TK_GE, /* >= */
|
||||
|
||||
TK_AND, /* && */
|
||||
TK_OR, /* || */
|
||||
TK_NOT, /* ! */
|
||||
|
||||
TK_LARROW, /* <- (chan recv) */
|
||||
TK_ARROW, /* -> (reserved) */
|
||||
TK_FATARROW, /* => (match arms) */
|
||||
|
||||
TK_LAST /* sentinel for tables */
|
||||
} Tkind;
|
||||
|
||||
struct Tok {
|
||||
Tkind kind;
|
||||
Pos pos;
|
||||
const char *text; /* lexeme (arena-owned, NUL-terminated) */
|
||||
u64 tlen; /* byte length of lexeme (sans NUL) */
|
||||
/* numeric values pre-parsed; string/rune unescaped */
|
||||
union {
|
||||
u64 uval; /* TK_INT, TK_RUNE */
|
||||
double fval; /* TK_FLOAT */
|
||||
} v;
|
||||
/* for typed numeric literals: "i32", "u8", "f64", ... or NULL. */
|
||||
const char *tsuffix;
|
||||
};
|
||||
|
||||
struct Lex {
|
||||
const char *file;
|
||||
const char *src; /* full source, NUL-terminated */
|
||||
u64 srclen;
|
||||
u64 pos; /* current byte offset */
|
||||
i32 line;
|
||||
i32 col;
|
||||
Arena *a; /* token-text arena */
|
||||
int errs;
|
||||
};
|
||||
|
||||
void lexinit(Lex*, Arena*, const char *file, const char *src, u64 len);
|
||||
Tok lexnext(Lex*);
|
||||
const char *tokname(Tkind); /* canonical spelling, e.g. "fn", "+=" */
|
||||
void tokprint(FILE*, Tok); /* one line, "%s:%d:%d: %s %q" */
|
||||
Tkind kwlookup(const char *s, u64 n); /* TK_NONE if not a keyword */
|
||||
|
||||
/* ---- AST (ast.c, parse.c) ----------------------------------------- */
|
||||
typedef enum {
|
||||
N_NONE = 0,
|
||||
|
||||
/* literals */
|
||||
N_INTLIT,
|
||||
N_FLOATLIT,
|
||||
N_STRLIT,
|
||||
N_RUNELIT,
|
||||
N_TRUE,
|
||||
N_FALSE,
|
||||
N_NIL,
|
||||
N_IDENT,
|
||||
|
||||
/* expressions */
|
||||
N_BIN, /* op, lhs, rhs */
|
||||
N_UN, /* op, lhs */
|
||||
N_CALL, /* lhs=callee, list=args */
|
||||
N_INDEX, /* lhs=base, rhs=index */
|
||||
N_DOT, /* lhs=base, str=field */
|
||||
N_CAST, /* lhs=expr, rhs=type-expr */
|
||||
N_STRUCTLIT, /* lhs=type-expr, list=N_FIELD */
|
||||
N_ARRLIT, /* list=elements (for [a,b,...]) */
|
||||
N_FIELD, /* str=name, lhs=value */
|
||||
N_ASSIGN, /* op, lhs, rhs */
|
||||
N_ALLOC, /* lhs=expr, rhs=size-or-null */
|
||||
N_FREE, /* lhs=expr */
|
||||
N_RECV, /* lhs (chan recv: <-c) */
|
||||
N_SLICE, /* lhs=base, rhs=lo or NULL, cond=hi or NULL */
|
||||
N_SPREAD, /* lhs (variadic spread in arg position: e...) */
|
||||
|
||||
/* statements */
|
||||
N_BLOCK, /* list=stmts */
|
||||
N_EXPRSTMT, /* lhs=expr */
|
||||
N_LET, /* str=name, lhs=type-expr|NULL, rhs=init|NULL */
|
||||
N_RETURN, /* lhs=expr|NULL */
|
||||
N_IF, /* cond, body, els */
|
||||
N_FOR, /* lhs=init, cond, rhs=post, body */
|
||||
N_FORRANGE, /* str=elem name, lhs=slice expr, body=block */
|
||||
N_DEFER, /* lhs=expr */
|
||||
N_BREAK,
|
||||
N_CONTINUE,
|
||||
N_SWITCH, /* lhs=scrutinee, list=cases */
|
||||
N_CASE, /* list=exprs (empty=default), body */
|
||||
|
||||
/* declarations */
|
||||
N_FILE, /* list=top decls */
|
||||
N_USE, /* str=path */
|
||||
N_DEF, /* str=name, lhs=type|NULL, rhs=init */
|
||||
N_TYPEDECL, /* str=name, lhs=type-expr */
|
||||
N_FNDECL, /* str=name, list=params, lhs=ret-type, body|NULL */
|
||||
N_PARAM, /* str=name, lhs=type-expr */
|
||||
|
||||
/* type expressions */
|
||||
N_TNAME, /* str */
|
||||
N_TPTR, /* lhs=inner */
|
||||
N_TSLICE, /* lhs=inner */
|
||||
N_TARRAY, /* lhs=element, rhs=len-expr */
|
||||
N_TFN, /* list=params, lhs=ret */
|
||||
N_TSTRUCT, /* list=fields */
|
||||
N_TFIELD, /* str=name, lhs=type */
|
||||
N_TCHAN, /* lhs=element */
|
||||
|
||||
/* attribute on a decl */
|
||||
N_ATTR, /* str=name, list=args */
|
||||
|
||||
/* multi-value (tuple) plumbing */
|
||||
N_TTUPLE, /* type expr: (T1, T2, ...). list = element type exprs */
|
||||
N_TTAGGED, /* type expr: (T1 | T2 | ...). list = variant type exprs */
|
||||
N_TUPLE, /* expr: (e1, e2, ...). list = element exprs */
|
||||
N_MATCH, /* match (lhs) { list of cases }; cases are N_MCASE */
|
||||
N_MCASE, /* str=binding name (or NULL), lhs=variant type expr or NULL, body */
|
||||
N_TRYPROP, /* lhs? — propagate error variant */
|
||||
N_TRYUNW, /* lhs! — abort on error variant */
|
||||
N_MLET, /* let a, b = expr; list = N_LET stubs (str, lhs=type), rhs = expr */
|
||||
N_MASSIGN, /* a, b = expr; list = lvalue exprs, rhs = expr */
|
||||
|
||||
N_LAST
|
||||
} Nkind;
|
||||
|
||||
struct Node {
|
||||
Nkind kind;
|
||||
Pos pos;
|
||||
Tkind op; /* for N_BIN/N_UN/N_ASSIGN */
|
||||
const char *str; /* identifier/literal/name/path */
|
||||
u64 strlen;
|
||||
u64 uval; /* int/rune lit */
|
||||
double fval; /* float lit */
|
||||
Node *lhs;
|
||||
Node *rhs;
|
||||
Node *cond;
|
||||
Node *body;
|
||||
Node *els;
|
||||
Node *list; /* head of singly-linked sibling chain */
|
||||
Node *next; /* sibling link inside `list` */
|
||||
Node *attr; /* @attribute chain (N_ATTR list) */
|
||||
int export;
|
||||
Type *type; /* filled in by checker */
|
||||
const char *tsuffix; /* typed numeric literal suffix */
|
||||
};
|
||||
|
||||
Node *newnode(Arena*, Nkind, Pos);
|
||||
void astprint(FILE*, Node*); /* s-expr, deterministic, one-line per node */
|
||||
|
||||
typedef struct Parser Parser;
|
||||
struct Parser {
|
||||
Lex *l;
|
||||
Arena *a;
|
||||
Tok cur;
|
||||
Tok la; /* one-token lookahead buffer */
|
||||
int hasla;
|
||||
int errs;
|
||||
int nocast; /* in case-selector ctx, ':' is a separator */
|
||||
};
|
||||
|
||||
void parserinit(Parser*, Arena*, Lex*);
|
||||
Node *parsefile(Parser*);
|
||||
Node *parseexpr_top(Parser*); /* for testing: parse one expression */
|
||||
|
||||
/* ---- types (type.c) ----------------------------------------------- */
|
||||
typedef enum {
|
||||
TY_NONE = 0,
|
||||
TY_VOID,
|
||||
TY_BOOL,
|
||||
TY_RUNE,
|
||||
TY_I8, TY_I16, TY_I32, TY_I64,
|
||||
TY_U8, TY_U16, TY_U32, TY_U64,
|
||||
TY_UINT, TY_INT,
|
||||
TY_UINTPTR,
|
||||
TY_F32, TY_F64,
|
||||
TY_STR,
|
||||
TY_PTR,
|
||||
TY_SLICE,
|
||||
TY_ARRAY,
|
||||
TY_STRUCT,
|
||||
TY_FN,
|
||||
TY_CHAN,
|
||||
TY_NAMED,
|
||||
TY_TUPLE,
|
||||
TY_TAGGED, /* (T1 | T2 | ...) — Hare-style sum type */
|
||||
TY_ERR,
|
||||
/* untyped constants (not surfaced to users; checker-internal) */
|
||||
TY_UNTYPED_INT,
|
||||
TY_UNTYPED_FLOAT,
|
||||
TY_UNTYPED_STR,
|
||||
TY_UNTYPED_RUNE,
|
||||
TY_UNTYPED_BOOL,
|
||||
TY_UNTYPED_NIL
|
||||
} TypeKind;
|
||||
|
||||
typedef struct Tfield Tfield;
|
||||
struct Tfield {
|
||||
const char *name;
|
||||
Type *type;
|
||||
u64 offset;
|
||||
Tfield *next;
|
||||
};
|
||||
|
||||
typedef struct Tparam Tparam;
|
||||
struct Tparam {
|
||||
const char *name;
|
||||
Type *type;
|
||||
Tparam *next;
|
||||
};
|
||||
|
||||
struct Type {
|
||||
TypeKind kind;
|
||||
u64 size;
|
||||
u64 align;
|
||||
Type *sub; /* ptr/slice/array/chan element */
|
||||
u64 alen; /* array length */
|
||||
Tfield *fields;/* struct */
|
||||
Tparam *params;/* fn */
|
||||
Type *ret; /* fn */
|
||||
int variadic;
|
||||
const char *name; /* named alias / debug */
|
||||
Type *under; /* underlying resolved type for NAMED */
|
||||
};
|
||||
|
||||
extern Type *ty_void, *ty_bool, *ty_rune;
|
||||
extern Type *ty_i8, *ty_i16, *ty_i32, *ty_i64;
|
||||
extern Type *ty_u8, *ty_u16, *ty_u32, *ty_u64;
|
||||
extern Type *ty_int, *ty_uint, *ty_uintptr;
|
||||
extern Type *ty_f32, *ty_f64, *ty_str;
|
||||
extern Type *ty_err;
|
||||
extern Type *ty_untyped_int, *ty_untyped_float, *ty_untyped_str;
|
||||
extern Type *ty_untyped_rune, *ty_untyped_bool, *ty_untyped_nil;
|
||||
|
||||
void typesinit(Arena*);
|
||||
Type *newtype(Arena*, TypeKind);
|
||||
Type *type_ptr(Arena*, Type *sub);
|
||||
Type *type_slice(Arena*, Type *sub);
|
||||
Type *type_array(Arena*, Type *sub, u64 len);
|
||||
Type *type_chan(Arena*, Type *sub);
|
||||
Type *type_named(Arena*, const char *name, Type *under);
|
||||
const char *type_name(Arena*, Type*); /* arena'd debug string */
|
||||
int type_eq(Type *a, Type *b); /* structural equality */
|
||||
int type_isint(Type *t);
|
||||
int type_isfloat(Type *t);
|
||||
int type_isnum(Type *t);
|
||||
int type_isunsigned(Type *t);
|
||||
int type_isuntyped(Type *t);
|
||||
int type_assignable(Type *dst, Type *src);
|
||||
Type *type_default(Type *t); /* untyped → default concrete */
|
||||
|
||||
/* ---- symbols (sym.c) ---------------------------------------------- */
|
||||
typedef enum {
|
||||
SK_NONE = 0,
|
||||
SK_VAR,
|
||||
SK_PARAM,
|
||||
SK_DEF,
|
||||
SK_TYPE,
|
||||
SK_FN,
|
||||
SK_USE,
|
||||
SK_FIELD /* not stored in scope; used by check internally */
|
||||
} Skind;
|
||||
|
||||
struct Sym {
|
||||
const char *name;
|
||||
Skind kind;
|
||||
Type *type;
|
||||
Node *decl;
|
||||
int exported;
|
||||
Sym *next; /* iteration */
|
||||
Sym *hashnext; /* bucket chain */
|
||||
Scope *scope;
|
||||
};
|
||||
|
||||
struct Scope {
|
||||
Scope *parent;
|
||||
Sym *first, *last;
|
||||
Sym **buckets;
|
||||
u64 nbuckets;
|
||||
Arena *a;
|
||||
};
|
||||
|
||||
Scope *newscope(Arena*, Scope *parent);
|
||||
Sym *scope_define(Scope*, const char *name, Skind, Type*, Node *decl);
|
||||
Sym *scope_lookup(Scope*, const char *name); /* walk up parents */
|
||||
Sym *scope_lookup_local(Scope*, const char *name);
|
||||
|
||||
/* ---- checker (check.c) -------------------------------------------- */
|
||||
typedef struct Checker Checker;
|
||||
struct Checker {
|
||||
Arena *a;
|
||||
Scope *top; /* file scope */
|
||||
Scope *cur; /* current scope */
|
||||
Type *ret; /* expected return type of current fn (or NULL) */
|
||||
int loops; /* nesting count for break/continue */
|
||||
int errs;
|
||||
};
|
||||
|
||||
void check_init(Checker*, Arena*);
|
||||
void check_file(Checker*, Node *file);
|
||||
|
||||
#endif /* WW_H */
|
||||
119
cmd/wwdump/main.c
Normal file
119
cmd/wwdump/main.c
Normal file
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
* wwdump — deterministic dump tool for ww source.
|
||||
*
|
||||
* Reads a .ww file and writes either a token stream or an AST
|
||||
* s-expression to stdout, byte-for-byte stable across runs. It is the
|
||||
* diff anchor for self-host: the C-side libwwc and the future ww-side
|
||||
* frontend must produce the same dump for the same input.
|
||||
*
|
||||
* wwdump -t file.ww tokens, one per line: "<file>:<l>:<c> <kind> [val]"
|
||||
* wwdump -a file.ww AST as s-expr, one node per line
|
||||
*
|
||||
* No newlines or trailing whitespace varies by phase of the moon. If
|
||||
* the bytes differ, somebody changed the front end.
|
||||
*/
|
||||
#include "ww.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static int
|
||||
slurp(const char *path, char **outbuf, u64 *outlen)
|
||||
{
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (f == NULL) return -1;
|
||||
fseek(f, 0, SEEK_END);
|
||||
long n = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
if (n < 0) { fclose(f); return -1; }
|
||||
char *b = malloc((size_t)n + 1);
|
||||
if (b == NULL) { fclose(f); return -1; }
|
||||
if (fread(b, 1, (size_t)n, f) != (size_t)n) { free(b); fclose(f); return -1; }
|
||||
b[n] = '\0';
|
||||
fclose(f);
|
||||
*outbuf = b;
|
||||
*outlen = (u64)n;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
dump_tokens(const char *src, char *buf, u64 len, FILE *out)
|
||||
{
|
||||
Arena *a = newarena();
|
||||
Lex l;
|
||||
lexinit(&l, a, src, buf, len);
|
||||
for (;;) {
|
||||
Tok t = lexnext(&l);
|
||||
tokprint(out, t);
|
||||
if (t.kind == TK_EOF || t.kind == TK_ERR) break;
|
||||
}
|
||||
int errs = l.errs;
|
||||
freearena(a);
|
||||
return errs ? 1 : 0;
|
||||
}
|
||||
|
||||
static int
|
||||
dump_ast(const char *src, char *buf, u64 len, FILE *out)
|
||||
{
|
||||
Arena *a = newarena();
|
||||
Lex l;
|
||||
Parser p;
|
||||
lexinit(&l, a, src, buf, len);
|
||||
parserinit(&p, a, &l);
|
||||
Node *file = parsefile(&p);
|
||||
int errs = l.errs || p.errs;
|
||||
if (file) astprint(out, file);
|
||||
freearena(a);
|
||||
return errs ? 1 : 0;
|
||||
}
|
||||
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
int mode = 't'; /* tokens by default */
|
||||
const char *src = NULL;
|
||||
const char *out = NULL;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
const char *a = argv[i];
|
||||
if (strcmp(a, "-t") == 0) mode = 't';
|
||||
else if (strcmp(a, "-a") == 0) mode = 'a';
|
||||
else if (strcmp(a, "-o") == 0 && i + 1 < argc) out = argv[++i];
|
||||
else if (a[0] == '-') {
|
||||
fprintf(stderr, "wwdump: unknown flag %s\n", a);
|
||||
return 2;
|
||||
}
|
||||
else if (src == NULL) src = a;
|
||||
else {
|
||||
fputs("wwdump: only one input supported\n", stderr);
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
if (src == NULL) {
|
||||
fputs("usage: wwdump [-t|-a] [-o out] file.ww\n", stderr);
|
||||
return 2;
|
||||
}
|
||||
|
||||
char *buf;
|
||||
u64 len;
|
||||
if (slurp(src, &buf, &len) < 0) {
|
||||
fprintf(stderr, "wwdump: %s: cannot read\n", src);
|
||||
return 1;
|
||||
}
|
||||
|
||||
FILE *of = stdout;
|
||||
if (out) {
|
||||
of = fopen(out, "wb");
|
||||
if (of == NULL) {
|
||||
fprintf(stderr, "wwdump: cannot open %s\n", out);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
int rc;
|
||||
if (mode == 'a') rc = dump_ast(src, buf, len, of);
|
||||
else rc = dump_tokens(src, buf, len, of);
|
||||
|
||||
if (of != stdout) fclose(of);
|
||||
free(buf);
|
||||
return rc;
|
||||
}
|
||||
Reference in New Issue
Block a user