blob: dd99ae3f941b37dc423b0e79f83eaa03b3e6cda2 [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 Lattner01ecf832006-07-19 05:42:48 +000020#include "llvm/Config/Alloca.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000021using namespace llvm;
22using namespace clang;
23
Chris Lattner78186052006-07-09 00:45:31 +000024//===----------------------------------------------------------------------===//
Chris Lattneree8760b2006-07-15 07:42:55 +000025// MacroArgs Implementation
Chris Lattner78186052006-07-09 00:45:31 +000026//===----------------------------------------------------------------------===//
27
Chris Lattnerc1410dc2006-07-26 05:22:49 +000028/// MacroArgs ctor function - This destroys the vector passed in.
29MacroArgs *MacroArgs::create(const MacroInfo *MI,
Chris Lattner7a4af3b2006-07-26 06:26:52 +000030 const LexerToken *UnexpArgTokens,
31 unsigned NumToks) {
Chris Lattner78186052006-07-09 00:45:31 +000032 assert(MI->isFunctionLike() &&
Chris Lattneree8760b2006-07-15 07:42:55 +000033 "Can't have args for an object-like macro!");
Chris Lattnerc1410dc2006-07-26 05:22:49 +000034
35 // Allocate memory for the MacroArgs object with the lexer tokens at the end.
Chris Lattnerc1410dc2006-07-26 05:22:49 +000036 MacroArgs *Result = (MacroArgs*)malloc(sizeof(MacroArgs) +
37 NumToks*sizeof(LexerToken));
38 // Construct the macroargs object.
39 new (Result) MacroArgs(NumToks);
40
41 // Copy the actual unexpanded tokens to immediately after the result ptr.
42 if (NumToks)
43 memcpy(const_cast<LexerToken*>(Result->getUnexpArgument(0)),
Chris Lattner7a4af3b2006-07-26 06:26:52 +000044 UnexpArgTokens, NumToks*sizeof(LexerToken));
Chris Lattnerc1410dc2006-07-26 05:22:49 +000045
46 return Result;
Chris Lattner78186052006-07-09 00:45:31 +000047}
48
Chris Lattnerc1410dc2006-07-26 05:22:49 +000049/// destroy - Destroy and deallocate the memory for this object.
50///
51void MacroArgs::destroy() {
52 // Run the dtor to deallocate the vectors.
53 this->~MacroArgs();
54 // Release the memory for the object.
55 free(this);
56}
57
58
Chris Lattner6fc08bc2006-07-26 04:55:32 +000059/// getArgLength - Given a pointer to an expanded or unexpanded argument,
60/// return the number of tokens, not counting the EOF, that make up the
61/// argument.
62unsigned MacroArgs::getArgLength(const LexerToken *ArgPtr) {
63 unsigned NumArgTokens = 0;
64 for (; ArgPtr->getKind() != tok::eof; ++ArgPtr)
65 ++NumArgTokens;
66 return NumArgTokens;
67}
68
69
Chris Lattner36b6e812006-07-21 06:38:30 +000070/// getUnexpArgument - Return the unexpanded tokens for the specified formal.
71///
72const LexerToken *MacroArgs::getUnexpArgument(unsigned Arg) const {
Chris Lattnerc1410dc2006-07-26 05:22:49 +000073 // The unexpanded argument tokens start immediately after the MacroArgs object
74 // in memory.
75 const LexerToken *Start = (const LexerToken *)(this+1);
Chris Lattner36b6e812006-07-21 06:38:30 +000076 const LexerToken *Result = Start;
Chris Lattnerc1410dc2006-07-26 05:22:49 +000077 // Scan to find Arg.
Chris Lattner36b6e812006-07-21 06:38:30 +000078 for (; Arg; ++Result) {
Chris Lattnerc1410dc2006-07-26 05:22:49 +000079 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
Chris Lattner36b6e812006-07-21 06:38:30 +000080 if (Result->getKind() == tok::eof)
81 --Arg;
82 }
83 return Result;
Chris Lattneree8760b2006-07-15 07:42:55 +000084}
85
Chris Lattner36b6e812006-07-21 06:38:30 +000086
Chris Lattner203b4562006-07-15 21:07:40 +000087/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
88/// by pre-expansion, return false. Otherwise, conservatively return true.
Chris Lattner36b6e812006-07-21 06:38:30 +000089bool MacroArgs::ArgNeedsPreexpansion(const LexerToken *ArgTok) const {
Chris Lattner203b4562006-07-15 21:07:40 +000090 // If there are no identifiers in the argument list, or if the identifiers are
91 // known to not be macros, pre-expansion won't modify it.
Chris Lattner36b6e812006-07-21 06:38:30 +000092 for (; ArgTok->getKind() != tok::eof; ++ArgTok)
93 if (IdentifierInfo *II = ArgTok->getIdentifierInfo()) {
Chris Lattner203b4562006-07-15 21:07:40 +000094 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled())
95 // Return true even though the macro could be a function-like macro
96 // without a following '(' token.
97 return true;
98 }
99 return false;
100}
101
Chris Lattner7667d0d2006-07-16 18:16:58 +0000102/// getPreExpArgument - Return the pre-expanded form of the specified
103/// argument.
104const std::vector<LexerToken> &
105MacroArgs::getPreExpArgument(unsigned Arg, Preprocessor &PP) {
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000106 assert(Arg < NumUnexpArgTokens && "Invalid argument number!");
Chris Lattner7667d0d2006-07-16 18:16:58 +0000107
108 // If we have already computed this, return it.
109 if (PreExpArgTokens.empty())
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000110 PreExpArgTokens.resize(NumUnexpArgTokens);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000111
112 std::vector<LexerToken> &Result = PreExpArgTokens[Arg];
113 if (!Result.empty()) return Result;
114
Chris Lattner36b6e812006-07-21 06:38:30 +0000115 const LexerToken *AT = getUnexpArgument(Arg);
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000116 unsigned NumToks = getArgLength(AT)+1; // Include the EOF.
Chris Lattner36b6e812006-07-21 06:38:30 +0000117
Chris Lattner7667d0d2006-07-16 18:16:58 +0000118 // Otherwise, we have to pre-expand this argument, populating Result. To do
119 // this, we set up a fake MacroExpander to lex from the unexpanded argument
120 // list. With this installed, we lex expanded tokens until we hit the EOF
121 // token at the end of the unexp list.
Chris Lattner70216572006-07-26 03:50:40 +0000122 PP.EnterTokenStream(AT, NumToks);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000123
124 // Lex all of the macro-expanded tokens into Result.
125 do {
126 Result.push_back(LexerToken());
127 PP.Lex(Result.back());
128 } while (Result.back().getKind() != tok::eof);
129
130 // Pop the token stream off the top of the stack. We know that the internal
131 // pointer inside of it is to the "end" of the token stream, but the stack
132 // will not otherwise be popped until the next token is lexed. The problem is
133 // that the token may be lexed sometime after the vector of tokens itself is
134 // destroyed, which would be badness.
135 PP.RemoveTopOfLexerStack();
136 return Result;
137}
138
Chris Lattneree8760b2006-07-15 07:42:55 +0000139
Chris Lattner0707bd32006-07-15 05:23:58 +0000140/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
141/// tokens into the literal string token that should be produced by the C #
142/// preprocessor operator.
143///
Chris Lattner36b6e812006-07-21 06:38:30 +0000144static LexerToken StringifyArgument(const LexerToken *ArgToks,
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000145 Preprocessor &PP, bool Charify = false) {
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000146 LexerToken Tok;
147 Tok.StartToken();
148 Tok.SetKind(tok::string_literal);
Chris Lattner0707bd32006-07-15 05:23:58 +0000149
Chris Lattner36b6e812006-07-21 06:38:30 +0000150 const LexerToken *ArgTokStart = ArgToks;
151
Chris Lattner0707bd32006-07-15 05:23:58 +0000152 // Stringify all the tokens.
153 std::string Result = "\"";
Chris Lattner7667d0d2006-07-16 18:16:58 +0000154 // FIXME: Optimize this loop to not use std::strings.
Chris Lattner36b6e812006-07-21 06:38:30 +0000155 bool isFirst = true;
156 for (; ArgToks->getKind() != tok::eof; ++ArgToks) {
157 const LexerToken &Tok = *ArgToks;
158 if (!isFirst && Tok.hasLeadingSpace())
Chris Lattner0707bd32006-07-15 05:23:58 +0000159 Result += ' ';
Chris Lattner36b6e812006-07-21 06:38:30 +0000160 isFirst = false;
Chris Lattner0707bd32006-07-15 05:23:58 +0000161
162 // If this is a string or character constant, escape the token as specified
163 // by 6.10.3.2p2.
164 if (Tok.getKind() == tok::string_literal || // "foo" and L"foo".
165 Tok.getKind() == tok::char_constant) { // 'x' and L'x'.
166 Result += Lexer::Stringify(PP.getSpelling(Tok));
167 } else {
168 // Otherwise, just append the token.
169 Result += PP.getSpelling(Tok);
170 }
171 }
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000172
Chris Lattner0707bd32006-07-15 05:23:58 +0000173 // If the last character of the string is a \, and if it isn't escaped, this
174 // is an invalid string literal, diagnose it as specified in C99.
175 if (Result[Result.size()-1] == '\\') {
176 // Count the number of consequtive \ characters. If even, then they are
177 // just escaped backslashes, otherwise it's an error.
178 unsigned FirstNonSlash = Result.size()-2;
179 // Guaranteed to find the starting " if nothing else.
180 while (Result[FirstNonSlash] == '\\')
181 --FirstNonSlash;
182 if ((Result.size()-1-FirstNonSlash) & 1) {
Chris Lattnerf2781502006-07-15 05:27:44 +0000183 // Diagnose errors for things like: #define F(X) #X / F(\)
Chris Lattner36b6e812006-07-21 06:38:30 +0000184 PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
Chris Lattner0707bd32006-07-15 05:23:58 +0000185 Result.erase(Result.end()-1); // remove one of the \'s.
186 }
187 }
Chris Lattner0707bd32006-07-15 05:23:58 +0000188 Result += '"';
189
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000190 // If this is the charify operation and the result is not a legal character
191 // constant, diagnose it.
192 if (Charify) {
193 // First step, turn double quotes into single quotes:
194 Result[0] = '\'';
195 Result[Result.size()-1] = '\'';
196
197 // Check for bogus character.
198 bool isBad = false;
Chris Lattner2ada5d32006-07-15 07:51:24 +0000199 if (Result.size() == 3) {
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000200 isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
201 } else {
202 isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
203 }
204
205 if (isBad) {
Chris Lattner36b6e812006-07-21 06:38:30 +0000206 PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
Chris Lattner7c581492006-07-15 07:56:31 +0000207 Result = "' '"; // Use something arbitrary, but legal.
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000208 }
209 }
210
Chris Lattner0707bd32006-07-15 05:23:58 +0000211 Tok.SetLength(Result.size());
212 Tok.SetLocation(PP.CreateString(&Result[0], Result.size()));
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000213 return Tok;
214}
215
216/// getStringifiedArgument - Compute, cache, and return the specified argument
217/// that has been 'stringified' as required by the # operator.
Chris Lattneree8760b2006-07-15 07:42:55 +0000218const LexerToken &MacroArgs::getStringifiedArgument(unsigned ArgNo,
219 Preprocessor &PP) {
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000220 assert(ArgNo < NumUnexpArgTokens && "Invalid argument number!");
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000221 if (StringifiedArgs.empty()) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000222 StringifiedArgs.resize(getNumArguments());
Chris Lattneree8760b2006-07-15 07:42:55 +0000223 memset(&StringifiedArgs[0], 0,
224 sizeof(StringifiedArgs[0])*getNumArguments());
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000225 }
226 if (StringifiedArgs[ArgNo].getKind() != tok::string_literal)
Chris Lattner36b6e812006-07-21 06:38:30 +0000227 StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000228 return StringifiedArgs[ArgNo];
229}
230
Chris Lattner78186052006-07-09 00:45:31 +0000231//===----------------------------------------------------------------------===//
232// MacroExpander Implementation
233//===----------------------------------------------------------------------===//
234
Chris Lattner7667d0d2006-07-16 18:16:58 +0000235/// Create a macro expander for the specified macro with the specified actual
236/// arguments. Note that this ctor takes ownership of the ActualArgs pointer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000237MacroExpander::MacroExpander(LexerToken &Tok, MacroArgs *Actuals,
Chris Lattner78186052006-07-09 00:45:31 +0000238 Preprocessor &pp)
Chris Lattner7667d0d2006-07-16 18:16:58 +0000239 : Macro(Tok.getIdentifierInfo()->getMacroInfo()),
Chris Lattneree8760b2006-07-15 07:42:55 +0000240 ActualArgs(Actuals), PP(pp), CurToken(0),
Chris Lattner50b497e2006-06-18 16:32:35 +0000241 InstantiateLoc(Tok.getLocation()),
Chris Lattnerd01e2912006-06-18 16:22:51 +0000242 AtStartOfLine(Tok.isAtStartOfLine()),
243 HasLeadingSpace(Tok.hasLeadingSpace()) {
Chris Lattner70216572006-07-26 03:50:40 +0000244 MacroTokens = &Macro->getReplacementTokens()[0];
245 NumMacroTokens = Macro->getReplacementTokens().size();
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000246
247 // If this is a function-like macro, expand the arguments and change
248 // MacroTokens to point to the expanded tokens.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000249 if (Macro->isFunctionLike() && Macro->getNumArgs())
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000250 ExpandFunctionArguments();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000251
252 // Mark the macro as currently disabled, so that it is not recursively
253 // expanded. The macro must be disabled only after argument pre-expansion of
254 // function-like macro arguments occurs.
255 Macro->DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000256}
257
Chris Lattner7667d0d2006-07-16 18:16:58 +0000258/// Create a macro expander for the specified token stream. This does not
259/// take ownership of the specified token vector.
Chris Lattner70216572006-07-26 03:50:40 +0000260MacroExpander::MacroExpander(const LexerToken *TokArray, unsigned NumToks,
Chris Lattner7667d0d2006-07-16 18:16:58 +0000261 Preprocessor &pp)
Chris Lattner70216572006-07-26 03:50:40 +0000262 : Macro(0), ActualArgs(0), PP(pp), MacroTokens(TokArray),
263 NumMacroTokens(NumToks), CurToken(0),
Chris Lattner7667d0d2006-07-16 18:16:58 +0000264 InstantiateLoc(SourceLocation()), AtStartOfLine(false),
265 HasLeadingSpace(false) {
266
267 // Set HasLeadingSpace/AtStartOfLine so that the first token will be
268 // returned unmodified.
Chris Lattner70216572006-07-26 03:50:40 +0000269 if (NumToks != 0) {
270 AtStartOfLine = TokArray[0].isAtStartOfLine();
271 HasLeadingSpace = TokArray[0].hasLeadingSpace();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000272 }
273}
274
275
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000276MacroExpander::~MacroExpander() {
277 // If this was a function-like macro that actually uses its arguments, delete
278 // the expanded tokens.
Chris Lattner70216572006-07-26 03:50:40 +0000279 if (Macro && MacroTokens != &Macro->getReplacementTokens()[0])
280 delete [] MacroTokens;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000281
282 // MacroExpander owns its formal arguments.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000283 if (ActualArgs) ActualArgs->destroy();
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000284}
285
286/// Expand the arguments of a function-like macro so that we can quickly
287/// return preexpanded tokens from MacroTokens.
288void MacroExpander::ExpandFunctionArguments() {
Chris Lattnerb57aa462006-07-27 03:42:15 +0000289 SmallVector<LexerToken, 128> ResultToks;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000290
291 // Loop through the MacroTokens tokens, expanding them into ResultToks. Keep
292 // track of whether we change anything. If not, no need to keep them. If so,
293 // we install the newly expanded sequence as MacroTokens.
294 bool MadeChange = false;
Chris Lattner70216572006-07-26 03:50:40 +0000295 for (unsigned i = 0, e = NumMacroTokens; i != e; ++i) {
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000296 // If we found the stringify operator, get the argument stringified. The
297 // preprocessor already verified that the following token is a macro name
298 // when the #define was parsed.
Chris Lattner70216572006-07-26 03:50:40 +0000299 const LexerToken &CurTok = MacroTokens[i];
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000300 if (CurTok.getKind() == tok::hash || CurTok.getKind() == tok::hashat) {
Chris Lattner70216572006-07-26 03:50:40 +0000301 int ArgNo = Macro->getArgumentNum(MacroTokens[i+1].getIdentifierInfo());
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000302 assert(ArgNo != -1 && "Token following # is not an argument?");
303
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000304 LexerToken Res;
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000305 if (CurTok.getKind() == tok::hash) // Stringify
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000306 Res = ActualArgs->getStringifiedArgument(ArgNo, PP);
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000307 else {
308 // 'charify': don't bother caching these.
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000309 Res = StringifyArgument(ActualArgs->getUnexpArgument(ArgNo), PP, true);
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000310 }
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000311
Chris Lattner60161692006-07-15 06:48:02 +0000312 // The stringified/charified string leading space flag gets set to match
313 // the #/#@ operator.
314 if (CurTok.hasLeadingSpace())
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000315 Res.SetFlag(LexerToken::LeadingSpace);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000316
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000317 ResultToks.push_back(Res);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000318 MadeChange = true;
319 ++i; // Skip arg name.
320 } else {
Chris Lattner203b4562006-07-15 21:07:40 +0000321 // Otherwise, if this is not an argument token, just add the token to the
322 // output buffer.
323 IdentifierInfo *II = CurTok.getIdentifierInfo();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000324 int ArgNo = II ? Macro->getArgumentNum(II) : -1;
Chris Lattner203b4562006-07-15 21:07:40 +0000325 if (ArgNo == -1) {
326 ResultToks.push_back(CurTok);
327 continue;
328 }
329
330 // An argument is expanded somehow, the result is different than the
331 // input.
332 MadeChange = true;
333
334 // Otherwise, this is a use of the argument. Find out if there is a paste
335 // (##) operator before or after the argument.
336 bool PasteBefore =
337 !ResultToks.empty() && ResultToks.back().getKind() == tok::hashhash;
338 bool PasteAfter =
Chris Lattner70216572006-07-26 03:50:40 +0000339 i+1 != e && MacroTokens[i+1].getKind() == tok::hashhash;
Chris Lattner203b4562006-07-15 21:07:40 +0000340
341 // If it is not the LHS/RHS of a ## operator, we must pre-expand the
342 // argument and substitute the expanded tokens into the result. This is
343 // C99 6.10.3.1p1.
344 if (!PasteBefore && !PasteAfter) {
Chris Lattner36b6e812006-07-21 06:38:30 +0000345 const LexerToken *ResultArgToks;
346
Chris Lattner203b4562006-07-15 21:07:40 +0000347 // Only preexpand the argument if it could possibly need it. This
348 // avoids some work in common cases.
Chris Lattner36b6e812006-07-21 06:38:30 +0000349 const LexerToken *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
350 if (ActualArgs->ArgNeedsPreexpansion(ArgTok))
351 ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0];
Chris Lattner7667d0d2006-07-16 18:16:58 +0000352 else
Chris Lattner36b6e812006-07-21 06:38:30 +0000353 ResultArgToks = ArgTok; // Use non-preexpanded tokens.
Chris Lattner203b4562006-07-15 21:07:40 +0000354
Chris Lattner36b6e812006-07-21 06:38:30 +0000355 if (ResultArgToks->getKind() != tok::eof) {
356 unsigned FirstResult = ResultToks.size();
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000357 unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
Chris Lattnerb57aa462006-07-27 03:42:15 +0000358 ResultToks.append(ResultArgToks, ResultArgToks+NumToks);
Chris Lattner203b4562006-07-15 21:07:40 +0000359
Chris Lattner36b6e812006-07-21 06:38:30 +0000360 // If any tokens were substituted from the argument, the whitespace
361 // before the first token should match the whitespace of the arg
362 // identifier.
363 ResultToks[FirstResult].SetFlagValue(LexerToken::LeadingSpace,
364 CurTok.hasLeadingSpace());
365 }
Chris Lattner203b4562006-07-15 21:07:40 +0000366 continue;
367 }
368
Chris Lattner7e2e6692006-07-19 03:51:26 +0000369 // Okay, we have a token that is either the LHS or RHS of a paste (##)
370 // argument. It gets substituted as its non-pre-expanded tokens.
Chris Lattner36b6e812006-07-21 06:38:30 +0000371 const LexerToken *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
Chris Lattner7e2e6692006-07-19 03:51:26 +0000372
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000373 unsigned NumToks = MacroArgs::getArgLength(ArgToks);
374 if (NumToks) { // Not an empty argument?
Chris Lattnerb57aa462006-07-27 03:42:15 +0000375 ResultToks.append(ArgToks, ArgToks+NumToks);
Chris Lattner7e2e6692006-07-19 03:51:26 +0000376 continue;
377 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000378
Chris Lattner7e2e6692006-07-19 03:51:26 +0000379 // FIXME: Handle comma swallowing GNU extension.
Chris Lattnera9dc5972006-07-28 05:07:04 +0000380
381 // If an empty argument is on the LHS or RHS of a paste, the standard (C99
382 // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur. We
383 // implement this by eating ## operators when a LHS or RHS expands to
384 // empty.
385 if (PasteAfter) {
386 // Discard the argument token and skip (don't copy to the expansion
387 // buffer) the paste operator after it.
388 ++i;
389 continue;
390 }
391
392 // If this is on the RHS of a paste operator, we've already copied the
393 // paste operator to the ResultToks list. Remove it.
394 assert(PasteBefore && ResultToks.back().getKind() == tok::hashhash);
395 ResultToks.pop_back();
396 continue;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000397 }
398 }
399
400 // If anything changed, install this as the new MacroTokens list.
401 if (MadeChange) {
402 // This is deleted in the dtor.
Chris Lattner70216572006-07-26 03:50:40 +0000403 NumMacroTokens = ResultToks.size();
404 LexerToken *Res = new LexerToken[ResultToks.size()];
405 memcpy(Res, &ResultToks[0], NumMacroTokens*sizeof(LexerToken));
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000406 MacroTokens = Res;
407 }
408}
Chris Lattner67b07cb2006-06-26 02:03:42 +0000409
Chris Lattner22eb9722006-06-18 05:43:12 +0000410/// Lex - Lex and return a token from this macro stream.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000411///
Chris Lattnercb283342006-06-18 06:48:37 +0000412void MacroExpander::Lex(LexerToken &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000413 // Lexing off the end of the macro, pop this macro off the expansion stack.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000414 if (isAtEnd()) {
415 // If this is a macro (not a token stream), mark the macro enabled now
416 // that it is no longer being expanded.
417 if (Macro) Macro->EnableMacro();
418
419 // Pop this context off the preprocessors lexer stack and get the next
Chris Lattner2183a6e2006-07-18 06:36:12 +0000420 // token. This will delete "this" so remember the PP instance var.
421 Preprocessor &PPCache = PP;
422 if (PP.HandleEndOfMacro(Tok))
423 return;
424
425 // HandleEndOfMacro may not return a token. If it doesn't, lex whatever is
426 // next.
427 return PPCache.Lex(Tok);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000428 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000429
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000430 // If this is the first token of the expanded result, we inherit spacing
431 // properties later.
432 bool isFirstToken = CurToken == 0;
433
Chris Lattner22eb9722006-06-18 05:43:12 +0000434 // Get the next token to return.
Chris Lattner70216572006-07-26 03:50:40 +0000435 Tok = MacroTokens[CurToken++];
Chris Lattner01ecf832006-07-19 05:42:48 +0000436
437 // If this token is followed by a token paste (##) operator, paste the tokens!
Chris Lattner70216572006-07-26 03:50:40 +0000438 if (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash)
Chris Lattner01ecf832006-07-19 05:42:48 +0000439 PasteTokens(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000440
Chris Lattnerc673f902006-06-30 06:10:41 +0000441 // The token's current location indicate where the token was lexed from. We
442 // need this information to compute the spelling of the token, but any
443 // diagnostics for the expanded token should appear as if they came from
444 // InstantiationLoc. Pull this information together into a new SourceLocation
445 // that captures all of this.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000446 if (InstantiateLoc.isValid()) { // Don't do this for token streams.
447 SourceManager &SrcMgr = PP.getSourceManager();
448 // The token could have come from a prior macro expansion. In that case,
449 // ignore the macro expand part to get to the physloc. This happens for
450 // stuff like: #define A(X) X A(A(X)) A(1)
451 SourceLocation PhysLoc = SrcMgr.getPhysicalLoc(Tok.getLocation());
452 Tok.SetLocation(SrcMgr.getInstantiationLoc(PhysLoc, InstantiateLoc));
453 }
454
Chris Lattner22eb9722006-06-18 05:43:12 +0000455 // If this is the first token, set the lexical properties of the token to
456 // match the lexical properties of the macro identifier.
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000457 if (isFirstToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000458 Tok.SetFlagValue(LexerToken::StartOfLine , AtStartOfLine);
459 Tok.SetFlagValue(LexerToken::LeadingSpace, HasLeadingSpace);
460 }
461
462 // Handle recursive expansion!
463 if (Tok.getIdentifierInfo())
464 return PP.HandleIdentifier(Tok);
465
466 // Otherwise, return a normal token.
Chris Lattner22eb9722006-06-18 05:43:12 +0000467}
Chris Lattnerafe603f2006-07-11 04:02:46 +0000468
Chris Lattner01ecf832006-07-19 05:42:48 +0000469/// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ##
470/// operator. Read the ## and RHS, and paste the LHS/RHS together. If there
471/// are is another ## after it, chomp it iteratively. Return the result as Tok.
472void MacroExpander::PasteTokens(LexerToken &Tok) {
473 do {
474 // Consume the ## operator.
Chris Lattner70216572006-07-26 03:50:40 +0000475 SourceLocation PasteOpLoc = MacroTokens[CurToken].getLocation();
Chris Lattner01ecf832006-07-19 05:42:48 +0000476 ++CurToken;
477 assert(!isAtEnd() && "No token on the RHS of a paste operator!");
478
479 // Get the RHS token.
Chris Lattner70216572006-07-26 03:50:40 +0000480 const LexerToken &RHS = MacroTokens[CurToken];
Chris Lattner01ecf832006-07-19 05:42:48 +0000481
482 bool isInvalid = false;
483
Chris Lattner01ecf832006-07-19 05:42:48 +0000484 // Allocate space for the result token. This is guaranteed to be enough for
485 // the two tokens and a null terminator.
486 char *Buffer = (char*)alloca(Tok.getLength() + RHS.getLength() + 1);
487
488 // Get the spelling of the LHS token in Buffer.
489 const char *BufPtr = Buffer;
490 unsigned LHSLen = PP.getSpelling(Tok, BufPtr);
491 if (BufPtr != Buffer) // Really, we want the chars in Buffer!
492 memcpy(Buffer, BufPtr, LHSLen);
493
494 BufPtr = Buffer+LHSLen;
495 unsigned RHSLen = PP.getSpelling(RHS, BufPtr);
496 if (BufPtr != Buffer+LHSLen) // Really, we want the chars in Buffer!
497 memcpy(Buffer+LHSLen, BufPtr, RHSLen);
498
499 // Add null terminator.
500 Buffer[LHSLen+RHSLen] = '\0';
501
502 // Plop the pasted result (including the trailing newline and null) into a
503 // scratch buffer where we can lex it.
504 SourceLocation ResultTokLoc = PP.CreateString(Buffer, LHSLen+RHSLen+1);
505
506 // Lex the resultant pasted token into Result.
507 LexerToken Result;
508
Chris Lattnera7e2e742006-07-19 06:32:35 +0000509 // Avoid testing /*, as the lexer would think it is the start of a comment
510 // and emit an error that it is unterminated.
511 if (Tok.getKind() == tok::slash && RHS.getKind() == tok::star) {
512 isInvalid = true;
Chris Lattner510ab612006-07-20 04:47:30 +0000513 } else if (Tok.getKind() == tok::identifier &&
Chris Lattner08ba4c02006-07-20 04:52:59 +0000514 RHS.getKind() == tok::identifier) {
Chris Lattner510ab612006-07-20 04:47:30 +0000515 // Common paste case: identifier+identifier = identifier. Avoid creating
516 // a lexer and other overhead.
517 PP.IncrementPasteCounter(true);
518 Result.StartToken();
519 Result.SetKind(tok::identifier);
520 Result.SetLocation(ResultTokLoc);
521 Result.SetLength(LHSLen+RHSLen);
Chris Lattnera7e2e742006-07-19 06:32:35 +0000522 } else {
Chris Lattner510ab612006-07-20 04:47:30 +0000523 PP.IncrementPasteCounter(false);
524
Chris Lattnera7e2e742006-07-19 06:32:35 +0000525 // Make a lexer to lex this string from.
526 SourceManager &SourceMgr = PP.getSourceManager();
527 const char *ResultStrData = SourceMgr.getCharacterData(ResultTokLoc);
528
529 unsigned FileID = ResultTokLoc.getFileID();
530 assert(FileID && "Could not get FileID for paste?");
531
532 // Make a lexer object so that we lex and expand the paste result.
533 Lexer *TL = new Lexer(SourceMgr.getBuffer(FileID), FileID, PP,
534 ResultStrData,
535 ResultStrData+LHSLen+RHSLen /*don't include null*/);
536
537 // Lex a token in raw mode. This way it won't look up identifiers
538 // automatically, lexing off the end will return an eof token, and
539 // warnings are disabled. This returns true if the result token is the
540 // entire buffer.
541 bool IsComplete = TL->LexRawToken(Result);
542
543 // If we got an EOF token, we didn't form even ONE token. For example, we
544 // did "/ ## /" to get "//".
545 IsComplete &= Result.getKind() != tok::eof;
546 isInvalid = !IsComplete;
547
548 // We're now done with the temporary lexer.
549 delete TL;
550 }
Chris Lattner01ecf832006-07-19 05:42:48 +0000551
552 // If pasting the two tokens didn't form a full new token, this is an error.
Chris Lattnera7e2e742006-07-19 06:32:35 +0000553 // This occurs with "x ## +" and other stuff. Return with Tok unmodified
554 // and with RHS as the next token to lex.
555 if (isInvalid) {
Chris Lattner01ecf832006-07-19 05:42:48 +0000556 // If not in assembler language mode.
557 PP.Diag(PasteOpLoc, diag::err_pp_bad_paste,
558 std::string(Buffer, Buffer+LHSLen+RHSLen));
559 return;
560 }
561
562 // Turn ## into 'other' to avoid # ## # from looking like a paste operator.
563 if (Result.getKind() == tok::hashhash)
564 Result.SetKind(tok::unknown);
565 // FIXME: Turn __VARRGS__ into "not a token"?
566
567 // Transfer properties of the LHS over the the Result.
568 Result.SetFlagValue(LexerToken::StartOfLine , Tok.isAtStartOfLine());
569 Result.SetFlagValue(LexerToken::LeadingSpace, Tok.hasLeadingSpace());
570
571 // Finally, replace LHS with the result, consume the RHS, and iterate.
572 ++CurToken;
573 Tok = Result;
Chris Lattner70216572006-07-26 03:50:40 +0000574 } while (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash);
Chris Lattner0f1f5052006-07-20 04:16:23 +0000575
576 // Now that we got the result token, it will be subject to expansion. Since
577 // token pasting re-lexes the result token in raw mode, identifier information
578 // isn't looked up. As such, if the result is an identifier, look up id info.
579 if (Tok.getKind() == tok::identifier) {
580 // Look up the identifier info for the token. We disabled identifier lookup
581 // by saying we're skipping contents, so we need to do this manually.
582 Tok.SetIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
583 }
Chris Lattner01ecf832006-07-19 05:42:48 +0000584}
585
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000586/// isNextTokenLParen - If the next token lexed will pop this macro off the
587/// expansion stack, return 2. If the next unexpanded token is a '(', return
588/// 1, otherwise return 0.
589unsigned MacroExpander::isNextTokenLParen() const {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000590 // Out of tokens?
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000591 if (isAtEnd())
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000592 return 2;
Chris Lattner70216572006-07-26 03:50:40 +0000593 return MacroTokens[CurToken].getKind() == tok::l_paren;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000594}