Skip to content

Commit

Permalink
Add ~ operator
Browse files Browse the repository at this point in the history
  • Loading branch information
rui314 committed Dec 7, 2020
1 parent 6b88bcb commit 46a96d6
Show file tree
Hide file tree
Showing 5 changed files with 15 additions and 1 deletion.
1 change: 1 addition & 0 deletions chibicc.h
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ typedef enum {
ND_ADDR, // unary &
ND_DEREF, // unary *
ND_NOT, // !
ND_BITNOT, // ~
ND_RETURN, // "return"
ND_IF, // "if"
ND_FOR, // "for" or "while"
Expand Down
4 changes: 4 additions & 0 deletions codegen.c
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,10 @@ static void gen_expr(Node *node) {
println(" sete %%al");
println(" movzx %%al, %%rax");
return;
case ND_BITNOT:
gen_expr(node->lhs);
println(" not %%rax");
return;
case ND_FUNCALL: {
int nargs = 0;
for (Node *arg = node->args; arg; arg = arg->next) {
Expand Down
5 changes: 4 additions & 1 deletion parse.c
Original file line number Diff line number Diff line change
Expand Up @@ -888,7 +888,7 @@ static Node *cast(Token **rest, Token *tok) {
return unary(rest, tok);
}

// unary = ("+" | "-" | "*" | "&" | "!") cast
// unary = ("+" | "-" | "*" | "&" | "!" | "~") cast
// | ("++" | "--") unary
// | postfix
static Node *unary(Token **rest, Token *tok) {
Expand All @@ -907,6 +907,9 @@ static Node *unary(Token **rest, Token *tok) {
if (equal(tok, "!"))
return new_unary(ND_NOT, cast(rest, tok->next), tok);

if (equal(tok, "~"))
return new_unary(ND_BITNOT, cast(rest, tok->next), tok);

// Read ++i as i+=1
if (equal(tok, "++"))
return to_assign(new_add(unary(rest, tok->next), new_num(1, tok), tok));
Expand Down
3 changes: 3 additions & 0 deletions test/arith.c
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ int main() {
ASSERT(4, sizeof(!(char)0));
ASSERT(4, sizeof(!(long)0));

ASSERT(-1, ~0);
ASSERT(0, ~-1);

printf("OK\n");
return 0;
}
3 changes: 3 additions & 0 deletions type.c
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,9 @@ void add_type(Node *node) {
case ND_NOT:
node->ty = ty_int;
return;
case ND_BITNOT:
node->ty = node->lhs->ty;
return;
case ND_VAR:
node->ty = node->var->ty;
return;
Expand Down

0 comments on commit 46a96d6

Please sign in to comment.