Add void type

This commit is contained in:
Rui Ueyama 2019-08-11 10:18:55 +09:00
parent 71b92d35c4
commit 8260122116
5 changed files with 29 additions and 4 deletions

View File

@ -144,6 +144,7 @@ Var *parse(Token *tok);
//
typedef enum {
TY_VOID,
TY_CHAR,
TY_SHORT,
TY_INT,
@ -193,6 +194,8 @@ struct Member {
int offset;
};
extern Type *ty_void;
extern Type *ty_char;
extern Type *ty_short;
extern Type *ty_int;

21
parse.c
View File

@ -211,8 +211,14 @@ static void push_tag_scope(Token *tok, Type *ty) {
scope->tags = sc;
}
// typespec = "char" | "short" | "int" | "long" | struct-decl | union-decl
// typespec = "void" | "char" | "short" | "int" | "long"
// | struct-decl | union-decl
static Type *typespec(Token **rest, Token *tok) {
if (equal(tok, "void")) {
*rest = tok->next;
return ty_void;
}
if (equal(tok, "char")) {
*rest = tok->next;
return ty_char;
@ -314,6 +320,9 @@ static Node *declaration(Token **rest, Token *tok) {
tok = skip(tok, ",");
Type *ty = declarator(&tok, tok, basety);
if (ty->kind == TY_VOID)
error_tok(tok, "variable declared void");
Var *var = new_lvar(get_ident(ty->name), ty);
if (!equal(tok, "="))
@ -333,8 +342,14 @@ static Node *declaration(Token **rest, Token *tok) {
// Returns true if a given token represents a type.
static bool is_typename(Token *tok) {
return equal(tok, "char") || equal(tok, "short") || equal(tok, "int") ||
equal(tok, "long") || equal(tok, "struct") || equal(tok, "union");
static char *kw[] = {
"void", "char", "short", "int", "long", "struct", "union",
};
for (int i = 0; i < sizeof(kw) / sizeof(*kw); i++)
if (equal(tok, kw[i]))
return true;
return false;
}
// stmt = "return" expr ";"

View File

@ -62,6 +62,8 @@ int main() {
ASSERT(3, ({ char *x[3]; char y; x[0]=&y; y=3; x[0][0]; }));
ASSERT(4, ({ char x[3]; char (*y)[3]=x; y[0][0]=4; y[0][0]; }));
{ void *x; }
printf("OK\n");
return 0;
}

View File

@ -117,7 +117,7 @@ static int from_hex(char c) {
static bool is_keyword(Token *tok) {
static char *kw[] = {
"return", "if", "else", "for", "while", "int", "sizeof", "char",
"struct", "union", "short", "long",
"struct", "union", "short", "long", "void",
};
for (int i = 0; i < sizeof(kw) / sizeof(*kw); i++)

5
type.c
View File

@ -1,5 +1,7 @@
#include "chibicc.h"
Type *ty_void = &(Type){TY_VOID, 1, 1};
Type *ty_char = &(Type){TY_CHAR, 1, 1};
Type *ty_short = &(Type){TY_SHORT, 2, 2};
Type *ty_int = &(Type){TY_INT, 4, 4};
@ -100,6 +102,9 @@ void add_type(Node *node) {
case ND_DEREF:
if (!node->lhs->ty->base)
error_tok(node->tok, "invalid pointer dereference");
if (node->lhs->ty->base->kind == TY_VOID)
error_tok(node->tok, "dereferencing a void pointer");
node->ty = node->lhs->ty->base;
return;
case ND_STMT_EXPR: