blob: a7a645d96f7cff1fa242c2d3567abeee9508ef3e [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,
Chris Lattner775d8322006-07-29 04:39:41 +000031 unsigned NumToks, bool VarargsElided) {
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.
Chris Lattner775d8322006-07-29 04:39:41 +000039 new (Result) MacroArgs(NumToks, VarargsElided);
Chris Lattnerc1410dc2006-07-26 05:22:49 +000040
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;
Chris Lattner8c204872006-10-14 05:19:21 +0000147 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.
Chris Lattnerd3e98952006-10-06 05:22:26 +0000164 if (Tok.getKind() == tok::string_literal || // "foo"
165 Tok.getKind() == tok::wide_string_literal || // L"foo"
166 Tok.getKind() == tok::char_constant) { // 'x' and L'x'.
Chris Lattner0707bd32006-07-15 05:23:58 +0000167 Result += Lexer::Stringify(PP.getSpelling(Tok));
168 } else {
169 // Otherwise, just append the token.
170 Result += PP.getSpelling(Tok);
171 }
172 }
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000173
Chris Lattner0707bd32006-07-15 05:23:58 +0000174 // If the last character of the string is a \, and if it isn't escaped, this
175 // is an invalid string literal, diagnose it as specified in C99.
176 if (Result[Result.size()-1] == '\\') {
177 // Count the number of consequtive \ characters. If even, then they are
178 // just escaped backslashes, otherwise it's an error.
179 unsigned FirstNonSlash = Result.size()-2;
180 // Guaranteed to find the starting " if nothing else.
181 while (Result[FirstNonSlash] == '\\')
182 --FirstNonSlash;
183 if ((Result.size()-1-FirstNonSlash) & 1) {
Chris Lattnerf2781502006-07-15 05:27:44 +0000184 // Diagnose errors for things like: #define F(X) #X / F(\)
Chris Lattner36b6e812006-07-21 06:38:30 +0000185 PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
Chris Lattner0707bd32006-07-15 05:23:58 +0000186 Result.erase(Result.end()-1); // remove one of the \'s.
187 }
188 }
Chris Lattner0707bd32006-07-15 05:23:58 +0000189 Result += '"';
190
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000191 // If this is the charify operation and the result is not a legal character
192 // constant, diagnose it.
193 if (Charify) {
194 // First step, turn double quotes into single quotes:
195 Result[0] = '\'';
196 Result[Result.size()-1] = '\'';
197
198 // Check for bogus character.
199 bool isBad = false;
Chris Lattner2ada5d32006-07-15 07:51:24 +0000200 if (Result.size() == 3) {
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000201 isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
202 } else {
203 isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
204 }
205
206 if (isBad) {
Chris Lattner36b6e812006-07-21 06:38:30 +0000207 PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
Chris Lattner7c581492006-07-15 07:56:31 +0000208 Result = "' '"; // Use something arbitrary, but legal.
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000209 }
210 }
211
Chris Lattner8c204872006-10-14 05:19:21 +0000212 Tok.setLength(Result.size());
213 Tok.setLocation(PP.CreateString(&Result[0], Result.size()));
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000214 return Tok;
215}
216
217/// getStringifiedArgument - Compute, cache, and return the specified argument
218/// that has been 'stringified' as required by the # operator.
Chris Lattneree8760b2006-07-15 07:42:55 +0000219const LexerToken &MacroArgs::getStringifiedArgument(unsigned ArgNo,
220 Preprocessor &PP) {
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000221 assert(ArgNo < NumUnexpArgTokens && "Invalid argument number!");
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000222 if (StringifiedArgs.empty()) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000223 StringifiedArgs.resize(getNumArguments());
Chris Lattneree8760b2006-07-15 07:42:55 +0000224 memset(&StringifiedArgs[0], 0,
225 sizeof(StringifiedArgs[0])*getNumArguments());
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000226 }
227 if (StringifiedArgs[ArgNo].getKind() != tok::string_literal)
Chris Lattner36b6e812006-07-21 06:38:30 +0000228 StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000229 return StringifiedArgs[ArgNo];
230}
231
Chris Lattner78186052006-07-09 00:45:31 +0000232//===----------------------------------------------------------------------===//
233// MacroExpander Implementation
234//===----------------------------------------------------------------------===//
235
Chris Lattner7667d0d2006-07-16 18:16:58 +0000236/// Create a macro expander for the specified macro with the specified actual
237/// arguments. Note that this ctor takes ownership of the ActualArgs pointer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000238MacroExpander::MacroExpander(LexerToken &Tok, MacroArgs *Actuals,
Chris Lattner78186052006-07-09 00:45:31 +0000239 Preprocessor &pp)
Chris Lattner7667d0d2006-07-16 18:16:58 +0000240 : Macro(Tok.getIdentifierInfo()->getMacroInfo()),
Chris Lattneree8760b2006-07-15 07:42:55 +0000241 ActualArgs(Actuals), PP(pp), CurToken(0),
Chris Lattner50b497e2006-06-18 16:32:35 +0000242 InstantiateLoc(Tok.getLocation()),
Chris Lattnerd01e2912006-06-18 16:22:51 +0000243 AtStartOfLine(Tok.isAtStartOfLine()),
244 HasLeadingSpace(Tok.hasLeadingSpace()) {
Chris Lattner70216572006-07-26 03:50:40 +0000245 MacroTokens = &Macro->getReplacementTokens()[0];
246 NumMacroTokens = Macro->getReplacementTokens().size();
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000247
248 // If this is a function-like macro, expand the arguments and change
249 // MacroTokens to point to the expanded tokens.
Chris Lattner95a06b32006-07-30 08:40:43 +0000250 if (Macro->isFunctionLike() && Macro->getNumArgs())
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000251 ExpandFunctionArguments();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000252
253 // Mark the macro as currently disabled, so that it is not recursively
254 // expanded. The macro must be disabled only after argument pre-expansion of
255 // function-like macro arguments occurs.
256 Macro->DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000257}
258
Chris Lattner7667d0d2006-07-16 18:16:58 +0000259/// Create a macro expander for the specified token stream. This does not
260/// take ownership of the specified token vector.
Chris Lattner70216572006-07-26 03:50:40 +0000261MacroExpander::MacroExpander(const LexerToken *TokArray, unsigned NumToks,
Chris Lattner7667d0d2006-07-16 18:16:58 +0000262 Preprocessor &pp)
Chris Lattner70216572006-07-26 03:50:40 +0000263 : Macro(0), ActualArgs(0), PP(pp), MacroTokens(TokArray),
264 NumMacroTokens(NumToks), CurToken(0),
Chris Lattner7667d0d2006-07-16 18:16:58 +0000265 InstantiateLoc(SourceLocation()), AtStartOfLine(false),
266 HasLeadingSpace(false) {
267
268 // Set HasLeadingSpace/AtStartOfLine so that the first token will be
269 // returned unmodified.
Chris Lattner70216572006-07-26 03:50:40 +0000270 if (NumToks != 0) {
271 AtStartOfLine = TokArray[0].isAtStartOfLine();
272 HasLeadingSpace = TokArray[0].hasLeadingSpace();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000273 }
274}
275
276
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000277MacroExpander::~MacroExpander() {
278 // If this was a function-like macro that actually uses its arguments, delete
279 // the expanded tokens.
Chris Lattner70216572006-07-26 03:50:40 +0000280 if (Macro && MacroTokens != &Macro->getReplacementTokens()[0])
281 delete [] MacroTokens;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000282
283 // MacroExpander owns its formal arguments.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000284 if (ActualArgs) ActualArgs->destroy();
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000285}
286
287/// Expand the arguments of a function-like macro so that we can quickly
288/// return preexpanded tokens from MacroTokens.
289void MacroExpander::ExpandFunctionArguments() {
Chris Lattnerb57aa462006-07-27 03:42:15 +0000290 SmallVector<LexerToken, 128> ResultToks;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000291
292 // Loop through the MacroTokens tokens, expanding them into ResultToks. Keep
293 // track of whether we change anything. If not, no need to keep them. If so,
294 // we install the newly expanded sequence as MacroTokens.
295 bool MadeChange = false;
Chris Lattner479b0af2006-07-29 04:16:20 +0000296
297 // NextTokGetsSpace - When this is true, the next token appended to the
298 // output list will get a leading space, regardless of whether it had one to
299 // begin with or not. This is used for placemarker support.
300 bool NextTokGetsSpace = false;
301
Chris Lattner70216572006-07-26 03:50:40 +0000302 for (unsigned i = 0, e = NumMacroTokens; i != e; ++i) {
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000303 // If we found the stringify operator, get the argument stringified. The
304 // preprocessor already verified that the following token is a macro name
305 // when the #define was parsed.
Chris Lattner70216572006-07-26 03:50:40 +0000306 const LexerToken &CurTok = MacroTokens[i];
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000307 if (CurTok.getKind() == tok::hash || CurTok.getKind() == tok::hashat) {
Chris Lattner70216572006-07-26 03:50:40 +0000308 int ArgNo = Macro->getArgumentNum(MacroTokens[i+1].getIdentifierInfo());
Chris Lattner95a06b32006-07-30 08:40:43 +0000309 assert(ArgNo != -1 && "Token following # is not an argument?");
310
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000311 LexerToken Res;
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000312 if (CurTok.getKind() == tok::hash) // Stringify
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000313 Res = ActualArgs->getStringifiedArgument(ArgNo, PP);
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000314 else {
315 // 'charify': don't bother caching these.
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000316 Res = StringifyArgument(ActualArgs->getUnexpArgument(ArgNo), PP, true);
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000317 }
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000318
Chris Lattner60161692006-07-15 06:48:02 +0000319 // The stringified/charified string leading space flag gets set to match
320 // the #/#@ operator.
Chris Lattner479b0af2006-07-29 04:16:20 +0000321 if (CurTok.hasLeadingSpace() || NextTokGetsSpace)
Chris Lattner8c204872006-10-14 05:19:21 +0000322 Res.setFlag(LexerToken::LeadingSpace);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000323
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000324 ResultToks.push_back(Res);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000325 MadeChange = true;
326 ++i; // Skip arg name.
Chris Lattner479b0af2006-07-29 04:16:20 +0000327 NextTokGetsSpace = false;
Chris Lattnera9dc5972006-07-28 05:07:04 +0000328 continue;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000329 }
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000330
331 // Otherwise, if this is not an argument token, just add the token to the
332 // output buffer.
333 IdentifierInfo *II = CurTok.getIdentifierInfo();
334 int ArgNo = II ? Macro->getArgumentNum(II) : -1;
335 if (ArgNo == -1) {
Chris Lattner95a06b32006-07-30 08:40:43 +0000336 // This isn't an argument, just add it.
337 ResultToks.push_back(CurTok);
Chris Lattner479b0af2006-07-29 04:16:20 +0000338
Chris Lattner95a06b32006-07-30 08:40:43 +0000339 if (NextTokGetsSpace) {
Chris Lattner8c204872006-10-14 05:19:21 +0000340 ResultToks.back().setFlag(LexerToken::LeadingSpace);
Chris Lattner95a06b32006-07-30 08:40:43 +0000341 NextTokGetsSpace = false;
Chris Lattner21c8b8f2006-07-29 04:04:22 +0000342 }
Chris Lattner95a06b32006-07-30 08:40:43 +0000343 continue;
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000344 }
345
346 // An argument is expanded somehow, the result is different than the
347 // input.
348 MadeChange = true;
349
350 // Otherwise, this is a use of the argument. Find out if there is a paste
351 // (##) operator before or after the argument.
352 bool PasteBefore =
353 !ResultToks.empty() && ResultToks.back().getKind() == tok::hashhash;
354 bool PasteAfter = i+1 != e && MacroTokens[i+1].getKind() == tok::hashhash;
355
356 // If it is not the LHS/RHS of a ## operator, we must pre-expand the
357 // argument and substitute the expanded tokens into the result. This is
358 // C99 6.10.3.1p1.
359 if (!PasteBefore && !PasteAfter) {
360 const LexerToken *ResultArgToks;
361
362 // Only preexpand the argument if it could possibly need it. This
363 // avoids some work in common cases.
364 const LexerToken *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
365 if (ActualArgs->ArgNeedsPreexpansion(ArgTok))
366 ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0];
367 else
368 ResultArgToks = ArgTok; // Use non-preexpanded tokens.
369
370 // If the arg token expanded into anything, append it.
371 if (ResultArgToks->getKind() != tok::eof) {
372 unsigned FirstResult = ResultToks.size();
373 unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
374 ResultToks.append(ResultArgToks, ResultArgToks+NumToks);
375
376 // If any tokens were substituted from the argument, the whitespace
377 // before the first token should match the whitespace of the arg
378 // identifier.
Chris Lattner8c204872006-10-14 05:19:21 +0000379 ResultToks[FirstResult].setFlagValue(LexerToken::LeadingSpace,
Chris Lattner479b0af2006-07-29 04:16:20 +0000380 CurTok.hasLeadingSpace() ||
381 NextTokGetsSpace);
382 NextTokGetsSpace = false;
383 } else {
384 // If this is an empty argument, and if there was whitespace before the
385 // formal token, make sure the next token gets whitespace before it.
386 NextTokGetsSpace = CurTok.hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000387 }
388 continue;
389 }
390
391 // Okay, we have a token that is either the LHS or RHS of a paste (##)
392 // argument. It gets substituted as its non-pre-expanded tokens.
393 const LexerToken *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
394 unsigned NumToks = MacroArgs::getArgLength(ArgToks);
395 if (NumToks) { // Not an empty argument?
396 ResultToks.append(ArgToks, ArgToks+NumToks);
Chris Lattner479b0af2006-07-29 04:16:20 +0000397
398 // If the next token was supposed to get leading whitespace, ensure it has
399 // it now.
400 if (NextTokGetsSpace) {
Chris Lattner8c204872006-10-14 05:19:21 +0000401 ResultToks[ResultToks.size()-NumToks].setFlag(LexerToken::LeadingSpace);
Chris Lattner479b0af2006-07-29 04:16:20 +0000402 NextTokGetsSpace = false;
403 }
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000404 continue;
405 }
406
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000407 // If an empty argument is on the LHS or RHS of a paste, the standard (C99
408 // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur. We
409 // implement this by eating ## operators when a LHS or RHS expands to
410 // empty.
Chris Lattner479b0af2006-07-29 04:16:20 +0000411 NextTokGetsSpace |= CurTok.hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000412 if (PasteAfter) {
413 // Discard the argument token and skip (don't copy to the expansion
414 // buffer) the paste operator after it.
Chris Lattner479b0af2006-07-29 04:16:20 +0000415 NextTokGetsSpace |= MacroTokens[i+1].hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000416 ++i;
417 continue;
418 }
419
420 // If this is on the RHS of a paste operator, we've already copied the
421 // paste operator to the ResultToks list. Remove it.
422 assert(PasteBefore && ResultToks.back().getKind() == tok::hashhash);
Chris Lattner479b0af2006-07-29 04:16:20 +0000423 NextTokGetsSpace |= ResultToks.back().hasLeadingSpace();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000424 ResultToks.pop_back();
Chris Lattner775d8322006-07-29 04:39:41 +0000425
426 // If this is the __VA_ARGS__ token, and if the argument wasn't provided,
427 // and if the macro had at least one real argument, and if the token before
428 // the ## was a comma, remove the comma.
Chris Lattner95a06b32006-07-30 08:40:43 +0000429 if ((unsigned)ArgNo == Macro->getNumArgs()-1 && // is __VA_ARGS__
Chris Lattner775d8322006-07-29 04:39:41 +0000430 ActualArgs->isVarargsElidedUse() && // Argument elided.
431 !ResultToks.empty() && ResultToks.back().getKind() == tok::comma) {
432 // Never add a space, even if the comma, ##, or arg had a space.
433 NextTokGetsSpace = false;
434 ResultToks.pop_back();
435 }
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000436 continue;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000437 }
438
439 // If anything changed, install this as the new MacroTokens list.
440 if (MadeChange) {
441 // This is deleted in the dtor.
Chris Lattner70216572006-07-26 03:50:40 +0000442 NumMacroTokens = ResultToks.size();
443 LexerToken *Res = new LexerToken[ResultToks.size()];
Chris Lattnerd97d2e72006-07-29 06:44:29 +0000444 if (NumMacroTokens)
445 memcpy(Res, &ResultToks[0], NumMacroTokens*sizeof(LexerToken));
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000446 MacroTokens = Res;
447 }
448}
Chris Lattner67b07cb2006-06-26 02:03:42 +0000449
Chris Lattner22eb9722006-06-18 05:43:12 +0000450/// Lex - Lex and return a token from this macro stream.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000451///
Chris Lattnercb283342006-06-18 06:48:37 +0000452void MacroExpander::Lex(LexerToken &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000453 // Lexing off the end of the macro, pop this macro off the expansion stack.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000454 if (isAtEnd()) {
455 // If this is a macro (not a token stream), mark the macro enabled now
456 // that it is no longer being expanded.
457 if (Macro) Macro->EnableMacro();
458
459 // Pop this context off the preprocessors lexer stack and get the next
Chris Lattner2183a6e2006-07-18 06:36:12 +0000460 // token. This will delete "this" so remember the PP instance var.
461 Preprocessor &PPCache = PP;
462 if (PP.HandleEndOfMacro(Tok))
463 return;
464
465 // HandleEndOfMacro may not return a token. If it doesn't, lex whatever is
466 // next.
467 return PPCache.Lex(Tok);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000468 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000469
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000470 // If this is the first token of the expanded result, we inherit spacing
471 // properties later.
472 bool isFirstToken = CurToken == 0;
473
Chris Lattner22eb9722006-06-18 05:43:12 +0000474 // Get the next token to return.
Chris Lattner70216572006-07-26 03:50:40 +0000475 Tok = MacroTokens[CurToken++];
Chris Lattner01ecf832006-07-19 05:42:48 +0000476
477 // If this token is followed by a token paste (##) operator, paste the tokens!
Chris Lattner70216572006-07-26 03:50:40 +0000478 if (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash)
Chris Lattner01ecf832006-07-19 05:42:48 +0000479 PasteTokens(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000480
Chris Lattnerc673f902006-06-30 06:10:41 +0000481 // The token's current location indicate where the token was lexed from. We
482 // need this information to compute the spelling of the token, but any
483 // diagnostics for the expanded token should appear as if they came from
484 // InstantiationLoc. Pull this information together into a new SourceLocation
485 // that captures all of this.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000486 if (InstantiateLoc.isValid()) { // Don't do this for token streams.
487 SourceManager &SrcMgr = PP.getSourceManager();
488 // The token could have come from a prior macro expansion. In that case,
489 // ignore the macro expand part to get to the physloc. This happens for
490 // stuff like: #define A(X) X A(A(X)) A(1)
491 SourceLocation PhysLoc = SrcMgr.getPhysicalLoc(Tok.getLocation());
Chris Lattner8c204872006-10-14 05:19:21 +0000492 Tok.setLocation(SrcMgr.getInstantiationLoc(PhysLoc, InstantiateLoc));
Chris Lattner7667d0d2006-07-16 18:16:58 +0000493 }
494
Chris Lattner22eb9722006-06-18 05:43:12 +0000495 // If this is the first token, set the lexical properties of the token to
496 // match the lexical properties of the macro identifier.
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000497 if (isFirstToken) {
Chris Lattner8c204872006-10-14 05:19:21 +0000498 Tok.setFlagValue(LexerToken::StartOfLine , AtStartOfLine);
499 Tok.setFlagValue(LexerToken::LeadingSpace, HasLeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +0000500 }
501
502 // Handle recursive expansion!
503 if (Tok.getIdentifierInfo())
504 return PP.HandleIdentifier(Tok);
505
506 // Otherwise, return a normal token.
Chris Lattner22eb9722006-06-18 05:43:12 +0000507}
Chris Lattnerafe603f2006-07-11 04:02:46 +0000508
Chris Lattner01ecf832006-07-19 05:42:48 +0000509/// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ##
510/// operator. Read the ## and RHS, and paste the LHS/RHS together. If there
511/// are is another ## after it, chomp it iteratively. Return the result as Tok.
512void MacroExpander::PasteTokens(LexerToken &Tok) {
513 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.
526 char *Buffer = (char*)alloca(Tok.getLength() + RHS.getLength() + 1);
527
528 // Get the spelling of the LHS token in Buffer.
529 const char *BufPtr = Buffer;
530 unsigned LHSLen = PP.getSpelling(Tok, BufPtr);
531 if (BufPtr != Buffer) // Really, we want the chars in Buffer!
532 memcpy(Buffer, BufPtr, LHSLen);
533
534 BufPtr = Buffer+LHSLen;
535 unsigned RHSLen = PP.getSpelling(RHS, BufPtr);
536 if (BufPtr != Buffer+LHSLen) // Really, we want the chars in Buffer!
537 memcpy(Buffer+LHSLen, BufPtr, RHSLen);
538
539 // Add null terminator.
540 Buffer[LHSLen+RHSLen] = '\0';
541
542 // Plop the pasted result (including the trailing newline and null) into a
543 // scratch buffer where we can lex it.
544 SourceLocation ResultTokLoc = PP.CreateString(Buffer, LHSLen+RHSLen+1);
545
546 // Lex the resultant pasted token into Result.
547 LexerToken Result;
548
Chris Lattnera7e2e742006-07-19 06:32:35 +0000549 // Avoid testing /*, as the lexer would think it is the start of a comment
550 // and emit an error that it is unterminated.
551 if (Tok.getKind() == tok::slash && RHS.getKind() == tok::star) {
552 isInvalid = true;
Chris Lattner510ab612006-07-20 04:47:30 +0000553 } else if (Tok.getKind() == tok::identifier &&
Chris Lattner08ba4c02006-07-20 04:52:59 +0000554 RHS.getKind() == tok::identifier) {
Chris Lattner510ab612006-07-20 04:47:30 +0000555 // Common paste case: identifier+identifier = identifier. Avoid creating
556 // a lexer and other overhead.
557 PP.IncrementPasteCounter(true);
Chris Lattner8c204872006-10-14 05:19:21 +0000558 Result.startToken();
559 Result.setKind(tok::identifier);
560 Result.setLocation(ResultTokLoc);
561 Result.setLength(LHSLen+RHSLen);
Chris Lattnera7e2e742006-07-19 06:32:35 +0000562 } else {
Chris Lattner510ab612006-07-20 04:47:30 +0000563 PP.IncrementPasteCounter(false);
564
Chris Lattnera7e2e742006-07-19 06:32:35 +0000565 // Make a lexer to lex this string from.
566 SourceManager &SourceMgr = PP.getSourceManager();
567 const char *ResultStrData = SourceMgr.getCharacterData(ResultTokLoc);
568
569 unsigned FileID = ResultTokLoc.getFileID();
570 assert(FileID && "Could not get FileID for paste?");
571
572 // Make a lexer object so that we lex and expand the paste result.
573 Lexer *TL = new Lexer(SourceMgr.getBuffer(FileID), FileID, PP,
574 ResultStrData,
575 ResultStrData+LHSLen+RHSLen /*don't include null*/);
576
577 // Lex a token in raw mode. This way it won't look up identifiers
578 // automatically, lexing off the end will return an eof token, and
579 // warnings are disabled. This returns true if the result token is the
580 // entire buffer.
581 bool IsComplete = TL->LexRawToken(Result);
582
583 // If we got an EOF token, we didn't form even ONE token. For example, we
584 // did "/ ## /" to get "//".
585 IsComplete &= Result.getKind() != tok::eof;
586 isInvalid = !IsComplete;
587
588 // We're now done with the temporary lexer.
589 delete TL;
590 }
Chris Lattner01ecf832006-07-19 05:42:48 +0000591
592 // If pasting the two tokens didn't form a full new token, this is an error.
Chris Lattnera7e2e742006-07-19 06:32:35 +0000593 // This occurs with "x ## +" and other stuff. Return with Tok unmodified
594 // and with RHS as the next token to lex.
595 if (isInvalid) {
Chris Lattner01ecf832006-07-19 05:42:48 +0000596 // If not in assembler language mode.
597 PP.Diag(PasteOpLoc, diag::err_pp_bad_paste,
598 std::string(Buffer, Buffer+LHSLen+RHSLen));
599 return;
600 }
601
602 // Turn ## into 'other' to avoid # ## # from looking like a paste operator.
603 if (Result.getKind() == tok::hashhash)
Chris Lattner8c204872006-10-14 05:19:21 +0000604 Result.setKind(tok::unknown);
Chris Lattner01ecf832006-07-19 05:42:48 +0000605 // FIXME: Turn __VARRGS__ into "not a token"?
606
607 // Transfer properties of the LHS over the the Result.
Chris Lattner8c204872006-10-14 05:19:21 +0000608 Result.setFlagValue(LexerToken::StartOfLine , Tok.isAtStartOfLine());
609 Result.setFlagValue(LexerToken::LeadingSpace, Tok.hasLeadingSpace());
Chris Lattner01ecf832006-07-19 05:42:48 +0000610
611 // Finally, replace LHS with the result, consume the RHS, and iterate.
612 ++CurToken;
613 Tok = Result;
Chris Lattner70216572006-07-26 03:50:40 +0000614 } while (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash);
Chris Lattner0f1f5052006-07-20 04:16:23 +0000615
616 // Now that we got the result token, it will be subject to expansion. Since
617 // token pasting re-lexes the result token in raw mode, identifier information
618 // isn't looked up. As such, if the result is an identifier, look up id info.
619 if (Tok.getKind() == tok::identifier) {
620 // Look up the identifier info for the token. We disabled identifier lookup
621 // by saying we're skipping contents, so we need to do this manually.
Chris Lattner8c204872006-10-14 05:19:21 +0000622 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
Chris Lattner0f1f5052006-07-20 04:16:23 +0000623 }
Chris Lattner01ecf832006-07-19 05:42:48 +0000624}
625
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000626/// isNextTokenLParen - If the next token lexed will pop this macro off the
627/// expansion stack, return 2. If the next unexpanded token is a '(', return
628/// 1, otherwise return 0.
629unsigned MacroExpander::isNextTokenLParen() const {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000630 // Out of tokens?
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000631 if (isAtEnd())
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000632 return 2;
Chris Lattner70216572006-07-26 03:50:40 +0000633 return MacroTokens[CurToken].getKind() == tok::l_paren;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000634}