blob: 19e39e372908c88bba6657bc58871d3d0a263e4b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +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"
17#include "clang/Basic/SourceManager.h"
18#include "clang/Basic/Diagnostic.h"
19#include "llvm/ADT/SmallVector.h"
20using namespace clang;
21
22//===----------------------------------------------------------------------===//
23// MacroArgs Implementation
24//===----------------------------------------------------------------------===//
25
26/// MacroArgs ctor function - This destroys the vector passed in.
27MacroArgs *MacroArgs::create(const MacroInfo *MI,
Chris Lattnerd2177732007-07-20 16:59:19 +000028 const Token *UnexpArgTokens,
Reid Spencer5f016e22007-07-11 17:01:13 +000029 unsigned NumToks, bool VarargsElided) {
30 assert(MI->isFunctionLike() &&
31 "Can't have args for an object-like macro!");
32
33 // Allocate memory for the MacroArgs object with the lexer tokens at the end.
34 MacroArgs *Result = (MacroArgs*)malloc(sizeof(MacroArgs) +
Chris Lattnerd2177732007-07-20 16:59:19 +000035 NumToks*sizeof(Token));
Reid Spencer5f016e22007-07-11 17:01:13 +000036 // Construct the macroargs object.
37 new (Result) MacroArgs(NumToks, VarargsElided);
38
39 // Copy the actual unexpanded tokens to immediately after the result ptr.
40 if (NumToks)
Chris Lattnerd2177732007-07-20 16:59:19 +000041 memcpy(const_cast<Token*>(Result->getUnexpArgument(0)),
42 UnexpArgTokens, NumToks*sizeof(Token));
Reid Spencer5f016e22007-07-11 17:01:13 +000043
44 return Result;
45}
46
47/// 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
57/// 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 Lattnerd2177732007-07-20 16:59:19 +000060unsigned MacroArgs::getArgLength(const Token *ArgPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +000061 unsigned NumArgTokens = 0;
62 for (; ArgPtr->getKind() != tok::eof; ++ArgPtr)
63 ++NumArgTokens;
64 return NumArgTokens;
65}
66
67
68/// getUnexpArgument - Return the unexpanded tokens for the specified formal.
69///
Chris Lattnerd2177732007-07-20 16:59:19 +000070const Token *MacroArgs::getUnexpArgument(unsigned Arg) const {
Reid Spencer5f016e22007-07-11 17:01:13 +000071 // The unexpanded argument tokens start immediately after the MacroArgs object
72 // in memory.
Chris Lattnerd2177732007-07-20 16:59:19 +000073 const Token *Start = (const Token *)(this+1);
74 const Token *Result = Start;
Reid Spencer5f016e22007-07-11 17:01:13 +000075 // Scan to find Arg.
76 for (; Arg; ++Result) {
77 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
78 if (Result->getKind() == tok::eof)
79 --Arg;
80 }
81 return Result;
82}
83
84
85/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
86/// by pre-expansion, return false. Otherwise, conservatively return true.
Chris Lattnercc1a8752007-10-07 08:44:20 +000087bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok,
88 Preprocessor &PP) const {
Reid Spencer5f016e22007-07-11 17:01:13 +000089 // If there are no identifiers in the argument list, or if the identifiers are
90 // known to not be macros, pre-expansion won't modify it.
91 for (; ArgTok->getKind() != tok::eof; ++ArgTok)
92 if (IdentifierInfo *II = ArgTok->getIdentifierInfo()) {
Chris Lattnercc1a8752007-10-07 08:44:20 +000093 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled())
Reid Spencer5f016e22007-07-11 17:01:13 +000094 // Return true even though the macro could be a function-like macro
95 // without a following '(' token.
96 return true;
97 }
98 return false;
99}
100
101/// getPreExpArgument - Return the pre-expanded form of the specified
102/// argument.
Chris Lattnerd2177732007-07-20 16:59:19 +0000103const std::vector<Token> &
Reid Spencer5f016e22007-07-11 17:01:13 +0000104MacroArgs::getPreExpArgument(unsigned Arg, Preprocessor &PP) {
105 assert(Arg < NumUnexpArgTokens && "Invalid argument number!");
106
107 // If we have already computed this, return it.
108 if (PreExpArgTokens.empty())
109 PreExpArgTokens.resize(NumUnexpArgTokens);
110
Chris Lattnerd2177732007-07-20 16:59:19 +0000111 std::vector<Token> &Result = PreExpArgTokens[Arg];
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 if (!Result.empty()) return Result;
113
Chris Lattnerd2177732007-07-20 16:59:19 +0000114 const Token *AT = getUnexpArgument(Arg);
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 unsigned NumToks = getArgLength(AT)+1; // Include the EOF.
116
117 // Otherwise, we have to pre-expand this argument, populating Result. To do
118 // this, we set up a fake MacroExpander to lex from the unexpanded argument
119 // list. With this installed, we lex expanded tokens until we hit the EOF
120 // token at the end of the unexp list.
121 PP.EnterTokenStream(AT, NumToks);
122
123 // Lex all of the macro-expanded tokens into Result.
124 do {
Chris Lattnerd2177732007-07-20 16:59:19 +0000125 Result.push_back(Token());
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 PP.Lex(Result.back());
127 } while (Result.back().getKind() != tok::eof);
128
129 // Pop the token stream off the top of the stack. We know that the internal
130 // pointer inside of it is to the "end" of the token stream, but the stack
131 // will not otherwise be popped until the next token is lexed. The problem is
132 // that the token may be lexed sometime after the vector of tokens itself is
133 // destroyed, which would be badness.
134 PP.RemoveTopOfLexerStack();
135 return Result;
136}
137
138
139/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
140/// tokens into the literal string token that should be produced by the C #
141/// preprocessor operator.
142///
Chris Lattnerd2177732007-07-20 16:59:19 +0000143static Token StringifyArgument(const Token *ArgToks,
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 Preprocessor &PP, bool Charify = false) {
Chris Lattnerd2177732007-07-20 16:59:19 +0000145 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 Tok.startToken();
147 Tok.setKind(tok::string_literal);
148
Chris Lattnerd2177732007-07-20 16:59:19 +0000149 const Token *ArgTokStart = ArgToks;
Reid Spencer5f016e22007-07-11 17:01:13 +0000150
151 // Stringify all the tokens.
152 std::string Result = "\"";
153 // FIXME: Optimize this loop to not use std::strings.
154 bool isFirst = true;
155 for (; ArgToks->getKind() != tok::eof; ++ArgToks) {
Chris Lattnerd2177732007-07-20 16:59:19 +0000156 const Token &Tok = *ArgToks;
Chris Lattner2b64fdc2007-07-19 16:11:58 +0000157 if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()))
Reid Spencer5f016e22007-07-11 17:01:13 +0000158 Result += ' ';
159 isFirst = false;
160
161 // If this is a string or character constant, escape the token as specified
162 // by 6.10.3.2p2.
163 if (Tok.getKind() == tok::string_literal || // "foo"
164 Tok.getKind() == tok::wide_string_literal || // L"foo"
165 Tok.getKind() == tok::char_constant) { // 'x' and L'x'.
166 Result += Lexer::Stringify(PP.getSpelling(Tok));
167 } else {
168 // Otherwise, just append the token.
169 Result += PP.getSpelling(Tok);
170 }
171 }
172
173 // If the last character of the string is a \, and if it isn't escaped, this
174 // is an invalid string literal, diagnose it as specified in C99.
175 if (Result[Result.size()-1] == '\\') {
176 // Count the number of consequtive \ characters. If even, then they are
177 // just escaped backslashes, otherwise it's an error.
178 unsigned FirstNonSlash = Result.size()-2;
179 // Guaranteed to find the starting " if nothing else.
180 while (Result[FirstNonSlash] == '\\')
181 --FirstNonSlash;
182 if ((Result.size()-1-FirstNonSlash) & 1) {
183 // Diagnose errors for things like: #define F(X) #X / F(\)
184 PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
185 Result.erase(Result.end()-1); // remove one of the \'s.
186 }
187 }
188 Result += '"';
189
190 // If this is the charify operation and the result is not a legal character
191 // constant, diagnose it.
192 if (Charify) {
193 // First step, turn double quotes into single quotes:
194 Result[0] = '\'';
195 Result[Result.size()-1] = '\'';
196
197 // Check for bogus character.
198 bool isBad = false;
199 if (Result.size() == 3) {
200 isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
201 } else {
202 isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
203 }
204
205 if (isBad) {
206 PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
207 Result = "' '"; // Use something arbitrary, but legal.
208 }
209 }
210
211 Tok.setLength(Result.size());
212 Tok.setLocation(PP.CreateString(&Result[0], Result.size()));
213 return Tok;
214}
215
216/// getStringifiedArgument - Compute, cache, and return the specified argument
217/// that has been 'stringified' as required by the # operator.
Chris Lattnerd2177732007-07-20 16:59:19 +0000218const Token &MacroArgs::getStringifiedArgument(unsigned ArgNo,
Reid Spencer5f016e22007-07-11 17:01:13 +0000219 Preprocessor &PP) {
220 assert(ArgNo < NumUnexpArgTokens && "Invalid argument number!");
221 if (StringifiedArgs.empty()) {
222 StringifiedArgs.resize(getNumArguments());
223 memset(&StringifiedArgs[0], 0,
224 sizeof(StringifiedArgs[0])*getNumArguments());
225 }
226 if (StringifiedArgs[ArgNo].getKind() != tok::string_literal)
227 StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP);
228 return StringifiedArgs[ArgNo];
229}
230
231//===----------------------------------------------------------------------===//
232// MacroExpander Implementation
233//===----------------------------------------------------------------------===//
234
235/// Create a macro expander for the specified macro with the specified actual
236/// arguments. Note that this ctor takes ownership of the ActualArgs pointer.
Chris Lattnerd2177732007-07-20 16:59:19 +0000237void MacroExpander::Init(Token &Tok, MacroArgs *Actuals) {
Chris Lattner9594acf2007-07-15 00:25:26 +0000238 // If the client is reusing a macro expander, make sure to free any memory
239 // associated with it.
240 destroy();
241
Chris Lattnercc1a8752007-10-07 08:44:20 +0000242 Macro = PP.getMacroInfo(Tok.getIdentifierInfo());
Chris Lattner9594acf2007-07-15 00:25:26 +0000243 ActualArgs = Actuals;
244 CurToken = 0;
245 InstantiateLoc = Tok.getLocation();
246 AtStartOfLine = Tok.isAtStartOfLine();
247 HasLeadingSpace = Tok.hasLeadingSpace();
Chris Lattnerc215bd62007-07-14 22:11:41 +0000248 MacroTokens = &*Macro->tokens_begin();
Chris Lattner9c683062007-07-22 01:16:55 +0000249 OwnsMacroTokens = false;
Chris Lattnerc215bd62007-07-14 22:11:41 +0000250 NumMacroTokens = Macro->tokens_end()-Macro->tokens_begin();
Reid Spencer5f016e22007-07-11 17:01:13 +0000251
252 // If this is a function-like macro, expand the arguments and change
253 // MacroTokens to point to the expanded tokens.
254 if (Macro->isFunctionLike() && Macro->getNumArgs())
255 ExpandFunctionArguments();
256
257 // Mark the macro as currently disabled, so that it is not recursively
258 // expanded. The macro must be disabled only after argument pre-expansion of
259 // function-like macro arguments occurs.
260 Macro->DisableMacro();
261}
262
Chris Lattner9594acf2007-07-15 00:25:26 +0000263
264
Reid Spencer5f016e22007-07-11 17:01:13 +0000265/// Create a macro expander for the specified token stream. This does not
266/// take ownership of the specified token vector.
Chris Lattnerd2177732007-07-20 16:59:19 +0000267void MacroExpander::Init(const Token *TokArray, unsigned NumToks) {
Chris Lattner9594acf2007-07-15 00:25:26 +0000268 // If the client is reusing a macro expander, make sure to free any memory
269 // associated with it.
270 destroy();
271
272 Macro = 0;
273 ActualArgs = 0;
274 MacroTokens = TokArray;
Chris Lattner9c683062007-07-22 01:16:55 +0000275 OwnsMacroTokens = false;
Chris Lattner9594acf2007-07-15 00:25:26 +0000276 NumMacroTokens = NumToks;
277 CurToken = 0;
278 InstantiateLoc = SourceLocation();
279 AtStartOfLine = false;
280 HasLeadingSpace = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000281
282 // Set HasLeadingSpace/AtStartOfLine so that the first token will be
283 // returned unmodified.
284 if (NumToks != 0) {
285 AtStartOfLine = TokArray[0].isAtStartOfLine();
286 HasLeadingSpace = TokArray[0].hasLeadingSpace();
287 }
288}
289
290
Chris Lattner9594acf2007-07-15 00:25:26 +0000291void MacroExpander::destroy() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000292 // If this was a function-like macro that actually uses its arguments, delete
293 // the expanded tokens.
Chris Lattner9c683062007-07-22 01:16:55 +0000294 if (OwnsMacroTokens) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 delete [] MacroTokens;
Chris Lattner9c683062007-07-22 01:16:55 +0000296 MacroTokens = 0;
297 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000298
299 // MacroExpander owns its formal arguments.
300 if (ActualArgs) ActualArgs->destroy();
301}
302
303/// Expand the arguments of a function-like macro so that we can quickly
304/// return preexpanded tokens from MacroTokens.
305void MacroExpander::ExpandFunctionArguments() {
Chris Lattnerd2177732007-07-20 16:59:19 +0000306 llvm::SmallVector<Token, 128> ResultToks;
Reid Spencer5f016e22007-07-11 17:01:13 +0000307
308 // Loop through the MacroTokens tokens, expanding them into ResultToks. Keep
309 // track of whether we change anything. If not, no need to keep them. If so,
310 // we install the newly expanded sequence as MacroTokens.
311 bool MadeChange = false;
312
313 // NextTokGetsSpace - When this is true, the next token appended to the
314 // output list will get a leading space, regardless of whether it had one to
315 // begin with or not. This is used for placemarker support.
316 bool NextTokGetsSpace = false;
317
318 for (unsigned i = 0, e = NumMacroTokens; i != e; ++i) {
319 // If we found the stringify operator, get the argument stringified. The
320 // preprocessor already verified that the following token is a macro name
321 // when the #define was parsed.
Chris Lattnerd2177732007-07-20 16:59:19 +0000322 const Token &CurTok = MacroTokens[i];
Reid Spencer5f016e22007-07-11 17:01:13 +0000323 if (CurTok.getKind() == tok::hash || CurTok.getKind() == tok::hashat) {
324 int ArgNo = Macro->getArgumentNum(MacroTokens[i+1].getIdentifierInfo());
325 assert(ArgNo != -1 && "Token following # is not an argument?");
326
Chris Lattnerd2177732007-07-20 16:59:19 +0000327 Token Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000328 if (CurTok.getKind() == tok::hash) // Stringify
329 Res = ActualArgs->getStringifiedArgument(ArgNo, PP);
330 else {
331 // 'charify': don't bother caching these.
332 Res = StringifyArgument(ActualArgs->getUnexpArgument(ArgNo), PP, true);
333 }
334
335 // The stringified/charified string leading space flag gets set to match
336 // the #/#@ operator.
337 if (CurTok.hasLeadingSpace() || NextTokGetsSpace)
Chris Lattnerd2177732007-07-20 16:59:19 +0000338 Res.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000339
340 ResultToks.push_back(Res);
341 MadeChange = true;
342 ++i; // Skip arg name.
343 NextTokGetsSpace = false;
344 continue;
345 }
346
347 // Otherwise, if this is not an argument token, just add the token to the
348 // output buffer.
349 IdentifierInfo *II = CurTok.getIdentifierInfo();
350 int ArgNo = II ? Macro->getArgumentNum(II) : -1;
351 if (ArgNo == -1) {
352 // This isn't an argument, just add it.
353 ResultToks.push_back(CurTok);
354
355 if (NextTokGetsSpace) {
Chris Lattnerd2177732007-07-20 16:59:19 +0000356 ResultToks.back().setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 NextTokGetsSpace = false;
358 }
359 continue;
360 }
361
362 // An argument is expanded somehow, the result is different than the
363 // input.
364 MadeChange = true;
365
366 // Otherwise, this is a use of the argument. Find out if there is a paste
367 // (##) operator before or after the argument.
368 bool PasteBefore =
369 !ResultToks.empty() && ResultToks.back().getKind() == tok::hashhash;
370 bool PasteAfter = i+1 != e && MacroTokens[i+1].getKind() == tok::hashhash;
371
372 // If it is not the LHS/RHS of a ## operator, we must pre-expand the
373 // argument and substitute the expanded tokens into the result. This is
374 // C99 6.10.3.1p1.
375 if (!PasteBefore && !PasteAfter) {
Chris Lattnerd2177732007-07-20 16:59:19 +0000376 const Token *ResultArgToks;
Reid Spencer5f016e22007-07-11 17:01:13 +0000377
378 // Only preexpand the argument if it could possibly need it. This
379 // avoids some work in common cases.
Chris Lattnerd2177732007-07-20 16:59:19 +0000380 const Token *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
Chris Lattnercc1a8752007-10-07 08:44:20 +0000381 if (ActualArgs->ArgNeedsPreexpansion(ArgTok, PP))
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0];
383 else
384 ResultArgToks = ArgTok; // Use non-preexpanded tokens.
385
386 // If the arg token expanded into anything, append it.
387 if (ResultArgToks->getKind() != tok::eof) {
388 unsigned FirstResult = ResultToks.size();
389 unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
390 ResultToks.append(ResultArgToks, ResultArgToks+NumToks);
391
392 // If any tokens were substituted from the argument, the whitespace
393 // before the first token should match the whitespace of the arg
394 // identifier.
Chris Lattnerd2177732007-07-20 16:59:19 +0000395 ResultToks[FirstResult].setFlagValue(Token::LeadingSpace,
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 CurTok.hasLeadingSpace() ||
397 NextTokGetsSpace);
398 NextTokGetsSpace = false;
399 } else {
400 // If this is an empty argument, and if there was whitespace before the
401 // formal token, make sure the next token gets whitespace before it.
402 NextTokGetsSpace = CurTok.hasLeadingSpace();
403 }
404 continue;
405 }
406
407 // Okay, we have a token that is either the LHS or RHS of a paste (##)
408 // argument. It gets substituted as its non-pre-expanded tokens.
Chris Lattnerd2177732007-07-20 16:59:19 +0000409 const Token *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 unsigned NumToks = MacroArgs::getArgLength(ArgToks);
411 if (NumToks) { // Not an empty argument?
412 ResultToks.append(ArgToks, ArgToks+NumToks);
413
414 // If the next token was supposed to get leading whitespace, ensure it has
415 // it now.
416 if (NextTokGetsSpace) {
Chris Lattnerd2177732007-07-20 16:59:19 +0000417 ResultToks[ResultToks.size()-NumToks].setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 NextTokGetsSpace = false;
419 }
420 continue;
421 }
422
423 // If an empty argument is on the LHS or RHS of a paste, the standard (C99
424 // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur. We
425 // implement this by eating ## operators when a LHS or RHS expands to
426 // empty.
427 NextTokGetsSpace |= CurTok.hasLeadingSpace();
428 if (PasteAfter) {
429 // Discard the argument token and skip (don't copy to the expansion
430 // buffer) the paste operator after it.
431 NextTokGetsSpace |= MacroTokens[i+1].hasLeadingSpace();
432 ++i;
433 continue;
434 }
435
436 // If this is on the RHS of a paste operator, we've already copied the
437 // paste operator to the ResultToks list. Remove it.
438 assert(PasteBefore && ResultToks.back().getKind() == tok::hashhash);
439 NextTokGetsSpace |= ResultToks.back().hasLeadingSpace();
440 ResultToks.pop_back();
441
442 // If this is the __VA_ARGS__ token, and if the argument wasn't provided,
443 // and if the macro had at least one real argument, and if the token before
444 // the ## was a comma, remove the comma.
445 if ((unsigned)ArgNo == Macro->getNumArgs()-1 && // is __VA_ARGS__
446 ActualArgs->isVarargsElidedUse() && // Argument elided.
447 !ResultToks.empty() && ResultToks.back().getKind() == tok::comma) {
448 // Never add a space, even if the comma, ##, or arg had a space.
449 NextTokGetsSpace = false;
450 ResultToks.pop_back();
451 }
452 continue;
453 }
454
455 // If anything changed, install this as the new MacroTokens list.
456 if (MadeChange) {
457 // This is deleted in the dtor.
458 NumMacroTokens = ResultToks.size();
Chris Lattnerd2177732007-07-20 16:59:19 +0000459 Token *Res = new Token[ResultToks.size()];
Reid Spencer5f016e22007-07-11 17:01:13 +0000460 if (NumMacroTokens)
Chris Lattnerd2177732007-07-20 16:59:19 +0000461 memcpy(Res, &ResultToks[0], NumMacroTokens*sizeof(Token));
Reid Spencer5f016e22007-07-11 17:01:13 +0000462 MacroTokens = Res;
Chris Lattner9c683062007-07-22 01:16:55 +0000463 OwnsMacroTokens = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 }
465}
466
467/// Lex - Lex and return a token from this macro stream.
468///
Chris Lattnerd2177732007-07-20 16:59:19 +0000469void MacroExpander::Lex(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 // Lexing off the end of the macro, pop this macro off the expansion stack.
471 if (isAtEnd()) {
472 // If this is a macro (not a token stream), mark the macro enabled now
473 // that it is no longer being expanded.
474 if (Macro) Macro->EnableMacro();
475
476 // Pop this context off the preprocessors lexer stack and get the next
477 // token. This will delete "this" so remember the PP instance var.
478 Preprocessor &PPCache = PP;
479 if (PP.HandleEndOfMacro(Tok))
480 return;
481
482 // HandleEndOfMacro may not return a token. If it doesn't, lex whatever is
483 // next.
484 return PPCache.Lex(Tok);
485 }
486
487 // If this is the first token of the expanded result, we inherit spacing
488 // properties later.
489 bool isFirstToken = CurToken == 0;
490
491 // Get the next token to return.
492 Tok = MacroTokens[CurToken++];
493
494 // If this token is followed by a token paste (##) operator, paste the tokens!
495 if (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash)
496 PasteTokens(Tok);
497
498 // The token's current location indicate where the token was lexed from. We
499 // need this information to compute the spelling of the token, but any
500 // diagnostics for the expanded token should appear as if they came from
501 // InstantiationLoc. Pull this information together into a new SourceLocation
502 // that captures all of this.
503 if (InstantiateLoc.isValid()) { // Don't do this for token streams.
504 SourceManager &SrcMgr = PP.getSourceManager();
Chris Lattnerabca2bb2007-07-15 06:35:27 +0000505 Tok.setLocation(SrcMgr.getInstantiationLoc(Tok.getLocation(),
506 InstantiateLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000507 }
508
509 // If this is the first token, set the lexical properties of the token to
510 // match the lexical properties of the macro identifier.
511 if (isFirstToken) {
Chris Lattnerd2177732007-07-20 16:59:19 +0000512 Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
513 Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000514 }
515
516 // Handle recursive expansion!
517 if (Tok.getIdentifierInfo())
518 return PP.HandleIdentifier(Tok);
519
520 // Otherwise, return a normal token.
521}
522
523/// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ##
524/// operator. Read the ## and RHS, and paste the LHS/RHS together. If there
525/// are is another ## after it, chomp it iteratively. Return the result as Tok.
Chris Lattnerd2177732007-07-20 16:59:19 +0000526void MacroExpander::PasteTokens(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 llvm::SmallVector<char, 128> Buffer;
528 do {
529 // Consume the ## operator.
530 SourceLocation PasteOpLoc = MacroTokens[CurToken].getLocation();
531 ++CurToken;
532 assert(!isAtEnd() && "No token on the RHS of a paste operator!");
533
534 // Get the RHS token.
Chris Lattnerd2177732007-07-20 16:59:19 +0000535 const Token &RHS = MacroTokens[CurToken];
Reid Spencer5f016e22007-07-11 17:01:13 +0000536
537 bool isInvalid = false;
538
539 // Allocate space for the result token. This is guaranteed to be enough for
540 // the two tokens and a null terminator.
541 Buffer.resize(Tok.getLength() + RHS.getLength() + 1);
542
543 // Get the spelling of the LHS token in Buffer.
544 const char *BufPtr = &Buffer[0];
545 unsigned LHSLen = PP.getSpelling(Tok, BufPtr);
546 if (BufPtr != &Buffer[0]) // Really, we want the chars in Buffer!
547 memcpy(&Buffer[0], BufPtr, LHSLen);
548
549 BufPtr = &Buffer[LHSLen];
550 unsigned RHSLen = PP.getSpelling(RHS, BufPtr);
551 if (BufPtr != &Buffer[LHSLen]) // Really, we want the chars in Buffer!
552 memcpy(&Buffer[LHSLen], BufPtr, RHSLen);
553
554 // Add null terminator.
555 Buffer[LHSLen+RHSLen] = '\0';
556
557 // Trim excess space.
558 Buffer.resize(LHSLen+RHSLen+1);
559
560 // Plop the pasted result (including the trailing newline and null) into a
561 // scratch buffer where we can lex it.
562 SourceLocation ResultTokLoc = PP.CreateString(&Buffer[0], Buffer.size());
563
564 // Lex the resultant pasted token into Result.
Chris Lattnerd2177732007-07-20 16:59:19 +0000565 Token Result;
Reid Spencer5f016e22007-07-11 17:01:13 +0000566
567 // Avoid testing /*, as the lexer would think it is the start of a comment
568 // and emit an error that it is unterminated.
569 if (Tok.getKind() == tok::slash && RHS.getKind() == tok::star) {
570 isInvalid = true;
571 } else if (Tok.getKind() == tok::identifier &&
572 RHS.getKind() == tok::identifier) {
573 // Common paste case: identifier+identifier = identifier. Avoid creating
574 // a lexer and other overhead.
575 PP.IncrementPasteCounter(true);
576 Result.startToken();
577 Result.setKind(tok::identifier);
578 Result.setLocation(ResultTokLoc);
579 Result.setLength(LHSLen+RHSLen);
580 } else {
581 PP.IncrementPasteCounter(false);
582
583 // Make a lexer to lex this string from.
584 SourceManager &SourceMgr = PP.getSourceManager();
585 const char *ResultStrData = SourceMgr.getCharacterData(ResultTokLoc);
586
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 // Make a lexer object so that we lex and expand the paste result.
Chris Lattner25bdb512007-07-20 16:52:03 +0000588 Lexer *TL = new Lexer(ResultTokLoc, PP, ResultStrData,
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 ResultStrData+LHSLen+RHSLen /*don't include null*/);
590
591 // Lex a token in raw mode. This way it won't look up identifiers
592 // automatically, lexing off the end will return an eof token, and
593 // warnings are disabled. This returns true if the result token is the
594 // entire buffer.
595 bool IsComplete = TL->LexRawToken(Result);
596
597 // If we got an EOF token, we didn't form even ONE token. For example, we
598 // did "/ ## /" to get "//".
599 IsComplete &= Result.getKind() != tok::eof;
600 isInvalid = !IsComplete;
601
602 // We're now done with the temporary lexer.
603 delete TL;
604 }
605
606 // If pasting the two tokens didn't form a full new token, this is an error.
607 // This occurs with "x ## +" and other stuff. Return with Tok unmodified
608 // and with RHS as the next token to lex.
609 if (isInvalid) {
610 // If not in assembler language mode.
611 PP.Diag(PasteOpLoc, diag::err_pp_bad_paste,
612 std::string(Buffer.begin(), Buffer.end()-1));
613 return;
614 }
615
616 // Turn ## into 'other' to avoid # ## # from looking like a paste operator.
617 if (Result.getKind() == tok::hashhash)
618 Result.setKind(tok::unknown);
619 // FIXME: Turn __VARRGS__ into "not a token"?
620
621 // Transfer properties of the LHS over the the Result.
Chris Lattnerd2177732007-07-20 16:59:19 +0000622 Result.setFlagValue(Token::StartOfLine , Tok.isAtStartOfLine());
623 Result.setFlagValue(Token::LeadingSpace, Tok.hasLeadingSpace());
Reid Spencer5f016e22007-07-11 17:01:13 +0000624
625 // Finally, replace LHS with the result, consume the RHS, and iterate.
626 ++CurToken;
627 Tok = Result;
628 } while (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash);
629
630 // Now that we got the result token, it will be subject to expansion. Since
631 // token pasting re-lexes the result token in raw mode, identifier information
632 // isn't looked up. As such, if the result is an identifier, look up id info.
633 if (Tok.getKind() == tok::identifier) {
634 // Look up the identifier info for the token. We disabled identifier lookup
635 // by saying we're skipping contents, so we need to do this manually.
636 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
637 }
638}
639
640/// isNextTokenLParen - If the next token lexed will pop this macro off the
641/// expansion stack, return 2. If the next unexpanded token is a '(', return
642/// 1, otherwise return 0.
643unsigned MacroExpander::isNextTokenLParen() const {
644 // Out of tokens?
645 if (isAtEnd())
646 return 2;
647 return MacroTokens[CurToken].getKind() == tok::l_paren;
648}