Skip to content

Commit

Permalink
Preserve newline and space during macro expansion
Browse files Browse the repository at this point in the history
  • Loading branch information
rui314 committed Dec 7, 2020
1 parent a8d76ad commit 8075582
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
6 changes: 6 additions & 0 deletions preprocess.c
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,8 @@ static Token *subst(Token *tok, MacroArg *args) {
// before they are substituted into a macro body.
if (arg) {
Token *t = preprocess2(arg->tok);
t->at_bol = tok->at_bol;
t->has_space = tok->has_space;
for (; t->kind != TK_EOF; t = t->next)
cur = cur->next = copy_token(t);
tok = tok->next;
Expand Down Expand Up @@ -563,6 +565,8 @@ static bool expand_macro(Token **rest, Token *tok) {
Hideset *hs = hideset_union(tok->hideset, new_hideset(m->name));
Token *body = add_hideset(m->body, hs);
*rest = append(body, tok->next);
(*rest)->at_bol = tok->at_bol;
(*rest)->has_space = tok->has_space;
return true;
}

Expand All @@ -587,6 +591,8 @@ static bool expand_macro(Token **rest, Token *tok) {
Token *body = subst(m->body, args);
body = add_hideset(body, hs);
*rest = append(body, tok->next);
(*rest)->at_bol = macro_token->at_bol;
(*rest)->has_space = macro_token->has_space;
return true;
}

Expand Down
16 changes: 16 additions & 0 deletions test/macro.c
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,22 @@ int main() {
#endif
ASSERT(5, m);

#define STR(x) #x
#define M12(x) STR(x)
#define M13(x) M12(foo.x)
ASSERT(0, strcmp(M13(bar), "foo.bar"));

#define M13(x) M12(foo. x)
ASSERT(0, strcmp(M13(bar), "foo. bar"));

#define M12 foo
#define M13(x) STR(x)
#define M14(x) M13(x.M12)
ASSERT(0, strcmp(M14(bar), "bar.foo"));

#define M14(x) M13(x. M12)
ASSERT(0, strcmp(M14(bar), "bar. foo"));

printf("OK\n");
return 0;
}

0 comments on commit 8075582

Please sign in to comment.