Skip to content
This repository has been archived by the owner on Feb 14, 2022. It is now read-only.

Commit

Permalink
Adding bitwise negation.
Browse files Browse the repository at this point in the history
  • Loading branch information
Wilfred committed Jul 14, 2014
1 parent 40cbac1 commit 32a8256
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 14 deletions.
1 change: 1 addition & 0 deletions babyc_lex.l
Expand Up @@ -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. */
Expand Down
37 changes: 26 additions & 11 deletions babyc_parse.y
Expand Up @@ -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");
Expand Down Expand Up @@ -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

%%

Expand All @@ -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;
}
;

14 changes: 11 additions & 3 deletions syntax.c
Expand Up @@ -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
3 changes: 3 additions & 0 deletions test_programs/negation__return_254.c
@@ -0,0 +1,3 @@
int main() {
return ~1;
}

0 comments on commit 32a8256

Please sign in to comment.