blob: c98949ec1d304104327270e89c6379e02ac52082 [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 Lattner7a4af3b2006-07-26 06:26:52 +000028 const LexerToken *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) +
35 NumToks*sizeof(LexerToken));
36 // 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)
41 memcpy(const_cast<LexerToken*>(Result->getUnexpArgument(0)),
Chris Lattner7a4af3b2006-07-26 06:26:52 +000042 UnexpArgTokens, NumToks*sizeof(LexerToken));
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.
60unsigned MacroArgs::getArgLength(const LexerToken *ArgPtr) {
61 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///
70const LexerToken *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.
73 const LexerToken *Start = (const LexerToken *)(this+1);
Chris Lattner36b6e812006-07-21 06:38:30 +000074 const LexerToken *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 Lattner36b6e812006-07-21 06:38:30 +000087bool MacroArgs::ArgNeedsPreexpansion(const LexerToken *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.
102const std::vector<LexerToken> &
103MacroArgs::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
110 std::vector<LexerToken> &Result = PreExpArgTokens[Arg];
111 if (!Result.empty()) return Result;
112
Chris Lattner36b6e812006-07-21 06:38:30 +0000113 const LexerToken *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 {
124 Result.push_back(LexerToken());
125 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 Lattner36b6e812006-07-21 06:38:30 +0000142static LexerToken StringifyArgument(const LexerToken *ArgToks,
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000143 Preprocessor &PP, bool Charify = false) {
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000144 LexerToken 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 Lattner36b6e812006-07-21 06:38:30 +0000148 const LexerToken *ArgTokStart = ArgToks;
149
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) {
155 const LexerToken &Tok = *ArgToks;
156 if (!isFirst && Tok.hasLeadingSpace())
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 Lattneree8760b2006-07-15 07:42:55 +0000217const LexerToken &MacroArgs::getStringifiedArgument(unsigned ArgNo,
218 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 Lattnerc02c4ab2007-07-15 00:25:26 +0000236void MacroExpander::Init(LexerToken &Tok, MacroArgs *Actuals) {
237 // 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();
248 NumMacroTokens = Macro->tokens_end()-Macro->tokens_begin();
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000249
250 // If this is a function-like macro, expand the arguments and change
251 // MacroTokens to point to the expanded tokens.
Chris Lattner95a06b32006-07-30 08:40:43 +0000252 if (Macro->isFunctionLike() && Macro->getNumArgs())
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000253 ExpandFunctionArguments();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000254
255 // Mark the macro as currently disabled, so that it is not recursively
256 // expanded. The macro must be disabled only after argument pre-expansion of
257 // function-like macro arguments occurs.
258 Macro->DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000259}
260
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000261
262
Chris Lattner7667d0d2006-07-16 18:16:58 +0000263/// Create a macro expander for the specified token stream. This does not
264/// take ownership of the specified token vector.
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000265void MacroExpander::Init(const LexerToken *TokArray, unsigned NumToks) {
266 // If the client is reusing a macro expander, make sure to free any memory
267 // associated with it.
268 destroy();
269
270 Macro = 0;
271 ActualArgs = 0;
272 MacroTokens = TokArray;
273 NumMacroTokens = NumToks;
274 CurToken = 0;
275 InstantiateLoc = SourceLocation();
276 AtStartOfLine = false;
277 HasLeadingSpace = false;
Chris Lattner7667d0d2006-07-16 18:16:58 +0000278
279 // Set HasLeadingSpace/AtStartOfLine so that the first token will be
280 // returned unmodified.
Chris Lattner70216572006-07-26 03:50:40 +0000281 if (NumToks != 0) {
282 AtStartOfLine = TokArray[0].isAtStartOfLine();
283 HasLeadingSpace = TokArray[0].hasLeadingSpace();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000284 }
285}
286
287
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000288void MacroExpander::destroy() {
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000289 // If this was a function-like macro that actually uses its arguments, delete
290 // the expanded tokens.
Chris Lattnerf40fe992007-07-14 22:11:41 +0000291 if (Macro && MacroTokens != &*Macro->tokens_begin())
Chris Lattner70216572006-07-26 03:50:40 +0000292 delete [] MacroTokens;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000293
294 // MacroExpander owns its formal arguments.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000295 if (ActualArgs) ActualArgs->destroy();
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000296}
297
298/// Expand the arguments of a function-like macro so that we can quickly
299/// return preexpanded tokens from MacroTokens.
300void MacroExpander::ExpandFunctionArguments() {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000301 llvm::SmallVector<LexerToken, 128> ResultToks;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000302
303 // Loop through the MacroTokens tokens, expanding them into ResultToks. Keep
304 // track of whether we change anything. If not, no need to keep them. If so,
305 // we install the newly expanded sequence as MacroTokens.
306 bool MadeChange = false;
Chris Lattner479b0af2006-07-29 04:16:20 +0000307
308 // NextTokGetsSpace - When this is true, the next token appended to the
309 // output list will get a leading space, regardless of whether it had one to
310 // begin with or not. This is used for placemarker support.
311 bool NextTokGetsSpace = false;
312
Chris Lattner70216572006-07-26 03:50:40 +0000313 for (unsigned i = 0, e = NumMacroTokens; i != e; ++i) {
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000314 // If we found the stringify operator, get the argument stringified. The
315 // preprocessor already verified that the following token is a macro name
316 // when the #define was parsed.
Chris Lattner70216572006-07-26 03:50:40 +0000317 const LexerToken &CurTok = MacroTokens[i];
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000318 if (CurTok.getKind() == tok::hash || CurTok.getKind() == tok::hashat) {
Chris Lattner70216572006-07-26 03:50:40 +0000319 int ArgNo = Macro->getArgumentNum(MacroTokens[i+1].getIdentifierInfo());
Chris Lattner95a06b32006-07-30 08:40:43 +0000320 assert(ArgNo != -1 && "Token following # is not an argument?");
321
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000322 LexerToken Res;
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000323 if (CurTok.getKind() == tok::hash) // Stringify
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000324 Res = ActualArgs->getStringifiedArgument(ArgNo, PP);
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000325 else {
326 // 'charify': don't bother caching these.
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000327 Res = StringifyArgument(ActualArgs->getUnexpArgument(ArgNo), PP, true);
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000328 }
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000329
Chris Lattner60161692006-07-15 06:48:02 +0000330 // The stringified/charified string leading space flag gets set to match
331 // the #/#@ operator.
Chris Lattner479b0af2006-07-29 04:16:20 +0000332 if (CurTok.hasLeadingSpace() || NextTokGetsSpace)
Chris Lattner8c204872006-10-14 05:19:21 +0000333 Res.setFlag(LexerToken::LeadingSpace);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000334
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000335 ResultToks.push_back(Res);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000336 MadeChange = true;
337 ++i; // Skip arg name.
Chris Lattner479b0af2006-07-29 04:16:20 +0000338 NextTokGetsSpace = false;
Chris Lattnera9dc5972006-07-28 05:07:04 +0000339 continue;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000340 }
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000341
342 // Otherwise, if this is not an argument token, just add the token to the
343 // output buffer.
344 IdentifierInfo *II = CurTok.getIdentifierInfo();
345 int ArgNo = II ? Macro->getArgumentNum(II) : -1;
346 if (ArgNo == -1) {
Chris Lattner95a06b32006-07-30 08:40:43 +0000347 // This isn't an argument, just add it.
348 ResultToks.push_back(CurTok);
Chris Lattner479b0af2006-07-29 04:16:20 +0000349
Chris Lattner95a06b32006-07-30 08:40:43 +0000350 if (NextTokGetsSpace) {
Chris Lattner8c204872006-10-14 05:19:21 +0000351 ResultToks.back().setFlag(LexerToken::LeadingSpace);
Chris Lattner95a06b32006-07-30 08:40:43 +0000352 NextTokGetsSpace = false;
Chris Lattner21c8b8f2006-07-29 04:04:22 +0000353 }
Chris Lattner95a06b32006-07-30 08:40:43 +0000354 continue;
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000355 }
356
357 // An argument is expanded somehow, the result is different than the
358 // input.
359 MadeChange = true;
360
361 // Otherwise, this is a use of the argument. Find out if there is a paste
362 // (##) operator before or after the argument.
363 bool PasteBefore =
364 !ResultToks.empty() && ResultToks.back().getKind() == tok::hashhash;
365 bool PasteAfter = i+1 != e && MacroTokens[i+1].getKind() == tok::hashhash;
366
367 // If it is not the LHS/RHS of a ## operator, we must pre-expand the
368 // argument and substitute the expanded tokens into the result. This is
369 // C99 6.10.3.1p1.
370 if (!PasteBefore && !PasteAfter) {
371 const LexerToken *ResultArgToks;
372
373 // Only preexpand the argument if it could possibly need it. This
374 // avoids some work in common cases.
375 const LexerToken *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
376 if (ActualArgs->ArgNeedsPreexpansion(ArgTok))
377 ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0];
378 else
379 ResultArgToks = ArgTok; // Use non-preexpanded tokens.
380
381 // If the arg token expanded into anything, append it.
382 if (ResultArgToks->getKind() != tok::eof) {
383 unsigned FirstResult = ResultToks.size();
384 unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
385 ResultToks.append(ResultArgToks, ResultArgToks+NumToks);
386
387 // If any tokens were substituted from the argument, the whitespace
388 // before the first token should match the whitespace of the arg
389 // identifier.
Chris Lattner8c204872006-10-14 05:19:21 +0000390 ResultToks[FirstResult].setFlagValue(LexerToken::LeadingSpace,
Chris Lattner479b0af2006-07-29 04:16:20 +0000391 CurTok.hasLeadingSpace() ||
392 NextTokGetsSpace);
393 NextTokGetsSpace = false;
394 } else {
395 // If this is an empty argument, and if there was whitespace before the
396 // formal token, make sure the next token gets whitespace before it.
397 NextTokGetsSpace = CurTok.hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000398 }
399 continue;
400 }
401
402 // Okay, we have a token that is either the LHS or RHS of a paste (##)
403 // argument. It gets substituted as its non-pre-expanded tokens.
404 const LexerToken *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
405 unsigned NumToks = MacroArgs::getArgLength(ArgToks);
406 if (NumToks) { // Not an empty argument?
407 ResultToks.append(ArgToks, ArgToks+NumToks);
Chris Lattner479b0af2006-07-29 04:16:20 +0000408
409 // If the next token was supposed to get leading whitespace, ensure it has
410 // it now.
411 if (NextTokGetsSpace) {
Chris Lattner8c204872006-10-14 05:19:21 +0000412 ResultToks[ResultToks.size()-NumToks].setFlag(LexerToken::LeadingSpace);
Chris Lattner479b0af2006-07-29 04:16:20 +0000413 NextTokGetsSpace = false;
414 }
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000415 continue;
416 }
417
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000418 // If an empty argument is on the LHS or RHS of a paste, the standard (C99
419 // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur. We
420 // implement this by eating ## operators when a LHS or RHS expands to
421 // empty.
Chris Lattner479b0af2006-07-29 04:16:20 +0000422 NextTokGetsSpace |= CurTok.hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000423 if (PasteAfter) {
424 // Discard the argument token and skip (don't copy to the expansion
425 // buffer) the paste operator after it.
Chris Lattner479b0af2006-07-29 04:16:20 +0000426 NextTokGetsSpace |= MacroTokens[i+1].hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000427 ++i;
428 continue;
429 }
430
431 // If this is on the RHS of a paste operator, we've already copied the
432 // paste operator to the ResultToks list. Remove it.
433 assert(PasteBefore && ResultToks.back().getKind() == tok::hashhash);
Chris Lattner479b0af2006-07-29 04:16:20 +0000434 NextTokGetsSpace |= ResultToks.back().hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000435 ResultToks.pop_back();
Chris Lattner775d8322006-07-29 04:39:41 +0000436
437 // If this is the __VA_ARGS__ token, and if the argument wasn't provided,
438 // and if the macro had at least one real argument, and if the token before
439 // the ## was a comma, remove the comma.
Chris Lattner95a06b32006-07-30 08:40:43 +0000440 if ((unsigned)ArgNo == Macro->getNumArgs()-1 && // is __VA_ARGS__
Chris Lattner775d8322006-07-29 04:39:41 +0000441 ActualArgs->isVarargsElidedUse() && // Argument elided.
442 !ResultToks.empty() && ResultToks.back().getKind() == tok::comma) {
443 // Never add a space, even if the comma, ##, or arg had a space.
444 NextTokGetsSpace = false;
445 ResultToks.pop_back();
446 }
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000447 continue;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000448 }
449
450 // If anything changed, install this as the new MacroTokens list.
451 if (MadeChange) {
452 // This is deleted in the dtor.
Chris Lattner70216572006-07-26 03:50:40 +0000453 NumMacroTokens = ResultToks.size();
454 LexerToken *Res = new LexerToken[ResultToks.size()];
Chris Lattnerd97d2e72006-07-29 06:44:29 +0000455 if (NumMacroTokens)
456 memcpy(Res, &ResultToks[0], NumMacroTokens*sizeof(LexerToken));
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000457 MacroTokens = Res;
458 }
459}
Chris Lattner67b07cb2006-06-26 02:03:42 +0000460
Chris Lattner22eb9722006-06-18 05:43:12 +0000461/// Lex - Lex and return a token from this macro stream.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000462///
Chris Lattnercb283342006-06-18 06:48:37 +0000463void MacroExpander::Lex(LexerToken &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000464 // Lexing off the end of the macro, pop this macro off the expansion stack.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000465 if (isAtEnd()) {
466 // If this is a macro (not a token stream), mark the macro enabled now
467 // that it is no longer being expanded.
468 if (Macro) Macro->EnableMacro();
469
470 // Pop this context off the preprocessors lexer stack and get the next
Chris Lattner2183a6e2006-07-18 06:36:12 +0000471 // token. This will delete "this" so remember the PP instance var.
472 Preprocessor &PPCache = PP;
473 if (PP.HandleEndOfMacro(Tok))
474 return;
475
476 // HandleEndOfMacro may not return a token. If it doesn't, lex whatever is
477 // next.
478 return PPCache.Lex(Tok);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000479 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000480
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000481 // If this is the first token of the expanded result, we inherit spacing
482 // properties later.
483 bool isFirstToken = CurToken == 0;
484
Chris Lattner22eb9722006-06-18 05:43:12 +0000485 // Get the next token to return.
Chris Lattner70216572006-07-26 03:50:40 +0000486 Tok = MacroTokens[CurToken++];
Chris Lattner01ecf832006-07-19 05:42:48 +0000487
488 // If this token is followed by a token paste (##) operator, paste the tokens!
Chris Lattner70216572006-07-26 03:50:40 +0000489 if (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash)
Chris Lattner01ecf832006-07-19 05:42:48 +0000490 PasteTokens(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000491
Chris Lattnerc673f902006-06-30 06:10:41 +0000492 // The token's current location indicate where the token was lexed from. We
493 // need this information to compute the spelling of the token, but any
494 // diagnostics for the expanded token should appear as if they came from
495 // InstantiationLoc. Pull this information together into a new SourceLocation
496 // that captures all of this.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000497 if (InstantiateLoc.isValid()) { // Don't do this for token streams.
498 SourceManager &SrcMgr = PP.getSourceManager();
499 // The token could have come from a prior macro expansion. In that case,
500 // ignore the macro expand part to get to the physloc. This happens for
501 // stuff like: #define A(X) X A(A(X)) A(1)
Chris Lattner3fc74e22007-07-15 06:35:27 +0000502 Tok.setLocation(SrcMgr.getInstantiationLoc(Tok.getLocation(),
503 InstantiateLoc));
Chris Lattner7667d0d2006-07-16 18:16:58 +0000504 }
505
Chris Lattner22eb9722006-06-18 05:43:12 +0000506 // If this is the first token, set the lexical properties of the token to
507 // match the lexical properties of the macro identifier.
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000508 if (isFirstToken) {
Chris Lattner8c204872006-10-14 05:19:21 +0000509 Tok.setFlagValue(LexerToken::StartOfLine , AtStartOfLine);
510 Tok.setFlagValue(LexerToken::LeadingSpace, HasLeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +0000511 }
512
513 // Handle recursive expansion!
514 if (Tok.getIdentifierInfo())
515 return PP.HandleIdentifier(Tok);
516
517 // Otherwise, return a normal token.
Chris Lattner22eb9722006-06-18 05:43:12 +0000518}
Chris Lattnerafe603f2006-07-11 04:02:46 +0000519
Chris Lattner01ecf832006-07-19 05:42:48 +0000520/// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ##
521/// operator. Read the ## and RHS, and paste the LHS/RHS together. If there
522/// are is another ## after it, chomp it iteratively. Return the result as Tok.
523void MacroExpander::PasteTokens(LexerToken &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000524 llvm::SmallVector<char, 128> Buffer;
Chris Lattner01ecf832006-07-19 05:42:48 +0000525 do {
526 // Consume the ## operator.
Chris Lattner70216572006-07-26 03:50:40 +0000527 SourceLocation PasteOpLoc = MacroTokens[CurToken].getLocation();
Chris Lattner01ecf832006-07-19 05:42:48 +0000528 ++CurToken;
529 assert(!isAtEnd() && "No token on the RHS of a paste operator!");
530
531 // Get the RHS token.
Chris Lattner70216572006-07-26 03:50:40 +0000532 const LexerToken &RHS = MacroTokens[CurToken];
Chris Lattner01ecf832006-07-19 05:42:48 +0000533
534 bool isInvalid = false;
535
Chris Lattner01ecf832006-07-19 05:42:48 +0000536 // Allocate space for the result token. This is guaranteed to be enough for
537 // the two tokens and a null terminator.
Chris Lattner57dd8362006-11-03 07:45:04 +0000538 Buffer.resize(Tok.getLength() + RHS.getLength() + 1);
Chris Lattner01ecf832006-07-19 05:42:48 +0000539
540 // Get the spelling of the LHS token in Buffer.
Chris Lattner57dd8362006-11-03 07:45:04 +0000541 const char *BufPtr = &Buffer[0];
Chris Lattner01ecf832006-07-19 05:42:48 +0000542 unsigned LHSLen = PP.getSpelling(Tok, BufPtr);
Chris Lattner57dd8362006-11-03 07:45:04 +0000543 if (BufPtr != &Buffer[0]) // Really, we want the chars in Buffer!
544 memcpy(&Buffer[0], BufPtr, LHSLen);
Chris Lattner01ecf832006-07-19 05:42:48 +0000545
Chris Lattner57dd8362006-11-03 07:45:04 +0000546 BufPtr = &Buffer[LHSLen];
Chris Lattner01ecf832006-07-19 05:42:48 +0000547 unsigned RHSLen = PP.getSpelling(RHS, BufPtr);
Chris Lattner57dd8362006-11-03 07:45:04 +0000548 if (BufPtr != &Buffer[LHSLen]) // Really, we want the chars in Buffer!
549 memcpy(&Buffer[LHSLen], BufPtr, RHSLen);
Chris Lattner01ecf832006-07-19 05:42:48 +0000550
551 // Add null terminator.
552 Buffer[LHSLen+RHSLen] = '\0';
553
Chris Lattner57dd8362006-11-03 07:45:04 +0000554 // Trim excess space.
555 Buffer.resize(LHSLen+RHSLen+1);
556
Chris Lattner01ecf832006-07-19 05:42:48 +0000557 // Plop the pasted result (including the trailing newline and null) into a
558 // scratch buffer where we can lex it.
Chris Lattner57dd8362006-11-03 07:45:04 +0000559 SourceLocation ResultTokLoc = PP.CreateString(&Buffer[0], Buffer.size());
Chris Lattner01ecf832006-07-19 05:42:48 +0000560
561 // Lex the resultant pasted token into Result.
562 LexerToken Result;
563
Chris Lattnera7e2e742006-07-19 06:32:35 +0000564 // Avoid testing /*, as the lexer would think it is the start of a comment
565 // and emit an error that it is unterminated.
566 if (Tok.getKind() == tok::slash && RHS.getKind() == tok::star) {
567 isInvalid = true;
Chris Lattner510ab612006-07-20 04:47:30 +0000568 } else if (Tok.getKind() == tok::identifier &&
Chris Lattner08ba4c02006-07-20 04:52:59 +0000569 RHS.getKind() == tok::identifier) {
Chris Lattner510ab612006-07-20 04:47:30 +0000570 // Common paste case: identifier+identifier = identifier. Avoid creating
571 // a lexer and other overhead.
572 PP.IncrementPasteCounter(true);
Chris Lattner8c204872006-10-14 05:19:21 +0000573 Result.startToken();
574 Result.setKind(tok::identifier);
575 Result.setLocation(ResultTokLoc);
576 Result.setLength(LHSLen+RHSLen);
Chris Lattnera7e2e742006-07-19 06:32:35 +0000577 } else {
Chris Lattner510ab612006-07-20 04:47:30 +0000578 PP.IncrementPasteCounter(false);
579
Chris Lattnera7e2e742006-07-19 06:32:35 +0000580 // Make a lexer to lex this string from.
581 SourceManager &SourceMgr = PP.getSourceManager();
582 const char *ResultStrData = SourceMgr.getCharacterData(ResultTokLoc);
583
584 unsigned FileID = ResultTokLoc.getFileID();
585 assert(FileID && "Could not get FileID for paste?");
586
587 // Make a lexer object so that we lex and expand the paste result.
588 Lexer *TL = new Lexer(SourceMgr.getBuffer(FileID), FileID, PP,
589 ResultStrData,
590 ResultStrData+LHSLen+RHSLen /*don't include null*/);
591
592 // Lex a token in raw mode. This way it won't look up identifiers
593 // automatically, lexing off the end will return an eof token, and
594 // warnings are disabled. This returns true if the result token is the
595 // entire buffer.
596 bool IsComplete = TL->LexRawToken(Result);
597
598 // If we got an EOF token, we didn't form even ONE token. For example, we
599 // did "/ ## /" to get "//".
600 IsComplete &= Result.getKind() != tok::eof;
601 isInvalid = !IsComplete;
602
603 // We're now done with the temporary lexer.
604 delete TL;
605 }
Chris Lattner01ecf832006-07-19 05:42:48 +0000606
607 // If pasting the two tokens didn't form a full new token, this is an error.
Chris Lattnera7e2e742006-07-19 06:32:35 +0000608 // This occurs with "x ## +" and other stuff. Return with Tok unmodified
609 // and with RHS as the next token to lex.
610 if (isInvalid) {
Chris Lattner01ecf832006-07-19 05:42:48 +0000611 // If not in assembler language mode.
612 PP.Diag(PasteOpLoc, diag::err_pp_bad_paste,
Chris Lattner57dd8362006-11-03 07:45:04 +0000613 std::string(Buffer.begin(), Buffer.end()-1));
Chris Lattner01ecf832006-07-19 05:42:48 +0000614 return;
615 }
616
617 // Turn ## into 'other' to avoid # ## # from looking like a paste operator.
618 if (Result.getKind() == tok::hashhash)
Chris Lattner8c204872006-10-14 05:19:21 +0000619 Result.setKind(tok::unknown);
Chris Lattner01ecf832006-07-19 05:42:48 +0000620 // FIXME: Turn __VARRGS__ into "not a token"?
621
622 // Transfer properties of the LHS over the the Result.
Chris Lattner8c204872006-10-14 05:19:21 +0000623 Result.setFlagValue(LexerToken::StartOfLine , Tok.isAtStartOfLine());
624 Result.setFlagValue(LexerToken::LeadingSpace, Tok.hasLeadingSpace());
Chris Lattner01ecf832006-07-19 05:42:48 +0000625
626 // Finally, replace LHS with the result, consume the RHS, and iterate.
627 ++CurToken;
628 Tok = Result;
Chris Lattner70216572006-07-26 03:50:40 +0000629 } while (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash);
Chris Lattner0f1f5052006-07-20 04:16:23 +0000630
631 // Now that we got the result token, it will be subject to expansion. Since
632 // token pasting re-lexes the result token in raw mode, identifier information
633 // isn't looked up. As such, if the result is an identifier, look up id info.
634 if (Tok.getKind() == tok::identifier) {
635 // Look up the identifier info for the token. We disabled identifier lookup
636 // by saying we're skipping contents, so we need to do this manually.
Chris Lattner8c204872006-10-14 05:19:21 +0000637 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
Chris Lattner0f1f5052006-07-20 04:16:23 +0000638 }
Chris Lattner01ecf832006-07-19 05:42:48 +0000639}
640
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000641/// isNextTokenLParen - If the next token lexed will pop this macro off the
642/// expansion stack, return 2. If the next unexpanded token is a '(', return
643/// 1, otherwise return 0.
644unsigned MacroExpander::isNextTokenLParen() const {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000645 // Out of tokens?
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000646 if (isAtEnd())
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000647 return 2;
Chris Lattner70216572006-07-26 03:50:40 +0000648 return MacroTokens[CurToken].getKind() == tok::l_paren;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000649}