This commit is contained in:
nora 2024-11-22 23:54:09 +01:00
parent f22293c78e
commit 923e6f2352
2 changed files with 46 additions and 13 deletions

View file

@ -269,19 +269,46 @@ function parse(tokens) {
return parseComma(tok); return parseComma(tok);
} }
function parseStatement(tok) {
switch (tok.peek()?.kind) {
case "ident": {
switch (tok.peek()?.ident) {
case "return": {
const span = tok.next("return").span;
let rhs = undefined;
if (tok.peek()?.kind !== ";") {
rhs = parseExpr(tok);
}
return {
kind: "return",
rhs,
span,
};
}
default: {
// fallthrough
}
}
}
default: {
const expr = parseExpr(tok);
return {
kind: "expr",
expr,
span: expr.span,
};
}
}
}
function parseBlock(tok) { function parseBlock(tok) {
tok.expect("{", "start of block"); tok.expect("{", "start of block");
const statements = []; const statements = [];
while (tok.peek()?.kind !== "}") { while (tok.peek()?.kind !== "}") {
// TODO: non-expression statements statements.push(parseStatement(tok));
const expr = parseExpr(tok);
statements.push({
kind: "expr",
expr,
span: expr.span,
});
tok.expect(";", "end of statement"); tok.expect(";", "end of statement");
} }
@ -477,6 +504,7 @@ function lower(ast) {
throw new Error("bad"); throw new Error("bad");
} }
// TODO: save
codegenExpr(ib, expr.args[0]); codegenExpr(ib, expr.args[0]);
ib.movEaxToEdi(); ib.movEaxToEdi();
ib.call(expr.lhs.string); ib.call(expr.lhs.string);
@ -505,7 +533,10 @@ function lower(ast) {
break; break;
} }
default: { default: {
throw new Error(`unsupported stmt: ${stmt.kind}`); if (stmt.rhs) {
codegenExpr(ib, stmt.rhs);
}
ib.ret();
} }
} }
} }
@ -706,7 +737,6 @@ function lower(ast) {
// text section // text section
const textIndex = sectionCount; const textIndex = sectionCount;
console.log(textContent);
writeSectionHeader(".text", { writeSectionHeader(".text", {
type: /*SHT_PROGBITS*/ 1, type: /*SHT_PROGBITS*/ 1,
flags: /*SHF_ALLOC*/ (1 << 1) | /*SHF_EXECINSTR*/ (1 << 2), flags: /*SHF_ALLOC*/ (1 << 1) | /*SHF_EXECINSTR*/ (1 << 2),
@ -743,9 +773,7 @@ function lower(ast) {
// r_addend // r_addend
rel.append(signedLittleEndian64(relocation.addend)); rel.append(signedLittleEndian64(relocation.addend));
} }
console.log(symbols, rel.buffer.length);
const symtabIndex = sectionCount + 1; const symtabIndex = sectionCount + 1;
console.log("text", textIndex);
writeSectionHeader(".rela", { writeSectionHeader(".rela", {
type: /*SHT_RELA*/ 4, type: /*SHT_RELA*/ 4,
flags: 0, flags: 0,

View file

@ -2,5 +2,10 @@
int main(int argc) int main(int argc)
{ {
exit(42); exit(thisismyfakeconstantbecauseidonthaveconstant(1));
}
int thisismyfakeconstantbecauseidonthaveconstant(int x)
{
return 9;
} }