Permalink
Browse files

Adding bitwise negation.

  • Loading branch information...
Wilfred committed Jul 14, 2014
1 parent 40cbac1 commit 32a82562096873f67c4fb36198eba43abc4ea8d6
Showing with 41 additions and 14 deletions.
  1. +1 −0 babyc_lex.l
  2. +26 −11 babyc_parse.y
  3. +11 −3 syntax.c
  4. +3 −0 test_programs/negation__return_254.c
@@ -12,6 +12,7 @@
"}" { return CLOSE_BRACE; }
"(" { return '('; }
")" { return ')'; }
"~" { return BITWISE_NEGATE; }
";" { return ';'; }
[0-9]+ {
/* TODO: check numbers are in the legal range, and don't start with 0. */
@@ -24,9 +24,15 @@ void write_skeleton(Syntax *syntax) {
fprintf(out, " .global _start\n\n");
fprintf(out, "_start:\n");
// Exit code as specified.
// TODO: convert to hex properly.
fprintf(out, " movl $%d, %%ebx\n", syntax->value);
// TODO: do everything in eax, then move to ebx for exit.
// TODO: recurse
if (syntax->type == UNARY_OPERATOR) {
fprintf(out, " movl $%d, %%ebx\n", syntax->expression->value);
fprintf(out, " not %%ebx\n", syntax->expression->value);
} else {
// Exit code as specified.
fprintf(out, " movl $%d, %%ebx\n", syntax->value);
}
fprintf(out, " movl $1, %%eax\n");
fprintf(out, " int $0x80\n");
@@ -60,18 +66,14 @@ int main(int argc, char *argv[])
printf(" $ ld -s -o out out.o\n");
return 0;
/* Syntax *babyc_parse(FILE *file) { */
/* yyin = file; */
/* yyparse(); */
/* return syntax; */
}
%}
%token INCLUDE HEADER_NAME
%token TYPE IDENTIFIER RETURN NUMBER
%token OPEN_BRACE CLOSE_BRACE
%token BITWISE_NEGATE
%%
@@ -80,16 +82,29 @@ program:
;
function:
TYPE IDENTIFIER '(' ')' OPEN_BRACE expression CLOSE_BRACE
TYPE IDENTIFIER '(' ')' OPEN_BRACE statement CLOSE_BRACE
;
statement:
RETURN expression ';'
;
expression:
RETURN NUMBER ';'
NUMBER
{
// TODO: fix the memory leak here.
Syntax *immediate = malloc(sizeof(Syntax));
immediate->value = $2;
immediate->type = IMMEDIATE;
immediate->value = $1;
syntax = immediate;
}
|
BITWISE_NEGATE expression
{
Syntax *unary = malloc(sizeof(Syntax));
unary->type = UNARY_OPERATOR;
unary->expression = syntax;
syntax = unary;
}
;
@@ -2,13 +2,21 @@
#ifndef BABYC_SYNTAX
#define BABYC_SYNTAX

typedef enum { IMMEDIATE } SyntaxType;
typedef enum { IMMEDIATE, UNARY_OPERATOR } SyntaxType;

typedef struct {
struct Syntax;
typedef struct Syntax Syntax;

struct Syntax {
SyntaxType type;
union {
// Immediate
int value;

// Unary operators
// TODO: store which operator
struct Syntax* expression;
};
} Syntax;
};

#endif
@@ -0,0 +1,3 @@
int main() {
return ~1;
}

0 comments on commit 32a8256

Please sign in to comment.