From 1699d97db7659d471390d2e173dbca6b35747f68 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Mon, 5 May 2025 14:43:17 +0900 Subject: support #define that replaces name with identifiers --- README.md | 2 +- main.c | 21 +++++++++++++++++---- tests/042.sh | 20 ++++++++++++++++++++ 3 files changed, 38 insertions(+), 5 deletions(-) create mode 100644 tests/042.sh diff --git a/README.md b/README.md index dc1f776..cf02911 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ To meet the four-day goal, many design decisions were made to reduce complexity * ~~No `while`~~ * Implemented after self-hosting * Limited preprocessor - * Supports only simple `#define` that replaces identifiers with integer literals + * Supports only simple `#define` that replaces identifiers with single integer or identifier * No global variables * Including `stdin`, `stdout`, and `stderr` * Only function/struct definitions/declarations are allowed at the top level diff --git a/main.c b/main.c index 988d524..83f7a22 100644 --- a/main.c +++ b/main.c @@ -334,16 +334,29 @@ struct Token* tokenize(char* src, int len) { pos += 1; } int start2 = pos; - while (isdigit(src[pos])) { - pos += 1; + int is_digit = isdigit(src[pos]); + if (is_digit) { + while (isdigit(src[pos])) { + pos += 1; + } + } else { + while (isalnum(src[pos]) || src[pos] == '_') { + pos += 1; + } } def->to = calloc(1, sizeof(struct Token)); - def->to->kind = TK_L_INT; + if (is_digit) { + def->to->kind = TK_L_INT; + } else { + def->to->kind = TK_IDENT; + } def->to->value = calloc(pos - start2 + 1, sizeof(char)); memcpy(def->to->value, src + start2, pos - start2); def += 1; } else { - fatal_error("unknown token"); + char* buf = calloc(1024, sizeof(char)); + sprintf(buf, "!!! %d", c); + fatal_error(buf); } } return tokens; diff --git a/tests/042.sh b/tests/042.sh new file mode 100644 index 0000000..b9f1749 --- /dev/null +++ b/tests/042.sh @@ -0,0 +1,20 @@ +set -e + +cat <<'EOF' > expected +42,123 +EOF +bash ../../test_diff.sh <<'EOF' +int printf(); + +#define A foo_a +#define B foo_b + +int main() { + int foo_a = 42; + int foo_b = 123; + + printf("%d,%d\n", A, B); + + return 0; +} +EOF -- cgit v1.2.3-70-g09d2