1 //===- TokenLexer.cpp - Lex from a token stream ---------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the TokenLexer interface.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Lex/TokenLexer.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/IdentifierTable.h"
16 #include "clang/Basic/LangOptions.h"
17 #include "clang/Basic/SourceLocation.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Basic/TokenKinds.h"
20 #include "clang/Lex/LexDiagnostic.h"
21 #include "clang/Lex/Lexer.h"
22 #include "clang/Lex/MacroArgs.h"
23 #include "clang/Lex/MacroInfo.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Lex/Token.h"
26 #include "clang/Lex/VariadicMacroSupport.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/iterator_range.h"
31 #include <cassert>
32 #include <cstring>
33 
34 using namespace clang;
35 
36 /// Create a TokenLexer for the specified macro with the specified actual
37 /// arguments.  Note that this ctor takes ownership of the ActualArgs pointer.
38 void TokenLexer::Init(Token &Tok, SourceLocation ELEnd, MacroInfo *MI,
39                       MacroArgs *Actuals) {
40   // If the client is reusing a TokenLexer, make sure to free any memory
41   // associated with it.
42   destroy();
43 
44   Macro = MI;
45   ActualArgs = Actuals;
46   CurTokenIdx = 0;
47 
48   ExpandLocStart = Tok.getLocation();
49   ExpandLocEnd = ELEnd;
50   AtStartOfLine = Tok.isAtStartOfLine();
51   HasLeadingSpace = Tok.hasLeadingSpace();
52   NextTokGetsSpace = false;
53   Tokens = &*Macro->tokens_begin();
54   OwnsTokens = false;
55   DisableMacroExpansion = false;
56   IsReinject = false;
57   NumTokens = Macro->tokens_end()-Macro->tokens_begin();
58   MacroExpansionStart = SourceLocation();
59 
60   SourceManager &SM = PP.getSourceManager();
61   MacroStartSLocOffset = SM.getNextLocalOffset();
62 
63   if (NumTokens > 0) {
64     assert(Tokens[0].getLocation().isValid());
65     assert((Tokens[0].getLocation().isFileID() || Tokens[0].is(tok::comment)) &&
66            "Macro defined in macro?");
67     assert(ExpandLocStart.isValid());
68 
69     // Reserve a source location entry chunk for the length of the macro
70     // definition. Tokens that get lexed directly from the definition will
71     // have their locations pointing inside this chunk. This is to avoid
72     // creating separate source location entries for each token.
73     MacroDefStart = SM.getExpansionLoc(Tokens[0].getLocation());
74     MacroDefLength = Macro->getDefinitionLength(SM);
75     MacroExpansionStart = SM.createExpansionLoc(MacroDefStart,
76                                                 ExpandLocStart,
77                                                 ExpandLocEnd,
78                                                 MacroDefLength);
79   }
80 
81   // If this is a function-like macro, expand the arguments and change
82   // Tokens to point to the expanded tokens.
83   if (Macro->isFunctionLike() && Macro->getNumParams())
84     ExpandFunctionArguments();
85 
86   // Mark the macro as currently disabled, so that it is not recursively
87   // expanded.  The macro must be disabled only after argument pre-expansion of
88   // function-like macro arguments occurs.
89   Macro->DisableMacro();
90 }
91 
92 /// Create a TokenLexer for the specified token stream.  This does not
93 /// take ownership of the specified token vector.
94 void TokenLexer::Init(const Token *TokArray, unsigned NumToks,
95                       bool disableMacroExpansion, bool ownsTokens,
96                       bool isReinject) {
97   assert(!isReinject || disableMacroExpansion);
98   // If the client is reusing a TokenLexer, make sure to free any memory
99   // associated with it.
100   destroy();
101 
102   Macro = nullptr;
103   ActualArgs = nullptr;
104   Tokens = TokArray;
105   OwnsTokens = ownsTokens;
106   DisableMacroExpansion = disableMacroExpansion;
107   IsReinject = isReinject;
108   NumTokens = NumToks;
109   CurTokenIdx = 0;
110   ExpandLocStart = ExpandLocEnd = SourceLocation();
111   AtStartOfLine = false;
112   HasLeadingSpace = false;
113   NextTokGetsSpace = false;
114   MacroExpansionStart = SourceLocation();
115 
116   // Set HasLeadingSpace/AtStartOfLine so that the first token will be
117   // returned unmodified.
118   if (NumToks != 0) {
119     AtStartOfLine   = TokArray[0].isAtStartOfLine();
120     HasLeadingSpace = TokArray[0].hasLeadingSpace();
121   }
122 }
123 
124 void TokenLexer::destroy() {
125   // If this was a function-like macro that actually uses its arguments, delete
126   // the expanded tokens.
127   if (OwnsTokens) {
128     delete [] Tokens;
129     Tokens = nullptr;
130     OwnsTokens = false;
131   }
132 
133   // TokenLexer owns its formal arguments.
134   if (ActualArgs) ActualArgs->destroy(PP);
135 }
136 
137 bool TokenLexer::MaybeRemoveCommaBeforeVaArgs(
138     SmallVectorImpl<Token> &ResultToks, bool HasPasteOperator, MacroInfo *Macro,
139     unsigned MacroArgNo, Preprocessor &PP) {
140   // Is the macro argument __VA_ARGS__?
141   if (!Macro->isVariadic() || MacroArgNo != Macro->getNumParams()-1)
142     return false;
143 
144   // In Microsoft-compatibility mode, a comma is removed in the expansion
145   // of " ... , __VA_ARGS__ " if __VA_ARGS__ is empty.  This extension is
146   // not supported by gcc.
147   if (!HasPasteOperator && !PP.getLangOpts().MSVCCompat)
148     return false;
149 
150   // GCC removes the comma in the expansion of " ... , ## __VA_ARGS__ " if
151   // __VA_ARGS__ is empty, but not in strict mode where there are no
152   // named arguments, where it remains.  With GNU extensions, it is removed
153   // regardless of named arguments.
154   // Microsoft also appears to support this extension, unofficially.
155   if (!PP.getLangOpts().GNUMode && Macro->getNumParams() < 2)
156     return false;
157 
158   // Is a comma available to be removed?
159   if (ResultToks.empty() || !ResultToks.back().is(tok::comma))
160     return false;
161 
162   // Issue an extension diagnostic for the paste operator.
163   if (HasPasteOperator)
164     PP.Diag(ResultToks.back().getLocation(), diag::ext_paste_comma);
165 
166   // Remove the comma.
167   ResultToks.pop_back();
168 
169   if (!ResultToks.empty()) {
170     // If the comma was right after another paste (e.g. "X##,##__VA_ARGS__"),
171     // then removal of the comma should produce a placemarker token (in C99
172     // terms) which we model by popping off the previous ##, giving us a plain
173     // "X" when __VA_ARGS__ is empty.
174     if (ResultToks.back().is(tok::hashhash))
175       ResultToks.pop_back();
176 
177     // Remember that this comma was elided.
178     ResultToks.back().setFlag(Token::CommaAfterElided);
179   }
180 
181   // Never add a space, even if the comma, ##, or arg had a space.
182   NextTokGetsSpace = false;
183   return true;
184 }
185 
186 void TokenLexer::stringifyVAOPTContents(
187     SmallVectorImpl<Token> &ResultToks, const VAOptExpansionContext &VCtx,
188     const SourceLocation VAOPTClosingParenLoc) {
189   const int NumToksPriorToVAOpt = VCtx.getNumberOfTokensPriorToVAOpt();
190   const unsigned int NumVAOptTokens = ResultToks.size() - NumToksPriorToVAOpt;
191   Token *const VAOPTTokens =
192       NumVAOptTokens ? &ResultToks[NumToksPriorToVAOpt] : nullptr;
193 
194   SmallVector<Token, 64> ConcatenatedVAOPTResultToks;
195   // FIXME: Should we keep track within VCtx that we did or didnot
196   // encounter pasting - and only then perform this loop.
197 
198   // Perform token pasting (concatenation) prior to stringization.
199   for (unsigned int CurTokenIdx = 0; CurTokenIdx != NumVAOptTokens;
200        ++CurTokenIdx) {
201     if (VAOPTTokens[CurTokenIdx].is(tok::hashhash)) {
202       assert(CurTokenIdx != 0 &&
203              "Can not have __VAOPT__ contents begin with a ##");
204       Token &LHS = VAOPTTokens[CurTokenIdx - 1];
205       pasteTokens(LHS, llvm::makeArrayRef(VAOPTTokens, NumVAOptTokens),
206                   CurTokenIdx);
207       // Replace the token prior to the first ## in this iteration.
208       ConcatenatedVAOPTResultToks.back() = LHS;
209       if (CurTokenIdx == NumVAOptTokens)
210         break;
211     }
212     ConcatenatedVAOPTResultToks.push_back(VAOPTTokens[CurTokenIdx]);
213   }
214 
215   ConcatenatedVAOPTResultToks.push_back(VCtx.getEOFTok());
216   // Get the SourceLocation that represents the start location within
217   // the macro definition that marks where this string is substituted
218   // into: i.e. the __VA_OPT__ and the ')' within the spelling of the
219   // macro definition, and use it to indicate that the stringified token
220   // was generated from that location.
221   const SourceLocation ExpansionLocStartWithinMacro =
222       getExpansionLocForMacroDefLoc(VCtx.getVAOptLoc());
223   const SourceLocation ExpansionLocEndWithinMacro =
224       getExpansionLocForMacroDefLoc(VAOPTClosingParenLoc);
225 
226   Token StringifiedVAOPT = MacroArgs::StringifyArgument(
227       &ConcatenatedVAOPTResultToks[0], PP, VCtx.hasCharifyBefore() /*Charify*/,
228       ExpansionLocStartWithinMacro, ExpansionLocEndWithinMacro);
229 
230   if (VCtx.getLeadingSpaceForStringifiedToken())
231     StringifiedVAOPT.setFlag(Token::LeadingSpace);
232 
233   StringifiedVAOPT.setFlag(Token::StringifiedInMacro);
234   // Resize (shrink) the token stream to just capture this stringified token.
235   ResultToks.resize(NumToksPriorToVAOpt + 1);
236   ResultToks.back() = StringifiedVAOPT;
237 }
238 
239 /// Expand the arguments of a function-like macro so that we can quickly
240 /// return preexpanded tokens from Tokens.
241 void TokenLexer::ExpandFunctionArguments() {
242   SmallVector<Token, 128> ResultToks;
243 
244   // Loop through 'Tokens', expanding them into ResultToks.  Keep
245   // track of whether we change anything.  If not, no need to keep them.  If so,
246   // we install the newly expanded sequence as the new 'Tokens' list.
247   bool MadeChange = false;
248 
249   Optional<bool> CalledWithVariadicArguments;
250 
251   VAOptExpansionContext VCtx(PP);
252 
253   for (unsigned I = 0, E = NumTokens; I != E; ++I) {
254     const Token &CurTok = Tokens[I];
255     // We don't want a space for the next token after a paste
256     // operator.  In valid code, the token will get smooshed onto the
257     // preceding one anyway. In assembler-with-cpp mode, invalid
258     // pastes are allowed through: in this case, we do not want the
259     // extra whitespace to be added.  For example, we want ". ## foo"
260     // -> ".foo" not ". foo".
261     if (I != 0 && !Tokens[I-1].is(tok::hashhash) && CurTok.hasLeadingSpace())
262       NextTokGetsSpace = true;
263 
264     if (VCtx.isVAOptToken(CurTok)) {
265       MadeChange = true;
266       assert(Tokens[I + 1].is(tok::l_paren) &&
267              "__VA_OPT__ must be followed by '('");
268 
269       ++I;             // Skip the l_paren
270       VCtx.sawVAOptFollowedByOpeningParens(CurTok.getLocation(),
271                                            ResultToks.size());
272 
273       continue;
274     }
275 
276     // We have entered into the __VA_OPT__ context, so handle tokens
277     // appropriately.
278     if (VCtx.isInVAOpt()) {
279       // If we are about to process a token that is either an argument to
280       // __VA_OPT__ or its closing rparen, then:
281       //  1) If the token is the closing rparen that exits us out of __VA_OPT__,
282       //  perform any necessary stringification or placemarker processing,
283       //  and/or skip to the next token.
284       //  2) else if macro was invoked without variadic arguments skip this
285       //  token.
286       //  3) else (macro was invoked with variadic arguments) process the token
287       //  normally.
288 
289       if (Tokens[I].is(tok::l_paren))
290         VCtx.sawOpeningParen(Tokens[I].getLocation());
291       // Continue skipping tokens within __VA_OPT__ if the macro was not
292       // called with variadic arguments, else let the rest of the loop handle
293       // this token. Note sawClosingParen() returns true only if the r_paren matches
294       // the closing r_paren of the __VA_OPT__.
295       if (!Tokens[I].is(tok::r_paren) || !VCtx.sawClosingParen()) {
296         // Lazily expand __VA_ARGS__ when we see the first __VA_OPT__.
297         if (!CalledWithVariadicArguments.hasValue()) {
298           CalledWithVariadicArguments =
299               ActualArgs->invokedWithVariadicArgument(Macro, PP);
300         }
301         if (!*CalledWithVariadicArguments) {
302           // Skip this token.
303           continue;
304         }
305         // ... else the macro was called with variadic arguments, and we do not
306         // have a closing rparen - so process this token normally.
307       } else {
308         // Current token is the closing r_paren which marks the end of the
309         // __VA_OPT__ invocation, so handle any place-marker pasting (if
310         // empty) by removing hashhash either before (if exists) or after. And
311         // also stringify the entire contents if VAOPT was preceded by a hash,
312         // but do so only after any token concatenation that needs to occur
313         // within the contents of VAOPT.
314 
315         if (VCtx.hasStringifyOrCharifyBefore()) {
316           // Replace all the tokens just added from within VAOPT into a single
317           // stringified token. This requires token-pasting to eagerly occur
318           // within these tokens. If either the contents of VAOPT were empty
319           // or the macro wasn't called with any variadic arguments, the result
320           // is a token that represents an empty string.
321           stringifyVAOPTContents(ResultToks, VCtx,
322                                  /*ClosingParenLoc*/ Tokens[I].getLocation());
323 
324         } else if (/*No tokens within VAOPT*/
325                    ResultToks.size() == VCtx.getNumberOfTokensPriorToVAOpt()) {
326           // Treat VAOPT as a placemarker token.  Eat either the '##' before the
327           // RHS/VAOPT (if one exists, suggesting that the LHS (if any) to that
328           // hashhash was not a placemarker) or the '##'
329           // after VAOPT, but not both.
330 
331           if (ResultToks.size() && ResultToks.back().is(tok::hashhash)) {
332             ResultToks.pop_back();
333           } else if ((I + 1 != E) && Tokens[I + 1].is(tok::hashhash)) {
334             ++I; // Skip the following hashhash.
335           }
336         } else {
337           // If there's a ## before the __VA_OPT__, we might have discovered
338           // that the __VA_OPT__ begins with a placeholder. We delay action on
339           // that to now to avoid messing up our stashed count of tokens before
340           // __VA_OPT__.
341           if (VCtx.beginsWithPlaceholder()) {
342             assert(VCtx.getNumberOfTokensPriorToVAOpt() > 0 &&
343                    ResultToks.size() >= VCtx.getNumberOfTokensPriorToVAOpt() &&
344                    ResultToks[VCtx.getNumberOfTokensPriorToVAOpt() - 1].is(
345                        tok::hashhash) &&
346                    "no token paste before __VA_OPT__");
347             ResultToks.erase(ResultToks.begin() +
348                              VCtx.getNumberOfTokensPriorToVAOpt() - 1);
349           }
350           // If the expansion of __VA_OPT__ ends with a placeholder, eat any
351           // following '##' token.
352           if (VCtx.endsWithPlaceholder() && I + 1 != E &&
353               Tokens[I + 1].is(tok::hashhash)) {
354             ++I;
355           }
356         }
357         VCtx.reset();
358         // We processed __VA_OPT__'s closing paren (and the exit out of
359         // __VA_OPT__), so skip to the next token.
360         continue;
361       }
362     }
363 
364     // If we found the stringify operator, get the argument stringified.  The
365     // preprocessor already verified that the following token is a macro
366     // parameter or __VA_OPT__ when the #define was lexed.
367 
368     if (CurTok.isOneOf(tok::hash, tok::hashat)) {
369       int ArgNo = Macro->getParameterNum(Tokens[I+1].getIdentifierInfo());
370       assert((ArgNo != -1 || VCtx.isVAOptToken(Tokens[I + 1])) &&
371              "Token following # is not an argument or __VA_OPT__!");
372 
373       if (ArgNo == -1) {
374         // Handle the __VA_OPT__ case.
375         VCtx.sawHashOrHashAtBefore(NextTokGetsSpace,
376                                    CurTok.is(tok::hashat));
377         continue;
378       }
379       // Else handle the simple argument case.
380       SourceLocation ExpansionLocStart =
381           getExpansionLocForMacroDefLoc(CurTok.getLocation());
382       SourceLocation ExpansionLocEnd =
383           getExpansionLocForMacroDefLoc(Tokens[I+1].getLocation());
384 
385       bool Charify = CurTok.is(tok::hashat);
386       const Token *UnexpArg = ActualArgs->getUnexpArgument(ArgNo);
387       Token Res = MacroArgs::StringifyArgument(
388           UnexpArg, PP, Charify, ExpansionLocStart, ExpansionLocEnd);
389       Res.setFlag(Token::StringifiedInMacro);
390 
391       // The stringified/charified string leading space flag gets set to match
392       // the #/#@ operator.
393       if (NextTokGetsSpace)
394         Res.setFlag(Token::LeadingSpace);
395 
396       ResultToks.push_back(Res);
397       MadeChange = true;
398       ++I;  // Skip arg name.
399       NextTokGetsSpace = false;
400       continue;
401     }
402 
403     // Find out if there is a paste (##) operator before or after the token.
404     bool NonEmptyPasteBefore =
405       !ResultToks.empty() && ResultToks.back().is(tok::hashhash);
406     bool PasteBefore = I != 0 && Tokens[I-1].is(tok::hashhash);
407     bool PasteAfter = I+1 != E && Tokens[I+1].is(tok::hashhash);
408     bool RParenAfter = I+1 != E && Tokens[I+1].is(tok::r_paren);
409 
410     assert((!NonEmptyPasteBefore || PasteBefore || VCtx.isInVAOpt()) &&
411            "unexpected ## in ResultToks");
412 
413     // Otherwise, if this is not an argument token, just add the token to the
414     // output buffer.
415     IdentifierInfo *II = CurTok.getIdentifierInfo();
416     int ArgNo = II ? Macro->getParameterNum(II) : -1;
417     if (ArgNo == -1) {
418       // This isn't an argument, just add it.
419       ResultToks.push_back(CurTok);
420 
421       if (NextTokGetsSpace) {
422         ResultToks.back().setFlag(Token::LeadingSpace);
423         NextTokGetsSpace = false;
424       } else if (PasteBefore && !NonEmptyPasteBefore)
425         ResultToks.back().clearFlag(Token::LeadingSpace);
426 
427       continue;
428     }
429 
430     // An argument is expanded somehow, the result is different than the
431     // input.
432     MadeChange = true;
433 
434     // Otherwise, this is a use of the argument.
435 
436     // In Microsoft mode, remove the comma before __VA_ARGS__ to ensure there
437     // are no trailing commas if __VA_ARGS__ is empty.
438     if (!PasteBefore && ActualArgs->isVarargsElidedUse() &&
439         MaybeRemoveCommaBeforeVaArgs(ResultToks,
440                                      /*HasPasteOperator=*/false,
441                                      Macro, ArgNo, PP))
442       continue;
443 
444     // If it is not the LHS/RHS of a ## operator, we must pre-expand the
445     // argument and substitute the expanded tokens into the result.  This is
446     // C99 6.10.3.1p1.
447     if (!PasteBefore && !PasteAfter) {
448       const Token *ResultArgToks;
449 
450       // Only preexpand the argument if it could possibly need it.  This
451       // avoids some work in common cases.
452       const Token *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
453       if (ActualArgs->ArgNeedsPreexpansion(ArgTok, PP))
454         ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0];
455       else
456         ResultArgToks = ArgTok;  // Use non-preexpanded tokens.
457 
458       // If the arg token expanded into anything, append it.
459       if (ResultArgToks->isNot(tok::eof)) {
460         size_t FirstResult = ResultToks.size();
461         unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
462         ResultToks.append(ResultArgToks, ResultArgToks+NumToks);
463 
464         // In Microsoft-compatibility mode, we follow MSVC's preprocessing
465         // behavior by not considering single commas from nested macro
466         // expansions as argument separators. Set a flag on the token so we can
467         // test for this later when the macro expansion is processed.
468         if (PP.getLangOpts().MSVCCompat && NumToks == 1 &&
469             ResultToks.back().is(tok::comma))
470           ResultToks.back().setFlag(Token::IgnoredComma);
471 
472         // If the '##' came from expanding an argument, turn it into 'unknown'
473         // to avoid pasting.
474         for (Token &Tok : llvm::make_range(ResultToks.begin() + FirstResult,
475                                            ResultToks.end())) {
476           if (Tok.is(tok::hashhash))
477             Tok.setKind(tok::unknown);
478         }
479 
480         if(ExpandLocStart.isValid()) {
481           updateLocForMacroArgTokens(CurTok.getLocation(),
482                                      ResultToks.begin()+FirstResult,
483                                      ResultToks.end());
484         }
485 
486         // If any tokens were substituted from the argument, the whitespace
487         // before the first token should match the whitespace of the arg
488         // identifier.
489         ResultToks[FirstResult].setFlagValue(Token::LeadingSpace,
490                                              NextTokGetsSpace);
491         ResultToks[FirstResult].setFlagValue(Token::StartOfLine, false);
492         NextTokGetsSpace = false;
493       } else {
494         // We're creating a placeholder token. Usually this doesn't matter,
495         // but it can affect paste behavior when at the start or end of a
496         // __VA_OPT__.
497         if (NonEmptyPasteBefore) {
498           // We're imagining a placeholder token is inserted here. If this is
499           // the first token in a __VA_OPT__ after a ##, delete the ##.
500           assert(VCtx.isInVAOpt() && "should only happen inside a __VA_OPT__");
501           VCtx.hasPlaceholderAfterHashhashAtStart();
502         }
503         if (RParenAfter)
504           VCtx.hasPlaceholderBeforeRParen();
505       }
506       continue;
507     }
508 
509     // Okay, we have a token that is either the LHS or RHS of a paste (##)
510     // argument.  It gets substituted as its non-pre-expanded tokens.
511     const Token *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
512     unsigned NumToks = MacroArgs::getArgLength(ArgToks);
513     if (NumToks) {  // Not an empty argument?
514       bool VaArgsPseudoPaste = false;
515       // If this is the GNU ", ## __VA_ARGS__" extension, and we just learned
516       // that __VA_ARGS__ expands to multiple tokens, avoid a pasting error when
517       // the expander tries to paste ',' with the first token of the __VA_ARGS__
518       // expansion.
519       if (NonEmptyPasteBefore && ResultToks.size() >= 2 &&
520           ResultToks[ResultToks.size()-2].is(tok::comma) &&
521           (unsigned)ArgNo == Macro->getNumParams()-1 &&
522           Macro->isVariadic()) {
523         VaArgsPseudoPaste = true;
524         // Remove the paste operator, report use of the extension.
525         PP.Diag(ResultToks.pop_back_val().getLocation(), diag::ext_paste_comma);
526       }
527 
528       ResultToks.append(ArgToks, ArgToks+NumToks);
529 
530       // If the '##' came from expanding an argument, turn it into 'unknown'
531       // to avoid pasting.
532       for (Token &Tok : llvm::make_range(ResultToks.end() - NumToks,
533                                          ResultToks.end())) {
534         if (Tok.is(tok::hashhash))
535           Tok.setKind(tok::unknown);
536       }
537 
538       if (ExpandLocStart.isValid()) {
539         updateLocForMacroArgTokens(CurTok.getLocation(),
540                                    ResultToks.end()-NumToks, ResultToks.end());
541       }
542 
543       // Transfer the leading whitespace information from the token
544       // (the macro argument) onto the first token of the
545       // expansion. Note that we don't do this for the GNU
546       // pseudo-paste extension ", ## __VA_ARGS__".
547       if (!VaArgsPseudoPaste) {
548         ResultToks[ResultToks.size() - NumToks].setFlagValue(Token::StartOfLine,
549                                                              false);
550         ResultToks[ResultToks.size() - NumToks].setFlagValue(
551             Token::LeadingSpace, NextTokGetsSpace);
552       }
553 
554       NextTokGetsSpace = false;
555       continue;
556     }
557 
558     // If an empty argument is on the LHS or RHS of a paste, the standard (C99
559     // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur.  We
560     // implement this by eating ## operators when a LHS or RHS expands to
561     // empty.
562     if (PasteAfter) {
563       // Discard the argument token and skip (don't copy to the expansion
564       // buffer) the paste operator after it.
565       ++I;
566       continue;
567     }
568 
569     if (RParenAfter)
570       VCtx.hasPlaceholderBeforeRParen();
571 
572     // If this is on the RHS of a paste operator, we've already copied the
573     // paste operator to the ResultToks list, unless the LHS was empty too.
574     // Remove it.
575     assert(PasteBefore);
576     if (NonEmptyPasteBefore) {
577       assert(ResultToks.back().is(tok::hashhash));
578       // Do not remove the paste operator if it is the one before __VA_OPT__
579       // (and we are still processing tokens within VA_OPT).  We handle the case
580       // of removing the paste operator if __VA_OPT__ reduces to the notional
581       // placemarker above when we encounter the closing paren of VA_OPT.
582       if (!VCtx.isInVAOpt() ||
583           ResultToks.size() > VCtx.getNumberOfTokensPriorToVAOpt())
584         ResultToks.pop_back();
585       else
586         VCtx.hasPlaceholderAfterHashhashAtStart();
587     }
588 
589     // If this is the __VA_ARGS__ token, and if the argument wasn't provided,
590     // and if the macro had at least one real argument, and if the token before
591     // the ## was a comma, remove the comma.  This is a GCC extension which is
592     // disabled when using -std=c99.
593     if (ActualArgs->isVarargsElidedUse())
594       MaybeRemoveCommaBeforeVaArgs(ResultToks,
595                                    /*HasPasteOperator=*/true,
596                                    Macro, ArgNo, PP);
597   }
598 
599   // If anything changed, install this as the new Tokens list.
600   if (MadeChange) {
601     assert(!OwnsTokens && "This would leak if we already own the token list");
602     // This is deleted in the dtor.
603     NumTokens = ResultToks.size();
604     // The tokens will be added to Preprocessor's cache and will be removed
605     // when this TokenLexer finishes lexing them.
606     Tokens = PP.cacheMacroExpandedTokens(this, ResultToks);
607 
608     // The preprocessor cache of macro expanded tokens owns these tokens,not us.
609     OwnsTokens = false;
610   }
611 }
612 
613 /// Checks if two tokens form wide string literal.
614 static bool isWideStringLiteralFromMacro(const Token &FirstTok,
615                                          const Token &SecondTok) {
616   return FirstTok.is(tok::identifier) &&
617          FirstTok.getIdentifierInfo()->isStr("L") && SecondTok.isLiteral() &&
618          SecondTok.stringifiedInMacro();
619 }
620 
621 /// Lex - Lex and return a token from this macro stream.
622 bool TokenLexer::Lex(Token &Tok) {
623   // Lexing off the end of the macro, pop this macro off the expansion stack.
624   if (isAtEnd()) {
625     // If this is a macro (not a token stream), mark the macro enabled now
626     // that it is no longer being expanded.
627     if (Macro) Macro->EnableMacro();
628 
629     Tok.startToken();
630     Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
631     Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace || NextTokGetsSpace);
632     if (CurTokenIdx == 0)
633       Tok.setFlag(Token::LeadingEmptyMacro);
634     return PP.HandleEndOfTokenLexer(Tok);
635   }
636 
637   SourceManager &SM = PP.getSourceManager();
638 
639   // If this is the first token of the expanded result, we inherit spacing
640   // properties later.
641   bool isFirstToken = CurTokenIdx == 0;
642 
643   // Get the next token to return.
644   Tok = Tokens[CurTokenIdx++];
645   if (IsReinject)
646     Tok.setFlag(Token::IsReinjected);
647 
648   bool TokenIsFromPaste = false;
649 
650   // If this token is followed by a token paste (##) operator, paste the tokens!
651   // Note that ## is a normal token when not expanding a macro.
652   if (!isAtEnd() && Macro &&
653       (Tokens[CurTokenIdx].is(tok::hashhash) ||
654        // Special processing of L#x macros in -fms-compatibility mode.
655        // Microsoft compiler is able to form a wide string literal from
656        // 'L#macro_arg' construct in a function-like macro.
657        (PP.getLangOpts().MSVCCompat &&
658         isWideStringLiteralFromMacro(Tok, Tokens[CurTokenIdx])))) {
659     // When handling the microsoft /##/ extension, the final token is
660     // returned by pasteTokens, not the pasted token.
661     if (pasteTokens(Tok))
662       return true;
663 
664     TokenIsFromPaste = true;
665   }
666 
667   // The token's current location indicate where the token was lexed from.  We
668   // need this information to compute the spelling of the token, but any
669   // diagnostics for the expanded token should appear as if they came from
670   // ExpansionLoc.  Pull this information together into a new SourceLocation
671   // that captures all of this.
672   if (ExpandLocStart.isValid() &&   // Don't do this for token streams.
673       // Check that the token's location was not already set properly.
674       SM.isBeforeInSLocAddrSpace(Tok.getLocation(), MacroStartSLocOffset)) {
675     SourceLocation instLoc;
676     if (Tok.is(tok::comment)) {
677       instLoc = SM.createExpansionLoc(Tok.getLocation(),
678                                       ExpandLocStart,
679                                       ExpandLocEnd,
680                                       Tok.getLength());
681     } else {
682       instLoc = getExpansionLocForMacroDefLoc(Tok.getLocation());
683     }
684 
685     Tok.setLocation(instLoc);
686   }
687 
688   // If this is the first token, set the lexical properties of the token to
689   // match the lexical properties of the macro identifier.
690   if (isFirstToken) {
691     Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
692     Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
693   } else {
694     // If this is not the first token, we may still need to pass through
695     // leading whitespace if we've expanded a macro.
696     if (AtStartOfLine) Tok.setFlag(Token::StartOfLine);
697     if (HasLeadingSpace) Tok.setFlag(Token::LeadingSpace);
698   }
699   AtStartOfLine = false;
700   HasLeadingSpace = false;
701 
702   // Handle recursive expansion!
703   if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
704     // Change the kind of this identifier to the appropriate token kind, e.g.
705     // turning "for" into a keyword.
706     IdentifierInfo *II = Tok.getIdentifierInfo();
707     Tok.setKind(II->getTokenID());
708 
709     // If this identifier was poisoned and from a paste, emit an error.  This
710     // won't be handled by Preprocessor::HandleIdentifier because this is coming
711     // from a macro expansion.
712     if (II->isPoisoned() && TokenIsFromPaste) {
713       PP.HandlePoisonedIdentifier(Tok);
714     }
715 
716     if (!DisableMacroExpansion && II->isHandleIdentifierCase())
717       return PP.HandleIdentifier(Tok);
718   }
719 
720   // Otherwise, return a normal token.
721   return true;
722 }
723 
724 bool TokenLexer::pasteTokens(Token &Tok) {
725   return pasteTokens(Tok, llvm::makeArrayRef(Tokens, NumTokens), CurTokenIdx);
726 }
727 
728 /// LHSTok is the LHS of a ## operator, and CurTokenIdx is the ##
729 /// operator.  Read the ## and RHS, and paste the LHS/RHS together.  If there
730 /// are more ## after it, chomp them iteratively.  Return the result as LHSTok.
731 /// If this returns true, the caller should immediately return the token.
732 bool TokenLexer::pasteTokens(Token &LHSTok, ArrayRef<Token> TokenStream,
733                              unsigned int &CurIdx) {
734   assert(CurIdx > 0 && "## can not be the first token within tokens");
735   assert((TokenStream[CurIdx].is(tok::hashhash) ||
736          (PP.getLangOpts().MSVCCompat &&
737           isWideStringLiteralFromMacro(LHSTok, TokenStream[CurIdx]))) &&
738              "Token at this Index must be ## or part of the MSVC 'L "
739              "#macro-arg' pasting pair");
740 
741   // MSVC: If previous token was pasted, this must be a recovery from an invalid
742   // paste operation. Ignore spaces before this token to mimic MSVC output.
743   // Required for generating valid UUID strings in some MS headers.
744   if (PP.getLangOpts().MicrosoftExt && (CurIdx >= 2) &&
745       TokenStream[CurIdx - 2].is(tok::hashhash))
746     LHSTok.clearFlag(Token::LeadingSpace);
747 
748   SmallString<128> Buffer;
749   const char *ResultTokStrPtr = nullptr;
750   SourceLocation StartLoc = LHSTok.getLocation();
751   SourceLocation PasteOpLoc;
752 
753   auto IsAtEnd = [&TokenStream, &CurIdx] {
754     return TokenStream.size() == CurIdx;
755   };
756 
757   do {
758     // Consume the ## operator if any.
759     PasteOpLoc = TokenStream[CurIdx].getLocation();
760     if (TokenStream[CurIdx].is(tok::hashhash))
761       ++CurIdx;
762     assert(!IsAtEnd() && "No token on the RHS of a paste operator!");
763 
764     // Get the RHS token.
765     const Token &RHS = TokenStream[CurIdx];
766 
767     // Allocate space for the result token.  This is guaranteed to be enough for
768     // the two tokens.
769     Buffer.resize(LHSTok.getLength() + RHS.getLength());
770 
771     // Get the spelling of the LHS token in Buffer.
772     const char *BufPtr = &Buffer[0];
773     bool Invalid = false;
774     unsigned LHSLen = PP.getSpelling(LHSTok, BufPtr, &Invalid);
775     if (BufPtr != &Buffer[0])   // Really, we want the chars in Buffer!
776       memcpy(&Buffer[0], BufPtr, LHSLen);
777     if (Invalid)
778       return true;
779 
780     BufPtr = Buffer.data() + LHSLen;
781     unsigned RHSLen = PP.getSpelling(RHS, BufPtr, &Invalid);
782     if (Invalid)
783       return true;
784     if (RHSLen && BufPtr != &Buffer[LHSLen])
785       // Really, we want the chars in Buffer!
786       memcpy(&Buffer[LHSLen], BufPtr, RHSLen);
787 
788     // Trim excess space.
789     Buffer.resize(LHSLen+RHSLen);
790 
791     // Plop the pasted result (including the trailing newline and null) into a
792     // scratch buffer where we can lex it.
793     Token ResultTokTmp;
794     ResultTokTmp.startToken();
795 
796     // Claim that the tmp token is a string_literal so that we can get the
797     // character pointer back from CreateString in getLiteralData().
798     ResultTokTmp.setKind(tok::string_literal);
799     PP.CreateString(Buffer, ResultTokTmp);
800     SourceLocation ResultTokLoc = ResultTokTmp.getLocation();
801     ResultTokStrPtr = ResultTokTmp.getLiteralData();
802 
803     // Lex the resultant pasted token into Result.
804     Token Result;
805 
806     if (LHSTok.isAnyIdentifier() && RHS.isAnyIdentifier()) {
807       // Common paste case: identifier+identifier = identifier.  Avoid creating
808       // a lexer and other overhead.
809       PP.IncrementPasteCounter(true);
810       Result.startToken();
811       Result.setKind(tok::raw_identifier);
812       Result.setRawIdentifierData(ResultTokStrPtr);
813       Result.setLocation(ResultTokLoc);
814       Result.setLength(LHSLen+RHSLen);
815     } else {
816       PP.IncrementPasteCounter(false);
817 
818       assert(ResultTokLoc.isFileID() &&
819              "Should be a raw location into scratch buffer");
820       SourceManager &SourceMgr = PP.getSourceManager();
821       FileID LocFileID = SourceMgr.getFileID(ResultTokLoc);
822 
823       bool Invalid = false;
824       const char *ScratchBufStart
825         = SourceMgr.getBufferData(LocFileID, &Invalid).data();
826       if (Invalid)
827         return false;
828 
829       // Make a lexer to lex this string from.  Lex just this one token.
830       // Make a lexer object so that we lex and expand the paste result.
831       Lexer TL(SourceMgr.getLocForStartOfFile(LocFileID),
832                PP.getLangOpts(), ScratchBufStart,
833                ResultTokStrPtr, ResultTokStrPtr+LHSLen+RHSLen);
834 
835       // Lex a token in raw mode.  This way it won't look up identifiers
836       // automatically, lexing off the end will return an eof token, and
837       // warnings are disabled.  This returns true if the result token is the
838       // entire buffer.
839       bool isInvalid = !TL.LexFromRawLexer(Result);
840 
841       // If we got an EOF token, we didn't form even ONE token.  For example, we
842       // did "/ ## /" to get "//".
843       isInvalid |= Result.is(tok::eof);
844 
845       // If pasting the two tokens didn't form a full new token, this is an
846       // error.  This occurs with "x ## +"  and other stuff.  Return with LHSTok
847       // unmodified and with RHS as the next token to lex.
848       if (isInvalid) {
849         // Explicitly convert the token location to have proper expansion
850         // information so that the user knows where it came from.
851         SourceManager &SM = PP.getSourceManager();
852         SourceLocation Loc =
853           SM.createExpansionLoc(PasteOpLoc, ExpandLocStart, ExpandLocEnd, 2);
854 
855         // Test for the Microsoft extension of /##/ turning into // here on the
856         // error path.
857         if (PP.getLangOpts().MicrosoftExt && LHSTok.is(tok::slash) &&
858             RHS.is(tok::slash)) {
859           HandleMicrosoftCommentPaste(LHSTok, Loc);
860           return true;
861         }
862 
863         // Do not emit the error when preprocessing assembler code.
864         if (!PP.getLangOpts().AsmPreprocessor) {
865           // If we're in microsoft extensions mode, downgrade this from a hard
866           // error to an extension that defaults to an error.  This allows
867           // disabling it.
868           PP.Diag(Loc, PP.getLangOpts().MicrosoftExt ? diag::ext_pp_bad_paste_ms
869                                                      : diag::err_pp_bad_paste)
870               << Buffer;
871         }
872 
873         // An error has occurred so exit loop.
874         break;
875       }
876 
877       // Turn ## into 'unknown' to avoid # ## # from looking like a paste
878       // operator.
879       if (Result.is(tok::hashhash))
880         Result.setKind(tok::unknown);
881     }
882 
883     // Transfer properties of the LHS over the Result.
884     Result.setFlagValue(Token::StartOfLine , LHSTok.isAtStartOfLine());
885     Result.setFlagValue(Token::LeadingSpace, LHSTok.hasLeadingSpace());
886 
887     // Finally, replace LHS with the result, consume the RHS, and iterate.
888     ++CurIdx;
889     LHSTok = Result;
890   } while (!IsAtEnd() && TokenStream[CurIdx].is(tok::hashhash));
891 
892   SourceLocation EndLoc = TokenStream[CurIdx - 1].getLocation();
893 
894   // The token's current location indicate where the token was lexed from.  We
895   // need this information to compute the spelling of the token, but any
896   // diagnostics for the expanded token should appear as if the token was
897   // expanded from the full ## expression. Pull this information together into
898   // a new SourceLocation that captures all of this.
899   SourceManager &SM = PP.getSourceManager();
900   if (StartLoc.isFileID())
901     StartLoc = getExpansionLocForMacroDefLoc(StartLoc);
902   if (EndLoc.isFileID())
903     EndLoc = getExpansionLocForMacroDefLoc(EndLoc);
904   FileID MacroFID = SM.getFileID(MacroExpansionStart);
905   while (SM.getFileID(StartLoc) != MacroFID)
906     StartLoc = SM.getImmediateExpansionRange(StartLoc).getBegin();
907   while (SM.getFileID(EndLoc) != MacroFID)
908     EndLoc = SM.getImmediateExpansionRange(EndLoc).getEnd();
909 
910   LHSTok.setLocation(SM.createExpansionLoc(LHSTok.getLocation(), StartLoc, EndLoc,
911                                         LHSTok.getLength()));
912 
913   // Now that we got the result token, it will be subject to expansion.  Since
914   // token pasting re-lexes the result token in raw mode, identifier information
915   // isn't looked up.  As such, if the result is an identifier, look up id info.
916   if (LHSTok.is(tok::raw_identifier)) {
917     // Look up the identifier info for the token.  We disabled identifier lookup
918     // by saying we're skipping contents, so we need to do this manually.
919     PP.LookUpIdentifierInfo(LHSTok);
920   }
921   return false;
922 }
923 
924 /// isNextTokenLParen - If the next token lexed will pop this macro off the
925 /// expansion stack, return 2.  If the next unexpanded token is a '(', return
926 /// 1, otherwise return 0.
927 unsigned TokenLexer::isNextTokenLParen() const {
928   // Out of tokens?
929   if (isAtEnd())
930     return 2;
931   return Tokens[CurTokenIdx].is(tok::l_paren);
932 }
933 
934 /// isParsingPreprocessorDirective - Return true if we are in the middle of a
935 /// preprocessor directive.
936 bool TokenLexer::isParsingPreprocessorDirective() const {
937   return Tokens[NumTokens-1].is(tok::eod) && !isAtEnd();
938 }
939 
940 /// HandleMicrosoftCommentPaste - In microsoft compatibility mode, /##/ pastes
941 /// together to form a comment that comments out everything in the current
942 /// macro, other active macros, and anything left on the current physical
943 /// source line of the expanded buffer.  Handle this by returning the
944 /// first token on the next line.
945 void TokenLexer::HandleMicrosoftCommentPaste(Token &Tok, SourceLocation OpLoc) {
946   PP.Diag(OpLoc, diag::ext_comment_paste_microsoft);
947 
948   // We 'comment out' the rest of this macro by just ignoring the rest of the
949   // tokens that have not been lexed yet, if any.
950 
951   // Since this must be a macro, mark the macro enabled now that it is no longer
952   // being expanded.
953   assert(Macro && "Token streams can't paste comments");
954   Macro->EnableMacro();
955 
956   PP.HandleMicrosoftCommentPaste(Tok);
957 }
958 
959 /// If \arg loc is a file ID and points inside the current macro
960 /// definition, returns the appropriate source location pointing at the
961 /// macro expansion source location entry, otherwise it returns an invalid
962 /// SourceLocation.
963 SourceLocation
964 TokenLexer::getExpansionLocForMacroDefLoc(SourceLocation loc) const {
965   assert(ExpandLocStart.isValid() && MacroExpansionStart.isValid() &&
966          "Not appropriate for token streams");
967   assert(loc.isValid() && loc.isFileID());
968 
969   SourceManager &SM = PP.getSourceManager();
970   assert(SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength) &&
971          "Expected loc to come from the macro definition");
972 
973   unsigned relativeOffset = 0;
974   SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength, &relativeOffset);
975   return MacroExpansionStart.getLocWithOffset(relativeOffset);
976 }
977 
978 /// Finds the tokens that are consecutive (from the same FileID)
979 /// creates a single SLocEntry, and assigns SourceLocations to each token that
980 /// point to that SLocEntry. e.g for
981 ///   assert(foo == bar);
982 /// There will be a single SLocEntry for the "foo == bar" chunk and locations
983 /// for the 'foo', '==', 'bar' tokens will point inside that chunk.
984 ///
985 /// \arg begin_tokens will be updated to a position past all the found
986 /// consecutive tokens.
987 static void updateConsecutiveMacroArgTokens(SourceManager &SM,
988                                             SourceLocation InstLoc,
989                                             Token *&begin_tokens,
990                                             Token * end_tokens) {
991   assert(begin_tokens < end_tokens);
992 
993   SourceLocation FirstLoc = begin_tokens->getLocation();
994   SourceLocation CurLoc = FirstLoc;
995 
996   // Compare the source location offset of tokens and group together tokens that
997   // are close, even if their locations point to different FileIDs. e.g.
998   //
999   //  |bar    |  foo | cake   |  (3 tokens from 3 consecutive FileIDs)
1000   //  ^                    ^
1001   //  |bar       foo   cake|     (one SLocEntry chunk for all tokens)
1002   //
1003   // we can perform this "merge" since the token's spelling location depends
1004   // on the relative offset.
1005 
1006   Token *NextTok = begin_tokens + 1;
1007   for (; NextTok < end_tokens; ++NextTok) {
1008     SourceLocation NextLoc = NextTok->getLocation();
1009     if (CurLoc.isFileID() != NextLoc.isFileID())
1010       break; // Token from different kind of FileID.
1011 
1012     int RelOffs;
1013     if (!SM.isInSameSLocAddrSpace(CurLoc, NextLoc, &RelOffs))
1014       break; // Token from different local/loaded location.
1015     // Check that token is not before the previous token or more than 50
1016     // "characters" away.
1017     if (RelOffs < 0 || RelOffs > 50)
1018       break;
1019 
1020     if (CurLoc.isMacroID() && !SM.isWrittenInSameFile(CurLoc, NextLoc))
1021       break; // Token from a different macro.
1022 
1023     CurLoc = NextLoc;
1024   }
1025 
1026   // For the consecutive tokens, find the length of the SLocEntry to contain
1027   // all of them.
1028   Token &LastConsecutiveTok = *(NextTok-1);
1029   int LastRelOffs = 0;
1030   SM.isInSameSLocAddrSpace(FirstLoc, LastConsecutiveTok.getLocation(),
1031                            &LastRelOffs);
1032   unsigned FullLength = LastRelOffs + LastConsecutiveTok.getLength();
1033 
1034   // Create a macro expansion SLocEntry that will "contain" all of the tokens.
1035   SourceLocation Expansion =
1036       SM.createMacroArgExpansionLoc(FirstLoc, InstLoc,FullLength);
1037 
1038   // Change the location of the tokens from the spelling location to the new
1039   // expanded location.
1040   for (; begin_tokens < NextTok; ++begin_tokens) {
1041     Token &Tok = *begin_tokens;
1042     int RelOffs = 0;
1043     SM.isInSameSLocAddrSpace(FirstLoc, Tok.getLocation(), &RelOffs);
1044     Tok.setLocation(Expansion.getLocWithOffset(RelOffs));
1045   }
1046 }
1047 
1048 /// Creates SLocEntries and updates the locations of macro argument
1049 /// tokens to their new expanded locations.
1050 ///
1051 /// \param ArgIdSpellLoc the location of the macro argument id inside the macro
1052 /// definition.
1053 void TokenLexer::updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc,
1054                                             Token *begin_tokens,
1055                                             Token *end_tokens) {
1056   SourceManager &SM = PP.getSourceManager();
1057 
1058   SourceLocation InstLoc =
1059       getExpansionLocForMacroDefLoc(ArgIdSpellLoc);
1060 
1061   while (begin_tokens < end_tokens) {
1062     // If there's only one token just create a SLocEntry for it.
1063     if (end_tokens - begin_tokens == 1) {
1064       Token &Tok = *begin_tokens;
1065       Tok.setLocation(SM.createMacroArgExpansionLoc(Tok.getLocation(),
1066                                                     InstLoc,
1067                                                     Tok.getLength()));
1068       return;
1069     }
1070 
1071     updateConsecutiveMacroArgTokens(SM, InstLoc, begin_tokens, end_tokens);
1072   }
1073 }
1074 
1075 void TokenLexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
1076   AtStartOfLine = Result.isAtStartOfLine();
1077   HasLeadingSpace = Result.hasLeadingSpace();
1078 }
1079