blob: 38970eca51026eee2ad9a88d91740c9320ddb65a [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 Lattneree8760b2006-07-15 07:42:55 +000027MacroArgs::MacroArgs(const MacroInfo *MI) {
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 Lattner78186052006-07-09 00:45:31 +000030 // Reserve space for arguments to avoid reallocation.
31 unsigned NumArgs = MI->getNumArgs();
32 if (MI->isC99Varargs() || MI->isGNUVarargs())
33 NumArgs += 3; // Varargs can have more than this, just some guess.
34
Chris Lattneree8760b2006-07-15 07:42:55 +000035 UnexpArgTokens.reserve(NumArgs);
Chris Lattner78186052006-07-09 00:45:31 +000036}
37
Chris Lattneree8760b2006-07-15 07:42:55 +000038/// addArgument - Add an argument for this invocation. This method destroys
39/// the vector passed in to avoid extraneous memory copies. This adds the EOF
40/// token to the end of the argument list as a marker. 'Loc' specifies a
41/// location at the end of the argument, e.g. the ',' token or the ')'.
42void MacroArgs::addArgument(std::vector<LexerToken> &ArgToks,
43 SourceLocation Loc) {
44 UnexpArgTokens.push_back(std::vector<LexerToken>());
45 UnexpArgTokens.back().swap(ArgToks);
46
47 // Add a marker EOF token to the end of the argument list, useful for handling
48 // empty arguments and macro pre-expansion.
49 LexerToken EOFTok;
50 EOFTok.StartToken();
51 EOFTok.SetKind(tok::eof);
52 EOFTok.SetLocation(Loc);
Chris Lattner203b4562006-07-15 21:07:40 +000053 EOFTok.SetLength(0);
Chris Lattneree8760b2006-07-15 07:42:55 +000054 UnexpArgTokens.back().push_back(EOFTok);
55}
56
Chris Lattner203b4562006-07-15 21:07:40 +000057/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
58/// by pre-expansion, return false. Otherwise, conservatively return true.
59bool MacroArgs::ArgNeedsPreexpansion(unsigned ArgNo) const {
60 const std::vector<LexerToken> &ArgTokens = getUnexpArgument(ArgNo);
61
62 // 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.
64 for (unsigned i = 0, e = ArgTokens.size()-1; i != e; ++i)
65 if (IdentifierInfo *II = ArgTokens[i].getIdentifierInfo()) {
66 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
87 // Otherwise, we have to pre-expand this argument, populating Result. To do
88 // this, we set up a fake MacroExpander to lex from the unexpanded argument
89 // list. With this installed, we lex expanded tokens until we hit the EOF
90 // token at the end of the unexp list.
91 PP.EnterTokenStream(UnexpArgTokens[Arg]);
92
93 // Lex all of the macro-expanded tokens into Result.
94 do {
95 Result.push_back(LexerToken());
96 PP.Lex(Result.back());
97 } while (Result.back().getKind() != tok::eof);
98
99 // Pop the token stream off the top of the stack. We know that the internal
100 // pointer inside of it is to the "end" of the token stream, but the stack
101 // will not otherwise be popped until the next token is lexed. The problem is
102 // that the token may be lexed sometime after the vector of tokens itself is
103 // destroyed, which would be badness.
104 PP.RemoveTopOfLexerStack();
105 return Result;
106}
107
Chris Lattneree8760b2006-07-15 07:42:55 +0000108
Chris Lattner0707bd32006-07-15 05:23:58 +0000109/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
110/// tokens into the literal string token that should be produced by the C #
111/// preprocessor operator.
112///
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000113static LexerToken StringifyArgument(const std::vector<LexerToken> &Toks,
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000114 Preprocessor &PP, bool Charify = false) {
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000115 LexerToken Tok;
116 Tok.StartToken();
117 Tok.SetKind(tok::string_literal);
Chris Lattner0707bd32006-07-15 05:23:58 +0000118
119 // Stringify all the tokens.
120 std::string Result = "\"";
Chris Lattner7667d0d2006-07-16 18:16:58 +0000121 // FIXME: Optimize this loop to not use std::strings.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000122 for (unsigned i = 0, e = Toks.size()-1 /*no eof*/; i != e; ++i) {
Chris Lattner0707bd32006-07-15 05:23:58 +0000123 const LexerToken &Tok = Toks[i];
Chris Lattner0707bd32006-07-15 05:23:58 +0000124 if (i != 0 && Tok.hasLeadingSpace())
125 Result += ' ';
126
127 // If this is a string or character constant, escape the token as specified
128 // by 6.10.3.2p2.
129 if (Tok.getKind() == tok::string_literal || // "foo" and L"foo".
130 Tok.getKind() == tok::char_constant) { // 'x' and L'x'.
131 Result += Lexer::Stringify(PP.getSpelling(Tok));
132 } else {
133 // Otherwise, just append the token.
134 Result += PP.getSpelling(Tok);
135 }
136 }
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000137
Chris Lattner0707bd32006-07-15 05:23:58 +0000138 // If the last character of the string is a \, and if it isn't escaped, this
139 // is an invalid string literal, diagnose it as specified in C99.
140 if (Result[Result.size()-1] == '\\') {
141 // Count the number of consequtive \ characters. If even, then they are
142 // just escaped backslashes, otherwise it's an error.
143 unsigned FirstNonSlash = Result.size()-2;
144 // Guaranteed to find the starting " if nothing else.
145 while (Result[FirstNonSlash] == '\\')
146 --FirstNonSlash;
147 if ((Result.size()-1-FirstNonSlash) & 1) {
Chris Lattnerf2781502006-07-15 05:27:44 +0000148 // Diagnose errors for things like: #define F(X) #X / F(\)
Chris Lattner0707bd32006-07-15 05:23:58 +0000149 PP.Diag(Toks.back(), diag::pp_invalid_string_literal);
150 Result.erase(Result.end()-1); // remove one of the \'s.
151 }
152 }
Chris Lattner0707bd32006-07-15 05:23:58 +0000153 Result += '"';
154
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000155 // If this is the charify operation and the result is not a legal character
156 // constant, diagnose it.
157 if (Charify) {
158 // First step, turn double quotes into single quotes:
159 Result[0] = '\'';
160 Result[Result.size()-1] = '\'';
161
162 // Check for bogus character.
163 bool isBad = false;
Chris Lattner2ada5d32006-07-15 07:51:24 +0000164 if (Result.size() == 3) {
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000165 isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
166 } else {
167 isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
168 }
169
170 if (isBad) {
Chris Lattner7c581492006-07-15 07:56:31 +0000171 assert(!Toks.empty() && "No eof token at least?");
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000172 PP.Diag(Toks[0], diag::err_invalid_character_to_charify);
Chris Lattner7c581492006-07-15 07:56:31 +0000173 Result = "' '"; // Use something arbitrary, but legal.
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000174 }
175 }
176
Chris Lattner0707bd32006-07-15 05:23:58 +0000177 Tok.SetLength(Result.size());
178 Tok.SetLocation(PP.CreateString(&Result[0], Result.size()));
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000179 return Tok;
180}
181
182/// getStringifiedArgument - Compute, cache, and return the specified argument
183/// that has been 'stringified' as required by the # operator.
Chris Lattneree8760b2006-07-15 07:42:55 +0000184const LexerToken &MacroArgs::getStringifiedArgument(unsigned ArgNo,
185 Preprocessor &PP) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000186 assert(ArgNo < UnexpArgTokens.size() && "Invalid argument number!");
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000187 if (StringifiedArgs.empty()) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000188 StringifiedArgs.resize(getNumArguments());
Chris Lattneree8760b2006-07-15 07:42:55 +0000189 memset(&StringifiedArgs[0], 0,
190 sizeof(StringifiedArgs[0])*getNumArguments());
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000191 }
192 if (StringifiedArgs[ArgNo].getKind() != tok::string_literal)
Chris Lattner2ada5d32006-07-15 07:51:24 +0000193 StringifiedArgs[ArgNo] = StringifyArgument(UnexpArgTokens[ArgNo], PP);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000194 return StringifiedArgs[ArgNo];
195}
196
Chris Lattner78186052006-07-09 00:45:31 +0000197//===----------------------------------------------------------------------===//
198// MacroExpander Implementation
199//===----------------------------------------------------------------------===//
200
Chris Lattner7667d0d2006-07-16 18:16:58 +0000201/// Create a macro expander for the specified macro with the specified actual
202/// arguments. Note that this ctor takes ownership of the ActualArgs pointer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000203MacroExpander::MacroExpander(LexerToken &Tok, MacroArgs *Actuals,
Chris Lattner78186052006-07-09 00:45:31 +0000204 Preprocessor &pp)
Chris Lattner7667d0d2006-07-16 18:16:58 +0000205 : Macro(Tok.getIdentifierInfo()->getMacroInfo()),
Chris Lattneree8760b2006-07-15 07:42:55 +0000206 ActualArgs(Actuals), PP(pp), CurToken(0),
Chris Lattner50b497e2006-06-18 16:32:35 +0000207 InstantiateLoc(Tok.getLocation()),
Chris Lattnerd01e2912006-06-18 16:22:51 +0000208 AtStartOfLine(Tok.isAtStartOfLine()),
209 HasLeadingSpace(Tok.hasLeadingSpace()) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000210 MacroTokens = &Macro->getReplacementTokens();
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000211
212 // If this is a function-like macro, expand the arguments and change
213 // MacroTokens to point to the expanded tokens.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000214 if (Macro->isFunctionLike() && Macro->getNumArgs())
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000215 ExpandFunctionArguments();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000216
217 // Mark the macro as currently disabled, so that it is not recursively
218 // expanded. The macro must be disabled only after argument pre-expansion of
219 // function-like macro arguments occurs.
220 Macro->DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000221}
222
Chris Lattner7667d0d2006-07-16 18:16:58 +0000223/// Create a macro expander for the specified token stream. This does not
224/// take ownership of the specified token vector.
225MacroExpander::MacroExpander(const std::vector<LexerToken> &TokStream,
226 Preprocessor &pp)
227 : Macro(0), ActualArgs(0), PP(pp), MacroTokens(&TokStream), CurToken(0),
228 InstantiateLoc(SourceLocation()), AtStartOfLine(false),
229 HasLeadingSpace(false) {
230
231 // Set HasLeadingSpace/AtStartOfLine so that the first token will be
232 // returned unmodified.
233 if (!TokStream.empty()) {
234 AtStartOfLine = TokStream[0].isAtStartOfLine();
235 HasLeadingSpace = TokStream[0].hasLeadingSpace();
236 }
237}
238
239
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000240MacroExpander::~MacroExpander() {
241 // If this was a function-like macro that actually uses its arguments, delete
242 // the expanded tokens.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000243 if (Macro && MacroTokens != &Macro->getReplacementTokens())
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000244 delete MacroTokens;
245
246 // MacroExpander owns its formal arguments.
Chris Lattneree8760b2006-07-15 07:42:55 +0000247 delete ActualArgs;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000248}
249
250/// Expand the arguments of a function-like macro so that we can quickly
251/// return preexpanded tokens from MacroTokens.
252void MacroExpander::ExpandFunctionArguments() {
253 std::vector<LexerToken> ResultToks;
254
255 // Loop through the MacroTokens tokens, expanding them into ResultToks. Keep
256 // track of whether we change anything. If not, no need to keep them. If so,
257 // we install the newly expanded sequence as MacroTokens.
258 bool MadeChange = false;
259 for (unsigned i = 0, e = MacroTokens->size(); i != e; ++i) {
260 // If we found the stringify operator, get the argument stringified. The
261 // preprocessor already verified that the following token is a macro name
262 // when the #define was parsed.
263 const LexerToken &CurTok = (*MacroTokens)[i];
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000264 if (CurTok.getKind() == tok::hash || CurTok.getKind() == tok::hashat) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000265 int ArgNo =Macro->getArgumentNum((*MacroTokens)[i+1].getIdentifierInfo());
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000266 assert(ArgNo != -1 && "Token following # is not an argument?");
267
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000268 if (CurTok.getKind() == tok::hash) // Stringify
Chris Lattneree8760b2006-07-15 07:42:55 +0000269 ResultToks.push_back(ActualArgs->getStringifiedArgument(ArgNo, PP));
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000270 else {
271 // 'charify': don't bother caching these.
272 ResultToks.push_back(StringifyArgument(
Chris Lattneree8760b2006-07-15 07:42:55 +0000273 ActualArgs->getUnexpArgument(ArgNo), PP, true));
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000274 }
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000275
Chris Lattner60161692006-07-15 06:48:02 +0000276 // The stringified/charified string leading space flag gets set to match
277 // the #/#@ operator.
278 if (CurTok.hasLeadingSpace())
279 ResultToks.back().SetFlag(LexerToken::LeadingSpace);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000280
281 MadeChange = true;
282 ++i; // Skip arg name.
283 } else {
Chris Lattner203b4562006-07-15 21:07:40 +0000284 // Otherwise, if this is not an argument token, just add the token to the
285 // output buffer.
286 IdentifierInfo *II = CurTok.getIdentifierInfo();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000287 int ArgNo = II ? Macro->getArgumentNum(II) : -1;
Chris Lattner203b4562006-07-15 21:07:40 +0000288 if (ArgNo == -1) {
289 ResultToks.push_back(CurTok);
290 continue;
291 }
292
293 // An argument is expanded somehow, the result is different than the
294 // input.
295 MadeChange = true;
296
297 // Otherwise, this is a use of the argument. Find out if there is a paste
298 // (##) operator before or after the argument.
299 bool PasteBefore =
300 !ResultToks.empty() && ResultToks.back().getKind() == tok::hashhash;
301 bool PasteAfter =
302 i+1 != e && (*MacroTokens)[i+1].getKind() == tok::hashhash;
303
304 // If it is not the LHS/RHS of a ## operator, we must pre-expand the
305 // argument and substitute the expanded tokens into the result. This is
306 // C99 6.10.3.1p1.
307 if (!PasteBefore && !PasteAfter) {
308 const std::vector<LexerToken> *ArgToks;
309 // Only preexpand the argument if it could possibly need it. This
310 // avoids some work in common cases.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000311 if (ActualArgs->ArgNeedsPreexpansion(ArgNo))
312 ArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP);
313 else
Chris Lattner203b4562006-07-15 21:07:40 +0000314 ArgToks = &ActualArgs->getUnexpArgument(ArgNo);
Chris Lattner203b4562006-07-15 21:07:40 +0000315
316 unsigned FirstTok = ResultToks.size();
317 ResultToks.insert(ResultToks.end(), ArgToks->begin(), ArgToks->end()-1);
318
319 // If any tokens were substituted from the argument, the whitespace
320 // before the first token should match the whitespace of the arg
321 // identifier.
322 if (FirstTok != ResultToks.size())
323 ResultToks[FirstTok].SetFlagValue(LexerToken::LeadingSpace,
324 CurTok.hasLeadingSpace());
325 continue;
326 }
327
Chris Lattner7e2e6692006-07-19 03:51:26 +0000328 // Okay, we have a token that is either the LHS or RHS of a paste (##)
329 // argument. It gets substituted as its non-pre-expanded tokens.
330 const std::vector<LexerToken> &ArgToks =
331 ActualArgs->getUnexpArgument(ArgNo);
332 assert(ArgToks.back().getKind() == tok::eof && "Bad argument!");
333
334 if (ArgToks.size() != 1) { // Not just an EOF token?
335 ResultToks.insert(ResultToks.end(), ArgToks.begin(), ArgToks.end()-1);
336 continue;
337 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000338
Chris Lattner7e2e6692006-07-19 03:51:26 +0000339 // FIXME: Handle comma swallowing GNU extension.
340 // FIXME: Handle 'placemarker' stuff.
341 assert(0 && "FIXME: handle empty arguments!");
342 //ResultToks.push_back(CurTok);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000343 }
344 }
345
346 // If anything changed, install this as the new MacroTokens list.
347 if (MadeChange) {
348 // This is deleted in the dtor.
349 std::vector<LexerToken> *Res = new std::vector<LexerToken>();
350 Res->swap(ResultToks);
351 MacroTokens = Res;
352 }
353}
Chris Lattner67b07cb2006-06-26 02:03:42 +0000354
Chris Lattner22eb9722006-06-18 05:43:12 +0000355/// Lex - Lex and return a token from this macro stream.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000356///
Chris Lattnercb283342006-06-18 06:48:37 +0000357void MacroExpander::Lex(LexerToken &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000358 // Lexing off the end of the macro, pop this macro off the expansion stack.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000359 if (isAtEnd()) {
360 // If this is a macro (not a token stream), mark the macro enabled now
361 // that it is no longer being expanded.
362 if (Macro) Macro->EnableMacro();
363
364 // Pop this context off the preprocessors lexer stack and get the next
Chris Lattner2183a6e2006-07-18 06:36:12 +0000365 // token. This will delete "this" so remember the PP instance var.
366 Preprocessor &PPCache = PP;
367 if (PP.HandleEndOfMacro(Tok))
368 return;
369
370 // HandleEndOfMacro may not return a token. If it doesn't, lex whatever is
371 // next.
372 return PPCache.Lex(Tok);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000373 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000374
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000375 // If this is the first token of the expanded result, we inherit spacing
376 // properties later.
377 bool isFirstToken = CurToken == 0;
378
Chris Lattner22eb9722006-06-18 05:43:12 +0000379 // Get the next token to return.
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000380 Tok = (*MacroTokens)[CurToken++];
Chris Lattner01ecf832006-07-19 05:42:48 +0000381
382 // If this token is followed by a token paste (##) operator, paste the tokens!
383 if (!isAtEnd() && (*MacroTokens)[CurToken].getKind() == tok::hashhash)
384 PasteTokens(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000385
Chris Lattnerc673f902006-06-30 06:10:41 +0000386 // The token's current location indicate where the token was lexed from. We
387 // need this information to compute the spelling of the token, but any
388 // diagnostics for the expanded token should appear as if they came from
389 // InstantiationLoc. Pull this information together into a new SourceLocation
390 // that captures all of this.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000391 if (InstantiateLoc.isValid()) { // Don't do this for token streams.
392 SourceManager &SrcMgr = PP.getSourceManager();
393 // The token could have come from a prior macro expansion. In that case,
394 // ignore the macro expand part to get to the physloc. This happens for
395 // stuff like: #define A(X) X A(A(X)) A(1)
396 SourceLocation PhysLoc = SrcMgr.getPhysicalLoc(Tok.getLocation());
397 Tok.SetLocation(SrcMgr.getInstantiationLoc(PhysLoc, InstantiateLoc));
398 }
399
Chris Lattner22eb9722006-06-18 05:43:12 +0000400 // If this is the first token, set the lexical properties of the token to
401 // match the lexical properties of the macro identifier.
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000402 if (isFirstToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000403 Tok.SetFlagValue(LexerToken::StartOfLine , AtStartOfLine);
404 Tok.SetFlagValue(LexerToken::LeadingSpace, HasLeadingSpace);
405 }
406
407 // Handle recursive expansion!
408 if (Tok.getIdentifierInfo())
409 return PP.HandleIdentifier(Tok);
410
411 // Otherwise, return a normal token.
Chris Lattner22eb9722006-06-18 05:43:12 +0000412}
Chris Lattnerafe603f2006-07-11 04:02:46 +0000413
Chris Lattner01ecf832006-07-19 05:42:48 +0000414/// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ##
415/// operator. Read the ## and RHS, and paste the LHS/RHS together. If there
416/// are is another ## after it, chomp it iteratively. Return the result as Tok.
417void MacroExpander::PasteTokens(LexerToken &Tok) {
418 do {
419 // Consume the ## operator.
420 SourceLocation PasteOpLoc = (*MacroTokens)[CurToken].getLocation();
421 ++CurToken;
422 assert(!isAtEnd() && "No token on the RHS of a paste operator!");
423
424 // Get the RHS token.
425 const LexerToken &RHS = (*MacroTokens)[CurToken];
426
427 bool isInvalid = false;
428
Chris Lattner01ecf832006-07-19 05:42:48 +0000429 // Allocate space for the result token. This is guaranteed to be enough for
430 // the two tokens and a null terminator.
431 char *Buffer = (char*)alloca(Tok.getLength() + RHS.getLength() + 1);
432
433 // Get the spelling of the LHS token in Buffer.
434 const char *BufPtr = Buffer;
435 unsigned LHSLen = PP.getSpelling(Tok, BufPtr);
436 if (BufPtr != Buffer) // Really, we want the chars in Buffer!
437 memcpy(Buffer, BufPtr, LHSLen);
438
439 BufPtr = Buffer+LHSLen;
440 unsigned RHSLen = PP.getSpelling(RHS, BufPtr);
441 if (BufPtr != Buffer+LHSLen) // Really, we want the chars in Buffer!
442 memcpy(Buffer+LHSLen, BufPtr, RHSLen);
443
444 // Add null terminator.
445 Buffer[LHSLen+RHSLen] = '\0';
446
447 // Plop the pasted result (including the trailing newline and null) into a
448 // scratch buffer where we can lex it.
449 SourceLocation ResultTokLoc = PP.CreateString(Buffer, LHSLen+RHSLen+1);
450
451 // Lex the resultant pasted token into Result.
452 LexerToken Result;
453
Chris Lattnera7e2e742006-07-19 06:32:35 +0000454 // Avoid testing /*, as the lexer would think it is the start of a comment
455 // and emit an error that it is unterminated.
456 if (Tok.getKind() == tok::slash && RHS.getKind() == tok::star) {
457 isInvalid = true;
Chris Lattner510ab612006-07-20 04:47:30 +0000458 } else if (Tok.getKind() == tok::identifier &&
Chris Lattner08ba4c02006-07-20 04:52:59 +0000459 RHS.getKind() == tok::identifier) {
Chris Lattner510ab612006-07-20 04:47:30 +0000460 // Common paste case: identifier+identifier = identifier. Avoid creating
461 // a lexer and other overhead.
462 PP.IncrementPasteCounter(true);
463 Result.StartToken();
464 Result.SetKind(tok::identifier);
465 Result.SetLocation(ResultTokLoc);
466 Result.SetLength(LHSLen+RHSLen);
Chris Lattnera7e2e742006-07-19 06:32:35 +0000467 } else {
Chris Lattner510ab612006-07-20 04:47:30 +0000468 PP.IncrementPasteCounter(false);
469
Chris Lattnera7e2e742006-07-19 06:32:35 +0000470 // Make a lexer to lex this string from.
471 SourceManager &SourceMgr = PP.getSourceManager();
472 const char *ResultStrData = SourceMgr.getCharacterData(ResultTokLoc);
473
474 unsigned FileID = ResultTokLoc.getFileID();
475 assert(FileID && "Could not get FileID for paste?");
476
477 // Make a lexer object so that we lex and expand the paste result.
478 Lexer *TL = new Lexer(SourceMgr.getBuffer(FileID), FileID, PP,
479 ResultStrData,
480 ResultStrData+LHSLen+RHSLen /*don't include null*/);
481
482 // Lex a token in raw mode. This way it won't look up identifiers
483 // automatically, lexing off the end will return an eof token, and
484 // warnings are disabled. This returns true if the result token is the
485 // entire buffer.
486 bool IsComplete = TL->LexRawToken(Result);
487
488 // If we got an EOF token, we didn't form even ONE token. For example, we
489 // did "/ ## /" to get "//".
490 IsComplete &= Result.getKind() != tok::eof;
491 isInvalid = !IsComplete;
492
493 // We're now done with the temporary lexer.
494 delete TL;
495 }
Chris Lattner01ecf832006-07-19 05:42:48 +0000496
497 // If pasting the two tokens didn't form a full new token, this is an error.
Chris Lattnera7e2e742006-07-19 06:32:35 +0000498 // This occurs with "x ## +" and other stuff. Return with Tok unmodified
499 // and with RHS as the next token to lex.
500 if (isInvalid) {
Chris Lattner01ecf832006-07-19 05:42:48 +0000501 // If not in assembler language mode.
502 PP.Diag(PasteOpLoc, diag::err_pp_bad_paste,
503 std::string(Buffer, Buffer+LHSLen+RHSLen));
504 return;
505 }
506
507 // Turn ## into 'other' to avoid # ## # from looking like a paste operator.
508 if (Result.getKind() == tok::hashhash)
509 Result.SetKind(tok::unknown);
510 // FIXME: Turn __VARRGS__ into "not a token"?
511
512 // Transfer properties of the LHS over the the Result.
513 Result.SetFlagValue(LexerToken::StartOfLine , Tok.isAtStartOfLine());
514 Result.SetFlagValue(LexerToken::LeadingSpace, Tok.hasLeadingSpace());
515
516 // Finally, replace LHS with the result, consume the RHS, and iterate.
517 ++CurToken;
518 Tok = Result;
519 } while (!isAtEnd() && (*MacroTokens)[CurToken].getKind() == tok::hashhash);
Chris Lattner0f1f5052006-07-20 04:16:23 +0000520
521 // Now that we got the result token, it will be subject to expansion. Since
522 // token pasting re-lexes the result token in raw mode, identifier information
523 // isn't looked up. As such, if the result is an identifier, look up id info.
524 if (Tok.getKind() == tok::identifier) {
525 // Look up the identifier info for the token. We disabled identifier lookup
526 // by saying we're skipping contents, so we need to do this manually.
527 Tok.SetIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
528 }
Chris Lattner01ecf832006-07-19 05:42:48 +0000529}
530
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000531/// isNextTokenLParen - If the next token lexed will pop this macro off the
532/// expansion stack, return 2. If the next unexpanded token is a '(', return
533/// 1, otherwise return 0.
534unsigned MacroExpander::isNextTokenLParen() const {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000535 // Out of tokens?
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000536 if (isAtEnd())
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000537 return 2;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000538 return (*MacroTokens)[CurToken].getKind() == tok::l_paren;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000539}