From 65f3a0171e25075db886f4d5cc4127ed04a77a88 Mon Sep 17 00:00:00 2001 From: Wilfred Hughes Date: Sat, 12 Jul 2014 01:05:17 +0100 Subject: [PATCH] Actually compiling return codes! --- minimal_c.l | 7 ++++++- minimal_c.y | 9 +++++++-- test_programs/two.c | 3 +++ 3 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 test_programs/two.c diff --git a/minimal_c.l b/minimal_c.l index f6317eb..d47f99d 100644 --- a/minimal_c.l +++ b/minimal_c.l @@ -13,7 +13,12 @@ "(" { return '('; } ")" { return ')'; } ";" { return ';'; } -[0-9]+ { return NUMBER; } +[0-9]+ { + /* TODO: check numbers are in the legal range, and don't start with 0. */ + printf("yytext: %s\n", yytext); + printf("yylval: %d\n", atoi(yytext)); + yylval=atoi(yytext); return NUMBER; + } "return" { return RETURN; } "int" { return TYPE; } diff --git a/minimal_c.y b/minimal_c.y index 2b7593b..1c3f547 100644 --- a/minimal_c.y +++ b/minimal_c.y @@ -14,6 +14,9 @@ int yywrap() extern FILE *yyin; +// Shameful hack. We should build a proper AST and traverse it. +static int return_code; + void write_skeleton() { FILE *out = fopen("out.s", "wb"); @@ -22,8 +25,9 @@ void write_skeleton() { fprintf(out, " .global _start\n\n"); fprintf(out, "_start:\n"); - // Exit code of zero. - fprintf(out, " movl $0, %%ebx\n"); + // Exit code as specified. + // TODO: convert to hex properly. + fprintf(out, " movl $%d, %%ebx\n", return_code); fprintf(out, " movl $1, %%eax\n"); fprintf(out, " int $0x80\n"); @@ -73,5 +77,6 @@ function: expression: RETURN NUMBER ';' + { return_code = $2; } ; diff --git a/test_programs/two.c b/test_programs/two.c new file mode 100644 index 0000000..5cca8e2 --- /dev/null +++ b/test_programs/two.c @@ -0,0 +1,3 @@ +int main() { + return 2; +}