diff --git a/9cc-memo.xmind b/9cc-memo.xmind index e12ceb1..b29505d 100644 Binary files a/9cc-memo.xmind and b/9cc-memo.xmind differ diff --git a/9cc.c b/9cc.c index 2a67809..531597d 100644 --- a/9cc.c +++ b/9cc.c @@ -94,7 +94,7 @@ bool at_eof() // 新しいトークンを作成してcurに繋げる Token *new_token(TokenKind kind, Token *cur, char *str) { - Token *tok = calloc(1, sizeof(Token)); //? callocの仕様を知りたい + Token *tok = calloc(1, sizeof(Token)); tok->kind = kind; tok->str = str; cur->next = tok; @@ -119,7 +119,7 @@ Token *tokenize() } // if (*p == '+' || *p == '-' || *p == '*' || *p == '/' || *p == '(' || *p == ')' ) - if (strchr("+-*/()",*p)) //strchrってどういう関数? + if (strchr("+-*/()",*p)) { cur = new_token(TK_RESERVED, cur, p++); continue; @@ -185,6 +185,7 @@ Node *new_node_num(int val) Node *expr(); Node *mul(); +Node *unary(); Node *primary(); // expr = mul ("+" mul | "-" mul)* @@ -203,22 +204,32 @@ Node *expr() } } -// mul = primary ("*" primary | "/" primary)* +// mul = unary ("*" unary | "/" unary)* // *,/ : 左結合演算子 Node *mul() { - Node *node = primary(); + Node *node = unary(); for (;;) { if (consume('*')) - node = new_node(ND_MUL, node, primary()); + node = new_node(ND_MUL, node, unary()); else if (consume('/')) - node = new_node(ND_DIV, node, primary()); + node = new_node(ND_DIV, node, unary()); else return node; } } +// unary = unary = ("+" | "-")? primary +Node *unary() +{ + if (consume('+')) + return primary(); + if (consume('-')) + return new_node(ND_SUB, new_node_num(0),primary()); + return primary(); +} + // primary = num | "(" expr ")" Node *primary() { @@ -246,7 +257,7 @@ void gen(Node *node) if (node->kind == ND_NUM ) { printf(" push %d\n", node->val); - return; //空returnはどう解釈される? + return; } gen(node->lhs); diff --git "a/images/\346\226\207\346\263\225\343\201\256\350\250\230\350\277\260\346\226\271\345\274\217\343\201\250 \345\206\215\345\270\260\344\270\213\351\231\215\346\247\213\346\226\207\350\247\243\346\236\220.png" "b/images/\346\226\207\346\263\225\343\201\256\350\250\230\350\277\260\346\226\271\345\274\217\343\201\250 \345\206\215\345\270\260\344\270\213\351\231\215\346\247\213\346\226\207\350\247\243\346\236\220.png" new file mode 100644 index 0000000..32d06f7 Binary files /dev/null and "b/images/\346\226\207\346\263\225\343\201\256\350\250\230\350\277\260\346\226\271\345\274\217\343\201\250 \345\206\215\345\270\260\344\270\213\351\231\215\346\247\213\346\226\207\350\247\243\346\236\220.png" differ diff --git a/test.sh b/test.sh index 1c43316..aa60a22 100755 --- a/test.sh +++ b/test.sh @@ -23,5 +23,6 @@ assert 41 " 12 + 34 - 5 " assert 47 '5+6*7' assert 15 '5*(9-6)' assert 4 '(3+5)/2' +assert 10 '-10 + 20' echo OK