Skip to content

Commit

Permalink
単行 +,-の追加
Browse files Browse the repository at this point in the history
  • Loading branch information
lvlnaga committed Jan 6, 2023
1 parent f1b1a96 commit 0dd18e5
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 7 deletions.
Binary file modified 9cc-memo.xmind
Binary file not shown.
25 changes: 18 additions & 7 deletions 9cc.c
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -185,6 +185,7 @@ Node *new_node_num(int val)

Node *expr();
Node *mul();
Node *unary();
Node *primary();

// expr = mul ("+" mul | "-" mul)*
Expand All @@ -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()
{
Expand Down Expand Up @@ -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);
Expand Down
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions test.sh
Expand Up @@ -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

0 comments on commit 0dd18e5

Please sign in to comment.