blob: 57bdfccc1103e89602678fc297397f0153816613 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- MacroExpander.cpp - Lex from a macro expansion -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the MacroExpander interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/MacroExpander.h"
15#include "clang/Lex/MacroInfo.h"
16#include "clang/Lex/Preprocessor.h"
Chris Lattner30709b032006-06-21 03:01:55 +000017#include "clang/Basic/SourceManager.h"
Chris Lattner0707bd32006-07-15 05:23:58 +000018#include "clang/Basic/Diagnostic.h"
Chris Lattnerb57aa462006-07-27 03:42:15 +000019#include "llvm/ADT/SmallVector.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000020using namespace clang;
21
Chris Lattner78186052006-07-09 00:45:31 +000022//===----------------------------------------------------------------------===//
Chris Lattneree8760b2006-07-15 07:42:55 +000023// MacroArgs Implementation
Chris Lattner78186052006-07-09 00:45:31 +000024//===----------------------------------------------------------------------===//
25
Chris Lattnerc1410dc2006-07-26 05:22:49 +000026/// MacroArgs ctor function - This destroys the vector passed in.
27MacroArgs *MacroArgs::create(const MacroInfo *MI,
Chris Lattner146762e2007-07-20 16:59:19 +000028 const Token *UnexpArgTokens,
Chris Lattner775d8322006-07-29 04:39:41 +000029 unsigned NumToks, bool VarargsElided) {
Chris Lattner78186052006-07-09 00:45:31 +000030 assert(MI->isFunctionLike() &&
Chris Lattneree8760b2006-07-15 07:42:55 +000031 "Can't have args for an object-like macro!");
Chris Lattnerc1410dc2006-07-26 05:22:49 +000032
33 // Allocate memory for the MacroArgs object with the lexer tokens at the end.
Chris Lattnerc1410dc2006-07-26 05:22:49 +000034 MacroArgs *Result = (MacroArgs*)malloc(sizeof(MacroArgs) +
Chris Lattner146762e2007-07-20 16:59:19 +000035 NumToks*sizeof(Token));
Chris Lattnerc1410dc2006-07-26 05:22:49 +000036 // Construct the macroargs object.
Chris Lattner775d8322006-07-29 04:39:41 +000037 new (Result) MacroArgs(NumToks, VarargsElided);
Chris Lattnerc1410dc2006-07-26 05:22:49 +000038
39 // Copy the actual unexpanded tokens to immediately after the result ptr.
40 if (NumToks)
Chris Lattner146762e2007-07-20 16:59:19 +000041 memcpy(const_cast<Token*>(Result->getUnexpArgument(0)),
42 UnexpArgTokens, NumToks*sizeof(Token));
Chris Lattnerc1410dc2006-07-26 05:22:49 +000043
44 return Result;
Chris Lattner78186052006-07-09 00:45:31 +000045}
46
Chris Lattnerc1410dc2006-07-26 05:22:49 +000047/// destroy - Destroy and deallocate the memory for this object.
48///
49void MacroArgs::destroy() {
50 // Run the dtor to deallocate the vectors.
51 this->~MacroArgs();
52 // Release the memory for the object.
53 free(this);
54}
55
56
Chris Lattner6fc08bc2006-07-26 04:55:32 +000057/// getArgLength - Given a pointer to an expanded or unexpanded argument,
58/// return the number of tokens, not counting the EOF, that make up the
59/// argument.
Chris Lattner146762e2007-07-20 16:59:19 +000060unsigned MacroArgs::getArgLength(const Token *ArgPtr) {
Chris Lattner6fc08bc2006-07-26 04:55:32 +000061 unsigned NumArgTokens = 0;
62 for (; ArgPtr->getKind() != tok::eof; ++ArgPtr)
63 ++NumArgTokens;
64 return NumArgTokens;
65}
66
67
Chris Lattner36b6e812006-07-21 06:38:30 +000068/// getUnexpArgument - Return the unexpanded tokens for the specified formal.
69///
Chris Lattner146762e2007-07-20 16:59:19 +000070const Token *MacroArgs::getUnexpArgument(unsigned Arg) const {
Chris Lattnerc1410dc2006-07-26 05:22:49 +000071 // The unexpanded argument tokens start immediately after the MacroArgs object
72 // in memory.
Chris Lattner146762e2007-07-20 16:59:19 +000073 const Token *Start = (const Token *)(this+1);
74 const Token *Result = Start;
Chris Lattnerc1410dc2006-07-26 05:22:49 +000075 // Scan to find Arg.
Chris Lattner36b6e812006-07-21 06:38:30 +000076 for (; Arg; ++Result) {
Chris Lattnerc1410dc2006-07-26 05:22:49 +000077 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
Chris Lattner36b6e812006-07-21 06:38:30 +000078 if (Result->getKind() == tok::eof)
79 --Arg;
80 }
81 return Result;
Chris Lattneree8760b2006-07-15 07:42:55 +000082}
83
Chris Lattner36b6e812006-07-21 06:38:30 +000084
Chris Lattner203b4562006-07-15 21:07:40 +000085/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
86/// by pre-expansion, return false. Otherwise, conservatively return true.
Chris Lattner146762e2007-07-20 16:59:19 +000087bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok) const {
Chris Lattner203b4562006-07-15 21:07:40 +000088 // If there are no identifiers in the argument list, or if the identifiers are
89 // known to not be macros, pre-expansion won't modify it.
Chris Lattner36b6e812006-07-21 06:38:30 +000090 for (; ArgTok->getKind() != tok::eof; ++ArgTok)
91 if (IdentifierInfo *II = ArgTok->getIdentifierInfo()) {
Chris Lattner203b4562006-07-15 21:07:40 +000092 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled())
93 // Return true even though the macro could be a function-like macro
94 // without a following '(' token.
95 return true;
96 }
97 return false;
98}
99
Chris Lattner7667d0d2006-07-16 18:16:58 +0000100/// getPreExpArgument - Return the pre-expanded form of the specified
101/// argument.
Chris Lattner146762e2007-07-20 16:59:19 +0000102const std::vector<Token> &
Chris Lattner7667d0d2006-07-16 18:16:58 +0000103MacroArgs::getPreExpArgument(unsigned Arg, Preprocessor &PP) {
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000104 assert(Arg < NumUnexpArgTokens && "Invalid argument number!");
Chris Lattner7667d0d2006-07-16 18:16:58 +0000105
106 // If we have already computed this, return it.
107 if (PreExpArgTokens.empty())
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000108 PreExpArgTokens.resize(NumUnexpArgTokens);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000109
Chris Lattner146762e2007-07-20 16:59:19 +0000110 std::vector<Token> &Result = PreExpArgTokens[Arg];
Chris Lattner7667d0d2006-07-16 18:16:58 +0000111 if (!Result.empty()) return Result;
112
Chris Lattner146762e2007-07-20 16:59:19 +0000113 const Token *AT = getUnexpArgument(Arg);
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000114 unsigned NumToks = getArgLength(AT)+1; // Include the EOF.
Chris Lattner36b6e812006-07-21 06:38:30 +0000115
Chris Lattner7667d0d2006-07-16 18:16:58 +0000116 // Otherwise, we have to pre-expand this argument, populating Result. To do
117 // this, we set up a fake MacroExpander to lex from the unexpanded argument
118 // list. With this installed, we lex expanded tokens until we hit the EOF
119 // token at the end of the unexp list.
Chris Lattner70216572006-07-26 03:50:40 +0000120 PP.EnterTokenStream(AT, NumToks);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000121
122 // Lex all of the macro-expanded tokens into Result.
123 do {
Chris Lattner146762e2007-07-20 16:59:19 +0000124 Result.push_back(Token());
Chris Lattner7667d0d2006-07-16 18:16:58 +0000125 PP.Lex(Result.back());
126 } while (Result.back().getKind() != tok::eof);
127
128 // Pop the token stream off the top of the stack. We know that the internal
129 // pointer inside of it is to the "end" of the token stream, but the stack
130 // will not otherwise be popped until the next token is lexed. The problem is
131 // that the token may be lexed sometime after the vector of tokens itself is
132 // destroyed, which would be badness.
133 PP.RemoveTopOfLexerStack();
134 return Result;
135}
136
Chris Lattneree8760b2006-07-15 07:42:55 +0000137
Chris Lattner0707bd32006-07-15 05:23:58 +0000138/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
139/// tokens into the literal string token that should be produced by the C #
140/// preprocessor operator.
141///
Chris Lattner146762e2007-07-20 16:59:19 +0000142static Token StringifyArgument(const Token *ArgToks,
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000143 Preprocessor &PP, bool Charify = false) {
Chris Lattner146762e2007-07-20 16:59:19 +0000144 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000145 Tok.startToken();
146 Tok.setKind(tok::string_literal);
Chris Lattner0707bd32006-07-15 05:23:58 +0000147
Chris Lattner146762e2007-07-20 16:59:19 +0000148 const Token *ArgTokStart = ArgToks;
Chris Lattner36b6e812006-07-21 06:38:30 +0000149
Chris Lattner0707bd32006-07-15 05:23:58 +0000150 // Stringify all the tokens.
151 std::string Result = "\"";
Chris Lattner7667d0d2006-07-16 18:16:58 +0000152 // FIXME: Optimize this loop to not use std::strings.
Chris Lattner36b6e812006-07-21 06:38:30 +0000153 bool isFirst = true;
154 for (; ArgToks->getKind() != tok::eof; ++ArgToks) {
Chris Lattner146762e2007-07-20 16:59:19 +0000155 const Token &Tok = *ArgToks;
Chris Lattner24dbee72007-07-19 16:11:58 +0000156 if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()))
Chris Lattner0707bd32006-07-15 05:23:58 +0000157 Result += ' ';
Chris Lattner36b6e812006-07-21 06:38:30 +0000158 isFirst = false;
Chris Lattner0707bd32006-07-15 05:23:58 +0000159
160 // If this is a string or character constant, escape the token as specified
161 // by 6.10.3.2p2.
Chris Lattnerd3e98952006-10-06 05:22:26 +0000162 if (Tok.getKind() == tok::string_literal || // "foo"
163 Tok.getKind() == tok::wide_string_literal || // L"foo"
164 Tok.getKind() == tok::char_constant) { // 'x' and L'x'.
Chris Lattner0707bd32006-07-15 05:23:58 +0000165 Result += Lexer::Stringify(PP.getSpelling(Tok));
166 } else {
167 // Otherwise, just append the token.
168 Result += PP.getSpelling(Tok);
169 }
170 }
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000171
Chris Lattner0707bd32006-07-15 05:23:58 +0000172 // If the last character of the string is a \, and if it isn't escaped, this
173 // is an invalid string literal, diagnose it as specified in C99.
174 if (Result[Result.size()-1] == '\\') {
175 // Count the number of consequtive \ characters. If even, then they are
176 // just escaped backslashes, otherwise it's an error.
177 unsigned FirstNonSlash = Result.size()-2;
178 // Guaranteed to find the starting " if nothing else.
179 while (Result[FirstNonSlash] == '\\')
180 --FirstNonSlash;
181 if ((Result.size()-1-FirstNonSlash) & 1) {
Chris Lattnerf2781502006-07-15 05:27:44 +0000182 // Diagnose errors for things like: #define F(X) #X / F(\)
Chris Lattner36b6e812006-07-21 06:38:30 +0000183 PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
Chris Lattner0707bd32006-07-15 05:23:58 +0000184 Result.erase(Result.end()-1); // remove one of the \'s.
185 }
186 }
Chris Lattner0707bd32006-07-15 05:23:58 +0000187 Result += '"';
188
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000189 // If this is the charify operation and the result is not a legal character
190 // constant, diagnose it.
191 if (Charify) {
192 // First step, turn double quotes into single quotes:
193 Result[0] = '\'';
194 Result[Result.size()-1] = '\'';
195
196 // Check for bogus character.
197 bool isBad = false;
Chris Lattner2ada5d32006-07-15 07:51:24 +0000198 if (Result.size() == 3) {
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000199 isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
200 } else {
201 isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
202 }
203
204 if (isBad) {
Chris Lattner36b6e812006-07-21 06:38:30 +0000205 PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
Chris Lattner7c581492006-07-15 07:56:31 +0000206 Result = "' '"; // Use something arbitrary, but legal.
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000207 }
208 }
209
Chris Lattner8c204872006-10-14 05:19:21 +0000210 Tok.setLength(Result.size());
211 Tok.setLocation(PP.CreateString(&Result[0], Result.size()));
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000212 return Tok;
213}
214
215/// getStringifiedArgument - Compute, cache, and return the specified argument
216/// that has been 'stringified' as required by the # operator.
Chris Lattner146762e2007-07-20 16:59:19 +0000217const Token &MacroArgs::getStringifiedArgument(unsigned ArgNo,
Chris Lattneree8760b2006-07-15 07:42:55 +0000218 Preprocessor &PP) {
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000219 assert(ArgNo < NumUnexpArgTokens && "Invalid argument number!");
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000220 if (StringifiedArgs.empty()) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000221 StringifiedArgs.resize(getNumArguments());
Chris Lattneree8760b2006-07-15 07:42:55 +0000222 memset(&StringifiedArgs[0], 0,
223 sizeof(StringifiedArgs[0])*getNumArguments());
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000224 }
225 if (StringifiedArgs[ArgNo].getKind() != tok::string_literal)
Chris Lattner36b6e812006-07-21 06:38:30 +0000226 StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000227 return StringifiedArgs[ArgNo];
228}
229
Chris Lattner78186052006-07-09 00:45:31 +0000230//===----------------------------------------------------------------------===//
231// MacroExpander Implementation
232//===----------------------------------------------------------------------===//
233
Chris Lattner7667d0d2006-07-16 18:16:58 +0000234/// Create a macro expander for the specified macro with the specified actual
235/// arguments. Note that this ctor takes ownership of the ActualArgs pointer.
Chris Lattner146762e2007-07-20 16:59:19 +0000236void MacroExpander::Init(Token &Tok, MacroArgs *Actuals) {
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000237 // If the client is reusing a macro expander, make sure to free any memory
238 // associated with it.
239 destroy();
240
241 Macro = Tok.getIdentifierInfo()->getMacroInfo();
242 ActualArgs = Actuals;
243 CurToken = 0;
244 InstantiateLoc = Tok.getLocation();
245 AtStartOfLine = Tok.isAtStartOfLine();
246 HasLeadingSpace = Tok.hasLeadingSpace();
Chris Lattnerf40fe992007-07-14 22:11:41 +0000247 MacroTokens = &*Macro->tokens_begin();
Chris Lattner9c724c42007-07-22 01:16:55 +0000248 OwnsMacroTokens = false;
Chris Lattnerf40fe992007-07-14 22:11:41 +0000249 NumMacroTokens = Macro->tokens_end()-Macro->tokens_begin();
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000250
251 // If this is a function-like macro, expand the arguments and change
252 // MacroTokens to point to the expanded tokens.
Chris Lattner95a06b32006-07-30 08:40:43 +0000253 if (Macro->isFunctionLike() && Macro->getNumArgs())
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000254 ExpandFunctionArguments();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000255
256 // Mark the macro as currently disabled, so that it is not recursively
257 // expanded. The macro must be disabled only after argument pre-expansion of
258 // function-like macro arguments occurs.
259 Macro->DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000260}
261
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000262
263
Chris Lattner7667d0d2006-07-16 18:16:58 +0000264/// Create a macro expander for the specified token stream. This does not
265/// take ownership of the specified token vector.
Chris Lattner146762e2007-07-20 16:59:19 +0000266void MacroExpander::Init(const Token *TokArray, unsigned NumToks) {
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000267 // If the client is reusing a macro expander, make sure to free any memory
268 // associated with it.
269 destroy();
270
271 Macro = 0;
272 ActualArgs = 0;
273 MacroTokens = TokArray;
Chris Lattner9c724c42007-07-22 01:16:55 +0000274 OwnsMacroTokens = false;
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000275 NumMacroTokens = NumToks;
276 CurToken = 0;
277 InstantiateLoc = SourceLocation();
278 AtStartOfLine = false;
279 HasLeadingSpace = false;
Chris Lattner7667d0d2006-07-16 18:16:58 +0000280
281 // Set HasLeadingSpace/AtStartOfLine so that the first token will be
282 // returned unmodified.
Chris Lattner70216572006-07-26 03:50:40 +0000283 if (NumToks != 0) {
284 AtStartOfLine = TokArray[0].isAtStartOfLine();
285 HasLeadingSpace = TokArray[0].hasLeadingSpace();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000286 }
287}
288
289
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000290void MacroExpander::destroy() {
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000291 // If this was a function-like macro that actually uses its arguments, delete
292 // the expanded tokens.
Chris Lattner9c724c42007-07-22 01:16:55 +0000293 if (OwnsMacroTokens) {
Chris Lattner70216572006-07-26 03:50:40 +0000294 delete [] MacroTokens;
Chris Lattner9c724c42007-07-22 01:16:55 +0000295 MacroTokens = 0;
296 }
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000297
298 // MacroExpander owns its formal arguments.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000299 if (ActualArgs) ActualArgs->destroy();
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000300}
301
302/// Expand the arguments of a function-like macro so that we can quickly
303/// return preexpanded tokens from MacroTokens.
304void MacroExpander::ExpandFunctionArguments() {
Chris Lattner146762e2007-07-20 16:59:19 +0000305 llvm::SmallVector<Token, 128> ResultToks;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000306
307 // Loop through the MacroTokens tokens, expanding them into ResultToks. Keep
308 // track of whether we change anything. If not, no need to keep them. If so,
309 // we install the newly expanded sequence as MacroTokens.
310 bool MadeChange = false;
Chris Lattner479b0af2006-07-29 04:16:20 +0000311
312 // NextTokGetsSpace - When this is true, the next token appended to the
313 // output list will get a leading space, regardless of whether it had one to
314 // begin with or not. This is used for placemarker support.
315 bool NextTokGetsSpace = false;
316
Chris Lattner70216572006-07-26 03:50:40 +0000317 for (unsigned i = 0, e = NumMacroTokens; i != e; ++i) {
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000318 // If we found the stringify operator, get the argument stringified. The
319 // preprocessor already verified that the following token is a macro name
320 // when the #define was parsed.
Chris Lattner146762e2007-07-20 16:59:19 +0000321 const Token &CurTok = MacroTokens[i];
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000322 if (CurTok.getKind() == tok::hash || CurTok.getKind() == tok::hashat) {
Chris Lattner70216572006-07-26 03:50:40 +0000323 int ArgNo = Macro->getArgumentNum(MacroTokens[i+1].getIdentifierInfo());
Chris Lattner95a06b32006-07-30 08:40:43 +0000324 assert(ArgNo != -1 && "Token following # is not an argument?");
325
Chris Lattner146762e2007-07-20 16:59:19 +0000326 Token Res;
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000327 if (CurTok.getKind() == tok::hash) // Stringify
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000328 Res = ActualArgs->getStringifiedArgument(ArgNo, PP);
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000329 else {
330 // 'charify': don't bother caching these.
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000331 Res = StringifyArgument(ActualArgs->getUnexpArgument(ArgNo), PP, true);
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000332 }
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000333
Chris Lattner60161692006-07-15 06:48:02 +0000334 // The stringified/charified string leading space flag gets set to match
335 // the #/#@ operator.
Chris Lattner479b0af2006-07-29 04:16:20 +0000336 if (CurTok.hasLeadingSpace() || NextTokGetsSpace)
Chris Lattner146762e2007-07-20 16:59:19 +0000337 Res.setFlag(Token::LeadingSpace);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000338
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000339 ResultToks.push_back(Res);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000340 MadeChange = true;
341 ++i; // Skip arg name.
Chris Lattner479b0af2006-07-29 04:16:20 +0000342 NextTokGetsSpace = false;
Chris Lattnera9dc5972006-07-28 05:07:04 +0000343 continue;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000344 }
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000345
346 // Otherwise, if this is not an argument token, just add the token to the
347 // output buffer.
348 IdentifierInfo *II = CurTok.getIdentifierInfo();
349 int ArgNo = II ? Macro->getArgumentNum(II) : -1;
350 if (ArgNo == -1) {
Chris Lattner95a06b32006-07-30 08:40:43 +0000351 // This isn't an argument, just add it.
352 ResultToks.push_back(CurTok);
Chris Lattner479b0af2006-07-29 04:16:20 +0000353
Chris Lattner95a06b32006-07-30 08:40:43 +0000354 if (NextTokGetsSpace) {
Chris Lattner146762e2007-07-20 16:59:19 +0000355 ResultToks.back().setFlag(Token::LeadingSpace);
Chris Lattner95a06b32006-07-30 08:40:43 +0000356 NextTokGetsSpace = false;
Chris Lattner21c8b8f2006-07-29 04:04:22 +0000357 }
Chris Lattner95a06b32006-07-30 08:40:43 +0000358 continue;
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000359 }
360
361 // An argument is expanded somehow, the result is different than the
362 // input.
363 MadeChange = true;
364
365 // Otherwise, this is a use of the argument. Find out if there is a paste
366 // (##) operator before or after the argument.
367 bool PasteBefore =
368 !ResultToks.empty() && ResultToks.back().getKind() == tok::hashhash;
369 bool PasteAfter = i+1 != e && MacroTokens[i+1].getKind() == tok::hashhash;
370
371 // If it is not the LHS/RHS of a ## operator, we must pre-expand the
372 // argument and substitute the expanded tokens into the result. This is
373 // C99 6.10.3.1p1.
374 if (!PasteBefore && !PasteAfter) {
Chris Lattner146762e2007-07-20 16:59:19 +0000375 const Token *ResultArgToks;
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000376
377 // Only preexpand the argument if it could possibly need it. This
378 // avoids some work in common cases.
Chris Lattner146762e2007-07-20 16:59:19 +0000379 const Token *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000380 if (ActualArgs->ArgNeedsPreexpansion(ArgTok))
381 ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0];
382 else
383 ResultArgToks = ArgTok; // Use non-preexpanded tokens.
384
385 // If the arg token expanded into anything, append it.
386 if (ResultArgToks->getKind() != tok::eof) {
387 unsigned FirstResult = ResultToks.size();
388 unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
389 ResultToks.append(ResultArgToks, ResultArgToks+NumToks);
390
391 // If any tokens were substituted from the argument, the whitespace
392 // before the first token should match the whitespace of the arg
393 // identifier.
Chris Lattner146762e2007-07-20 16:59:19 +0000394 ResultToks[FirstResult].setFlagValue(Token::LeadingSpace,
Chris Lattner479b0af2006-07-29 04:16:20 +0000395 CurTok.hasLeadingSpace() ||
396 NextTokGetsSpace);
397 NextTokGetsSpace = false;
398 } else {
399 // If this is an empty argument, and if there was whitespace before the
400 // formal token, make sure the next token gets whitespace before it.
401 NextTokGetsSpace = CurTok.hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000402 }
403 continue;
404 }
405
406 // Okay, we have a token that is either the LHS or RHS of a paste (##)
407 // argument. It gets substituted as its non-pre-expanded tokens.
Chris Lattner146762e2007-07-20 16:59:19 +0000408 const Token *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000409 unsigned NumToks = MacroArgs::getArgLength(ArgToks);
410 if (NumToks) { // Not an empty argument?
411 ResultToks.append(ArgToks, ArgToks+NumToks);
Chris Lattner479b0af2006-07-29 04:16:20 +0000412
413 // If the next token was supposed to get leading whitespace, ensure it has
414 // it now.
415 if (NextTokGetsSpace) {
Chris Lattner146762e2007-07-20 16:59:19 +0000416 ResultToks[ResultToks.size()-NumToks].setFlag(Token::LeadingSpace);
Chris Lattner479b0af2006-07-29 04:16:20 +0000417 NextTokGetsSpace = false;
418 }
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000419 continue;
420 }
421
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000422 // If an empty argument is on the LHS or RHS of a paste, the standard (C99
423 // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur. We
424 // implement this by eating ## operators when a LHS or RHS expands to
425 // empty.
Chris Lattner479b0af2006-07-29 04:16:20 +0000426 NextTokGetsSpace |= CurTok.hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000427 if (PasteAfter) {
428 // Discard the argument token and skip (don't copy to the expansion
429 // buffer) the paste operator after it.
Chris Lattner479b0af2006-07-29 04:16:20 +0000430 NextTokGetsSpace |= MacroTokens[i+1].hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000431 ++i;
432 continue;
433 }
434
435 // If this is on the RHS of a paste operator, we've already copied the
436 // paste operator to the ResultToks list. Remove it.
437 assert(PasteBefore && ResultToks.back().getKind() == tok::hashhash);
Chris Lattner479b0af2006-07-29 04:16:20 +0000438 NextTokGetsSpace |= ResultToks.back().hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000439 ResultToks.pop_back();
Chris Lattner775d8322006-07-29 04:39:41 +0000440
441 // If this is the __VA_ARGS__ token, and if the argument wasn't provided,
442 // and if the macro had at least one real argument, and if the token before
443 // the ## was a comma, remove the comma.
Chris Lattner95a06b32006-07-30 08:40:43 +0000444 if ((unsigned)ArgNo == Macro->getNumArgs()-1 && // is __VA_ARGS__
Chris Lattner775d8322006-07-29 04:39:41 +0000445 ActualArgs->isVarargsElidedUse() && // Argument elided.
446 !ResultToks.empty() && ResultToks.back().getKind() == tok::comma) {
447 // Never add a space, even if the comma, ##, or arg had a space.
448 NextTokGetsSpace = false;
449 ResultToks.pop_back();
450 }
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000451 continue;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000452 }
453
454 // If anything changed, install this as the new MacroTokens list.
455 if (MadeChange) {
456 // This is deleted in the dtor.
Chris Lattner70216572006-07-26 03:50:40 +0000457 NumMacroTokens = ResultToks.size();
Chris Lattner146762e2007-07-20 16:59:19 +0000458 Token *Res = new Token[ResultToks.size()];
Chris Lattnerd97d2e72006-07-29 06:44:29 +0000459 if (NumMacroTokens)
Chris Lattner146762e2007-07-20 16:59:19 +0000460 memcpy(Res, &ResultToks[0], NumMacroTokens*sizeof(Token));
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000461 MacroTokens = Res;
Chris Lattner9c724c42007-07-22 01:16:55 +0000462 OwnsMacroTokens = true;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000463 }
464}
Chris Lattner67b07cb2006-06-26 02:03:42 +0000465
Chris Lattner22eb9722006-06-18 05:43:12 +0000466/// Lex - Lex and return a token from this macro stream.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000467///
Chris Lattner146762e2007-07-20 16:59:19 +0000468void MacroExpander::Lex(Token &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000469 // Lexing off the end of the macro, pop this macro off the expansion stack.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000470 if (isAtEnd()) {
471 // If this is a macro (not a token stream), mark the macro enabled now
472 // that it is no longer being expanded.
473 if (Macro) Macro->EnableMacro();
474
475 // Pop this context off the preprocessors lexer stack and get the next
Chris Lattner2183a6e2006-07-18 06:36:12 +0000476 // token. This will delete "this" so remember the PP instance var.
477 Preprocessor &PPCache = PP;
478 if (PP.HandleEndOfMacro(Tok))
479 return;
480
481 // HandleEndOfMacro may not return a token. If it doesn't, lex whatever is
482 // next.
483 return PPCache.Lex(Tok);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000484 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000485
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000486 // If this is the first token of the expanded result, we inherit spacing
487 // properties later.
488 bool isFirstToken = CurToken == 0;
489
Chris Lattner22eb9722006-06-18 05:43:12 +0000490 // Get the next token to return.
Chris Lattner70216572006-07-26 03:50:40 +0000491 Tok = MacroTokens[CurToken++];
Chris Lattner01ecf832006-07-19 05:42:48 +0000492
493 // If this token is followed by a token paste (##) operator, paste the tokens!
Chris Lattner70216572006-07-26 03:50:40 +0000494 if (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash)
Chris Lattner01ecf832006-07-19 05:42:48 +0000495 PasteTokens(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000496
Chris Lattnerc673f902006-06-30 06:10:41 +0000497 // The token's current location indicate where the token was lexed from. We
498 // need this information to compute the spelling of the token, but any
499 // diagnostics for the expanded token should appear as if they came from
500 // InstantiationLoc. Pull this information together into a new SourceLocation
501 // that captures all of this.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000502 if (InstantiateLoc.isValid()) { // Don't do this for token streams.
503 SourceManager &SrcMgr = PP.getSourceManager();
Chris Lattner3fc74e22007-07-15 06:35:27 +0000504 Tok.setLocation(SrcMgr.getInstantiationLoc(Tok.getLocation(),
505 InstantiateLoc));
Chris Lattner7667d0d2006-07-16 18:16:58 +0000506 }
507
Chris Lattner22eb9722006-06-18 05:43:12 +0000508 // If this is the first token, set the lexical properties of the token to
509 // match the lexical properties of the macro identifier.
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000510 if (isFirstToken) {
Chris Lattner146762e2007-07-20 16:59:19 +0000511 Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
512 Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +0000513 }
514
515 // Handle recursive expansion!
516 if (Tok.getIdentifierInfo())
517 return PP.HandleIdentifier(Tok);
518
519 // Otherwise, return a normal token.
Chris Lattner22eb9722006-06-18 05:43:12 +0000520}
Chris Lattnerafe603f2006-07-11 04:02:46 +0000521
Chris Lattner01ecf832006-07-19 05:42:48 +0000522/// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ##
523/// operator. Read the ## and RHS, and paste the LHS/RHS together. If there
524/// are is another ## after it, chomp it iteratively. Return the result as Tok.
Chris Lattner146762e2007-07-20 16:59:19 +0000525void MacroExpander::PasteTokens(Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000526 llvm::SmallVector<char, 128> Buffer;
Chris Lattner01ecf832006-07-19 05:42:48 +0000527 do {
528 // Consume the ## operator.
Chris Lattner70216572006-07-26 03:50:40 +0000529 SourceLocation PasteOpLoc = MacroTokens[CurToken].getLocation();
Chris Lattner01ecf832006-07-19 05:42:48 +0000530 ++CurToken;
531 assert(!isAtEnd() && "No token on the RHS of a paste operator!");
532
533 // Get the RHS token.
Chris Lattner146762e2007-07-20 16:59:19 +0000534 const Token &RHS = MacroTokens[CurToken];
Chris Lattner01ecf832006-07-19 05:42:48 +0000535
536 bool isInvalid = false;
537
Chris Lattner01ecf832006-07-19 05:42:48 +0000538 // Allocate space for the result token. This is guaranteed to be enough for
539 // the two tokens and a null terminator.
Chris Lattner57dd8362006-11-03 07:45:04 +0000540 Buffer.resize(Tok.getLength() + RHS.getLength() + 1);
Chris Lattner01ecf832006-07-19 05:42:48 +0000541
542 // Get the spelling of the LHS token in Buffer.
Chris Lattner57dd8362006-11-03 07:45:04 +0000543 const char *BufPtr = &Buffer[0];
Chris Lattner01ecf832006-07-19 05:42:48 +0000544 unsigned LHSLen = PP.getSpelling(Tok, BufPtr);
Chris Lattner57dd8362006-11-03 07:45:04 +0000545 if (BufPtr != &Buffer[0]) // Really, we want the chars in Buffer!
546 memcpy(&Buffer[0], BufPtr, LHSLen);
Chris Lattner01ecf832006-07-19 05:42:48 +0000547
Chris Lattner57dd8362006-11-03 07:45:04 +0000548 BufPtr = &Buffer[LHSLen];
Chris Lattner01ecf832006-07-19 05:42:48 +0000549 unsigned RHSLen = PP.getSpelling(RHS, BufPtr);
Chris Lattner57dd8362006-11-03 07:45:04 +0000550 if (BufPtr != &Buffer[LHSLen]) // Really, we want the chars in Buffer!
551 memcpy(&Buffer[LHSLen], BufPtr, RHSLen);
Chris Lattner01ecf832006-07-19 05:42:48 +0000552
553 // Add null terminator.
554 Buffer[LHSLen+RHSLen] = '\0';
555
Chris Lattner57dd8362006-11-03 07:45:04 +0000556 // Trim excess space.
557 Buffer.resize(LHSLen+RHSLen+1);
558
Chris Lattner01ecf832006-07-19 05:42:48 +0000559 // Plop the pasted result (including the trailing newline and null) into a
560 // scratch buffer where we can lex it.
Chris Lattner57dd8362006-11-03 07:45:04 +0000561 SourceLocation ResultTokLoc = PP.CreateString(&Buffer[0], Buffer.size());
Chris Lattner01ecf832006-07-19 05:42:48 +0000562
563 // Lex the resultant pasted token into Result.
Chris Lattner146762e2007-07-20 16:59:19 +0000564 Token Result;
Chris Lattner01ecf832006-07-19 05:42:48 +0000565
Chris Lattnera7e2e742006-07-19 06:32:35 +0000566 // Avoid testing /*, as the lexer would think it is the start of a comment
567 // and emit an error that it is unterminated.
568 if (Tok.getKind() == tok::slash && RHS.getKind() == tok::star) {
569 isInvalid = true;
Chris Lattner510ab612006-07-20 04:47:30 +0000570 } else if (Tok.getKind() == tok::identifier &&
Chris Lattner08ba4c02006-07-20 04:52:59 +0000571 RHS.getKind() == tok::identifier) {
Chris Lattner510ab612006-07-20 04:47:30 +0000572 // Common paste case: identifier+identifier = identifier. Avoid creating
573 // a lexer and other overhead.
574 PP.IncrementPasteCounter(true);
Chris Lattner8c204872006-10-14 05:19:21 +0000575 Result.startToken();
576 Result.setKind(tok::identifier);
577 Result.setLocation(ResultTokLoc);
578 Result.setLength(LHSLen+RHSLen);
Chris Lattnera7e2e742006-07-19 06:32:35 +0000579 } else {
Chris Lattner510ab612006-07-20 04:47:30 +0000580 PP.IncrementPasteCounter(false);
581
Chris Lattnera7e2e742006-07-19 06:32:35 +0000582 // Make a lexer to lex this string from.
583 SourceManager &SourceMgr = PP.getSourceManager();
584 const char *ResultStrData = SourceMgr.getCharacterData(ResultTokLoc);
585
Chris Lattnera7e2e742006-07-19 06:32:35 +0000586 // Make a lexer object so that we lex and expand the paste result.
Chris Lattner77e9de52007-07-20 16:52:03 +0000587 Lexer *TL = new Lexer(ResultTokLoc, PP, ResultStrData,
Chris Lattnera7e2e742006-07-19 06:32:35 +0000588 ResultStrData+LHSLen+RHSLen /*don't include null*/);
589
590 // Lex a token in raw mode. This way it won't look up identifiers
591 // automatically, lexing off the end will return an eof token, and
592 // warnings are disabled. This returns true if the result token is the
593 // entire buffer.
594 bool IsComplete = TL->LexRawToken(Result);
595
596 // If we got an EOF token, we didn't form even ONE token. For example, we
597 // did "/ ## /" to get "//".
598 IsComplete &= Result.getKind() != tok::eof;
599 isInvalid = !IsComplete;
600
601 // We're now done with the temporary lexer.
602 delete TL;
603 }
Chris Lattner01ecf832006-07-19 05:42:48 +0000604
605 // If pasting the two tokens didn't form a full new token, this is an error.
Chris Lattnera7e2e742006-07-19 06:32:35 +0000606 // This occurs with "x ## +" and other stuff. Return with Tok unmodified
607 // and with RHS as the next token to lex.
608 if (isInvalid) {
Chris Lattner01ecf832006-07-19 05:42:48 +0000609 // If not in assembler language mode.
610 PP.Diag(PasteOpLoc, diag::err_pp_bad_paste,
Chris Lattner57dd8362006-11-03 07:45:04 +0000611 std::string(Buffer.begin(), Buffer.end()-1));
Chris Lattner01ecf832006-07-19 05:42:48 +0000612 return;
613 }
614
615 // Turn ## into 'other' to avoid # ## # from looking like a paste operator.
616 if (Result.getKind() == tok::hashhash)
Chris Lattner8c204872006-10-14 05:19:21 +0000617 Result.setKind(tok::unknown);
Chris Lattner01ecf832006-07-19 05:42:48 +0000618 // FIXME: Turn __VARRGS__ into "not a token"?
619
620 // Transfer properties of the LHS over the the Result.
Chris Lattner146762e2007-07-20 16:59:19 +0000621 Result.setFlagValue(Token::StartOfLine , Tok.isAtStartOfLine());
622 Result.setFlagValue(Token::LeadingSpace, Tok.hasLeadingSpace());
Chris Lattner01ecf832006-07-19 05:42:48 +0000623
624 // Finally, replace LHS with the result, consume the RHS, and iterate.
625 ++CurToken;
626 Tok = Result;
Chris Lattner70216572006-07-26 03:50:40 +0000627 } while (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash);
Chris Lattner0f1f5052006-07-20 04:16:23 +0000628
629 // Now that we got the result token, it will be subject to expansion. Since
630 // token pasting re-lexes the result token in raw mode, identifier information
631 // isn't looked up. As such, if the result is an identifier, look up id info.
632 if (Tok.getKind() == tok::identifier) {
633 // Look up the identifier info for the token. We disabled identifier lookup
634 // by saying we're skipping contents, so we need to do this manually.
Chris Lattner8c204872006-10-14 05:19:21 +0000635 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
Chris Lattner0f1f5052006-07-20 04:16:23 +0000636 }
Chris Lattner01ecf832006-07-19 05:42:48 +0000637}
638
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000639/// isNextTokenLParen - If the next token lexed will pop this macro off the
640/// expansion stack, return 2. If the next unexpanded token is a '(', return
641/// 1, otherwise return 0.
642unsigned MacroExpander::isNextTokenLParen() const {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000643 // Out of tokens?
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000644 if (isAtEnd())
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000645 return 2;
Chris Lattner70216572006-07-26 03:50:40 +0000646 return MacroTokens[CurToken].getKind() == tok::l_paren;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000647}