From 1dc85fbbdfb70cae498c9577b364a53d3921c2cc Mon Sep 17 00:00:00 2001 From: Laurent Huberdeau Date: Thu, 6 Feb 2025 12:34:16 -0500 Subject: [PATCH] Don't re-expand macro if current macro is unnamed macro_is_already_expanding had a small bug where if the currently expanding macro was unnamed, it returned false even if the macro was present somewhere on the stack. --- pnut.c | 7 +++++-- tests/_all/preprocessor/macro/self-reference.c | 16 +++++++++++++++- .../preprocessor/macro/self-reference.golden | 1 + 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/pnut.c b/pnut.c index 6a662aa9..b8540464 100644 --- a/pnut.c +++ b/pnut.c @@ -1660,8 +1660,11 @@ void begin_macro_expansion(int ident, int tokens, int args) { // Search the macro stack to see if the macro is already expanding. bool macro_is_already_expanding(int ident) { int i = macro_stack_ix; - if (ident == 0 || macro_ident == 0) return false; // Unnamed macro or no macro is expanding - if (ident == macro_ident) return true; // The same macro is already expanding + // Unnamed macro (i.e. replaying tokens or playing a macro argument) + if (ident == 0) return false; + + // The macro is currently expanding + if (ident == macro_ident) return true; // Traverse the stack to see if the macro is already expanding while (i > 0) { diff --git a/tests/_all/preprocessor/macro/self-reference.c b/tests/_all/preprocessor/macro/self-reference.c index 04859f9e..f1e21003 100644 --- a/tests/_all/preprocessor/macro/self-reference.c +++ b/tests/_all/preprocessor/macro/self-reference.c @@ -1,7 +1,7 @@ // tests for recursion depth of macros -// putchar #include +#include int test1 = 1; int test2 = 2; @@ -33,7 +33,21 @@ void B(int a, int b) { #define B(a1, a2) C(a1, a2) #define C(a1, a2) B(a1, a2) +struct STATE { + int regA; + int regB; +}; + +struct STATE *global_state; + +#define struct_field(sym) global_state->sym +#define regA struct_field(regA) + void main() { + global_state = malloc(sizeof (struct STATE)); + regA = 'A'; + putchar(regA); putchar('\n'); + putdigit(test1); putdigit(test2); putdigit(test3); diff --git a/tests/_all/preprocessor/macro/self-reference.golden b/tests/_all/preprocessor/macro/self-reference.golden index 05578747..afef4903 100644 --- a/tests/_all/preprocessor/macro/self-reference.golden +++ b/tests/_all/preprocessor/macro/self-reference.golden @@ -1,3 +1,4 @@ +A 1 2 3