blob: daf0c555ade64f8abcec43579e2c7efdbc4c3e05 [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 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 Lattnerc1410dc2006-07-26 05:22:49 +000027/// MacroArgs ctor function - This destroys the vector passed in.
28MacroArgs *MacroArgs::create(const MacroInfo *MI,
Chris Lattner7a4af3b2006-07-26 06:26:52 +000029 const LexerToken *UnexpArgTokens,
Chris Lattner775d8322006-07-29 04:39:41 +000030 unsigned NumToks, bool VarargsElided) {
Chris Lattner78186052006-07-09 00:45:31 +000031 assert(MI->isFunctionLike() &&
Chris Lattneree8760b2006-07-15 07:42:55 +000032 "Can't have args for an object-like macro!");
Chris Lattnerc1410dc2006-07-26 05:22:49 +000033
34 // Allocate memory for the MacroArgs object with the lexer tokens at the end.
Chris Lattnerc1410dc2006-07-26 05:22:49 +000035 MacroArgs *Result = (MacroArgs*)malloc(sizeof(MacroArgs) +
36 NumToks*sizeof(LexerToken));
37 // Construct the macroargs object.
Chris Lattner775d8322006-07-29 04:39:41 +000038 new (Result) MacroArgs(NumToks, VarargsElided);
Chris Lattnerc1410dc2006-07-26 05:22:49 +000039
40 // Copy the actual unexpanded tokens to immediately after the result ptr.
41 if (NumToks)
42 memcpy(const_cast<LexerToken*>(Result->getUnexpArgument(0)),
Chris Lattner7a4af3b2006-07-26 06:26:52 +000043 UnexpArgTokens, NumToks*sizeof(LexerToken));
Chris Lattnerc1410dc2006-07-26 05:22:49 +000044
45 return Result;
Chris Lattner78186052006-07-09 00:45:31 +000046}
47
Chris Lattnerc1410dc2006-07-26 05:22:49 +000048/// destroy - Destroy and deallocate the memory for this object.
49///
50void MacroArgs::destroy() {
51 // Run the dtor to deallocate the vectors.
52 this->~MacroArgs();
53 // Release the memory for the object.
54 free(this);
55}
56
57
Chris Lattner6fc08bc2006-07-26 04:55:32 +000058/// getArgLength - Given a pointer to an expanded or unexpanded argument,
59/// return the number of tokens, not counting the EOF, that make up the
60/// argument.
61unsigned MacroArgs::getArgLength(const LexerToken *ArgPtr) {
62 unsigned NumArgTokens = 0;
63 for (; ArgPtr->getKind() != tok::eof; ++ArgPtr)
64 ++NumArgTokens;
65 return NumArgTokens;
66}
67
68
Chris Lattner36b6e812006-07-21 06:38:30 +000069/// getUnexpArgument - Return the unexpanded tokens for the specified formal.
70///
71const LexerToken *MacroArgs::getUnexpArgument(unsigned Arg) const {
Chris Lattnerc1410dc2006-07-26 05:22:49 +000072 // The unexpanded argument tokens start immediately after the MacroArgs object
73 // in memory.
74 const LexerToken *Start = (const LexerToken *)(this+1);
Chris Lattner36b6e812006-07-21 06:38:30 +000075 const LexerToken *Result = Start;
Chris Lattnerc1410dc2006-07-26 05:22:49 +000076 // Scan to find Arg.
Chris Lattner36b6e812006-07-21 06:38:30 +000077 for (; Arg; ++Result) {
Chris Lattnerc1410dc2006-07-26 05:22:49 +000078 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
Chris Lattner36b6e812006-07-21 06:38:30 +000079 if (Result->getKind() == tok::eof)
80 --Arg;
81 }
82 return Result;
Chris Lattneree8760b2006-07-15 07:42:55 +000083}
84
Chris Lattner36b6e812006-07-21 06:38:30 +000085
Chris Lattner203b4562006-07-15 21:07:40 +000086/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
87/// by pre-expansion, return false. Otherwise, conservatively return true.
Chris Lattner36b6e812006-07-21 06:38:30 +000088bool MacroArgs::ArgNeedsPreexpansion(const LexerToken *ArgTok) const {
Chris Lattner203b4562006-07-15 21:07:40 +000089 // If there are no identifiers in the argument list, or if the identifiers are
90 // known to not be macros, pre-expansion won't modify it.
Chris Lattner36b6e812006-07-21 06:38:30 +000091 for (; ArgTok->getKind() != tok::eof; ++ArgTok)
92 if (IdentifierInfo *II = ArgTok->getIdentifierInfo()) {
Chris Lattner203b4562006-07-15 21:07:40 +000093 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled())
94 // Return true even though the macro could be a function-like macro
95 // without a following '(' token.
96 return true;
97 }
98 return false;
99}
100
Chris Lattner7667d0d2006-07-16 18:16:58 +0000101/// getPreExpArgument - Return the pre-expanded form of the specified
102/// argument.
103const std::vector<LexerToken> &
104MacroArgs::getPreExpArgument(unsigned Arg, Preprocessor &PP) {
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000105 assert(Arg < NumUnexpArgTokens && "Invalid argument number!");
Chris Lattner7667d0d2006-07-16 18:16:58 +0000106
107 // If we have already computed this, return it.
108 if (PreExpArgTokens.empty())
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000109 PreExpArgTokens.resize(NumUnexpArgTokens);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000110
111 std::vector<LexerToken> &Result = PreExpArgTokens[Arg];
112 if (!Result.empty()) return Result;
113
Chris Lattner36b6e812006-07-21 06:38:30 +0000114 const LexerToken *AT = getUnexpArgument(Arg);
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000115 unsigned NumToks = getArgLength(AT)+1; // Include the EOF.
Chris Lattner36b6e812006-07-21 06:38:30 +0000116
Chris Lattner7667d0d2006-07-16 18:16:58 +0000117 // Otherwise, we have to pre-expand this argument, populating Result. To do
118 // this, we set up a fake MacroExpander to lex from the unexpanded argument
119 // list. With this installed, we lex expanded tokens until we hit the EOF
120 // token at the end of the unexp list.
Chris Lattner70216572006-07-26 03:50:40 +0000121 PP.EnterTokenStream(AT, NumToks);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000122
123 // Lex all of the macro-expanded tokens into Result.
124 do {
125 Result.push_back(LexerToken());
126 PP.Lex(Result.back());
127 } while (Result.back().getKind() != tok::eof);
128
129 // Pop the token stream off the top of the stack. We know that the internal
130 // pointer inside of it is to the "end" of the token stream, but the stack
131 // will not otherwise be popped until the next token is lexed. The problem is
132 // that the token may be lexed sometime after the vector of tokens itself is
133 // destroyed, which would be badness.
134 PP.RemoveTopOfLexerStack();
135 return Result;
136}
137
Chris Lattneree8760b2006-07-15 07:42:55 +0000138
Chris Lattner0707bd32006-07-15 05:23:58 +0000139/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
140/// tokens into the literal string token that should be produced by the C #
141/// preprocessor operator.
142///
Chris Lattner36b6e812006-07-21 06:38:30 +0000143static LexerToken StringifyArgument(const LexerToken *ArgToks,
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000144 Preprocessor &PP, bool Charify = false) {
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000145 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000146 Tok.startToken();
147 Tok.setKind(tok::string_literal);
Chris Lattner0707bd32006-07-15 05:23:58 +0000148
Chris Lattner36b6e812006-07-21 06:38:30 +0000149 const LexerToken *ArgTokStart = ArgToks;
150
Chris Lattner0707bd32006-07-15 05:23:58 +0000151 // Stringify all the tokens.
152 std::string Result = "\"";
Chris Lattner7667d0d2006-07-16 18:16:58 +0000153 // FIXME: Optimize this loop to not use std::strings.
Chris Lattner36b6e812006-07-21 06:38:30 +0000154 bool isFirst = true;
155 for (; ArgToks->getKind() != tok::eof; ++ArgToks) {
156 const LexerToken &Tok = *ArgToks;
157 if (!isFirst && Tok.hasLeadingSpace())
Chris Lattner0707bd32006-07-15 05:23:58 +0000158 Result += ' ';
Chris Lattner36b6e812006-07-21 06:38:30 +0000159 isFirst = false;
Chris Lattner0707bd32006-07-15 05:23:58 +0000160
161 // If this is a string or character constant, escape the token as specified
162 // by 6.10.3.2p2.
Chris Lattnerd3e98952006-10-06 05:22:26 +0000163 if (Tok.getKind() == tok::string_literal || // "foo"
164 Tok.getKind() == tok::wide_string_literal || // L"foo"
165 Tok.getKind() == tok::char_constant) { // 'x' and L'x'.
Chris Lattner0707bd32006-07-15 05:23:58 +0000166 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 Lattner8c204872006-10-14 05:19:21 +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 Lattner95a06b32006-07-30 08:40:43 +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 Lattner479b0af2006-07-29 04:16:20 +0000295
296 // NextTokGetsSpace - When this is true, the next token appended to the
297 // output list will get a leading space, regardless of whether it had one to
298 // begin with or not. This is used for placemarker support.
299 bool NextTokGetsSpace = false;
300
Chris Lattner70216572006-07-26 03:50:40 +0000301 for (unsigned i = 0, e = NumMacroTokens; i != e; ++i) {
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000302 // If we found the stringify operator, get the argument stringified. The
303 // preprocessor already verified that the following token is a macro name
304 // when the #define was parsed.
Chris Lattner70216572006-07-26 03:50:40 +0000305 const LexerToken &CurTok = MacroTokens[i];
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000306 if (CurTok.getKind() == tok::hash || CurTok.getKind() == tok::hashat) {
Chris Lattner70216572006-07-26 03:50:40 +0000307 int ArgNo = Macro->getArgumentNum(MacroTokens[i+1].getIdentifierInfo());
Chris Lattner95a06b32006-07-30 08:40:43 +0000308 assert(ArgNo != -1 && "Token following # is not an argument?");
309
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000310 LexerToken Res;
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000311 if (CurTok.getKind() == tok::hash) // Stringify
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000312 Res = ActualArgs->getStringifiedArgument(ArgNo, PP);
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000313 else {
314 // 'charify': don't bother caching these.
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000315 Res = StringifyArgument(ActualArgs->getUnexpArgument(ArgNo), PP, true);
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000316 }
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000317
Chris Lattner60161692006-07-15 06:48:02 +0000318 // The stringified/charified string leading space flag gets set to match
319 // the #/#@ operator.
Chris Lattner479b0af2006-07-29 04:16:20 +0000320 if (CurTok.hasLeadingSpace() || NextTokGetsSpace)
Chris Lattner8c204872006-10-14 05:19:21 +0000321 Res.setFlag(LexerToken::LeadingSpace);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000322
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000323 ResultToks.push_back(Res);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000324 MadeChange = true;
325 ++i; // Skip arg name.
Chris Lattner479b0af2006-07-29 04:16:20 +0000326 NextTokGetsSpace = false;
Chris Lattnera9dc5972006-07-28 05:07:04 +0000327 continue;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000328 }
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000329
330 // Otherwise, if this is not an argument token, just add the token to the
331 // output buffer.
332 IdentifierInfo *II = CurTok.getIdentifierInfo();
333 int ArgNo = II ? Macro->getArgumentNum(II) : -1;
334 if (ArgNo == -1) {
Chris Lattner95a06b32006-07-30 08:40:43 +0000335 // This isn't an argument, just add it.
336 ResultToks.push_back(CurTok);
Chris Lattner479b0af2006-07-29 04:16:20 +0000337
Chris Lattner95a06b32006-07-30 08:40:43 +0000338 if (NextTokGetsSpace) {
Chris Lattner8c204872006-10-14 05:19:21 +0000339 ResultToks.back().setFlag(LexerToken::LeadingSpace);
Chris Lattner95a06b32006-07-30 08:40:43 +0000340 NextTokGetsSpace = false;
Chris Lattner21c8b8f2006-07-29 04:04:22 +0000341 }
Chris Lattner95a06b32006-07-30 08:40:43 +0000342 continue;
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000343 }
344
345 // An argument is expanded somehow, the result is different than the
346 // input.
347 MadeChange = true;
348
349 // Otherwise, this is a use of the argument. Find out if there is a paste
350 // (##) operator before or after the argument.
351 bool PasteBefore =
352 !ResultToks.empty() && ResultToks.back().getKind() == tok::hashhash;
353 bool PasteAfter = i+1 != e && MacroTokens[i+1].getKind() == tok::hashhash;
354
355 // If it is not the LHS/RHS of a ## operator, we must pre-expand the
356 // argument and substitute the expanded tokens into the result. This is
357 // C99 6.10.3.1p1.
358 if (!PasteBefore && !PasteAfter) {
359 const LexerToken *ResultArgToks;
360
361 // Only preexpand the argument if it could possibly need it. This
362 // avoids some work in common cases.
363 const LexerToken *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
364 if (ActualArgs->ArgNeedsPreexpansion(ArgTok))
365 ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0];
366 else
367 ResultArgToks = ArgTok; // Use non-preexpanded tokens.
368
369 // If the arg token expanded into anything, append it.
370 if (ResultArgToks->getKind() != tok::eof) {
371 unsigned FirstResult = ResultToks.size();
372 unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
373 ResultToks.append(ResultArgToks, ResultArgToks+NumToks);
374
375 // If any tokens were substituted from the argument, the whitespace
376 // before the first token should match the whitespace of the arg
377 // identifier.
Chris Lattner8c204872006-10-14 05:19:21 +0000378 ResultToks[FirstResult].setFlagValue(LexerToken::LeadingSpace,
Chris Lattner479b0af2006-07-29 04:16:20 +0000379 CurTok.hasLeadingSpace() ||
380 NextTokGetsSpace);
381 NextTokGetsSpace = false;
382 } else {
383 // If this is an empty argument, and if there was whitespace before the
384 // formal token, make sure the next token gets whitespace before it.
385 NextTokGetsSpace = CurTok.hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000386 }
387 continue;
388 }
389
390 // Okay, we have a token that is either the LHS or RHS of a paste (##)
391 // argument. It gets substituted as its non-pre-expanded tokens.
392 const LexerToken *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
393 unsigned NumToks = MacroArgs::getArgLength(ArgToks);
394 if (NumToks) { // Not an empty argument?
395 ResultToks.append(ArgToks, ArgToks+NumToks);
Chris Lattner479b0af2006-07-29 04:16:20 +0000396
397 // If the next token was supposed to get leading whitespace, ensure it has
398 // it now.
399 if (NextTokGetsSpace) {
Chris Lattner8c204872006-10-14 05:19:21 +0000400 ResultToks[ResultToks.size()-NumToks].setFlag(LexerToken::LeadingSpace);
Chris Lattner479b0af2006-07-29 04:16:20 +0000401 NextTokGetsSpace = false;
402 }
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000403 continue;
404 }
405
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000406 // If an empty argument is on the LHS or RHS of a paste, the standard (C99
407 // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur. We
408 // implement this by eating ## operators when a LHS or RHS expands to
409 // empty.
Chris Lattner479b0af2006-07-29 04:16:20 +0000410 NextTokGetsSpace |= CurTok.hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000411 if (PasteAfter) {
412 // Discard the argument token and skip (don't copy to the expansion
413 // buffer) the paste operator after it.
Chris Lattner479b0af2006-07-29 04:16:20 +0000414 NextTokGetsSpace |= MacroTokens[i+1].hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000415 ++i;
416 continue;
417 }
418
419 // If this is on the RHS of a paste operator, we've already copied the
420 // paste operator to the ResultToks list. Remove it.
421 assert(PasteBefore && ResultToks.back().getKind() == tok::hashhash);
Chris Lattner479b0af2006-07-29 04:16:20 +0000422 NextTokGetsSpace |= ResultToks.back().hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000423 ResultToks.pop_back();
Chris Lattner775d8322006-07-29 04:39:41 +0000424
425 // If this is the __VA_ARGS__ token, and if the argument wasn't provided,
426 // and if the macro had at least one real argument, and if the token before
427 // the ## was a comma, remove the comma.
Chris Lattner95a06b32006-07-30 08:40:43 +0000428 if ((unsigned)ArgNo == Macro->getNumArgs()-1 && // is __VA_ARGS__
Chris Lattner775d8322006-07-29 04:39:41 +0000429 ActualArgs->isVarargsElidedUse() && // Argument elided.
430 !ResultToks.empty() && ResultToks.back().getKind() == tok::comma) {
431 // Never add a space, even if the comma, ##, or arg had a space.
432 NextTokGetsSpace = false;
433 ResultToks.pop_back();
434 }
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000435 continue;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000436 }
437
438 // If anything changed, install this as the new MacroTokens list.
439 if (MadeChange) {
440 // This is deleted in the dtor.
Chris Lattner70216572006-07-26 03:50:40 +0000441 NumMacroTokens = ResultToks.size();
442 LexerToken *Res = new LexerToken[ResultToks.size()];
Chris Lattnerd97d2e72006-07-29 06:44:29 +0000443 if (NumMacroTokens)
444 memcpy(Res, &ResultToks[0], NumMacroTokens*sizeof(LexerToken));
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000445 MacroTokens = Res;
446 }
447}
Chris Lattner67b07cb2006-06-26 02:03:42 +0000448
Chris Lattner22eb9722006-06-18 05:43:12 +0000449/// Lex - Lex and return a token from this macro stream.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000450///
Chris Lattnercb283342006-06-18 06:48:37 +0000451void MacroExpander::Lex(LexerToken &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000452 // Lexing off the end of the macro, pop this macro off the expansion stack.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000453 if (isAtEnd()) {
454 // If this is a macro (not a token stream), mark the macro enabled now
455 // that it is no longer being expanded.
456 if (Macro) Macro->EnableMacro();
457
458 // Pop this context off the preprocessors lexer stack and get the next
Chris Lattner2183a6e2006-07-18 06:36:12 +0000459 // token. This will delete "this" so remember the PP instance var.
460 Preprocessor &PPCache = PP;
461 if (PP.HandleEndOfMacro(Tok))
462 return;
463
464 // HandleEndOfMacro may not return a token. If it doesn't, lex whatever is
465 // next.
466 return PPCache.Lex(Tok);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000467 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000468
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000469 // If this is the first token of the expanded result, we inherit spacing
470 // properties later.
471 bool isFirstToken = CurToken == 0;
472
Chris Lattner22eb9722006-06-18 05:43:12 +0000473 // Get the next token to return.
Chris Lattner70216572006-07-26 03:50:40 +0000474 Tok = MacroTokens[CurToken++];
Chris Lattner01ecf832006-07-19 05:42:48 +0000475
476 // If this token is followed by a token paste (##) operator, paste the tokens!
Chris Lattner70216572006-07-26 03:50:40 +0000477 if (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash)
Chris Lattner01ecf832006-07-19 05:42:48 +0000478 PasteTokens(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000479
Chris Lattnerc673f902006-06-30 06:10:41 +0000480 // The token's current location indicate where the token was lexed from. We
481 // need this information to compute the spelling of the token, but any
482 // diagnostics for the expanded token should appear as if they came from
483 // InstantiationLoc. Pull this information together into a new SourceLocation
484 // that captures all of this.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000485 if (InstantiateLoc.isValid()) { // Don't do this for token streams.
486 SourceManager &SrcMgr = PP.getSourceManager();
487 // The token could have come from a prior macro expansion. In that case,
488 // ignore the macro expand part to get to the physloc. This happens for
489 // stuff like: #define A(X) X A(A(X)) A(1)
490 SourceLocation PhysLoc = SrcMgr.getPhysicalLoc(Tok.getLocation());
Chris Lattner8c204872006-10-14 05:19:21 +0000491 Tok.setLocation(SrcMgr.getInstantiationLoc(PhysLoc, InstantiateLoc));
Chris Lattner7667d0d2006-07-16 18:16:58 +0000492 }
493
Chris Lattner22eb9722006-06-18 05:43:12 +0000494 // If this is the first token, set the lexical properties of the token to
495 // match the lexical properties of the macro identifier.
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000496 if (isFirstToken) {
Chris Lattner8c204872006-10-14 05:19:21 +0000497 Tok.setFlagValue(LexerToken::StartOfLine , AtStartOfLine);
498 Tok.setFlagValue(LexerToken::LeadingSpace, HasLeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +0000499 }
500
501 // Handle recursive expansion!
502 if (Tok.getIdentifierInfo())
503 return PP.HandleIdentifier(Tok);
504
505 // Otherwise, return a normal token.
Chris Lattner22eb9722006-06-18 05:43:12 +0000506}
Chris Lattnerafe603f2006-07-11 04:02:46 +0000507
Chris Lattner01ecf832006-07-19 05:42:48 +0000508/// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ##
509/// operator. Read the ## and RHS, and paste the LHS/RHS together. If there
510/// are is another ## after it, chomp it iteratively. Return the result as Tok.
511void MacroExpander::PasteTokens(LexerToken &Tok) {
Chris Lattner57dd8362006-11-03 07:45:04 +0000512 SmallVector<char, 128> Buffer;
Chris Lattner01ecf832006-07-19 05:42:48 +0000513 do {
514 // Consume the ## operator.
Chris Lattner70216572006-07-26 03:50:40 +0000515 SourceLocation PasteOpLoc = MacroTokens[CurToken].getLocation();
Chris Lattner01ecf832006-07-19 05:42:48 +0000516 ++CurToken;
517 assert(!isAtEnd() && "No token on the RHS of a paste operator!");
518
519 // Get the RHS token.
Chris Lattner70216572006-07-26 03:50:40 +0000520 const LexerToken &RHS = MacroTokens[CurToken];
Chris Lattner01ecf832006-07-19 05:42:48 +0000521
522 bool isInvalid = false;
523
Chris Lattner01ecf832006-07-19 05:42:48 +0000524 // Allocate space for the result token. This is guaranteed to be enough for
525 // the two tokens and a null terminator.
Chris Lattner57dd8362006-11-03 07:45:04 +0000526 Buffer.resize(Tok.getLength() + RHS.getLength() + 1);
Chris Lattner01ecf832006-07-19 05:42:48 +0000527
528 // Get the spelling of the LHS token in Buffer.
Chris Lattner57dd8362006-11-03 07:45:04 +0000529 const char *BufPtr = &Buffer[0];
Chris Lattner01ecf832006-07-19 05:42:48 +0000530 unsigned LHSLen = PP.getSpelling(Tok, BufPtr);
Chris Lattner57dd8362006-11-03 07:45:04 +0000531 if (BufPtr != &Buffer[0]) // Really, we want the chars in Buffer!
532 memcpy(&Buffer[0], BufPtr, LHSLen);
Chris Lattner01ecf832006-07-19 05:42:48 +0000533
Chris Lattner57dd8362006-11-03 07:45:04 +0000534 BufPtr = &Buffer[LHSLen];
Chris Lattner01ecf832006-07-19 05:42:48 +0000535 unsigned RHSLen = PP.getSpelling(RHS, BufPtr);
Chris Lattner57dd8362006-11-03 07:45:04 +0000536 if (BufPtr != &Buffer[LHSLen]) // Really, we want the chars in Buffer!
537 memcpy(&Buffer[LHSLen], BufPtr, RHSLen);
Chris Lattner01ecf832006-07-19 05:42:48 +0000538
539 // Add null terminator.
540 Buffer[LHSLen+RHSLen] = '\0';
541
Chris Lattner57dd8362006-11-03 07:45:04 +0000542 // Trim excess space.
543 Buffer.resize(LHSLen+RHSLen+1);
544
Chris Lattner01ecf832006-07-19 05:42:48 +0000545 // Plop the pasted result (including the trailing newline and null) into a
546 // scratch buffer where we can lex it.
Chris Lattner57dd8362006-11-03 07:45:04 +0000547 SourceLocation ResultTokLoc = PP.CreateString(&Buffer[0], Buffer.size());
Chris Lattner01ecf832006-07-19 05:42:48 +0000548
549 // Lex the resultant pasted token into Result.
550 LexerToken Result;
551
Chris Lattnera7e2e742006-07-19 06:32:35 +0000552 // Avoid testing /*, as the lexer would think it is the start of a comment
553 // and emit an error that it is unterminated.
554 if (Tok.getKind() == tok::slash && RHS.getKind() == tok::star) {
555 isInvalid = true;
Chris Lattner510ab612006-07-20 04:47:30 +0000556 } else if (Tok.getKind() == tok::identifier &&
Chris Lattner08ba4c02006-07-20 04:52:59 +0000557 RHS.getKind() == tok::identifier) {
Chris Lattner510ab612006-07-20 04:47:30 +0000558 // Common paste case: identifier+identifier = identifier. Avoid creating
559 // a lexer and other overhead.
560 PP.IncrementPasteCounter(true);
Chris Lattner8c204872006-10-14 05:19:21 +0000561 Result.startToken();
562 Result.setKind(tok::identifier);
563 Result.setLocation(ResultTokLoc);
564 Result.setLength(LHSLen+RHSLen);
Chris Lattnera7e2e742006-07-19 06:32:35 +0000565 } else {
Chris Lattner510ab612006-07-20 04:47:30 +0000566 PP.IncrementPasteCounter(false);
567
Chris Lattnera7e2e742006-07-19 06:32:35 +0000568 // Make a lexer to lex this string from.
569 SourceManager &SourceMgr = PP.getSourceManager();
570 const char *ResultStrData = SourceMgr.getCharacterData(ResultTokLoc);
571
572 unsigned FileID = ResultTokLoc.getFileID();
573 assert(FileID && "Could not get FileID for paste?");
574
575 // Make a lexer object so that we lex and expand the paste result.
576 Lexer *TL = new Lexer(SourceMgr.getBuffer(FileID), FileID, PP,
577 ResultStrData,
578 ResultStrData+LHSLen+RHSLen /*don't include null*/);
579
580 // Lex a token in raw mode. This way it won't look up identifiers
581 // automatically, lexing off the end will return an eof token, and
582 // warnings are disabled. This returns true if the result token is the
583 // entire buffer.
584 bool IsComplete = TL->LexRawToken(Result);
585
586 // If we got an EOF token, we didn't form even ONE token. For example, we
587 // did "/ ## /" to get "//".
588 IsComplete &= Result.getKind() != tok::eof;
589 isInvalid = !IsComplete;
590
591 // We're now done with the temporary lexer.
592 delete TL;
593 }
Chris Lattner01ecf832006-07-19 05:42:48 +0000594
595 // If pasting the two tokens didn't form a full new token, this is an error.
Chris Lattnera7e2e742006-07-19 06:32:35 +0000596 // This occurs with "x ## +" and other stuff. Return with Tok unmodified
597 // and with RHS as the next token to lex.
598 if (isInvalid) {
Chris Lattner01ecf832006-07-19 05:42:48 +0000599 // If not in assembler language mode.
600 PP.Diag(PasteOpLoc, diag::err_pp_bad_paste,
Chris Lattner57dd8362006-11-03 07:45:04 +0000601 std::string(Buffer.begin(), Buffer.end()-1));
Chris Lattner01ecf832006-07-19 05:42:48 +0000602 return;
603 }
604
605 // Turn ## into 'other' to avoid # ## # from looking like a paste operator.
606 if (Result.getKind() == tok::hashhash)
Chris Lattner8c204872006-10-14 05:19:21 +0000607 Result.setKind(tok::unknown);
Chris Lattner01ecf832006-07-19 05:42:48 +0000608 // FIXME: Turn __VARRGS__ into "not a token"?
609
610 // Transfer properties of the LHS over the the Result.
Chris Lattner8c204872006-10-14 05:19:21 +0000611 Result.setFlagValue(LexerToken::StartOfLine , Tok.isAtStartOfLine());
612 Result.setFlagValue(LexerToken::LeadingSpace, Tok.hasLeadingSpace());
Chris Lattner01ecf832006-07-19 05:42:48 +0000613
614 // Finally, replace LHS with the result, consume the RHS, and iterate.
615 ++CurToken;
616 Tok = Result;
Chris Lattner70216572006-07-26 03:50:40 +0000617 } while (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash);
Chris Lattner0f1f5052006-07-20 04:16:23 +0000618
619 // Now that we got the result token, it will be subject to expansion. Since
620 // token pasting re-lexes the result token in raw mode, identifier information
621 // isn't looked up. As such, if the result is an identifier, look up id info.
622 if (Tok.getKind() == tok::identifier) {
623 // Look up the identifier info for the token. We disabled identifier lookup
624 // by saying we're skipping contents, so we need to do this manually.
Chris Lattner8c204872006-10-14 05:19:21 +0000625 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
Chris Lattner0f1f5052006-07-20 04:16:23 +0000626 }
Chris Lattner01ecf832006-07-19 05:42:48 +0000627}
628
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000629/// isNextTokenLParen - If the next token lexed will pop this macro off the
630/// expansion stack, return 2. If the next unexpanded token is a '(', return
631/// 1, otherwise return 0.
632unsigned MacroExpander::isNextTokenLParen() const {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000633 // Out of tokens?
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000634 if (isAtEnd())
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000635 return 2;
Chris Lattner70216572006-07-26 03:50:40 +0000636 return MacroTokens[CurToken].getKind() == tok::l_paren;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000637}