Skip to content

Commit

Permalink
Add ! operator
Browse files Browse the repository at this point in the history
  • Loading branch information
rui314 committed Aug 13, 2019
1 parent f78c409 commit 5ec5e38
Show file tree
Hide file tree
Showing 6 changed files with 18 additions and 3 deletions.
1 change: 1 addition & 0 deletions chibi.h
Expand Up @@ -109,6 +109,7 @@ typedef enum {
ND_MEMBER, // . (struct member access)
ND_ADDR, // unary &
ND_DEREF, // unary *
ND_NOT, // !
ND_RETURN, // "return"
ND_IF, // "if"
ND_WHILE, // "while"
Expand Down
8 changes: 8 additions & 0 deletions codegen.c
Expand Up @@ -260,6 +260,14 @@ static void gen(Node *node) {
if (node->ty->kind != TY_ARRAY)
load(node->ty);
return;
case ND_NOT:
gen(node->lhs);
printf(" pop rax\n");
printf(" cmp rax, 0\n");
printf(" sete al\n");
printf(" movzb rax, al\n");
printf(" push rax\n");
return;
case ND_IF: {
int seq = labelseq++;
if (node->els) {
Expand Down
3 changes: 1 addition & 2 deletions examples/nqueen.c
Expand Up @@ -38,8 +38,7 @@ int solve(int (*board)[10], int row) {
return 0;
}
for (int i = 0; i < 10; i++) {
if (conflict(board, row, i)) {
} else {
if (!conflict(board, row, i)) {
board[row][i] = 1;
solve(board, row + 1);
board[row][i] = 0;
Expand Down
4 changes: 3 additions & 1 deletion parse.c
Expand Up @@ -885,7 +885,7 @@ static Node *cast(void) {
return unary();
}

// unary = ("+" | "-" | "*" | "&")? cast
// unary = ("+" | "-" | "*" | "&" | "!")? cast
// | ("++" | "--") unary
// | postfix
static Node *unary(void) {
Expand All @@ -898,6 +898,8 @@ static Node *unary(void) {
return new_unary(ND_ADDR, cast(), tok);
if (tok = consume("*"))
return new_unary(ND_DEREF, cast(), tok);
if (tok = consume("!"))
return new_unary(ND_NOT, cast(), tok);
if (tok = consume("++"))
return new_unary(ND_PRE_INC, unary(), tok);
if (tok = consume("--"))
Expand Down
4 changes: 4 additions & 0 deletions tests
Expand Up @@ -390,6 +390,10 @@ int main() {
assert(47, 0b101111, "0b101111");
assert(47, 0B101111, "0B101111");

assert(0, !1, "!1");
assert(0, !2, "!2");
assert(1, !0, "!0");

printf("OK\n");
return 0;
}
1 change: 1 addition & 0 deletions type.c
Expand Up @@ -76,6 +76,7 @@ void add_type(Node *node) {
case ND_LT:
case ND_LE:
case ND_NUM:
case ND_NOT:
node->ty = long_type;
return;
case ND_PTR_ADD:
Expand Down

0 comments on commit 5ec5e38

Please sign in to comment.