-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.c
57 lines (50 loc) · 1.03 KB
/
utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "chibicc.h"
bool startwith(char *p, char *q)
{
return strncmp(p, q, strlen(q)) == 0;
}
bool equal(Token *tok, char *op)
{
return strncmp(tok->loc, op, tok->len) == 0 &&
op[tok->len] == '\0';
}
Token *skip(Token *tok, char *s)
{
if (!equal(tok, s))
{
error_tok(tok, "expected token string '%s', actual '%s'",
s, tok->loc);
exit(1);
}
return tok->next;
}
bool consume_if_same(Token **rest, Token *tok, char *str)
{
if (equal(tok, str))
{
*rest = tok->next;
return true;
}
*rest = tok;
return false;
}
char *get_ident(Token *tok)
{
if (tok->kind != TK_IDENT)
error_tok(tok, "expected token kind %d, actual %d",
TK_IDENT, tok->kind);
return strndup(tok->loc, tok->len);
}
int get_number(Token *tok)
{
if (tok->kind != TK_NUM)
error_tok(tok, "expected token kind %d, actual %d",
TK_NUM, tok->kind);
return tok->val;
}
bool is_type(Token *tok)
{
return equal(tok, "int") || equal(tok, "char") ||
equal(tok, "short") || equal(tok, "long") ||
equal(tok, "void") || equal(tok, "struct");
}