blob: 194ceecc0708b52147fde4d27ee2371ebf87cde4 [file] [log] [blame]
Chris Lattner95d72cd2008-03-09 02:18:51 +00001//===--- TokenLexer.cpp - Lex from a token stream -------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner95d72cd2008-03-09 02:18:51 +000010// This file implements the TokenLexer interface.
Chris Lattner22eb9722006-06-18 05:43:12 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner5bb36002008-03-09 02:22:57 +000014#include "clang/Lex/TokenLexer.h"
Chris Lattner30709b032006-06-21 03:01:55 +000015#include "clang/Basic/SourceManager.h"
Chris Lattner60f36222009-01-29 05:15:15 +000016#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000017#include "clang/Lex/MacroArgs.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/MacroInfo.h"
19#include "clang/Lex/Preprocessor.h"
Faisal Vali18268422017-10-15 01:26:26 +000020#include "clang/Lex/VariadicMacroSupport.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000021#include "llvm/ADT/SmallString.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000022
Eugene Zelenko1ced5092016-02-12 22:53:10 +000023using namespace clang;
Chris Lattner78186052006-07-09 00:45:31 +000024
Chris Lattner95d72cd2008-03-09 02:18:51 +000025/// Create a TokenLexer for the specified macro with the specified actual
Chris Lattner7667d0d2006-07-16 18:16:58 +000026/// arguments. Note that this ctor takes ownership of the ActualArgs pointer.
Richard Smith5edd5832012-08-30 13:38:46 +000027void TokenLexer::Init(Token &Tok, SourceLocation ELEnd, MacroInfo *MI,
28 MacroArgs *Actuals) {
Chris Lattner95d72cd2008-03-09 02:18:51 +000029 // If the client is reusing a TokenLexer, make sure to free any memory
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000030 // associated with it.
31 destroy();
Mike Stump11289f42009-09-09 15:08:12 +000032
Richard Smith5edd5832012-08-30 13:38:46 +000033 Macro = MI;
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000034 ActualArgs = Actuals;
Faisal Valib8ece9f2017-10-03 00:52:14 +000035 CurTokenIdx = 0;
Mike Stump11289f42009-09-09 15:08:12 +000036
Chandler Carruthc9c84192011-07-14 08:20:34 +000037 ExpandLocStart = Tok.getLocation();
38 ExpandLocEnd = ELEnd;
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000039 AtStartOfLine = Tok.isAtStartOfLine();
40 HasLeadingSpace = Tok.hasLeadingSpace();
Justin Bognereacd96d2014-02-04 19:18:32 +000041 NextTokGetsSpace = false;
Chris Lattnerd7daed12008-03-09 02:07:49 +000042 Tokens = &*Macro->tokens_begin();
43 OwnsTokens = false;
Chris Lattner3e468322008-03-10 06:06:04 +000044 DisableMacroExpansion = false;
Chris Lattnerd7daed12008-03-09 02:07:49 +000045 NumTokens = Macro->tokens_end()-Macro->tokens_begin();
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +000046 MacroExpansionStart = SourceLocation();
47
48 SourceManager &SM = PP.getSourceManager();
Douglas Gregor925296b2011-07-19 16:10:42 +000049 MacroStartSLocOffset = SM.getNextLocalOffset();
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +000050
51 if (NumTokens > 0) {
52 assert(Tokens[0].getLocation().isValid());
53 assert((Tokens[0].getLocation().isFileID() || Tokens[0].is(tok::comment)) &&
54 "Macro defined in macro?");
Chandler Carruthc9c84192011-07-14 08:20:34 +000055 assert(ExpandLocStart.isValid());
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +000056
57 // Reserve a source location entry chunk for the length of the macro
58 // definition. Tokens that get lexed directly from the definition will
59 // have their locations pointing inside this chunk. This is to avoid
60 // creating separate source location entries for each token.
Argyrios Kyrtzidise7f75162011-08-23 21:02:38 +000061 MacroDefStart = SM.getExpansionLoc(Tokens[0].getLocation());
62 MacroDefLength = Macro->getDefinitionLength(SM);
63 MacroExpansionStart = SM.createExpansionLoc(MacroDefStart,
Chandler Carruth115b0772011-07-26 03:03:05 +000064 ExpandLocStart,
65 ExpandLocEnd,
Argyrios Kyrtzidise7f75162011-08-23 21:02:38 +000066 MacroDefLength);
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +000067 }
Chris Lattnerb935d8c2006-07-14 06:54:44 +000068
69 // If this is a function-like macro, expand the arguments and change
Chris Lattnerd7daed12008-03-09 02:07:49 +000070 // Tokens to point to the expanded tokens.
Faisal Valiac506d72017-07-17 17:18:43 +000071 if (Macro->isFunctionLike() && Macro->getNumParams())
Chris Lattnerb935d8c2006-07-14 06:54:44 +000072 ExpandFunctionArguments();
Mike Stump11289f42009-09-09 15:08:12 +000073
Chris Lattner7667d0d2006-07-16 18:16:58 +000074 // Mark the macro as currently disabled, so that it is not recursively
75 // expanded. The macro must be disabled only after argument pre-expansion of
76 // function-like macro arguments occurs.
77 Macro->DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +000078}
79
Chris Lattner95d72cd2008-03-09 02:18:51 +000080/// Create a TokenLexer for the specified token stream. This does not
Chris Lattner7667d0d2006-07-16 18:16:58 +000081/// take ownership of the specified token vector.
Chris Lattner3e468322008-03-10 06:06:04 +000082void TokenLexer::Init(const Token *TokArray, unsigned NumToks,
83 bool disableMacroExpansion, bool ownsTokens) {
Chris Lattner95d72cd2008-03-09 02:18:51 +000084 // If the client is reusing a TokenLexer, make sure to free any memory
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000085 // associated with it.
86 destroy();
Mike Stump11289f42009-09-09 15:08:12 +000087
Craig Topperd2d442c2014-05-17 23:10:59 +000088 Macro = nullptr;
89 ActualArgs = nullptr;
Chris Lattnerd7daed12008-03-09 02:07:49 +000090 Tokens = TokArray;
Chris Lattner3e468322008-03-10 06:06:04 +000091 OwnsTokens = ownsTokens;
92 DisableMacroExpansion = disableMacroExpansion;
Chris Lattnerd7daed12008-03-09 02:07:49 +000093 NumTokens = NumToks;
Faisal Valib8ece9f2017-10-03 00:52:14 +000094 CurTokenIdx = 0;
Chandler Carruthc9c84192011-07-14 08:20:34 +000095 ExpandLocStart = ExpandLocEnd = SourceLocation();
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000096 AtStartOfLine = false;
97 HasLeadingSpace = false;
Justin Bognereacd96d2014-02-04 19:18:32 +000098 NextTokGetsSpace = false;
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +000099 MacroExpansionStart = SourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000100
Chris Lattner7667d0d2006-07-16 18:16:58 +0000101 // Set HasLeadingSpace/AtStartOfLine so that the first token will be
102 // returned unmodified.
Chris Lattner70216572006-07-26 03:50:40 +0000103 if (NumToks != 0) {
104 AtStartOfLine = TokArray[0].isAtStartOfLine();
105 HasLeadingSpace = TokArray[0].hasLeadingSpace();
Chris Lattner7667d0d2006-07-16 18:16:58 +0000106 }
107}
108
Chris Lattner95d72cd2008-03-09 02:18:51 +0000109void TokenLexer::destroy() {
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000110 // If this was a function-like macro that actually uses its arguments, delete
111 // the expanded tokens.
Chris Lattnerd7daed12008-03-09 02:07:49 +0000112 if (OwnsTokens) {
113 delete [] Tokens;
Craig Topperd2d442c2014-05-17 23:10:59 +0000114 Tokens = nullptr;
Chris Lattner8322dc82009-03-04 06:50:57 +0000115 OwnsTokens = false;
Chris Lattner9c724c42007-07-22 01:16:55 +0000116 }
Mike Stump11289f42009-09-09 15:08:12 +0000117
Chris Lattner95d72cd2008-03-09 02:18:51 +0000118 // TokenLexer owns its formal arguments.
Chris Lattnerffbf2de2009-12-14 22:12:52 +0000119 if (ActualArgs) ActualArgs->destroy(PP);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000120}
121
Nico Weber0e9da352014-05-09 01:00:48 +0000122bool TokenLexer::MaybeRemoveCommaBeforeVaArgs(
123 SmallVectorImpl<Token> &ResultToks, bool HasPasteOperator, MacroInfo *Macro,
124 unsigned MacroArgNo, Preprocessor &PP) {
Andy Gibbs571df352012-11-09 13:24:30 +0000125 // Is the macro argument __VA_ARGS__?
Faisal Valiac506d72017-07-17 17:18:43 +0000126 if (!Macro->isVariadic() || MacroArgNo != Macro->getNumParams()-1)
Andy Gibbs571df352012-11-09 13:24:30 +0000127 return false;
128
129 // In Microsoft-compatibility mode, a comma is removed in the expansion
130 // of " ... , __VA_ARGS__ " if __VA_ARGS__ is empty. This extension is
131 // not supported by gcc.
Alp Tokerbfa39342014-01-14 12:51:41 +0000132 if (!HasPasteOperator && !PP.getLangOpts().MSVCCompat)
Andy Gibbs571df352012-11-09 13:24:30 +0000133 return false;
134
135 // GCC removes the comma in the expansion of " ... , ## __VA_ARGS__ " if
136 // __VA_ARGS__ is empty, but not in strict C99 mode where there are no
137 // named arguments, where it remains. In all other modes, including C99
138 // with GNU extensions, it is removed regardless of named arguments.
139 // Microsoft also appears to support this extension, unofficially.
140 if (PP.getLangOpts().C99 && !PP.getLangOpts().GNUMode
Faisal Valiac506d72017-07-17 17:18:43 +0000141 && Macro->getNumParams() < 2)
Andy Gibbs571df352012-11-09 13:24:30 +0000142 return false;
143
144 // Is a comma available to be removed?
145 if (ResultToks.empty() || !ResultToks.back().is(tok::comma))
146 return false;
147
148 // Issue an extension diagnostic for the paste operator.
149 if (HasPasteOperator)
150 PP.Diag(ResultToks.back().getLocation(), diag::ext_paste_comma);
151
152 // Remove the comma.
153 ResultToks.pop_back();
154
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000155 if (!ResultToks.empty()) {
156 // If the comma was right after another paste (e.g. "X##,##__VA_ARGS__"),
157 // then removal of the comma should produce a placemarker token (in C99
158 // terms) which we model by popping off the previous ##, giving us a plain
159 // "X" when __VA_ARGS__ is empty.
160 if (ResultToks.back().is(tok::hashhash))
161 ResultToks.pop_back();
162
163 // Remember that this comma was elided.
164 ResultToks.back().setFlag(Token::CommaAfterElided);
165 }
Andy Gibbs571df352012-11-09 13:24:30 +0000166
167 // Never add a space, even if the comma, ##, or arg had a space.
168 NextTokGetsSpace = false;
169 return true;
170}
171
Faisal Vali18268422017-10-15 01:26:26 +0000172void TokenLexer::stringifyVAOPTContents(
173 SmallVectorImpl<Token> &ResultToks, const VAOptExpansionContext &VCtx,
174 const SourceLocation VAOPTClosingParenLoc) {
175 const int NumToksPriorToVAOpt = VCtx.getNumberOfTokensPriorToVAOpt();
176 const unsigned int NumVAOptTokens = ResultToks.size() - NumToksPriorToVAOpt;
177 Token *const VAOPTTokens =
178 NumVAOptTokens ? &ResultToks[NumToksPriorToVAOpt] : nullptr;
179
180 SmallVector<Token, 64> ConcatenatedVAOPTResultToks;
181 // FIXME: Should we keep track within VCtx that we did or didnot
182 // encounter pasting - and only then perform this loop.
183
184 // Perform token pasting (concatenation) prior to stringization.
185 for (unsigned int CurTokenIdx = 0; CurTokenIdx != NumVAOptTokens;
186 ++CurTokenIdx) {
Faisal Vali18268422017-10-15 01:26:26 +0000187 if (VAOPTTokens[CurTokenIdx].is(tok::hashhash)) {
188 assert(CurTokenIdx != 0 &&
189 "Can not have __VAOPT__ contents begin with a ##");
190 Token &LHS = VAOPTTokens[CurTokenIdx - 1];
191 pasteTokens(LHS, llvm::makeArrayRef(VAOPTTokens, NumVAOptTokens),
192 CurTokenIdx);
Faisal Vali18268422017-10-15 01:26:26 +0000193 // Replace the token prior to the first ## in this iteration.
194 ConcatenatedVAOPTResultToks.back() = LHS;
195 if (CurTokenIdx == NumVAOptTokens)
196 break;
197 }
198 ConcatenatedVAOPTResultToks.push_back(VAOPTTokens[CurTokenIdx]);
199 }
200
201 ConcatenatedVAOPTResultToks.push_back(VCtx.getEOFTok());
202 // Get the SourceLocation that represents the start location within
203 // the macro definition that marks where this string is substituted
204 // into: i.e. the __VA_OPT__ and the ')' within the spelling of the
205 // macro definition, and use it to indicate that the stringified token
206 // was generated from that location.
207 const SourceLocation ExpansionLocStartWithinMacro =
208 getExpansionLocForMacroDefLoc(VCtx.getVAOptLoc());
209 const SourceLocation ExpansionLocEndWithinMacro =
210 getExpansionLocForMacroDefLoc(VAOPTClosingParenLoc);
211
212 Token StringifiedVAOPT = MacroArgs::StringifyArgument(
213 &ConcatenatedVAOPTResultToks[0], PP, VCtx.hasCharifyBefore() /*Charify*/,
214 ExpansionLocStartWithinMacro, ExpansionLocEndWithinMacro);
215
216 if (VCtx.getLeadingSpaceForStringifiedToken())
217 StringifiedVAOPT.setFlag(Token::LeadingSpace);
218
219 StringifiedVAOPT.setFlag(Token::StringifiedInMacro);
220 // Resize (shrink) the token stream to just capture this stringified token.
221 ResultToks.resize(NumToksPriorToVAOpt + 1);
222 ResultToks.back() = StringifiedVAOPT;
223}
224
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000225/// Expand the arguments of a function-like macro so that we can quickly
Chris Lattnerd7daed12008-03-09 02:07:49 +0000226/// return preexpanded tokens from Tokens.
Chris Lattner95d72cd2008-03-09 02:18:51 +0000227void TokenLexer::ExpandFunctionArguments() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000228 SmallVector<Token, 128> ResultToks;
Mike Stump11289f42009-09-09 15:08:12 +0000229
Chris Lattnerd7daed12008-03-09 02:07:49 +0000230 // Loop through 'Tokens', expanding them into ResultToks. Keep
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000231 // track of whether we change anything. If not, no need to keep them. If so,
Chris Lattnerd7daed12008-03-09 02:07:49 +0000232 // we install the newly expanded sequence as the new 'Tokens' list.
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000233 bool MadeChange = false;
Mike Stump11289f42009-09-09 15:08:12 +0000234
Faisal Vali18268422017-10-15 01:26:26 +0000235 const bool CalledWithVariadicArguments =
236 ActualArgs->invokedWithVariadicArgument(Macro);
237
238 VAOptExpansionContext VCtx(PP);
239
Faisal Valif4c46422017-07-20 01:10:56 +0000240 for (unsigned I = 0, E = NumTokens; I != E; ++I) {
Faisal Vali18268422017-10-15 01:26:26 +0000241
Faisal Valif4c46422017-07-20 01:10:56 +0000242 const Token &CurTok = Tokens[I];
James Y Knight7f319012017-05-04 21:31:17 +0000243 // We don't want a space for the next token after a paste
244 // operator. In valid code, the token will get smooshed onto the
245 // preceding one anyway. In assembler-with-cpp mode, invalid
246 // pastes are allowed through: in this case, we do not want the
247 // extra whitespace to be added. For example, we want ". ## foo"
248 // -> ".foo" not ". foo".
Faisal Valif4c46422017-07-20 01:10:56 +0000249 if (I != 0 && !Tokens[I-1].is(tok::hashhash) && CurTok.hasLeadingSpace())
Justin Bognerd554a8e2014-02-04 19:18:37 +0000250 NextTokGetsSpace = true;
251
Faisal Vali18268422017-10-15 01:26:26 +0000252 if (VCtx.isVAOptToken(CurTok)) {
253 MadeChange = true;
254 assert(Tokens[I + 1].is(tok::l_paren) &&
255 "__VA_OPT__ must be followed by '('");
256
257 ++I; // Skip the l_paren
258 VCtx.sawVAOptFollowedByOpeningParens(CurTok.getLocation(),
259 ResultToks.size());
260
261 continue;
262 }
263
264 // We have entered into the __VA_OPT__ context, so handle tokens
265 // appropriately.
266 if (VCtx.isInVAOpt()) {
267 // If we are about to process a token that is either an argument to
268 // __VA_OPT__ or its closing rparen, then:
269 // 1) If the token is the closing rparen that exits us out of __VA_OPT__,
270 // perform any necessary stringification or placemarker processing,
271 // and/or skip to the next token.
272 // 2) else if macro was invoked without variadic arguments skip this
273 // token.
274 // 3) else (macro was invoked with variadic arguments) process the token
275 // normally.
276
277 if (Tokens[I].is(tok::l_paren))
278 VCtx.sawOpeningParen(Tokens[I].getLocation());
279 // Continue skipping tokens within __VA_OPT__ if the macro was not
280 // called with variadic arguments, else let the rest of the loop handle
281 // this token. Note sawClosingParen() returns true only if the r_paren matches
282 // the closing r_paren of the __VA_OPT__.
283 if (!Tokens[I].is(tok::r_paren) || !VCtx.sawClosingParen()) {
284 if (!CalledWithVariadicArguments) {
285 // Skip this token.
286 continue;
287 }
288 // ... else the macro was called with variadic arguments, and we do not
289 // have a closing rparen - so process this token normally.
290
291 } else {
292 // Current token is the closing r_paren which marks the end of the
293 // __VA_OPT__ invocation, so handle any place-marker pasting (if
294 // empty) by removing hashhash either before (if exists) or after. And
295 // also stringify the entire contents if VAOPT was preceded by a hash,
296 // but do so only after any token concatenation that needs to occur
297 // within the contents of VAOPT.
298
299 if (VCtx.hasStringifyOrCharifyBefore()) {
300 // Replace all the tokens just added from within VAOPT into a single
301 // stringified token. This requires token-pasting to eagerly occur
302 // within these tokens. If either the contents of VAOPT were empty
303 // or the macro wasn't called with any variadic arguments, the result
304 // is a token that represents an empty string.
305 stringifyVAOPTContents(ResultToks, VCtx,
306 /*ClosingParenLoc*/ Tokens[I].getLocation());
307
308 } else if (/*No tokens within VAOPT*/ !(
309 ResultToks.size() - VCtx.getNumberOfTokensPriorToVAOpt())) {
310 // Treat VAOPT as a placemarker token. Eat either the '##' before the
311 // RHS/VAOPT (if one exists, suggesting that the LHS (if any) to that
312 // hashhash was not a placemarker) or the '##'
313 // after VAOPT, but not both.
314
315 if (ResultToks.size() && ResultToks.back().is(tok::hashhash)) {
316 ResultToks.pop_back();
317 } else if ((I + 1 != E) && Tokens[I + 1].is(tok::hashhash)) {
318 ++I; // Skip the following hashhash.
319 }
320 }
321 VCtx.reset();
322 // We processed __VA_OPT__'s closing paren (and the exit out of
323 // __VA_OPT__), so skip to the next token.
324 continue;
325 }
326 }
327
328 // If we found the stringify operator, get the argument stringified. The
329 // preprocessor already verified that the following token is a macro
330 // parameter or __VA_OPT__ when the #define was lexed.
331
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000332 if (CurTok.isOneOf(tok::hash, tok::hashat)) {
Faisal Valif4c46422017-07-20 01:10:56 +0000333 int ArgNo = Macro->getParameterNum(Tokens[I+1].getIdentifierInfo());
Faisal Vali18268422017-10-15 01:26:26 +0000334 assert((ArgNo != -1 || VCtx.isVAOptToken(Tokens[I + 1])) &&
335 "Token following # is not an argument or __VA_OPT__!");
336
337 if (ArgNo == -1) {
338 // Handle the __VA_OPT__ case.
339 VCtx.sawHashOrHashAtBefore(NextTokGetsSpace,
340 CurTok.is(tok::hashat));
341 continue;
342 }
343 // Else handle the simple argument case.
Abramo Bagnarae398e602011-10-03 18:39:03 +0000344 SourceLocation ExpansionLocStart =
Argyrios Kyrtzidis7a7ff682011-08-23 21:02:32 +0000345 getExpansionLocForMacroDefLoc(CurTok.getLocation());
Abramo Bagnarae398e602011-10-03 18:39:03 +0000346 SourceLocation ExpansionLocEnd =
Faisal Valif4c46422017-07-20 01:10:56 +0000347 getExpansionLocForMacroDefLoc(Tokens[I+1].getLocation());
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000348
Chris Lattner146762e2007-07-20 16:59:19 +0000349 Token Res;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000350 if (CurTok.is(tok::hash)) // Stringify
Abramo Bagnarae398e602011-10-03 18:39:03 +0000351 Res = ActualArgs->getStringifiedArgument(ArgNo, PP,
352 ExpansionLocStart,
353 ExpansionLocEnd);
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000354 else {
355 // 'charify': don't bother caching these.
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000356 Res = MacroArgs::StringifyArgument(ActualArgs->getUnexpArgument(ArgNo),
Abramo Bagnarae398e602011-10-03 18:39:03 +0000357 PP, true,
358 ExpansionLocStart,
359 ExpansionLocEnd);
Chris Lattnerc783d1d2006-07-15 06:11:25 +0000360 }
Alexey Bataev583b0762014-12-15 04:18:11 +0000361 Res.setFlag(Token::StringifiedInMacro);
Mike Stump11289f42009-09-09 15:08:12 +0000362
Chris Lattner60161692006-07-15 06:48:02 +0000363 // The stringified/charified string leading space flag gets set to match
364 // the #/#@ operator.
Justin Bognerd554a8e2014-02-04 19:18:37 +0000365 if (NextTokGetsSpace)
Chris Lattner146762e2007-07-20 16:59:19 +0000366 Res.setFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +0000367
Chris Lattner6fc08bc2006-07-26 04:55:32 +0000368 ResultToks.push_back(Res);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000369 MadeChange = true;
Faisal Valif4c46422017-07-20 01:10:56 +0000370 ++I; // Skip arg name.
Chris Lattner479b0af2006-07-29 04:16:20 +0000371 NextTokGetsSpace = false;
Chris Lattnera9dc5972006-07-28 05:07:04 +0000372 continue;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000373 }
Mike Stump11289f42009-09-09 15:08:12 +0000374
Justin Bogner502155a2014-02-04 19:18:28 +0000375 // Find out if there is a paste (##) operator before or after the token.
376 bool NonEmptyPasteBefore =
377 !ResultToks.empty() && ResultToks.back().is(tok::hashhash);
Faisal Valif4c46422017-07-20 01:10:56 +0000378 bool PasteBefore = I != 0 && Tokens[I-1].is(tok::hashhash);
379 bool PasteAfter = I+1 != E && Tokens[I+1].is(tok::hashhash);
Faisal Vali18268422017-10-15 01:26:26 +0000380
381 assert((!NonEmptyPasteBefore || PasteBefore || VCtx.isInVAOpt()) &&
382 "unexpected ## in ResultToks");
Justin Bogner502155a2014-02-04 19:18:28 +0000383
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000384 // Otherwise, if this is not an argument token, just add the token to the
385 // output buffer.
386 IdentifierInfo *II = CurTok.getIdentifierInfo();
Faisal Valiac506d72017-07-17 17:18:43 +0000387 int ArgNo = II ? Macro->getParameterNum(II) : -1;
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000388 if (ArgNo == -1) {
Chris Lattner95a06b32006-07-30 08:40:43 +0000389 // This isn't an argument, just add it.
390 ResultToks.push_back(CurTok);
Chris Lattner479b0af2006-07-29 04:16:20 +0000391
Chris Lattner95a06b32006-07-30 08:40:43 +0000392 if (NextTokGetsSpace) {
Chris Lattner146762e2007-07-20 16:59:19 +0000393 ResultToks.back().setFlag(Token::LeadingSpace);
Chris Lattner95a06b32006-07-30 08:40:43 +0000394 NextTokGetsSpace = false;
Justin Bogner502155a2014-02-04 19:18:28 +0000395 } else if (PasteBefore && !NonEmptyPasteBefore)
396 ResultToks.back().clearFlag(Token::LeadingSpace);
397
Chris Lattner95a06b32006-07-30 08:40:43 +0000398 continue;
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000399 }
Mike Stump11289f42009-09-09 15:08:12 +0000400
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000401 // An argument is expanded somehow, the result is different than the
402 // input.
403 MadeChange = true;
404
Justin Bogner502155a2014-02-04 19:18:28 +0000405 // Otherwise, this is a use of the argument.
Mike Stump11289f42009-09-09 15:08:12 +0000406
Andy Gibbs571df352012-11-09 13:24:30 +0000407 // In Microsoft mode, remove the comma before __VA_ARGS__ to ensure there
408 // are no trailing commas if __VA_ARGS__ is empty.
409 if (!PasteBefore && ActualArgs->isVarargsElidedUse() &&
Justin Bognereacd96d2014-02-04 19:18:32 +0000410 MaybeRemoveCommaBeforeVaArgs(ResultToks,
Andy Gibbs571df352012-11-09 13:24:30 +0000411 /*HasPasteOperator=*/false,
412 Macro, ArgNo, PP))
413 continue;
414
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000415 // If it is not the LHS/RHS of a ## operator, we must pre-expand the
416 // argument and substitute the expanded tokens into the result. This is
417 // C99 6.10.3.1p1.
418 if (!PasteBefore && !PasteAfter) {
Chris Lattner146762e2007-07-20 16:59:19 +0000419 const Token *ResultArgToks;
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000420
421 // Only preexpand the argument if it could possibly need it. This
422 // avoids some work in common cases.
Chris Lattner146762e2007-07-20 16:59:19 +0000423 const Token *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000424 if (ActualArgs->ArgNeedsPreexpansion(ArgTok, PP))
Faisal Vali333133e2017-09-30 13:58:38 +0000425 ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0];
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000426 else
427 ResultArgToks = ArgTok; // Use non-preexpanded tokens.
Mike Stump11289f42009-09-09 15:08:12 +0000428
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000429 // If the arg token expanded into anything, append it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000430 if (ResultArgToks->isNot(tok::eof)) {
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000431 size_t FirstResult = ResultToks.size();
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000432 unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
433 ResultToks.append(ResultArgToks, ResultArgToks+NumToks);
Mike Stump11289f42009-09-09 15:08:12 +0000434
Reid Kleckner596b85c2013-06-26 17:16:08 +0000435 // In Microsoft-compatibility mode, we follow MSVC's preprocessing
436 // behavior by not considering single commas from nested macro
437 // expansions as argument separators. Set a flag on the token so we can
438 // test for this later when the macro expansion is processed.
Alp Tokerbfa39342014-01-14 12:51:41 +0000439 if (PP.getLangOpts().MSVCCompat && NumToks == 1 &&
Reid Kleckner596b85c2013-06-26 17:16:08 +0000440 ResultToks.back().is(tok::comma))
441 ResultToks.back().setFlag(Token::IgnoredComma);
442
Argyrios Kyrtzidisdccf6e12011-07-07 18:04:47 +0000443 // If the '##' came from expanding an argument, turn it into 'unknown'
444 // to avoid pasting.
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000445 for (Token &Tok : llvm::make_range(ResultToks.begin() + FirstResult,
446 ResultToks.end())) {
Argyrios Kyrtzidisdccf6e12011-07-07 18:04:47 +0000447 if (Tok.is(tok::hashhash))
448 Tok.setKind(tok::unknown);
449 }
450
Chandler Carruthc9c84192011-07-14 08:20:34 +0000451 if(ExpandLocStart.isValid()) {
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +0000452 updateLocForMacroArgTokens(CurTok.getLocation(),
453 ResultToks.begin()+FirstResult,
454 ResultToks.end());
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000455 }
456
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000457 // If any tokens were substituted from the argument, the whitespace
458 // before the first token should match the whitespace of the arg
459 // identifier.
Chris Lattner146762e2007-07-20 16:59:19 +0000460 ResultToks[FirstResult].setFlagValue(Token::LeadingSpace,
Chris Lattner479b0af2006-07-29 04:16:20 +0000461 NextTokGetsSpace);
Richard Smith4b838862016-01-15 03:24:18 +0000462 ResultToks[FirstResult].setFlagValue(Token::StartOfLine, false);
Chris Lattner479b0af2006-07-29 04:16:20 +0000463 NextTokGetsSpace = false;
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000464 }
465 continue;
466 }
Mike Stump11289f42009-09-09 15:08:12 +0000467
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000468 // Okay, we have a token that is either the LHS or RHS of a paste (##)
469 // argument. It gets substituted as its non-pre-expanded tokens.
Chris Lattner146762e2007-07-20 16:59:19 +0000470 const Token *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000471 unsigned NumToks = MacroArgs::getArgLength(ArgToks);
472 if (NumToks) { // Not an empty argument?
James Y Knight7f319012017-05-04 21:31:17 +0000473 bool VaArgsPseudoPaste = false;
Richard Smith19b02cd2012-06-22 23:59:08 +0000474 // If this is the GNU ", ## __VA_ARGS__" extension, and we just learned
475 // that __VA_ARGS__ expands to multiple tokens, avoid a pasting error when
476 // the expander trys to paste ',' with the first token of the __VA_ARGS__
Chris Lattner0c8a1ed2008-01-29 07:54:23 +0000477 // expansion.
Argyrios Kyrtzidis977026c2013-05-25 01:35:18 +0000478 if (NonEmptyPasteBefore && ResultToks.size() >= 2 &&
Chris Lattner0c8a1ed2008-01-29 07:54:23 +0000479 ResultToks[ResultToks.size()-2].is(tok::comma) &&
Faisal Valiac506d72017-07-17 17:18:43 +0000480 (unsigned)ArgNo == Macro->getNumParams()-1 &&
Chris Lattner0c8a1ed2008-01-29 07:54:23 +0000481 Macro->isVariadic()) {
James Y Knight7f319012017-05-04 21:31:17 +0000482 VaArgsPseudoPaste = true;
Chris Lattner0c8a1ed2008-01-29 07:54:23 +0000483 // Remove the paste operator, report use of the extension.
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000484 PP.Diag(ResultToks.pop_back_val().getLocation(), diag::ext_paste_comma);
Chris Lattner0c8a1ed2008-01-29 07:54:23 +0000485 }
Mike Stump11289f42009-09-09 15:08:12 +0000486
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000487 ResultToks.append(ArgToks, ArgToks+NumToks);
Mike Stump11289f42009-09-09 15:08:12 +0000488
Argyrios Kyrtzidisdccf6e12011-07-07 18:04:47 +0000489 // If the '##' came from expanding an argument, turn it into 'unknown'
490 // to avoid pasting.
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000491 for (Token &Tok : llvm::make_range(ResultToks.end() - NumToks,
492 ResultToks.end())) {
Argyrios Kyrtzidisdccf6e12011-07-07 18:04:47 +0000493 if (Tok.is(tok::hashhash))
494 Tok.setKind(tok::unknown);
495 }
496
Chandler Carruthc9c84192011-07-14 08:20:34 +0000497 if (ExpandLocStart.isValid()) {
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +0000498 updateLocForMacroArgTokens(CurTok.getLocation(),
499 ResultToks.end()-NumToks, ResultToks.end());
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000500 }
501
James Y Knight7f319012017-05-04 21:31:17 +0000502 // Transfer the leading whitespace information from the token
503 // (the macro argument) onto the first token of the
504 // expansion. Note that we don't do this for the GNU
505 // pseudo-paste extension ", ## __VA_ARGS__".
506 if (!VaArgsPseudoPaste) {
507 ResultToks[ResultToks.size() - NumToks].setFlagValue(Token::StartOfLine,
508 false);
509 ResultToks[ResultToks.size() - NumToks].setFlagValue(
510 Token::LeadingSpace, NextTokGetsSpace);
511 }
Mike Stump11289f42009-09-09 15:08:12 +0000512
Chris Lattner7ce761d2009-05-25 16:23:08 +0000513 NextTokGetsSpace = false;
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000514 continue;
515 }
Mike Stump11289f42009-09-09 15:08:12 +0000516
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000517 // If an empty argument is on the LHS or RHS of a paste, the standard (C99
518 // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur. We
519 // implement this by eating ## operators when a LHS or RHS expands to
520 // empty.
521 if (PasteAfter) {
522 // Discard the argument token and skip (don't copy to the expansion
523 // buffer) the paste operator after it.
Faisal Valif4c46422017-07-20 01:10:56 +0000524 ++I;
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000525 continue;
526 }
Mike Stump11289f42009-09-09 15:08:12 +0000527
Chris Lattnerf3f1c702006-07-28 05:10:36 +0000528 // If this is on the RHS of a paste operator, we've already copied the
Argyrios Kyrtzidis977026c2013-05-25 01:35:18 +0000529 // paste operator to the ResultToks list, unless the LHS was empty too.
530 // Remove it.
531 assert(PasteBefore);
532 if (NonEmptyPasteBefore) {
533 assert(ResultToks.back().is(tok::hashhash));
Faisal Vali18268422017-10-15 01:26:26 +0000534 // Do not remove the paste operator if it is the one before __VA_OPT__
535 // (and we are still processing tokens within VA_OPT). We handle the case
536 // of removing the paste operator if __VA_OPT__ reduces to the notional
537 // placemarker above when we encounter the closing paren of VA_OPT.
538 if (!VCtx.isInVAOpt() ||
539 ResultToks.size() > VCtx.getNumberOfTokensPriorToVAOpt())
540 ResultToks.pop_back();
Argyrios Kyrtzidis977026c2013-05-25 01:35:18 +0000541 }
Mike Stump11289f42009-09-09 15:08:12 +0000542
Chris Lattner775d8322006-07-29 04:39:41 +0000543 // If this is the __VA_ARGS__ token, and if the argument wasn't provided,
544 // and if the macro had at least one real argument, and if the token before
Andy Gibbs571df352012-11-09 13:24:30 +0000545 // the ## was a comma, remove the comma. This is a GCC extension which is
546 // disabled when using -std=c99.
547 if (ActualArgs->isVarargsElidedUse())
Justin Bognereacd96d2014-02-04 19:18:32 +0000548 MaybeRemoveCommaBeforeVaArgs(ResultToks,
Andy Gibbs571df352012-11-09 13:24:30 +0000549 /*HasPasteOperator=*/true,
550 Macro, ArgNo, PP);
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000551 }
Mike Stump11289f42009-09-09 15:08:12 +0000552
Chris Lattnerd7daed12008-03-09 02:07:49 +0000553 // If anything changed, install this as the new Tokens list.
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000554 if (MadeChange) {
Chris Lattner8322dc82009-03-04 06:50:57 +0000555 assert(!OwnsTokens && "This would leak if we already own the token list");
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000556 // This is deleted in the dtor.
Chris Lattnerd7daed12008-03-09 02:07:49 +0000557 NumTokens = ResultToks.size();
Argyrios Kyrtzidis8cc04592011-06-29 22:20:11 +0000558 // The tokens will be added to Preprocessor's cache and will be removed
559 // when this TokenLexer finishes lexing them.
560 Tokens = PP.cacheMacroExpandedTokens(this, ResultToks);
Mike Stump11289f42009-09-09 15:08:12 +0000561
Argyrios Kyrtzidis8cc04592011-06-29 22:20:11 +0000562 // The preprocessor cache of macro expanded tokens owns these tokens,not us.
Chris Lattner8322dc82009-03-04 06:50:57 +0000563 OwnsTokens = false;
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000564 }
565}
Chris Lattner67b07cb2006-06-26 02:03:42 +0000566
Alexey Bataev583b0762014-12-15 04:18:11 +0000567/// \brief Checks if two tokens form wide string literal.
568static bool isWideStringLiteralFromMacro(const Token &FirstTok,
569 const Token &SecondTok) {
570 return FirstTok.is(tok::identifier) &&
571 FirstTok.getIdentifierInfo()->isStr("L") && SecondTok.isLiteral() &&
572 SecondTok.stringifiedInMacro();
573}
574
Chris Lattner22eb9722006-06-18 05:43:12 +0000575/// Lex - Lex and return a token from this macro stream.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000576///
Eli Friedman0834a4b2013-09-19 00:41:32 +0000577bool TokenLexer::Lex(Token &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000578 // Lexing off the end of the macro, pop this macro off the expansion stack.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000579 if (isAtEnd()) {
580 // If this is a macro (not a token stream), mark the macro enabled now
581 // that it is no longer being expanded.
582 if (Macro) Macro->EnableMacro();
583
Eli Friedman0834a4b2013-09-19 00:41:32 +0000584 Tok.startToken();
585 Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
Justin Bognereacd96d2014-02-04 19:18:32 +0000586 Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace || NextTokGetsSpace);
Faisal Valib8ece9f2017-10-03 00:52:14 +0000587 if (CurTokenIdx == 0)
Eli Friedman0834a4b2013-09-19 00:41:32 +0000588 Tok.setFlag(Token::LeadingEmptyMacro);
589 return PP.HandleEndOfTokenLexer(Tok);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000590 }
Mike Stump11289f42009-09-09 15:08:12 +0000591
Argyrios Kyrtzidise245aa22011-07-07 03:40:37 +0000592 SourceManager &SM = PP.getSourceManager();
593
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000594 // If this is the first token of the expanded result, we inherit spacing
595 // properties later.
Faisal Valib8ece9f2017-10-03 00:52:14 +0000596 bool isFirstToken = CurTokenIdx == 0;
Mike Stump11289f42009-09-09 15:08:12 +0000597
Chris Lattner22eb9722006-06-18 05:43:12 +0000598 // Get the next token to return.
Faisal Valib8ece9f2017-10-03 00:52:14 +0000599 Tok = Tokens[CurTokenIdx++];
Mike Stump11289f42009-09-09 15:08:12 +0000600
Chris Lattner1c1a00c2009-04-19 20:29:42 +0000601 bool TokenIsFromPaste = false;
Mike Stump11289f42009-09-09 15:08:12 +0000602
Chris Lattner01ecf832006-07-19 05:42:48 +0000603 // If this token is followed by a token paste (##) operator, paste the tokens!
Chris Lattner848fa212011-06-14 18:19:37 +0000604 // Note that ## is a normal token when not expanding a macro.
Alexey Bataev583b0762014-12-15 04:18:11 +0000605 if (!isAtEnd() && Macro &&
Faisal Valib8ece9f2017-10-03 00:52:14 +0000606 (Tokens[CurTokenIdx].is(tok::hashhash) ||
Alexey Bataev583b0762014-12-15 04:18:11 +0000607 // Special processing of L#x macros in -fms-compatibility mode.
608 // Microsoft compiler is able to form a wide string literal from
609 // 'L#macro_arg' construct in a function-like macro.
610 (PP.getLangOpts().MSVCCompat &&
Faisal Valib8ece9f2017-10-03 00:52:14 +0000611 isWideStringLiteralFromMacro(Tok, Tokens[CurTokenIdx])))) {
Chris Lattner6aab7312009-12-04 06:14:03 +0000612 // When handling the microsoft /##/ extension, the final token is
Faisal Valib8ece9f2017-10-03 00:52:14 +0000613 // returned by pasteTokens, not the pasted token.
614 if (pasteTokens(Tok))
Eli Friedman0834a4b2013-09-19 00:41:32 +0000615 return true;
Kovarththanan Rajaratname5f1c192010-03-13 08:53:33 +0000616
Chris Lattner6aab7312009-12-04 06:14:03 +0000617 TokenIsFromPaste = true;
Mike Stump11289f42009-09-09 15:08:12 +0000618 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000619
Chris Lattnerc673f902006-06-30 06:10:41 +0000620 // The token's current location indicate where the token was lexed from. We
621 // need this information to compute the spelling of the token, but any
622 // diagnostics for the expanded token should appear as if they came from
Chandler Carruthc9c84192011-07-14 08:20:34 +0000623 // ExpansionLoc. Pull this information together into a new SourceLocation
Chris Lattnerc673f902006-06-30 06:10:41 +0000624 // that captures all of this.
Chandler Carruthc9c84192011-07-14 08:20:34 +0000625 if (ExpandLocStart.isValid() && // Don't do this for token streams.
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000626 // Check that the token's location was not already set properly.
Argyrios Kyrtzidis5451a392011-08-23 21:02:35 +0000627 SM.isBeforeInSLocAddrSpace(Tok.getLocation(), MacroStartSLocOffset)) {
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000628 SourceLocation instLoc;
629 if (Tok.is(tok::comment)) {
Chandler Carruth115b0772011-07-26 03:03:05 +0000630 instLoc = SM.createExpansionLoc(Tok.getLocation(),
631 ExpandLocStart,
632 ExpandLocEnd,
633 Tok.getLength());
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000634 } else {
Argyrios Kyrtzidis60617122011-08-19 22:34:14 +0000635 instLoc = getExpansionLocForMacroDefLoc(Tok.getLocation());
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000636 }
637
638 Tok.setLocation(instLoc);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000639 }
Mike Stump11289f42009-09-09 15:08:12 +0000640
Chris Lattner22eb9722006-06-18 05:43:12 +0000641 // If this is the first token, set the lexical properties of the token to
642 // match the lexical properties of the macro identifier.
Chris Lattnere8dcfef2006-07-19 05:45:55 +0000643 if (isFirstToken) {
Chris Lattner146762e2007-07-20 16:59:19 +0000644 Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
645 Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Justin Bogner79c93842014-02-04 19:18:35 +0000646 } else {
647 // If this is not the first token, we may still need to pass through
648 // leading whitespace if we've expanded a macro.
Richard Smithf2baa702014-02-24 20:45:00 +0000649 if (AtStartOfLine) Tok.setFlag(Token::StartOfLine);
Justin Bogner79c93842014-02-04 19:18:35 +0000650 if (HasLeadingSpace) Tok.setFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +0000651 }
Justin Bogner79c93842014-02-04 19:18:35 +0000652 AtStartOfLine = false;
653 HasLeadingSpace = false;
Mike Stump11289f42009-09-09 15:08:12 +0000654
Chris Lattner22eb9722006-06-18 05:43:12 +0000655 // Handle recursive expansion!
Craig Topperd2d442c2014-05-17 23:10:59 +0000656 if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
Chris Lattner1f6c7fe2009-01-23 18:35:48 +0000657 // Change the kind of this identifier to the appropriate token kind, e.g.
658 // turning "for" into a keyword.
Argyrios Kyrtzidis48ce3b52009-05-22 21:09:31 +0000659 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner1f6c7fe2009-01-23 18:35:48 +0000660 Tok.setKind(II->getTokenID());
Mike Stump11289f42009-09-09 15:08:12 +0000661
Chris Lattner1c1a00c2009-04-19 20:29:42 +0000662 // If this identifier was poisoned and from a paste, emit an error. This
663 // won't be handled by Preprocessor::HandleIdentifier because this is coming
664 // from a macro expansion.
665 if (II->isPoisoned() && TokenIsFromPaste) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000666 PP.HandlePoisonedIdentifier(Tok);
Chris Lattner1c1a00c2009-04-19 20:29:42 +0000667 }
Mike Stump11289f42009-09-09 15:08:12 +0000668
Chris Lattner1f6c7fe2009-01-23 18:35:48 +0000669 if (!DisableMacroExpansion && II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +0000670 return PP.HandleIdentifier(Tok);
Chris Lattner1f6c7fe2009-01-23 18:35:48 +0000671 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000672
673 // Otherwise, return a normal token.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000674 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +0000675}
Chris Lattnerafe603f2006-07-11 04:02:46 +0000676
Faisal Valib8ece9f2017-10-03 00:52:14 +0000677bool TokenLexer::pasteTokens(Token &Tok) {
678 return pasteTokens(Tok, llvm::makeArrayRef(Tokens, NumTokens), CurTokenIdx);
679}
680/// LHSTok is the LHS of a ## operator, and CurTokenIdx is the ##
Chris Lattner01ecf832006-07-19 05:42:48 +0000681/// operator. Read the ## and RHS, and paste the LHS/RHS together. If there
Faisal Valib8ece9f2017-10-03 00:52:14 +0000682/// are more ## after it, chomp them iteratively. Return the result as LHSTok.
Chris Lattner3b5054d2008-02-07 06:03:59 +0000683/// If this returns true, the caller should immediately return the token.
Faisal Valib8ece9f2017-10-03 00:52:14 +0000684bool TokenLexer::pasteTokens(Token &LHSTok, ArrayRef<Token> TokenStream,
685 unsigned int &CurIdx) {
686 assert(CurIdx > 0 && "## can not be the first token within tokens");
Faisal Vali03b7b152017-10-03 01:33:36 +0000687 assert((TokenStream[CurIdx].is(tok::hashhash) ||
Faisal Valib8ece9f2017-10-03 00:52:14 +0000688 (PP.getLangOpts().MSVCCompat &&
Faisal Vali03b7b152017-10-03 01:33:36 +0000689 isWideStringLiteralFromMacro(LHSTok, TokenStream[CurIdx]))) &&
Faisal Valib8ece9f2017-10-03 00:52:14 +0000690 "Token at this Index must be ## or part of the MSVC 'L "
691 "#macro-arg' pasting pair");
692
Will Wilsondb2588a2015-04-17 12:43:57 +0000693 // MSVC: If previous token was pasted, this must be a recovery from an invalid
694 // paste operation. Ignore spaces before this token to mimic MSVC output.
695 // Required for generating valid UUID strings in some MS headers.
Faisal Valib8ece9f2017-10-03 00:52:14 +0000696 if (PP.getLangOpts().MicrosoftExt && (CurIdx >= 2) &&
697 TokenStream[CurIdx - 2].is(tok::hashhash))
698 LHSTok.clearFlag(Token::LeadingSpace);
Will Wilsondb2588a2015-04-17 12:43:57 +0000699
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000700 SmallString<128> Buffer;
Craig Topperd2d442c2014-05-17 23:10:59 +0000701 const char *ResultTokStrPtr = nullptr;
Faisal Valib8ece9f2017-10-03 00:52:14 +0000702 SourceLocation StartLoc = LHSTok.getLocation();
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000703 SourceLocation PasteOpLoc;
Faisal Valib8ece9f2017-10-03 00:52:14 +0000704
705 auto IsAtEnd = [&TokenStream, &CurIdx] {
706 return TokenStream.size() == CurIdx;
707 };
708
Chris Lattner01ecf832006-07-19 05:42:48 +0000709 do {
Alexey Bataev583b0762014-12-15 04:18:11 +0000710 // Consume the ## operator if any.
Faisal Valib8ece9f2017-10-03 00:52:14 +0000711 PasteOpLoc = TokenStream[CurIdx].getLocation();
712 if (TokenStream[CurIdx].is(tok::hashhash))
713 ++CurIdx;
714 assert(!IsAtEnd() && "No token on the RHS of a paste operator!");
Mike Stump11289f42009-09-09 15:08:12 +0000715
Chris Lattner01ecf832006-07-19 05:42:48 +0000716 // Get the RHS token.
Faisal Valib8ece9f2017-10-03 00:52:14 +0000717 const Token &RHS = TokenStream[CurIdx];
Mike Stump11289f42009-09-09 15:08:12 +0000718
Chris Lattner01ecf832006-07-19 05:42:48 +0000719 // Allocate space for the result token. This is guaranteed to be enough for
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000720 // the two tokens.
Faisal Valib8ece9f2017-10-03 00:52:14 +0000721 Buffer.resize(LHSTok.getLength() + RHS.getLength());
Mike Stump11289f42009-09-09 15:08:12 +0000722
Chris Lattner01ecf832006-07-19 05:42:48 +0000723 // Get the spelling of the LHS token in Buffer.
Chris Lattner57dd8362006-11-03 07:45:04 +0000724 const char *BufPtr = &Buffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000725 bool Invalid = false;
Faisal Valib8ece9f2017-10-03 00:52:14 +0000726 unsigned LHSLen = PP.getSpelling(LHSTok, BufPtr, &Invalid);
Chris Lattner57dd8362006-11-03 07:45:04 +0000727 if (BufPtr != &Buffer[0]) // Really, we want the chars in Buffer!
728 memcpy(&Buffer[0], BufPtr, LHSLen);
Douglas Gregordc970f02010-03-16 22:30:13 +0000729 if (Invalid)
730 return true;
David Majnemerd3c3e782014-10-25 11:40:40 +0000731
732 BufPtr = Buffer.data() + LHSLen;
Douglas Gregordc970f02010-03-16 22:30:13 +0000733 unsigned RHSLen = PP.getSpelling(RHS, BufPtr, &Invalid);
734 if (Invalid)
735 return true;
David Majnemerd3c3e782014-10-25 11:40:40 +0000736 if (RHSLen && BufPtr != &Buffer[LHSLen])
737 // Really, we want the chars in Buffer!
Chris Lattner57dd8362006-11-03 07:45:04 +0000738 memcpy(&Buffer[LHSLen], BufPtr, RHSLen);
Mike Stump11289f42009-09-09 15:08:12 +0000739
Chris Lattner57dd8362006-11-03 07:45:04 +0000740 // Trim excess space.
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000741 Buffer.resize(LHSLen+RHSLen);
Mike Stump11289f42009-09-09 15:08:12 +0000742
Chris Lattner01ecf832006-07-19 05:42:48 +0000743 // Plop the pasted result (including the trailing newline and null) into a
744 // scratch buffer where we can lex it.
Chris Lattner5a7971e2009-01-26 19:29:26 +0000745 Token ResultTokTmp;
746 ResultTokTmp.startToken();
Mike Stump11289f42009-09-09 15:08:12 +0000747
Chris Lattner5a7971e2009-01-26 19:29:26 +0000748 // Claim that the tmp token is a string_literal so that we can get the
Chris Lattner43c8be52009-12-23 21:29:53 +0000749 // character pointer back from CreateString in getLiteralData().
Chris Lattner5a7971e2009-01-26 19:29:26 +0000750 ResultTokTmp.setKind(tok::string_literal);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000751 PP.CreateString(Buffer, ResultTokTmp);
Chris Lattner5a7971e2009-01-26 19:29:26 +0000752 SourceLocation ResultTokLoc = ResultTokTmp.getLocation();
753 ResultTokStrPtr = ResultTokTmp.getLiteralData();
754
Chris Lattner01ecf832006-07-19 05:42:48 +0000755 // Lex the resultant pasted token into Result.
Chris Lattner146762e2007-07-20 16:59:19 +0000756 Token Result;
Mike Stump11289f42009-09-09 15:08:12 +0000757
Faisal Valib8ece9f2017-10-03 00:52:14 +0000758 if (LHSTok.isAnyIdentifier() && RHS.isAnyIdentifier()) {
Chris Lattner510ab612006-07-20 04:47:30 +0000759 // Common paste case: identifier+identifier = identifier. Avoid creating
760 // a lexer and other overhead.
761 PP.IncrementPasteCounter(true);
Chris Lattner8c204872006-10-14 05:19:21 +0000762 Result.startToken();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000763 Result.setKind(tok::raw_identifier);
764 Result.setRawIdentifierData(ResultTokStrPtr);
Chris Lattner8c204872006-10-14 05:19:21 +0000765 Result.setLocation(ResultTokLoc);
766 Result.setLength(LHSLen+RHSLen);
Chris Lattnera7e2e742006-07-19 06:32:35 +0000767 } else {
Chris Lattner510ab612006-07-20 04:47:30 +0000768 PP.IncrementPasteCounter(false);
Mike Stump11289f42009-09-09 15:08:12 +0000769
Chris Lattner29a2a192009-01-19 06:46:35 +0000770 assert(ResultTokLoc.isFileID() &&
771 "Should be a raw location into scratch buffer");
Chris Lattnera7e2e742006-07-19 06:32:35 +0000772 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner5a7971e2009-01-26 19:29:26 +0000773 FileID LocFileID = SourceMgr.getFileID(ResultTokLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000774
Douglas Gregore0fbb832010-03-16 00:06:06 +0000775 bool Invalid = false;
Douglas Gregor802b7762010-03-15 22:54:52 +0000776 const char *ScratchBufStart
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000777 = SourceMgr.getBufferData(LocFileID, &Invalid).data();
Douglas Gregore0fbb832010-03-16 00:06:06 +0000778 if (Invalid)
Douglas Gregor802b7762010-03-15 22:54:52 +0000779 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000780
Chris Lattner29a2a192009-01-19 06:46:35 +0000781 // Make a lexer to lex this string from. Lex just this one token.
Chris Lattnera7e2e742006-07-19 06:32:35 +0000782 // Make a lexer object so that we lex and expand the paste result.
Chris Lattner5a7971e2009-01-26 19:29:26 +0000783 Lexer TL(SourceMgr.getLocForStartOfFile(LocFileID),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000784 PP.getLangOpts(), ScratchBufStart,
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000785 ResultTokStrPtr, ResultTokStrPtr+LHSLen+RHSLen);
Mike Stump11289f42009-09-09 15:08:12 +0000786
Chris Lattnera7e2e742006-07-19 06:32:35 +0000787 // Lex a token in raw mode. This way it won't look up identifiers
788 // automatically, lexing off the end will return an eof token, and
789 // warnings are disabled. This returns true if the result token is the
790 // entire buffer.
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000791 bool isInvalid = !TL.LexFromRawLexer(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000792
Chris Lattnera7e2e742006-07-19 06:32:35 +0000793 // If we got an EOF token, we didn't form even ONE token. For example, we
794 // did "/ ## /" to get "//".
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000795 isInvalid |= Result.is(tok::eof);
Mike Stump11289f42009-09-09 15:08:12 +0000796
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000797 // If pasting the two tokens didn't form a full new token, this is an
Faisal Valib8ece9f2017-10-03 00:52:14 +0000798 // error. This occurs with "x ## +" and other stuff. Return with LHSTok
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000799 // unmodified and with RHS as the next token to lex.
800 if (isInvalid) {
Nico Weber446cf252015-12-29 23:06:17 +0000801 // Explicitly convert the token location to have proper expansion
802 // information so that the user knows where it came from.
803 SourceManager &SM = PP.getSourceManager();
804 SourceLocation Loc =
805 SM.createExpansionLoc(PasteOpLoc, ExpandLocStart, ExpandLocEnd, 2);
806
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000807 // Test for the Microsoft extension of /##/ turning into // here on the
808 // error path.
Faisal Valib8ece9f2017-10-03 00:52:14 +0000809 if (PP.getLangOpts().MicrosoftExt && LHSTok.is(tok::slash) &&
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000810 RHS.is(tok::slash)) {
Faisal Valib8ece9f2017-10-03 00:52:14 +0000811 HandleMicrosoftCommentPaste(LHSTok, Loc);
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000812 return true;
813 }
Mike Stump11289f42009-09-09 15:08:12 +0000814
Chris Lattner52c00bd2010-07-17 16:24:30 +0000815 // Do not emit the error when preprocessing assembler code.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000816 if (!PP.getLangOpts().AsmPreprocessor) {
Chris Lattner52c00bd2010-07-17 16:24:30 +0000817 // If we're in microsoft extensions mode, downgrade this from a hard
Richard Smith7b157342014-02-18 00:45:50 +0000818 // error to an extension that defaults to an error. This allows
Chris Lattner52c00bd2010-07-17 16:24:30 +0000819 // disabling it.
Richard Smith7b157342014-02-18 00:45:50 +0000820 PP.Diag(Loc, PP.getLangOpts().MicrosoftExt ? diag::ext_pp_bad_paste_ms
821 : diag::err_pp_bad_paste)
Yaron Keren92e1b622015-03-18 10:17:07 +0000822 << Buffer;
Chris Lattner7f4153d2009-05-28 05:39:39 +0000823 }
Mike Stump11289f42009-09-09 15:08:12 +0000824
Richard Smitha60742a2012-06-13 19:02:56 +0000825 // An error has occurred so exit loop.
826 break;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000827 }
Mike Stump11289f42009-09-09 15:08:12 +0000828
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000829 // Turn ## into 'unknown' to avoid # ## # from looking like a paste
830 // operator.
831 if (Result.is(tok::hashhash))
832 Result.setKind(tok::unknown);
Chris Lattner01ecf832006-07-19 05:42:48 +0000833 }
Mike Stump11289f42009-09-09 15:08:12 +0000834
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000835 // Transfer properties of the LHS over the Result.
Faisal Valib8ece9f2017-10-03 00:52:14 +0000836 Result.setFlagValue(Token::StartOfLine , LHSTok.isAtStartOfLine());
837 Result.setFlagValue(Token::LeadingSpace, LHSTok.hasLeadingSpace());
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000838
Chris Lattner01ecf832006-07-19 05:42:48 +0000839 // Finally, replace LHS with the result, consume the RHS, and iterate.
Faisal Valib8ece9f2017-10-03 00:52:14 +0000840 ++CurIdx;
841 LHSTok = Result;
842 } while (!IsAtEnd() && TokenStream[CurIdx].is(tok::hashhash));
Mike Stump11289f42009-09-09 15:08:12 +0000843
Faisal Valib8ece9f2017-10-03 00:52:14 +0000844 SourceLocation EndLoc = TokenStream[CurIdx - 1].getLocation();
Abramo Bagnarae398e602011-10-03 18:39:03 +0000845
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000846 // The token's current location indicate where the token was lexed from. We
847 // need this information to compute the spelling of the token, but any
848 // diagnostics for the expanded token should appear as if the token was
Abramo Bagnarae398e602011-10-03 18:39:03 +0000849 // expanded from the full ## expression. Pull this information together into
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000850 // a new SourceLocation that captures all of this.
Argyrios Kyrtzidis7a7ff682011-08-23 21:02:32 +0000851 SourceManager &SM = PP.getSourceManager();
Abramo Bagnarae398e602011-10-03 18:39:03 +0000852 if (StartLoc.isFileID())
853 StartLoc = getExpansionLocForMacroDefLoc(StartLoc);
854 if (EndLoc.isFileID())
855 EndLoc = getExpansionLocForMacroDefLoc(EndLoc);
Eli Friedmanfe9d1102012-12-01 01:15:54 +0000856 FileID MacroFID = SM.getFileID(MacroExpansionStart);
857 while (SM.getFileID(StartLoc) != MacroFID)
858 StartLoc = SM.getImmediateExpansionRange(StartLoc).first;
859 while (SM.getFileID(EndLoc) != MacroFID)
860 EndLoc = SM.getImmediateExpansionRange(EndLoc).second;
861
Faisal Valib8ece9f2017-10-03 00:52:14 +0000862 LHSTok.setLocation(SM.createExpansionLoc(LHSTok.getLocation(), StartLoc, EndLoc,
863 LHSTok.getLength()));
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000864
Chris Lattner0f1f5052006-07-20 04:16:23 +0000865 // Now that we got the result token, it will be subject to expansion. Since
866 // token pasting re-lexes the result token in raw mode, identifier information
867 // isn't looked up. As such, if the result is an identifier, look up id info.
Faisal Valib8ece9f2017-10-03 00:52:14 +0000868 if (LHSTok.is(tok::raw_identifier)) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000869 // Look up the identifier info for the token. We disabled identifier lookup
870 // by saying we're skipping contents, so we need to do this manually.
Faisal Valib8ece9f2017-10-03 00:52:14 +0000871 PP.LookUpIdentifierInfo(LHSTok);
Chris Lattner0f1f5052006-07-20 04:16:23 +0000872 }
Chris Lattner3b5054d2008-02-07 06:03:59 +0000873 return false;
Chris Lattner01ecf832006-07-19 05:42:48 +0000874}
875
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000876/// isNextTokenLParen - If the next token lexed will pop this macro off the
877/// expansion stack, return 2. If the next unexpanded token is a '(', return
878/// 1, otherwise return 0.
Chris Lattner95d72cd2008-03-09 02:18:51 +0000879unsigned TokenLexer::isNextTokenLParen() const {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000880 // Out of tokens?
Chris Lattnerb935d8c2006-07-14 06:54:44 +0000881 if (isAtEnd())
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000882 return 2;
Faisal Valib8ece9f2017-10-03 00:52:14 +0000883 return Tokens[CurTokenIdx].is(tok::l_paren);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000884}
Chris Lattner3b5054d2008-02-07 06:03:59 +0000885
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000886/// isParsingPreprocessorDirective - Return true if we are in the middle of a
887/// preprocessor directive.
888bool TokenLexer::isParsingPreprocessorDirective() const {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000889 return Tokens[NumTokens-1].is(tok::eod) && !isAtEnd();
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000890}
Chris Lattner3b5054d2008-02-07 06:03:59 +0000891
892/// HandleMicrosoftCommentPaste - In microsoft compatibility mode, /##/ pastes
893/// together to form a comment that comments out everything in the current
894/// macro, other active macros, and anything left on the current physical
Chandler Carruthc9c84192011-07-14 08:20:34 +0000895/// source line of the expanded buffer. Handle this by returning the
Chris Lattner3b5054d2008-02-07 06:03:59 +0000896/// first token on the next line.
Nico Weber446cf252015-12-29 23:06:17 +0000897void TokenLexer::HandleMicrosoftCommentPaste(Token &Tok, SourceLocation OpLoc) {
898 PP.Diag(OpLoc, diag::ext_comment_paste_microsoft);
899
Chris Lattner3b5054d2008-02-07 06:03:59 +0000900 // We 'comment out' the rest of this macro by just ignoring the rest of the
901 // tokens that have not been lexed yet, if any.
Mike Stump11289f42009-09-09 15:08:12 +0000902
Chris Lattner3b5054d2008-02-07 06:03:59 +0000903 // Since this must be a macro, mark the macro enabled now that it is no longer
904 // being expanded.
905 assert(Macro && "Token streams can't paste comments");
906 Macro->EnableMacro();
Mike Stump11289f42009-09-09 15:08:12 +0000907
Chris Lattner3b5054d2008-02-07 06:03:59 +0000908 PP.HandleMicrosoftCommentPaste(Tok);
909}
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000910
Argyrios Kyrtzidis60617122011-08-19 22:34:14 +0000911/// \brief If \arg loc is a file ID and points inside the current macro
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000912/// definition, returns the appropriate source location pointing at the
Argyrios Kyrtzidis60617122011-08-19 22:34:14 +0000913/// macro expansion source location entry, otherwise it returns an invalid
914/// SourceLocation.
915SourceLocation
916TokenLexer::getExpansionLocForMacroDefLoc(SourceLocation loc) const {
Chandler Carruthc9c84192011-07-14 08:20:34 +0000917 assert(ExpandLocStart.isValid() && MacroExpansionStart.isValid() &&
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000918 "Not appropriate for token streams");
Argyrios Kyrtzidis7a7ff682011-08-23 21:02:32 +0000919 assert(loc.isValid() && loc.isFileID());
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000920
921 SourceManager &SM = PP.getSourceManager();
Argyrios Kyrtzidise7f75162011-08-23 21:02:38 +0000922 assert(SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength) &&
923 "Expected loc to come from the macro definition");
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000924
Argyrios Kyrtzidise7f75162011-08-23 21:02:38 +0000925 unsigned relativeOffset = 0;
926 SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength, &relativeOffset);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000927 return MacroExpansionStart.getLocWithOffset(relativeOffset);
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000928}
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +0000929
930/// \brief Finds the tokens that are consecutive (from the same FileID)
931/// creates a single SLocEntry, and assigns SourceLocations to each token that
932/// point to that SLocEntry. e.g for
933/// assert(foo == bar);
934/// There will be a single SLocEntry for the "foo == bar" chunk and locations
935/// for the 'foo', '==', 'bar' tokens will point inside that chunk.
936///
937/// \arg begin_tokens will be updated to a position past all the found
938/// consecutive tokens.
939static void updateConsecutiveMacroArgTokens(SourceManager &SM,
940 SourceLocation InstLoc,
941 Token *&begin_tokens,
942 Token * end_tokens) {
943 assert(begin_tokens < end_tokens);
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +0000944
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +0000945 SourceLocation FirstLoc = begin_tokens->getLocation();
946 SourceLocation CurLoc = FirstLoc;
947
948 // Compare the source location offset of tokens and group together tokens that
949 // are close, even if their locations point to different FileIDs. e.g.
950 //
951 // |bar | foo | cake | (3 tokens from 3 consecutive FileIDs)
952 // ^ ^
953 // |bar foo cake| (one SLocEntry chunk for all tokens)
954 //
955 // we can perform this "merge" since the token's spelling location depends
956 // on the relative offset.
957
958 Token *NextTok = begin_tokens + 1;
959 for (; NextTok < end_tokens; ++NextTok) {
Argyrios Kyrtzidis5e149252012-12-19 23:55:44 +0000960 SourceLocation NextLoc = NextTok->getLocation();
961 if (CurLoc.isFileID() != NextLoc.isFileID())
962 break; // Token from different kind of FileID.
963
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +0000964 int RelOffs;
Argyrios Kyrtzidis5e149252012-12-19 23:55:44 +0000965 if (!SM.isInSameSLocAddrSpace(CurLoc, NextLoc, &RelOffs))
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +0000966 break; // Token from different local/loaded location.
967 // Check that token is not before the previous token or more than 50
968 // "characters" away.
969 if (RelOffs < 0 || RelOffs > 50)
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +0000970 break;
Vedant Kumar3339c562016-07-07 22:38:29 +0000971
972 if (CurLoc.isMacroID() && !SM.isWrittenInSameFile(CurLoc, NextLoc))
973 break; // Token from a different macro.
974
Argyrios Kyrtzidis5e149252012-12-19 23:55:44 +0000975 CurLoc = NextLoc;
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +0000976 }
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +0000977
978 // For the consecutive tokens, find the length of the SLocEntry to contain
979 // all of them.
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +0000980 Token &LastConsecutiveTok = *(NextTok-1);
Argyrios Kyrtzidisb87ea982011-08-24 20:33:05 +0000981 int LastRelOffs = 0;
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +0000982 SM.isInSameSLocAddrSpace(FirstLoc, LastConsecutiveTok.getLocation(),
983 &LastRelOffs);
984 unsigned FullLength = LastRelOffs + LastConsecutiveTok.getLength();
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +0000985
986 // Create a macro expansion SLocEntry that will "contain" all of the tokens.
987 SourceLocation Expansion =
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +0000988 SM.createMacroArgExpansionLoc(FirstLoc, InstLoc,FullLength);
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +0000989
990 // Change the location of the tokens from the spelling location to the new
991 // expanded location.
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +0000992 for (; begin_tokens < NextTok; ++begin_tokens) {
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +0000993 Token &Tok = *begin_tokens;
Argyrios Kyrtzidisb87ea982011-08-24 20:33:05 +0000994 int RelOffs = 0;
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +0000995 SM.isInSameSLocAddrSpace(FirstLoc, Tok.getLocation(), &RelOffs);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000996 Tok.setLocation(Expansion.getLocWithOffset(RelOffs));
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +0000997 }
998}
999
1000/// \brief Creates SLocEntries and updates the locations of macro argument
1001/// tokens to their new expanded locations.
1002///
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00001003/// \param ArgIdSpellLoc the location of the macro argument id inside the macro
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +00001004/// definition.
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +00001005void TokenLexer::updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc,
1006 Token *begin_tokens,
1007 Token *end_tokens) {
1008 SourceManager &SM = PP.getSourceManager();
1009
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +00001010 SourceLocation InstLoc =
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +00001011 getExpansionLocForMacroDefLoc(ArgIdSpellLoc);
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +00001012
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +00001013 while (begin_tokens < end_tokens) {
1014 // If there's only one token just create a SLocEntry for it.
1015 if (end_tokens - begin_tokens == 1) {
1016 Token &Tok = *begin_tokens;
1017 Tok.setLocation(SM.createMacroArgExpansionLoc(Tok.getLocation(),
1018 InstLoc,
1019 Tok.getLength()));
1020 return;
1021 }
1022
1023 updateConsecutiveMacroArgTokens(SM, InstLoc, begin_tokens, end_tokens);
1024 }
Argyrios Kyrtzidiseeca36f2011-08-19 22:34:17 +00001025}
Eli Friedman0834a4b2013-09-19 00:41:32 +00001026
1027void TokenLexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
1028 AtStartOfLine = Result.isAtStartOfLine();
1029 HasLeadingSpace = Result.hasLeadingSpace();
1030}