blob: cd802ee4e8ae6b8970a03a9651423ea4eb30bfc9 [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 Lattner01ecf832006-07-19 05:42:48 +000019#include "llvm/Config/Alloca.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000020using namespace llvm;
21using namespace clang;
22
Chris Lattner78186052006-07-09 00:45:31 +000023//===----------------------------------------------------------------------===//
Chris Lattneree8760b2006-07-15 07:42:55 +000024// MacroArgs Implementation
Chris Lattner78186052006-07-09 00:45:31 +000025//===----------------------------------------------------------------------===//
26
Chris Lattner36b6e812006-07-21 06:38:30 +000027MacroArgs::MacroArgs(const MacroInfo *MI, std::vector<LexerToken> &UnexpArgs) {
Chris Lattner78186052006-07-09 00:45:31 +000028 assert(MI->isFunctionLike() &&
Chris Lattneree8760b2006-07-15 07:42:55 +000029 "Can't have args for an object-like macro!");
Chris Lattner36b6e812006-07-21 06:38:30 +000030 UnexpArgTokens.swap(UnexpArgs);
Chris Lattner78186052006-07-09 00:45:31 +000031}
32
Chris Lattner6fc08bc2006-07-26 04:55:32 +000033/// getArgLength - Given a pointer to an expanded or unexpanded argument,
34/// return the number of tokens, not counting the EOF, that make up the
35/// argument.
36unsigned MacroArgs::getArgLength(const LexerToken *ArgPtr) {
37 unsigned NumArgTokens = 0;
38 for (; ArgPtr->getKind() != tok::eof; ++ArgPtr)
39 ++NumArgTokens;
40 return NumArgTokens;
41}
42
43
Chris Lattner36b6e812006-07-21 06:38:30 +000044/// getUnexpArgument - Return the unexpanded tokens for the specified formal.
45///
46const LexerToken *MacroArgs::getUnexpArgument(unsigned Arg) const {
47 // Scan to find Arg.
48 const LexerToken *Start = &UnexpArgTokens[0];
49 const LexerToken *Result = Start;
50 for (; Arg; ++Result) {
51 assert(Result < Start+UnexpArgTokens.size() && "Invalid arg #");
52 if (Result->getKind() == tok::eof)
53 --Arg;
54 }
55 return Result;
Chris Lattneree8760b2006-07-15 07:42:55 +000056}
57
Chris Lattner36b6e812006-07-21 06:38:30 +000058
Chris Lattner203b4562006-07-15 21:07:40 +000059/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
60/// by pre-expansion, return false. Otherwise, conservatively return true.
Chris Lattner36b6e812006-07-21 06:38:30 +000061bool MacroArgs::ArgNeedsPreexpansion(const LexerToken *ArgTok) const {
Chris Lattner203b4562006-07-15 21:07:40 +000062 // If there are no identifiers in the argument list, or if the identifiers are
63 // known to not be macros, pre-expansion won't modify it.
Chris Lattner36b6e812006-07-21 06:38:30 +000064 for (; ArgTok->getKind() != tok::eof; ++ArgTok)
65 if (IdentifierInfo *II = ArgTok->getIdentifierInfo()) {
Chris Lattner203b4562006-07-15 21:07:40 +000066 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled())
67 // Return true even though the macro could be a function-like macro
68 // without a following '(' token.
69 return true;
70 }
71 return false;
72}
73
Chris Lattner7667d0d2006-07-16 18:16:58 +000074/// getPreExpArgument - Return the pre-expanded form of the specified
75/// argument.
76const std::vector<LexerToken> &
77MacroArgs::getPreExpArgument(unsigned Arg, Preprocessor &PP) {
78 assert(Arg < UnexpArgTokens.size() && "Invalid argument number!");
79
80 // If we have already computed this, return it.
81 if (PreExpArgTokens.empty())
82 PreExpArgTokens.resize(UnexpArgTokens.size());
83
84 std::vector<LexerToken> &Result = PreExpArgTokens[Arg];
85 if (!Result.empty()) return Result;
86
Chris Lattner36b6e812006-07-21 06:38:30 +000087 const LexerToken *AT = getUnexpArgument(Arg);
Chris Lattner6fc08bc2006-07-26 04:55:32 +000088 unsigned NumToks = getArgLength(AT)+1; // Include the EOF.
Chris Lattner36b6e812006-07-21 06:38:30 +000089
Chris Lattner7667d0d2006-07-16 18:16:58 +000090 // Otherwise, we have to pre-expand this argument, populating Result. To do
91 // this, we set up a fake MacroExpander to lex from the unexpanded argument
92 // list. With this installed, we lex expanded tokens until we hit the EOF
93 // token at the end of the unexp list.
Chris Lattner70216572006-07-26 03:50:40 +000094 PP.EnterTokenStream(AT, NumToks);
Chris Lattner7667d0d2006-07-16 18:16:58 +000095
96 // Lex all of the macro-expanded tokens into Result.
97 do {
98 Result.push_back(LexerToken());
99 PP.Lex(Result.back());
100 } while (Result.back().getKind() != tok::eof);
101
102 // Pop the token stream off the top of the stack. We know that the internal
103 // pointer inside of it is to the "end" of the token stream, but the stack
104 // will not otherwise be popped until the next token is lexed. The problem is
105 // that the token may be lexed sometime after the vector of tokens itself is
106 // destroyed, which would be badness.
107 PP.RemoveTopOfLexerStack();
108 return Result;
109}
110
Chris Lattneree8760b2006-07-15 07:42:55 +0000111
Chris Lattner0707bd32006-07-15 05:23:58 +0000112/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
113/// tokens into the literal string token that should be produced by the C #
114/// preprocessor operator.
115///
Chris Lattner36b6e812006-07-21 06:38:30 +0000116static LexerToken StringifyArgument(const LexerToken *ArgToks,
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000117 Preprocessor &PP, bool Charify = false) {
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000118 LexerToken Tok;
119 Tok.StartToken();
120 Tok.SetKind(tok::string_literal);
Chris Lattner0707bd32006-07-15 05:23:58 +0000121
Chris Lattner36b6e812006-07-21 06:38:30 +0000122 const LexerToken *ArgTokStart = ArgToks;
123
Chris Lattner0707bd32006-07-15 05:23:58 +0000124 // Stringify all the tokens.
125 std::string Result = "\"";
Chris Lattner7667d0d2006-07-16 18:16:58 +0000126 // FIXME: Optimize this loop to not use std::strings.
Chris Lattner36b6e812006-07-21 06:38:30 +0000127 bool isFirst = true;
128 for (; ArgToks->getKind() != tok::eof; ++ArgToks) {
129 const LexerToken &Tok = *ArgToks;
130 if (!isFirst && Tok.hasLeadingSpace())
Chris Lattner0707bd32006-07-15 05:23:58 +0000131 Result += ' ';
Chris Lattner36b6e812006-07-21 06:38:30 +0000132 isFirst = false;
Chris Lattner0707bd32006-07-15 05:23:58 +0000133
134 // If this is a string or character constant, escape the token as specified
135 // by 6.10.3.2p2.
136 if (Tok.getKind() == tok::string_literal || // "foo" and L"foo".
137 Tok.getKind() == tok::char_constant) { // 'x' and L'x'.
138 Result += Lexer::Stringify(PP.getSpelling(Tok));
139 } else {
140 // Otherwise, just append the token.
141 Result += PP.getSpelling(Tok);
142 }
143 }
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000144
Chris Lattner0707bd32006-07-15 05:23:58 +0000145 // If the last character of the string is a \, and if it isn't escaped, this
146 // is an invalid string literal, diagnose it as specified in C99.
147 if (Result[Result.size()-1] == '\\') {
148 // Count the number of consequtive \ characters. If even, then they are
149 // just escaped backslashes, otherwise it's an error.
150 unsigned FirstNonSlash = Result.size()-2;
151 // Guaranteed to find the starting " if nothing else.
152 while (Result[FirstNonSlash] == '\\')
153 --FirstNonSlash;
154 if ((Result.size()-1-FirstNonSlash) & 1) {
Chris Lattnerf2781502006-07-15 05:27:44 +0000155 // Diagnose errors for things like: #define F(X) #X / F(\)
Chris Lattner36b6e812006-07-21 06:38:30 +0000156 PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
Chris Lattner0707bd32006-07-15 05:23:58 +0000157 Result.erase(Result.end()-1); // remove one of the \'s.
158 }
159 }
Chris Lattner0707bd32006-07-15 05:23:58 +0000160 Result += '"';
161
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000162 // If this is the charify operation and the result is not a legal character
163 // constant, diagnose it.
164 if (Charify) {
165 // First step, turn double quotes into single quotes:
166 Result[0] = '\'';
167 Result[Result.size()-1] = '\'';
168
169 // Check for bogus character.
170 bool isBad = false;
Chris Lattner2ada5d32006-07-15 07:51:24 +0000171 if (Result.size() == 3) {
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000172 isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
173 } else {
174 isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
175 }
176
177 if (isBad) {
Chris Lattner36b6e812006-07-21 06:38:30 +0000178 PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
Chris Lattner7c581492006-07-15 07:56:31 +0000179 Result = "' '"; // Use something arbitrary, but legal.
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000180 }
181 }
182
Chris Lattner0707bd32006-07-15 05:23:58 +0000183 Tok.SetLength(Result.size());
184 Tok.SetLocation(PP.CreateString(&Result[0], Result.size()));
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000185 return Tok;
186}
187
188/// getStringifiedArgument - Compute, cache, and return the specified argument
189/// that has been 'stringified' as required by the # operator.
Chris Lattneree8760b2006-07-15 07:42:55 +0000190const LexerToken &MacroArgs::getStringifiedArgument(unsigned ArgNo,
191 Preprocessor &PP) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000192 assert(ArgNo < UnexpArgTokens.size() && "Invalid argument number!");
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000193 if (StringifiedArgs.empty()) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000194 StringifiedArgs.resize(getNumArguments());
Chris Lattneree8760b2006-07-15 07:42:55 +0000195 memset(&StringifiedArgs[0], 0,
196 sizeof(StringifiedArgs[0])*getNumArguments());
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000197 }
198 if (StringifiedArgs[ArgNo].getKind() != tok::string_literal)
Chris Lattner36b6e812006-07-21 06:38:30 +0000199 StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000200 return StringifiedArgs[ArgNo];
201}
202
Chris Lattner78186052006-07-09 00:45:31 +0000203//===----------------------------------------------------------------------===//
204// MacroExpander Implementation
205//===----------------------------------------------------------------------===//
206
Chris Lattner7667d0d2006-07-16 18:16:58 +0000207/// Create a macro expander for the specified macro with the specified actual
208/// arguments. Note that this ctor takes ownership of the ActualArgs pointer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000209MacroExpander::MacroExpander(LexerToken &Tok, MacroArgs *Actuals,
Chris Lattner78186052006-07-09 00:45:31 +0000210 Preprocessor &pp)
Chris Lattner7667d0d2006-07-16 18:16:58 +0000211 : Macro(Tok.getIdentifierInfo()->getMacroInfo()),
Chris Lattneree8760b2006-07-15 07:42:55 +0000212 ActualArgs(Actuals), PP(pp), CurToken(0),
Chris Lattner50b497e2006-06-18 16:32:35 +0000213 InstantiateLoc(Tok.getLocation()),
Chris Lattnerd01e2912006-06-18 16:22:51 +0000214 AtStartOfLine(Tok.isAtStartOfLine()),
215 HasLeadingSpace(Tok.hasLeadingSpace()) {
Chris Lattner70216572006-07-26 03:50:40 +0000216 MacroTokens = &Macro->getReplacementTokens()[0];
217 NumMacroTokens = Macro->getReplacementTokens().size();
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000218
219 // If this is a function-like macro, expand the arguments and change
220 // MacroTokens to point to the expanded tokens.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000221 if (Macro->isFunctionLike() && Macro->getNumArgs())
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000222 ExpandFunctionArguments();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000223
224 // Mark the macro as currently disabled, so that it is not recursively
225 // expanded. The macro must be disabled only after argument pre-expansion of
226 // function-like macro arguments occurs.
227 Macro->DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000228}
229
Chris Lattner7667d0d2006-07-16 18:16:58 +0000230/// Create a macro expander for the specified token stream. This does not
231/// take ownership of the specified token vector.
Chris Lattner70216572006-07-26 03:50:40 +0000232MacroExpander::MacroExpander(const LexerToken *TokArray, unsigned NumToks,
Chris Lattner7667d0d2006-07-16 18:16:58 +0000233 Preprocessor &pp)
Chris Lattner70216572006-07-26 03:50:40 +0000234 : Macro(0), ActualArgs(0), PP(pp), MacroTokens(TokArray),
235 NumMacroTokens(NumToks), CurToken(0),
Chris Lattner7667d0d2006-07-16 18:16:58 +0000236 InstantiateLoc(SourceLocation()), AtStartOfLine(false),
237 HasLeadingSpace(false) {
238
239 // Set HasLeadingSpace/AtStartOfLine so that the first token will be
240 // returned unmodified.
Chris Lattner70216572006-07-26 03:50:40 +0000241 if (NumToks != 0) {
242 AtStartOfLine = TokArray[0].isAtStartOfLine();
243 HasLeadingSpace = TokArray[0].hasLeadingSpace();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000244 }
245}
246
247
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000248MacroExpander::~MacroExpander() {
249 // If this was a function-like macro that actually uses its arguments, delete
250 // the expanded tokens.
Chris Lattner70216572006-07-26 03:50:40 +0000251 if (Macro && MacroTokens != &Macro->getReplacementTokens()[0])
252 delete [] MacroTokens;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000253
254 // MacroExpander owns its formal arguments.
Chris Lattneree8760b2006-07-15 07:42:55 +0000255 delete ActualArgs;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000256}
257
258/// Expand the arguments of a function-like macro so that we can quickly
259/// return preexpanded tokens from MacroTokens.
260void MacroExpander::ExpandFunctionArguments() {
261 std::vector<LexerToken> ResultToks;
262
263 // Loop through the MacroTokens tokens, expanding them into ResultToks. Keep
264 // track of whether we change anything. If not, no need to keep them. If so,
265 // we install the newly expanded sequence as MacroTokens.
266 bool MadeChange = false;
Chris Lattner70216572006-07-26 03:50:40 +0000267 for (unsigned i = 0, e = NumMacroTokens; i != e; ++i) {
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000268 // If we found the stringify operator, get the argument stringified. The
269 // preprocessor already verified that the following token is a macro name
270 // when the #define was parsed.
Chris Lattner70216572006-07-26 03:50:40 +0000271 const LexerToken &CurTok = MacroTokens[i];
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000272 if (CurTok.getKind() == tok::hash || CurTok.getKind() == tok::hashat) {
Chris Lattner70216572006-07-26 03:50:40 +0000273 int ArgNo = Macro->getArgumentNum(MacroTokens[i+1].getIdentifierInfo());
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000274 assert(ArgNo != -1 && "Token following # is not an argument?");
275
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000276 LexerToken Res;
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000277 if (CurTok.getKind() == tok::hash) // Stringify
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000278 Res = ActualArgs->getStringifiedArgument(ArgNo, PP);
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000279 else {
280 // 'charify': don't bother caching these.
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000281 Res = StringifyArgument(ActualArgs->getUnexpArgument(ArgNo), PP, true);
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000282 }
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000283
Chris Lattner60161692006-07-15 06:48:02 +0000284 // The stringified/charified string leading space flag gets set to match
285 // the #/#@ operator.
286 if (CurTok.hasLeadingSpace())
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000287 Res.SetFlag(LexerToken::LeadingSpace);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000288
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000289 ResultToks.push_back(Res);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000290 MadeChange = true;
291 ++i; // Skip arg name.
292 } else {
Chris Lattner203b4562006-07-15 21:07:40 +0000293 // Otherwise, if this is not an argument token, just add the token to the
294 // output buffer.
295 IdentifierInfo *II = CurTok.getIdentifierInfo();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000296 int ArgNo = II ? Macro->getArgumentNum(II) : -1;
Chris Lattner203b4562006-07-15 21:07:40 +0000297 if (ArgNo == -1) {
298 ResultToks.push_back(CurTok);
299 continue;
300 }
301
302 // An argument is expanded somehow, the result is different than the
303 // input.
304 MadeChange = true;
305
306 // Otherwise, this is a use of the argument. Find out if there is a paste
307 // (##) operator before or after the argument.
308 bool PasteBefore =
309 !ResultToks.empty() && ResultToks.back().getKind() == tok::hashhash;
310 bool PasteAfter =
Chris Lattner70216572006-07-26 03:50:40 +0000311 i+1 != e && MacroTokens[i+1].getKind() == tok::hashhash;
Chris Lattner203b4562006-07-15 21:07:40 +0000312
313 // If it is not the LHS/RHS of a ## operator, we must pre-expand the
314 // argument and substitute the expanded tokens into the result. This is
315 // C99 6.10.3.1p1.
316 if (!PasteBefore && !PasteAfter) {
Chris Lattner36b6e812006-07-21 06:38:30 +0000317 const LexerToken *ResultArgToks;
318
Chris Lattner203b4562006-07-15 21:07:40 +0000319 // Only preexpand the argument if it could possibly need it. This
320 // avoids some work in common cases.
Chris Lattner36b6e812006-07-21 06:38:30 +0000321 const LexerToken *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
322 if (ActualArgs->ArgNeedsPreexpansion(ArgTok))
323 ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0];
Chris Lattner7667d0d2006-07-16 18:16:58 +0000324 else
Chris Lattner36b6e812006-07-21 06:38:30 +0000325 ResultArgToks = ArgTok; // Use non-preexpanded tokens.
Chris Lattner203b4562006-07-15 21:07:40 +0000326
Chris Lattner36b6e812006-07-21 06:38:30 +0000327 if (ResultArgToks->getKind() != tok::eof) {
328 unsigned FirstResult = ResultToks.size();
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000329 unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
330 ResultToks.insert(ResultToks.end(), ResultArgToks,
331 ResultArgToks+NumToks);
Chris Lattner203b4562006-07-15 21:07:40 +0000332
Chris Lattner36b6e812006-07-21 06:38:30 +0000333 // If any tokens were substituted from the argument, the whitespace
334 // before the first token should match the whitespace of the arg
335 // identifier.
336 ResultToks[FirstResult].SetFlagValue(LexerToken::LeadingSpace,
337 CurTok.hasLeadingSpace());
338 }
Chris Lattner203b4562006-07-15 21:07:40 +0000339 continue;
340 }
341
Chris Lattner7e2e6692006-07-19 03:51:26 +0000342 // Okay, we have a token that is either the LHS or RHS of a paste (##)
343 // argument. It gets substituted as its non-pre-expanded tokens.
Chris Lattner36b6e812006-07-21 06:38:30 +0000344 const LexerToken *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
Chris Lattner7e2e6692006-07-19 03:51:26 +0000345
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000346 unsigned NumToks = MacroArgs::getArgLength(ArgToks);
347 if (NumToks) { // Not an empty argument?
348 ResultToks.insert(ResultToks.end(), ArgToks, ArgToks+NumToks);
Chris Lattner7e2e6692006-07-19 03:51:26 +0000349 continue;
350 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000351
Chris Lattner7e2e6692006-07-19 03:51:26 +0000352 // FIXME: Handle comma swallowing GNU extension.
353 // FIXME: Handle 'placemarker' stuff.
354 assert(0 && "FIXME: handle empty arguments!");
355 //ResultToks.push_back(CurTok);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000356 }
357 }
358
359 // If anything changed, install this as the new MacroTokens list.
360 if (MadeChange) {
361 // This is deleted in the dtor.
Chris Lattner70216572006-07-26 03:50:40 +0000362 NumMacroTokens = ResultToks.size();
363 LexerToken *Res = new LexerToken[ResultToks.size()];
364 memcpy(Res, &ResultToks[0], NumMacroTokens*sizeof(LexerToken));
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000365 MacroTokens = Res;
366 }
367}
Chris Lattner67b07cb2006-06-26 02:03:42 +0000368
Chris Lattner22eb9722006-06-18 05:43:12 +0000369/// Lex - Lex and return a token from this macro stream.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000370///
Chris Lattnercb283342006-06-18 06:48:37 +0000371void MacroExpander::Lex(LexerToken &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000372 // Lexing off the end of the macro, pop this macro off the expansion stack.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000373 if (isAtEnd()) {
374 // If this is a macro (not a token stream), mark the macro enabled now
375 // that it is no longer being expanded.
376 if (Macro) Macro->EnableMacro();
377
378 // Pop this context off the preprocessors lexer stack and get the next
Chris Lattner2183a6e2006-07-18 06:36:12 +0000379 // token. This will delete "this" so remember the PP instance var.
380 Preprocessor &PPCache = PP;
381 if (PP.HandleEndOfMacro(Tok))
382 return;
383
384 // HandleEndOfMacro may not return a token. If it doesn't, lex whatever is
385 // next.
386 return PPCache.Lex(Tok);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000387 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000388
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000389 // If this is the first token of the expanded result, we inherit spacing
390 // properties later.
391 bool isFirstToken = CurToken == 0;
392
Chris Lattner22eb9722006-06-18 05:43:12 +0000393 // Get the next token to return.
Chris Lattner70216572006-07-26 03:50:40 +0000394 Tok = MacroTokens[CurToken++];
Chris Lattner01ecf832006-07-19 05:42:48 +0000395
396 // If this token is followed by a token paste (##) operator, paste the tokens!
Chris Lattner70216572006-07-26 03:50:40 +0000397 if (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash)
Chris Lattner01ecf832006-07-19 05:42:48 +0000398 PasteTokens(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000399
Chris Lattnerc673f902006-06-30 06:10:41 +0000400 // The token's current location indicate where the token was lexed from. We
401 // need this information to compute the spelling of the token, but any
402 // diagnostics for the expanded token should appear as if they came from
403 // InstantiationLoc. Pull this information together into a new SourceLocation
404 // that captures all of this.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000405 if (InstantiateLoc.isValid()) { // Don't do this for token streams.
406 SourceManager &SrcMgr = PP.getSourceManager();
407 // The token could have come from a prior macro expansion. In that case,
408 // ignore the macro expand part to get to the physloc. This happens for
409 // stuff like: #define A(X) X A(A(X)) A(1)
410 SourceLocation PhysLoc = SrcMgr.getPhysicalLoc(Tok.getLocation());
411 Tok.SetLocation(SrcMgr.getInstantiationLoc(PhysLoc, InstantiateLoc));
412 }
413
Chris Lattner22eb9722006-06-18 05:43:12 +0000414 // If this is the first token, set the lexical properties of the token to
415 // match the lexical properties of the macro identifier.
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000416 if (isFirstToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000417 Tok.SetFlagValue(LexerToken::StartOfLine , AtStartOfLine);
418 Tok.SetFlagValue(LexerToken::LeadingSpace, HasLeadingSpace);
419 }
420
421 // Handle recursive expansion!
422 if (Tok.getIdentifierInfo())
423 return PP.HandleIdentifier(Tok);
424
425 // Otherwise, return a normal token.
Chris Lattner22eb9722006-06-18 05:43:12 +0000426}
Chris Lattnerafe603f2006-07-11 04:02:46 +0000427
Chris Lattner01ecf832006-07-19 05:42:48 +0000428/// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ##
429/// operator. Read the ## and RHS, and paste the LHS/RHS together. If there
430/// are is another ## after it, chomp it iteratively. Return the result as Tok.
431void MacroExpander::PasteTokens(LexerToken &Tok) {
432 do {
433 // Consume the ## operator.
Chris Lattner70216572006-07-26 03:50:40 +0000434 SourceLocation PasteOpLoc = MacroTokens[CurToken].getLocation();
Chris Lattner01ecf832006-07-19 05:42:48 +0000435 ++CurToken;
436 assert(!isAtEnd() && "No token on the RHS of a paste operator!");
437
438 // Get the RHS token.
Chris Lattner70216572006-07-26 03:50:40 +0000439 const LexerToken &RHS = MacroTokens[CurToken];
Chris Lattner01ecf832006-07-19 05:42:48 +0000440
441 bool isInvalid = false;
442
Chris Lattner01ecf832006-07-19 05:42:48 +0000443 // Allocate space for the result token. This is guaranteed to be enough for
444 // the two tokens and a null terminator.
445 char *Buffer = (char*)alloca(Tok.getLength() + RHS.getLength() + 1);
446
447 // Get the spelling of the LHS token in Buffer.
448 const char *BufPtr = Buffer;
449 unsigned LHSLen = PP.getSpelling(Tok, BufPtr);
450 if (BufPtr != Buffer) // Really, we want the chars in Buffer!
451 memcpy(Buffer, BufPtr, LHSLen);
452
453 BufPtr = Buffer+LHSLen;
454 unsigned RHSLen = PP.getSpelling(RHS, BufPtr);
455 if (BufPtr != Buffer+LHSLen) // Really, we want the chars in Buffer!
456 memcpy(Buffer+LHSLen, BufPtr, RHSLen);
457
458 // Add null terminator.
459 Buffer[LHSLen+RHSLen] = '\0';
460
461 // Plop the pasted result (including the trailing newline and null) into a
462 // scratch buffer where we can lex it.
463 SourceLocation ResultTokLoc = PP.CreateString(Buffer, LHSLen+RHSLen+1);
464
465 // Lex the resultant pasted token into Result.
466 LexerToken Result;
467
Chris Lattnera7e2e742006-07-19 06:32:35 +0000468 // Avoid testing /*, as the lexer would think it is the start of a comment
469 // and emit an error that it is unterminated.
470 if (Tok.getKind() == tok::slash && RHS.getKind() == tok::star) {
471 isInvalid = true;
Chris Lattner510ab612006-07-20 04:47:30 +0000472 } else if (Tok.getKind() == tok::identifier &&
Chris Lattner08ba4c02006-07-20 04:52:59 +0000473 RHS.getKind() == tok::identifier) {
Chris Lattner510ab612006-07-20 04:47:30 +0000474 // Common paste case: identifier+identifier = identifier. Avoid creating
475 // a lexer and other overhead.
476 PP.IncrementPasteCounter(true);
477 Result.StartToken();
478 Result.SetKind(tok::identifier);
479 Result.SetLocation(ResultTokLoc);
480 Result.SetLength(LHSLen+RHSLen);
Chris Lattnera7e2e742006-07-19 06:32:35 +0000481 } else {
Chris Lattner510ab612006-07-20 04:47:30 +0000482 PP.IncrementPasteCounter(false);
483
Chris Lattnera7e2e742006-07-19 06:32:35 +0000484 // Make a lexer to lex this string from.
485 SourceManager &SourceMgr = PP.getSourceManager();
486 const char *ResultStrData = SourceMgr.getCharacterData(ResultTokLoc);
487
488 unsigned FileID = ResultTokLoc.getFileID();
489 assert(FileID && "Could not get FileID for paste?");
490
491 // Make a lexer object so that we lex and expand the paste result.
492 Lexer *TL = new Lexer(SourceMgr.getBuffer(FileID), FileID, PP,
493 ResultStrData,
494 ResultStrData+LHSLen+RHSLen /*don't include null*/);
495
496 // Lex a token in raw mode. This way it won't look up identifiers
497 // automatically, lexing off the end will return an eof token, and
498 // warnings are disabled. This returns true if the result token is the
499 // entire buffer.
500 bool IsComplete = TL->LexRawToken(Result);
501
502 // If we got an EOF token, we didn't form even ONE token. For example, we
503 // did "/ ## /" to get "//".
504 IsComplete &= Result.getKind() != tok::eof;
505 isInvalid = !IsComplete;
506
507 // We're now done with the temporary lexer.
508 delete TL;
509 }
Chris Lattner01ecf832006-07-19 05:42:48 +0000510
511 // If pasting the two tokens didn't form a full new token, this is an error.
Chris Lattnera7e2e742006-07-19 06:32:35 +0000512 // This occurs with "x ## +" and other stuff. Return with Tok unmodified
513 // and with RHS as the next token to lex.
514 if (isInvalid) {
Chris Lattner01ecf832006-07-19 05:42:48 +0000515 // If not in assembler language mode.
516 PP.Diag(PasteOpLoc, diag::err_pp_bad_paste,
517 std::string(Buffer, Buffer+LHSLen+RHSLen));
518 return;
519 }
520
521 // Turn ## into 'other' to avoid # ## # from looking like a paste operator.
522 if (Result.getKind() == tok::hashhash)
523 Result.SetKind(tok::unknown);
524 // FIXME: Turn __VARRGS__ into "not a token"?
525
526 // Transfer properties of the LHS over the the Result.
527 Result.SetFlagValue(LexerToken::StartOfLine , Tok.isAtStartOfLine());
528 Result.SetFlagValue(LexerToken::LeadingSpace, Tok.hasLeadingSpace());
529
530 // Finally, replace LHS with the result, consume the RHS, and iterate.
531 ++CurToken;
532 Tok = Result;
Chris Lattner70216572006-07-26 03:50:40 +0000533 } while (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash);
Chris Lattner0f1f5052006-07-20 04:16:23 +0000534
535 // Now that we got the result token, it will be subject to expansion. Since
536 // token pasting re-lexes the result token in raw mode, identifier information
537 // isn't looked up. As such, if the result is an identifier, look up id info.
538 if (Tok.getKind() == tok::identifier) {
539 // Look up the identifier info for the token. We disabled identifier lookup
540 // by saying we're skipping contents, so we need to do this manually.
541 Tok.SetIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
542 }
Chris Lattner01ecf832006-07-19 05:42:48 +0000543}
544
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000545/// isNextTokenLParen - If the next token lexed will pop this macro off the
546/// expansion stack, return 2. If the next unexpanded token is a '(', return
547/// 1, otherwise return 0.
548unsigned MacroExpander::isNextTokenLParen() const {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000549 // Out of tokens?
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000550 if (isAtEnd())
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000551 return 2;
Chris Lattner70216572006-07-26 03:50:40 +0000552 return MacroTokens[CurToken].getKind() == tok::l_paren;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000553}