Skip to content

Commit

Permalink
impl if macro with number evaluation
Browse files Browse the repository at this point in the history
  • Loading branch information
omdxp committed Sep 4, 2024
1 parent a5b0714 commit 542f76e
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
44 changes: 44 additions & 0 deletions preprocessor/preprocessor.c
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,14 @@ bool preprocessor_token_is_ifndef(struct token *token) {
return S_EQ(token->sval, "ifndef");
}

bool preprocessor_token_is_if(struct token *token) {
if (!preprocessor_token_is_preprocessor_keyword(token)) {
return false;
}

return S_EQ(token->sval, "if");
}

struct buffer *
preprocessor_multi_value_string(struct compile_process *compiler) {
struct buffer *str_buf = buffer_create();
Expand Down Expand Up @@ -749,6 +757,39 @@ void preprocessor_read_to_endif(struct compile_process *compiler,
}
}

int preprocessor_evaluate_number(struct preprocessor_node *node) {
return node->const_val.llnum;
}

int preprocessor_evaluate(struct compile_process *compiler,
struct preprocessor_node *root_node) {
struct preprocessor_node *current = root_node;
int res = 0;
switch (current->type) {
case PREPROCESSOR_NUMBER_NODE:
res = preprocessor_evaluate_number(current);
break;
}

return res;
}

int preprocessor_parse_evaluate(struct compile_process *compiler,
struct vector *token_vec) {
struct vector *node_vec = vector_create(sizeof(struct preprocessor_node *));
struct expressionable *expressionable = expressionable_create(
&preprocessor_expressionable_config, token_vec, node_vec, 0);
expressionable_parse(expressionable);

struct preprocessor_node *root_node = expressionable_node_pop(expressionable);
return preprocessor_evaluate(compiler, root_node);
}

void preprocessor_handle_if_token(struct compile_process *compiler) {
int res = preprocessor_parse_evaluate(compiler, compiler->token_vec_original);
preprocessor_read_to_endif(compiler, res > 0);
}

void preprocessor_handle_ifdef_token(struct compile_process *compiler) {
struct token *cond_token = preprocessor_next_token(compiler);
if (!cond_token) {
Expand Down Expand Up @@ -794,6 +835,9 @@ int preprocessor_handle_hashtag_token(struct compile_process *compiler,
} else if (preprocessor_token_is_ifndef(next_token)) {
preprocessor_handle_ifndef_token(compiler);
is_preprocessed = true;
} else if (preprocessor_token_is_if(next_token)) {
preprocessor_handle_if_token(compiler);
is_preprocessed = true;
}

return is_preprocessed;
Expand Down
3 changes: 1 addition & 2 deletions test.c
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#define ABC
#ifndef ABC
#if 0
#error testing
#endif

0 comments on commit 542f76e

Please sign in to comment.