xref: /freebsd/contrib/llvm-project/clang/lib/Lex/TokenLexer.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
10b57cec5SDimitry Andric //===- TokenLexer.cpp - Lex from a token stream ---------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the TokenLexer interface.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "clang/Lex/TokenLexer.h"
140b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
150b57cec5SDimitry Andric #include "clang/Basic/IdentifierTable.h"
160b57cec5SDimitry Andric #include "clang/Basic/LangOptions.h"
170b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h"
180b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
190b57cec5SDimitry Andric #include "clang/Basic/TokenKinds.h"
200b57cec5SDimitry Andric #include "clang/Lex/LexDiagnostic.h"
210b57cec5SDimitry Andric #include "clang/Lex/Lexer.h"
220b57cec5SDimitry Andric #include "clang/Lex/MacroArgs.h"
230b57cec5SDimitry Andric #include "clang/Lex/MacroInfo.h"
240b57cec5SDimitry Andric #include "clang/Lex/Preprocessor.h"
250b57cec5SDimitry Andric #include "clang/Lex/Token.h"
260b57cec5SDimitry Andric #include "clang/Lex/VariadicMacroSupport.h"
270b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
28bdd1243dSDimitry Andric #include "llvm/ADT/STLExtras.h"
290b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
300b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
310b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
320b57cec5SDimitry Andric #include <cassert>
330b57cec5SDimitry Andric #include <cstring>
34bdd1243dSDimitry Andric #include <optional>
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric using namespace clang;
370b57cec5SDimitry Andric 
380b57cec5SDimitry Andric /// Create a TokenLexer for the specified macro with the specified actual
390b57cec5SDimitry Andric /// arguments.  Note that this ctor takes ownership of the ActualArgs pointer.
Init(Token & Tok,SourceLocation ELEnd,MacroInfo * MI,MacroArgs * Actuals)400b57cec5SDimitry Andric void TokenLexer::Init(Token &Tok, SourceLocation ELEnd, MacroInfo *MI,
410b57cec5SDimitry Andric                       MacroArgs *Actuals) {
420b57cec5SDimitry Andric   // If the client is reusing a TokenLexer, make sure to free any memory
430b57cec5SDimitry Andric   // associated with it.
440b57cec5SDimitry Andric   destroy();
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric   Macro = MI;
470b57cec5SDimitry Andric   ActualArgs = Actuals;
480b57cec5SDimitry Andric   CurTokenIdx = 0;
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric   ExpandLocStart = Tok.getLocation();
510b57cec5SDimitry Andric   ExpandLocEnd = ELEnd;
520b57cec5SDimitry Andric   AtStartOfLine = Tok.isAtStartOfLine();
530b57cec5SDimitry Andric   HasLeadingSpace = Tok.hasLeadingSpace();
540b57cec5SDimitry Andric   NextTokGetsSpace = false;
550b57cec5SDimitry Andric   Tokens = &*Macro->tokens_begin();
560b57cec5SDimitry Andric   OwnsTokens = false;
570b57cec5SDimitry Andric   DisableMacroExpansion = false;
580b57cec5SDimitry Andric   IsReinject = false;
590b57cec5SDimitry Andric   NumTokens = Macro->tokens_end()-Macro->tokens_begin();
600b57cec5SDimitry Andric   MacroExpansionStart = SourceLocation();
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric   SourceManager &SM = PP.getSourceManager();
630b57cec5SDimitry Andric   MacroStartSLocOffset = SM.getNextLocalOffset();
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric   if (NumTokens > 0) {
660b57cec5SDimitry Andric     assert(Tokens[0].getLocation().isValid());
670b57cec5SDimitry Andric     assert((Tokens[0].getLocation().isFileID() || Tokens[0].is(tok::comment)) &&
680b57cec5SDimitry Andric            "Macro defined in macro?");
690b57cec5SDimitry Andric     assert(ExpandLocStart.isValid());
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric     // Reserve a source location entry chunk for the length of the macro
720b57cec5SDimitry Andric     // definition. Tokens that get lexed directly from the definition will
730b57cec5SDimitry Andric     // have their locations pointing inside this chunk. This is to avoid
740b57cec5SDimitry Andric     // creating separate source location entries for each token.
750b57cec5SDimitry Andric     MacroDefStart = SM.getExpansionLoc(Tokens[0].getLocation());
760b57cec5SDimitry Andric     MacroDefLength = Macro->getDefinitionLength(SM);
770b57cec5SDimitry Andric     MacroExpansionStart = SM.createExpansionLoc(MacroDefStart,
780b57cec5SDimitry Andric                                                 ExpandLocStart,
790b57cec5SDimitry Andric                                                 ExpandLocEnd,
800b57cec5SDimitry Andric                                                 MacroDefLength);
810b57cec5SDimitry Andric   }
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric   // If this is a function-like macro, expand the arguments and change
840b57cec5SDimitry Andric   // Tokens to point to the expanded tokens.
850b57cec5SDimitry Andric   if (Macro->isFunctionLike() && Macro->getNumParams())
860b57cec5SDimitry Andric     ExpandFunctionArguments();
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric   // Mark the macro as currently disabled, so that it is not recursively
890b57cec5SDimitry Andric   // expanded.  The macro must be disabled only after argument pre-expansion of
900b57cec5SDimitry Andric   // function-like macro arguments occurs.
910b57cec5SDimitry Andric   Macro->DisableMacro();
920b57cec5SDimitry Andric }
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric /// Create a TokenLexer for the specified token stream.  This does not
950b57cec5SDimitry Andric /// take ownership of the specified token vector.
Init(const Token * TokArray,unsigned NumToks,bool disableMacroExpansion,bool ownsTokens,bool isReinject)960b57cec5SDimitry Andric void TokenLexer::Init(const Token *TokArray, unsigned NumToks,
970b57cec5SDimitry Andric                       bool disableMacroExpansion, bool ownsTokens,
980b57cec5SDimitry Andric                       bool isReinject) {
990b57cec5SDimitry Andric   assert(!isReinject || disableMacroExpansion);
1000b57cec5SDimitry Andric   // If the client is reusing a TokenLexer, make sure to free any memory
1010b57cec5SDimitry Andric   // associated with it.
1020b57cec5SDimitry Andric   destroy();
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric   Macro = nullptr;
1050b57cec5SDimitry Andric   ActualArgs = nullptr;
1060b57cec5SDimitry Andric   Tokens = TokArray;
1070b57cec5SDimitry Andric   OwnsTokens = ownsTokens;
1080b57cec5SDimitry Andric   DisableMacroExpansion = disableMacroExpansion;
1090b57cec5SDimitry Andric   IsReinject = isReinject;
1100b57cec5SDimitry Andric   NumTokens = NumToks;
1110b57cec5SDimitry Andric   CurTokenIdx = 0;
1120b57cec5SDimitry Andric   ExpandLocStart = ExpandLocEnd = SourceLocation();
1130b57cec5SDimitry Andric   AtStartOfLine = false;
1140b57cec5SDimitry Andric   HasLeadingSpace = false;
1150b57cec5SDimitry Andric   NextTokGetsSpace = false;
1160b57cec5SDimitry Andric   MacroExpansionStart = SourceLocation();
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric   // Set HasLeadingSpace/AtStartOfLine so that the first token will be
1190b57cec5SDimitry Andric   // returned unmodified.
1200b57cec5SDimitry Andric   if (NumToks != 0) {
1210b57cec5SDimitry Andric     AtStartOfLine   = TokArray[0].isAtStartOfLine();
1220b57cec5SDimitry Andric     HasLeadingSpace = TokArray[0].hasLeadingSpace();
1230b57cec5SDimitry Andric   }
1240b57cec5SDimitry Andric }
1250b57cec5SDimitry Andric 
destroy()1260b57cec5SDimitry Andric void TokenLexer::destroy() {
1270b57cec5SDimitry Andric   // If this was a function-like macro that actually uses its arguments, delete
1280b57cec5SDimitry Andric   // the expanded tokens.
1290b57cec5SDimitry Andric   if (OwnsTokens) {
1300b57cec5SDimitry Andric     delete [] Tokens;
1310b57cec5SDimitry Andric     Tokens = nullptr;
1320b57cec5SDimitry Andric     OwnsTokens = false;
1330b57cec5SDimitry Andric   }
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric   // TokenLexer owns its formal arguments.
1360b57cec5SDimitry Andric   if (ActualArgs) ActualArgs->destroy(PP);
1370b57cec5SDimitry Andric }
1380b57cec5SDimitry Andric 
MaybeRemoveCommaBeforeVaArgs(SmallVectorImpl<Token> & ResultToks,bool HasPasteOperator,MacroInfo * Macro,unsigned MacroArgNo,Preprocessor & PP)1390b57cec5SDimitry Andric bool TokenLexer::MaybeRemoveCommaBeforeVaArgs(
1400b57cec5SDimitry Andric     SmallVectorImpl<Token> &ResultToks, bool HasPasteOperator, MacroInfo *Macro,
1410b57cec5SDimitry Andric     unsigned MacroArgNo, Preprocessor &PP) {
1420b57cec5SDimitry Andric   // Is the macro argument __VA_ARGS__?
1430b57cec5SDimitry Andric   if (!Macro->isVariadic() || MacroArgNo != Macro->getNumParams()-1)
1440b57cec5SDimitry Andric     return false;
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric   // In Microsoft-compatibility mode, a comma is removed in the expansion
1470b57cec5SDimitry Andric   // of " ... , __VA_ARGS__ " if __VA_ARGS__ is empty.  This extension is
1480b57cec5SDimitry Andric   // not supported by gcc.
1490b57cec5SDimitry Andric   if (!HasPasteOperator && !PP.getLangOpts().MSVCCompat)
1500b57cec5SDimitry Andric     return false;
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric   // GCC removes the comma in the expansion of " ... , ## __VA_ARGS__ " if
153d409305fSDimitry Andric   // __VA_ARGS__ is empty, but not in strict C99 mode where there are no
154d409305fSDimitry Andric   // named arguments, where it remains.  In all other modes, including C99
155d409305fSDimitry Andric   // with GNU extensions, it is removed regardless of named arguments.
1560b57cec5SDimitry Andric   // Microsoft also appears to support this extension, unofficially.
157d409305fSDimitry Andric   if (PP.getLangOpts().C99 && !PP.getLangOpts().GNUMode
158d409305fSDimitry Andric         && Macro->getNumParams() < 2)
1590b57cec5SDimitry Andric     return false;
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   // Is a comma available to be removed?
1620b57cec5SDimitry Andric   if (ResultToks.empty() || !ResultToks.back().is(tok::comma))
1630b57cec5SDimitry Andric     return false;
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   // Issue an extension diagnostic for the paste operator.
1660b57cec5SDimitry Andric   if (HasPasteOperator)
1670b57cec5SDimitry Andric     PP.Diag(ResultToks.back().getLocation(), diag::ext_paste_comma);
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric   // Remove the comma.
1700b57cec5SDimitry Andric   ResultToks.pop_back();
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   if (!ResultToks.empty()) {
1730b57cec5SDimitry Andric     // If the comma was right after another paste (e.g. "X##,##__VA_ARGS__"),
1740b57cec5SDimitry Andric     // then removal of the comma should produce a placemarker token (in C99
1750b57cec5SDimitry Andric     // terms) which we model by popping off the previous ##, giving us a plain
1760b57cec5SDimitry Andric     // "X" when __VA_ARGS__ is empty.
1770b57cec5SDimitry Andric     if (ResultToks.back().is(tok::hashhash))
1780b57cec5SDimitry Andric       ResultToks.pop_back();
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric     // Remember that this comma was elided.
1810b57cec5SDimitry Andric     ResultToks.back().setFlag(Token::CommaAfterElided);
1820b57cec5SDimitry Andric   }
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric   // Never add a space, even if the comma, ##, or arg had a space.
1850b57cec5SDimitry Andric   NextTokGetsSpace = false;
1860b57cec5SDimitry Andric   return true;
1870b57cec5SDimitry Andric }
1880b57cec5SDimitry Andric 
stringifyVAOPTContents(SmallVectorImpl<Token> & ResultToks,const VAOptExpansionContext & VCtx,const SourceLocation VAOPTClosingParenLoc)1890b57cec5SDimitry Andric void TokenLexer::stringifyVAOPTContents(
1900b57cec5SDimitry Andric     SmallVectorImpl<Token> &ResultToks, const VAOptExpansionContext &VCtx,
1910b57cec5SDimitry Andric     const SourceLocation VAOPTClosingParenLoc) {
1920b57cec5SDimitry Andric   const int NumToksPriorToVAOpt = VCtx.getNumberOfTokensPriorToVAOpt();
1930b57cec5SDimitry Andric   const unsigned int NumVAOptTokens = ResultToks.size() - NumToksPriorToVAOpt;
1940b57cec5SDimitry Andric   Token *const VAOPTTokens =
1950b57cec5SDimitry Andric       NumVAOptTokens ? &ResultToks[NumToksPriorToVAOpt] : nullptr;
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   SmallVector<Token, 64> ConcatenatedVAOPTResultToks;
1980b57cec5SDimitry Andric   // FIXME: Should we keep track within VCtx that we did or didnot
1990b57cec5SDimitry Andric   // encounter pasting - and only then perform this loop.
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric   // Perform token pasting (concatenation) prior to stringization.
2020b57cec5SDimitry Andric   for (unsigned int CurTokenIdx = 0; CurTokenIdx != NumVAOptTokens;
2030b57cec5SDimitry Andric        ++CurTokenIdx) {
2040b57cec5SDimitry Andric     if (VAOPTTokens[CurTokenIdx].is(tok::hashhash)) {
2050b57cec5SDimitry Andric       assert(CurTokenIdx != 0 &&
2060b57cec5SDimitry Andric              "Can not have __VAOPT__ contents begin with a ##");
2070b57cec5SDimitry Andric       Token &LHS = VAOPTTokens[CurTokenIdx - 1];
208bdd1243dSDimitry Andric       pasteTokens(LHS, llvm::ArrayRef(VAOPTTokens, NumVAOptTokens),
2090b57cec5SDimitry Andric                   CurTokenIdx);
2100b57cec5SDimitry Andric       // Replace the token prior to the first ## in this iteration.
2110b57cec5SDimitry Andric       ConcatenatedVAOPTResultToks.back() = LHS;
2120b57cec5SDimitry Andric       if (CurTokenIdx == NumVAOptTokens)
2130b57cec5SDimitry Andric         break;
2140b57cec5SDimitry Andric     }
2150b57cec5SDimitry Andric     ConcatenatedVAOPTResultToks.push_back(VAOPTTokens[CurTokenIdx]);
2160b57cec5SDimitry Andric   }
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric   ConcatenatedVAOPTResultToks.push_back(VCtx.getEOFTok());
2190b57cec5SDimitry Andric   // Get the SourceLocation that represents the start location within
2200b57cec5SDimitry Andric   // the macro definition that marks where this string is substituted
2210b57cec5SDimitry Andric   // into: i.e. the __VA_OPT__ and the ')' within the spelling of the
2220b57cec5SDimitry Andric   // macro definition, and use it to indicate that the stringified token
2230b57cec5SDimitry Andric   // was generated from that location.
2240b57cec5SDimitry Andric   const SourceLocation ExpansionLocStartWithinMacro =
2250b57cec5SDimitry Andric       getExpansionLocForMacroDefLoc(VCtx.getVAOptLoc());
2260b57cec5SDimitry Andric   const SourceLocation ExpansionLocEndWithinMacro =
2270b57cec5SDimitry Andric       getExpansionLocForMacroDefLoc(VAOPTClosingParenLoc);
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric   Token StringifiedVAOPT = MacroArgs::StringifyArgument(
2300b57cec5SDimitry Andric       &ConcatenatedVAOPTResultToks[0], PP, VCtx.hasCharifyBefore() /*Charify*/,
2310b57cec5SDimitry Andric       ExpansionLocStartWithinMacro, ExpansionLocEndWithinMacro);
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric   if (VCtx.getLeadingSpaceForStringifiedToken())
2340b57cec5SDimitry Andric     StringifiedVAOPT.setFlag(Token::LeadingSpace);
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric   StringifiedVAOPT.setFlag(Token::StringifiedInMacro);
2370b57cec5SDimitry Andric   // Resize (shrink) the token stream to just capture this stringified token.
2380b57cec5SDimitry Andric   ResultToks.resize(NumToksPriorToVAOpt + 1);
2390b57cec5SDimitry Andric   ResultToks.back() = StringifiedVAOPT;
2400b57cec5SDimitry Andric }
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric /// Expand the arguments of a function-like macro so that we can quickly
2430b57cec5SDimitry Andric /// return preexpanded tokens from Tokens.
ExpandFunctionArguments()2440b57cec5SDimitry Andric void TokenLexer::ExpandFunctionArguments() {
2450b57cec5SDimitry Andric   SmallVector<Token, 128> ResultToks;
2460b57cec5SDimitry Andric 
2470b57cec5SDimitry Andric   // Loop through 'Tokens', expanding them into ResultToks.  Keep
2480b57cec5SDimitry Andric   // track of whether we change anything.  If not, no need to keep them.  If so,
2490b57cec5SDimitry Andric   // we install the newly expanded sequence as the new 'Tokens' list.
2500b57cec5SDimitry Andric   bool MadeChange = false;
2510b57cec5SDimitry Andric 
252bdd1243dSDimitry Andric   std::optional<bool> CalledWithVariadicArguments;
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric   VAOptExpansionContext VCtx(PP);
2550b57cec5SDimitry Andric 
2560b57cec5SDimitry Andric   for (unsigned I = 0, E = NumTokens; I != E; ++I) {
2570b57cec5SDimitry Andric     const Token &CurTok = Tokens[I];
2580b57cec5SDimitry Andric     // We don't want a space for the next token after a paste
2590b57cec5SDimitry Andric     // operator.  In valid code, the token will get smooshed onto the
2600b57cec5SDimitry Andric     // preceding one anyway. In assembler-with-cpp mode, invalid
2610b57cec5SDimitry Andric     // pastes are allowed through: in this case, we do not want the
2620b57cec5SDimitry Andric     // extra whitespace to be added.  For example, we want ". ## foo"
2630b57cec5SDimitry Andric     // -> ".foo" not ". foo".
2640b57cec5SDimitry Andric     if (I != 0 && !Tokens[I-1].is(tok::hashhash) && CurTok.hasLeadingSpace())
2650b57cec5SDimitry Andric       NextTokGetsSpace = true;
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric     if (VCtx.isVAOptToken(CurTok)) {
2680b57cec5SDimitry Andric       MadeChange = true;
2690b57cec5SDimitry Andric       assert(Tokens[I + 1].is(tok::l_paren) &&
2700b57cec5SDimitry Andric              "__VA_OPT__ must be followed by '('");
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric       ++I;             // Skip the l_paren
2730b57cec5SDimitry Andric       VCtx.sawVAOptFollowedByOpeningParens(CurTok.getLocation(),
2740b57cec5SDimitry Andric                                            ResultToks.size());
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric       continue;
2770b57cec5SDimitry Andric     }
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric     // We have entered into the __VA_OPT__ context, so handle tokens
2800b57cec5SDimitry Andric     // appropriately.
2810b57cec5SDimitry Andric     if (VCtx.isInVAOpt()) {
2820b57cec5SDimitry Andric       // If we are about to process a token that is either an argument to
2830b57cec5SDimitry Andric       // __VA_OPT__ or its closing rparen, then:
2840b57cec5SDimitry Andric       //  1) If the token is the closing rparen that exits us out of __VA_OPT__,
2850b57cec5SDimitry Andric       //  perform any necessary stringification or placemarker processing,
2860b57cec5SDimitry Andric       //  and/or skip to the next token.
2870b57cec5SDimitry Andric       //  2) else if macro was invoked without variadic arguments skip this
2880b57cec5SDimitry Andric       //  token.
2890b57cec5SDimitry Andric       //  3) else (macro was invoked with variadic arguments) process the token
2900b57cec5SDimitry Andric       //  normally.
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric       if (Tokens[I].is(tok::l_paren))
2930b57cec5SDimitry Andric         VCtx.sawOpeningParen(Tokens[I].getLocation());
2940b57cec5SDimitry Andric       // Continue skipping tokens within __VA_OPT__ if the macro was not
2950b57cec5SDimitry Andric       // called with variadic arguments, else let the rest of the loop handle
2960b57cec5SDimitry Andric       // this token. Note sawClosingParen() returns true only if the r_paren matches
2970b57cec5SDimitry Andric       // the closing r_paren of the __VA_OPT__.
2980b57cec5SDimitry Andric       if (!Tokens[I].is(tok::r_paren) || !VCtx.sawClosingParen()) {
2990b57cec5SDimitry Andric         // Lazily expand __VA_ARGS__ when we see the first __VA_OPT__.
30081ad6265SDimitry Andric         if (!CalledWithVariadicArguments) {
3010b57cec5SDimitry Andric           CalledWithVariadicArguments =
3020b57cec5SDimitry Andric               ActualArgs->invokedWithVariadicArgument(Macro, PP);
3030b57cec5SDimitry Andric         }
3040b57cec5SDimitry Andric         if (!*CalledWithVariadicArguments) {
3050b57cec5SDimitry Andric           // Skip this token.
3060b57cec5SDimitry Andric           continue;
3070b57cec5SDimitry Andric         }
3080b57cec5SDimitry Andric         // ... else the macro was called with variadic arguments, and we do not
3090b57cec5SDimitry Andric         // have a closing rparen - so process this token normally.
3100b57cec5SDimitry Andric       } else {
3110b57cec5SDimitry Andric         // Current token is the closing r_paren which marks the end of the
3120b57cec5SDimitry Andric         // __VA_OPT__ invocation, so handle any place-marker pasting (if
3130b57cec5SDimitry Andric         // empty) by removing hashhash either before (if exists) or after. And
3140b57cec5SDimitry Andric         // also stringify the entire contents if VAOPT was preceded by a hash,
3150b57cec5SDimitry Andric         // but do so only after any token concatenation that needs to occur
3160b57cec5SDimitry Andric         // within the contents of VAOPT.
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric         if (VCtx.hasStringifyOrCharifyBefore()) {
3190b57cec5SDimitry Andric           // Replace all the tokens just added from within VAOPT into a single
3200b57cec5SDimitry Andric           // stringified token. This requires token-pasting to eagerly occur
3210b57cec5SDimitry Andric           // within these tokens. If either the contents of VAOPT were empty
3220b57cec5SDimitry Andric           // or the macro wasn't called with any variadic arguments, the result
3230b57cec5SDimitry Andric           // is a token that represents an empty string.
3240b57cec5SDimitry Andric           stringifyVAOPTContents(ResultToks, VCtx,
3250b57cec5SDimitry Andric                                  /*ClosingParenLoc*/ Tokens[I].getLocation());
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric         } else if (/*No tokens within VAOPT*/
3280b57cec5SDimitry Andric                    ResultToks.size() == VCtx.getNumberOfTokensPriorToVAOpt()) {
3290b57cec5SDimitry Andric           // Treat VAOPT as a placemarker token.  Eat either the '##' before the
3300b57cec5SDimitry Andric           // RHS/VAOPT (if one exists, suggesting that the LHS (if any) to that
3310b57cec5SDimitry Andric           // hashhash was not a placemarker) or the '##'
3320b57cec5SDimitry Andric           // after VAOPT, but not both.
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric           if (ResultToks.size() && ResultToks.back().is(tok::hashhash)) {
3350b57cec5SDimitry Andric             ResultToks.pop_back();
3360b57cec5SDimitry Andric           } else if ((I + 1 != E) && Tokens[I + 1].is(tok::hashhash)) {
3370b57cec5SDimitry Andric             ++I; // Skip the following hashhash.
3380b57cec5SDimitry Andric           }
3390b57cec5SDimitry Andric         } else {
3400b57cec5SDimitry Andric           // If there's a ## before the __VA_OPT__, we might have discovered
3410b57cec5SDimitry Andric           // that the __VA_OPT__ begins with a placeholder. We delay action on
3420b57cec5SDimitry Andric           // that to now to avoid messing up our stashed count of tokens before
3430b57cec5SDimitry Andric           // __VA_OPT__.
3440b57cec5SDimitry Andric           if (VCtx.beginsWithPlaceholder()) {
3450b57cec5SDimitry Andric             assert(VCtx.getNumberOfTokensPriorToVAOpt() > 0 &&
3460b57cec5SDimitry Andric                    ResultToks.size() >= VCtx.getNumberOfTokensPriorToVAOpt() &&
3470b57cec5SDimitry Andric                    ResultToks[VCtx.getNumberOfTokensPriorToVAOpt() - 1].is(
3480b57cec5SDimitry Andric                        tok::hashhash) &&
3490b57cec5SDimitry Andric                    "no token paste before __VA_OPT__");
3500b57cec5SDimitry Andric             ResultToks.erase(ResultToks.begin() +
3510b57cec5SDimitry Andric                              VCtx.getNumberOfTokensPriorToVAOpt() - 1);
3520b57cec5SDimitry Andric           }
3530b57cec5SDimitry Andric           // If the expansion of __VA_OPT__ ends with a placeholder, eat any
3540b57cec5SDimitry Andric           // following '##' token.
3550b57cec5SDimitry Andric           if (VCtx.endsWithPlaceholder() && I + 1 != E &&
3560b57cec5SDimitry Andric               Tokens[I + 1].is(tok::hashhash)) {
3570b57cec5SDimitry Andric             ++I;
3580b57cec5SDimitry Andric           }
3590b57cec5SDimitry Andric         }
3600b57cec5SDimitry Andric         VCtx.reset();
3610b57cec5SDimitry Andric         // We processed __VA_OPT__'s closing paren (and the exit out of
3620b57cec5SDimitry Andric         // __VA_OPT__), so skip to the next token.
3630b57cec5SDimitry Andric         continue;
3640b57cec5SDimitry Andric       }
3650b57cec5SDimitry Andric     }
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric     // If we found the stringify operator, get the argument stringified.  The
3680b57cec5SDimitry Andric     // preprocessor already verified that the following token is a macro
3690b57cec5SDimitry Andric     // parameter or __VA_OPT__ when the #define was lexed.
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric     if (CurTok.isOneOf(tok::hash, tok::hashat)) {
3720b57cec5SDimitry Andric       int ArgNo = Macro->getParameterNum(Tokens[I+1].getIdentifierInfo());
3730b57cec5SDimitry Andric       assert((ArgNo != -1 || VCtx.isVAOptToken(Tokens[I + 1])) &&
3740b57cec5SDimitry Andric              "Token following # is not an argument or __VA_OPT__!");
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric       if (ArgNo == -1) {
3770b57cec5SDimitry Andric         // Handle the __VA_OPT__ case.
3780b57cec5SDimitry Andric         VCtx.sawHashOrHashAtBefore(NextTokGetsSpace,
3790b57cec5SDimitry Andric                                    CurTok.is(tok::hashat));
3800b57cec5SDimitry Andric         continue;
3810b57cec5SDimitry Andric       }
3820b57cec5SDimitry Andric       // Else handle the simple argument case.
3830b57cec5SDimitry Andric       SourceLocation ExpansionLocStart =
3840b57cec5SDimitry Andric           getExpansionLocForMacroDefLoc(CurTok.getLocation());
3850b57cec5SDimitry Andric       SourceLocation ExpansionLocEnd =
3860b57cec5SDimitry Andric           getExpansionLocForMacroDefLoc(Tokens[I+1].getLocation());
3870b57cec5SDimitry Andric 
388a7dea167SDimitry Andric       bool Charify = CurTok.is(tok::hashat);
389a7dea167SDimitry Andric       const Token *UnexpArg = ActualArgs->getUnexpArgument(ArgNo);
390a7dea167SDimitry Andric       Token Res = MacroArgs::StringifyArgument(
391a7dea167SDimitry Andric           UnexpArg, PP, Charify, ExpansionLocStart, ExpansionLocEnd);
3920b57cec5SDimitry Andric       Res.setFlag(Token::StringifiedInMacro);
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric       // The stringified/charified string leading space flag gets set to match
3950b57cec5SDimitry Andric       // the #/#@ operator.
3960b57cec5SDimitry Andric       if (NextTokGetsSpace)
3970b57cec5SDimitry Andric         Res.setFlag(Token::LeadingSpace);
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric       ResultToks.push_back(Res);
4000b57cec5SDimitry Andric       MadeChange = true;
4010b57cec5SDimitry Andric       ++I;  // Skip arg name.
4020b57cec5SDimitry Andric       NextTokGetsSpace = false;
4030b57cec5SDimitry Andric       continue;
4040b57cec5SDimitry Andric     }
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric     // Find out if there is a paste (##) operator before or after the token.
4070b57cec5SDimitry Andric     bool NonEmptyPasteBefore =
4080b57cec5SDimitry Andric       !ResultToks.empty() && ResultToks.back().is(tok::hashhash);
4090b57cec5SDimitry Andric     bool PasteBefore = I != 0 && Tokens[I-1].is(tok::hashhash);
4100b57cec5SDimitry Andric     bool PasteAfter = I+1 != E && Tokens[I+1].is(tok::hashhash);
4110b57cec5SDimitry Andric     bool RParenAfter = I+1 != E && Tokens[I+1].is(tok::r_paren);
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric     assert((!NonEmptyPasteBefore || PasteBefore || VCtx.isInVAOpt()) &&
4140b57cec5SDimitry Andric            "unexpected ## in ResultToks");
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric     // Otherwise, if this is not an argument token, just add the token to the
4170b57cec5SDimitry Andric     // output buffer.
4180b57cec5SDimitry Andric     IdentifierInfo *II = CurTok.getIdentifierInfo();
4190b57cec5SDimitry Andric     int ArgNo = II ? Macro->getParameterNum(II) : -1;
4200b57cec5SDimitry Andric     if (ArgNo == -1) {
4210b57cec5SDimitry Andric       // This isn't an argument, just add it.
4220b57cec5SDimitry Andric       ResultToks.push_back(CurTok);
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric       if (NextTokGetsSpace) {
4250b57cec5SDimitry Andric         ResultToks.back().setFlag(Token::LeadingSpace);
4260b57cec5SDimitry Andric         NextTokGetsSpace = false;
4270b57cec5SDimitry Andric       } else if (PasteBefore && !NonEmptyPasteBefore)
4280b57cec5SDimitry Andric         ResultToks.back().clearFlag(Token::LeadingSpace);
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric       continue;
4310b57cec5SDimitry Andric     }
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric     // An argument is expanded somehow, the result is different than the
4340b57cec5SDimitry Andric     // input.
4350b57cec5SDimitry Andric     MadeChange = true;
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric     // Otherwise, this is a use of the argument.
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric     // In Microsoft mode, remove the comma before __VA_ARGS__ to ensure there
4400b57cec5SDimitry Andric     // are no trailing commas if __VA_ARGS__ is empty.
4410b57cec5SDimitry Andric     if (!PasteBefore && ActualArgs->isVarargsElidedUse() &&
4420b57cec5SDimitry Andric         MaybeRemoveCommaBeforeVaArgs(ResultToks,
4430b57cec5SDimitry Andric                                      /*HasPasteOperator=*/false,
4440b57cec5SDimitry Andric                                      Macro, ArgNo, PP))
4450b57cec5SDimitry Andric       continue;
4460b57cec5SDimitry Andric 
4470b57cec5SDimitry Andric     // If it is not the LHS/RHS of a ## operator, we must pre-expand the
4480b57cec5SDimitry Andric     // argument and substitute the expanded tokens into the result.  This is
4490b57cec5SDimitry Andric     // C99 6.10.3.1p1.
4500b57cec5SDimitry Andric     if (!PasteBefore && !PasteAfter) {
4510b57cec5SDimitry Andric       const Token *ResultArgToks;
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric       // Only preexpand the argument if it could possibly need it.  This
4540b57cec5SDimitry Andric       // avoids some work in common cases.
4550b57cec5SDimitry Andric       const Token *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
4560b57cec5SDimitry Andric       if (ActualArgs->ArgNeedsPreexpansion(ArgTok, PP))
4570b57cec5SDimitry Andric         ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0];
4580b57cec5SDimitry Andric       else
4590b57cec5SDimitry Andric         ResultArgToks = ArgTok;  // Use non-preexpanded tokens.
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric       // If the arg token expanded into anything, append it.
4620b57cec5SDimitry Andric       if (ResultArgToks->isNot(tok::eof)) {
4630b57cec5SDimitry Andric         size_t FirstResult = ResultToks.size();
4640b57cec5SDimitry Andric         unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
4650b57cec5SDimitry Andric         ResultToks.append(ResultArgToks, ResultArgToks+NumToks);
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric         // In Microsoft-compatibility mode, we follow MSVC's preprocessing
4680b57cec5SDimitry Andric         // behavior by not considering single commas from nested macro
4690b57cec5SDimitry Andric         // expansions as argument separators. Set a flag on the token so we can
4700b57cec5SDimitry Andric         // test for this later when the macro expansion is processed.
4710b57cec5SDimitry Andric         if (PP.getLangOpts().MSVCCompat && NumToks == 1 &&
4720b57cec5SDimitry Andric             ResultToks.back().is(tok::comma))
4730b57cec5SDimitry Andric           ResultToks.back().setFlag(Token::IgnoredComma);
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric         // If the '##' came from expanding an argument, turn it into 'unknown'
4760b57cec5SDimitry Andric         // to avoid pasting.
4770eae32dcSDimitry Andric         for (Token &Tok : llvm::drop_begin(ResultToks, FirstResult))
4780b57cec5SDimitry Andric           if (Tok.is(tok::hashhash))
4790b57cec5SDimitry Andric             Tok.setKind(tok::unknown);
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric         if(ExpandLocStart.isValid()) {
4820b57cec5SDimitry Andric           updateLocForMacroArgTokens(CurTok.getLocation(),
4830b57cec5SDimitry Andric                                      ResultToks.begin()+FirstResult,
4840b57cec5SDimitry Andric                                      ResultToks.end());
4850b57cec5SDimitry Andric         }
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric         // If any tokens were substituted from the argument, the whitespace
4880b57cec5SDimitry Andric         // before the first token should match the whitespace of the arg
4890b57cec5SDimitry Andric         // identifier.
4900b57cec5SDimitry Andric         ResultToks[FirstResult].setFlagValue(Token::LeadingSpace,
4910b57cec5SDimitry Andric                                              NextTokGetsSpace);
4920b57cec5SDimitry Andric         ResultToks[FirstResult].setFlagValue(Token::StartOfLine, false);
4930b57cec5SDimitry Andric         NextTokGetsSpace = false;
4940b57cec5SDimitry Andric       } else {
4950b57cec5SDimitry Andric         // We're creating a placeholder token. Usually this doesn't matter,
4960b57cec5SDimitry Andric         // but it can affect paste behavior when at the start or end of a
4970b57cec5SDimitry Andric         // __VA_OPT__.
4980b57cec5SDimitry Andric         if (NonEmptyPasteBefore) {
4990b57cec5SDimitry Andric           // We're imagining a placeholder token is inserted here. If this is
5000b57cec5SDimitry Andric           // the first token in a __VA_OPT__ after a ##, delete the ##.
5010b57cec5SDimitry Andric           assert(VCtx.isInVAOpt() && "should only happen inside a __VA_OPT__");
5020b57cec5SDimitry Andric           VCtx.hasPlaceholderAfterHashhashAtStart();
503*06c3fb27SDimitry Andric         } else if (RParenAfter)
5040b57cec5SDimitry Andric           VCtx.hasPlaceholderBeforeRParen();
5050b57cec5SDimitry Andric       }
5060b57cec5SDimitry Andric       continue;
5070b57cec5SDimitry Andric     }
5080b57cec5SDimitry Andric 
5090b57cec5SDimitry Andric     // Okay, we have a token that is either the LHS or RHS of a paste (##)
5100b57cec5SDimitry Andric     // argument.  It gets substituted as its non-pre-expanded tokens.
5110b57cec5SDimitry Andric     const Token *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
5120b57cec5SDimitry Andric     unsigned NumToks = MacroArgs::getArgLength(ArgToks);
5130b57cec5SDimitry Andric     if (NumToks) {  // Not an empty argument?
5140b57cec5SDimitry Andric       bool VaArgsPseudoPaste = false;
5150b57cec5SDimitry Andric       // If this is the GNU ", ## __VA_ARGS__" extension, and we just learned
5160b57cec5SDimitry Andric       // that __VA_ARGS__ expands to multiple tokens, avoid a pasting error when
5170b57cec5SDimitry Andric       // the expander tries to paste ',' with the first token of the __VA_ARGS__
5180b57cec5SDimitry Andric       // expansion.
5190b57cec5SDimitry Andric       if (NonEmptyPasteBefore && ResultToks.size() >= 2 &&
5200b57cec5SDimitry Andric           ResultToks[ResultToks.size()-2].is(tok::comma) &&
5210b57cec5SDimitry Andric           (unsigned)ArgNo == Macro->getNumParams()-1 &&
5220b57cec5SDimitry Andric           Macro->isVariadic()) {
5230b57cec5SDimitry Andric         VaArgsPseudoPaste = true;
5240b57cec5SDimitry Andric         // Remove the paste operator, report use of the extension.
5250b57cec5SDimitry Andric         PP.Diag(ResultToks.pop_back_val().getLocation(), diag::ext_paste_comma);
5260b57cec5SDimitry Andric       }
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric       ResultToks.append(ArgToks, ArgToks+NumToks);
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric       // If the '##' came from expanding an argument, turn it into 'unknown'
5310b57cec5SDimitry Andric       // to avoid pasting.
5320b57cec5SDimitry Andric       for (Token &Tok : llvm::make_range(ResultToks.end() - NumToks,
5330b57cec5SDimitry Andric                                          ResultToks.end())) {
5340b57cec5SDimitry Andric         if (Tok.is(tok::hashhash))
5350b57cec5SDimitry Andric           Tok.setKind(tok::unknown);
5360b57cec5SDimitry Andric       }
5370b57cec5SDimitry Andric 
5380b57cec5SDimitry Andric       if (ExpandLocStart.isValid()) {
5390b57cec5SDimitry Andric         updateLocForMacroArgTokens(CurTok.getLocation(),
5400b57cec5SDimitry Andric                                    ResultToks.end()-NumToks, ResultToks.end());
5410b57cec5SDimitry Andric       }
5420b57cec5SDimitry Andric 
5430b57cec5SDimitry Andric       // Transfer the leading whitespace information from the token
5440b57cec5SDimitry Andric       // (the macro argument) onto the first token of the
5450b57cec5SDimitry Andric       // expansion. Note that we don't do this for the GNU
5460b57cec5SDimitry Andric       // pseudo-paste extension ", ## __VA_ARGS__".
5470b57cec5SDimitry Andric       if (!VaArgsPseudoPaste) {
5480b57cec5SDimitry Andric         ResultToks[ResultToks.size() - NumToks].setFlagValue(Token::StartOfLine,
5490b57cec5SDimitry Andric                                                              false);
5500b57cec5SDimitry Andric         ResultToks[ResultToks.size() - NumToks].setFlagValue(
5510b57cec5SDimitry Andric             Token::LeadingSpace, NextTokGetsSpace);
5520b57cec5SDimitry Andric       }
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric       NextTokGetsSpace = false;
5550b57cec5SDimitry Andric       continue;
5560b57cec5SDimitry Andric     }
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric     // If an empty argument is on the LHS or RHS of a paste, the standard (C99
5590b57cec5SDimitry Andric     // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur.  We
5600b57cec5SDimitry Andric     // implement this by eating ## operators when a LHS or RHS expands to
5610b57cec5SDimitry Andric     // empty.
5620b57cec5SDimitry Andric     if (PasteAfter) {
5630b57cec5SDimitry Andric       // Discard the argument token and skip (don't copy to the expansion
5640b57cec5SDimitry Andric       // buffer) the paste operator after it.
5650b57cec5SDimitry Andric       ++I;
5660b57cec5SDimitry Andric       continue;
5670b57cec5SDimitry Andric     }
5680b57cec5SDimitry Andric 
569*06c3fb27SDimitry Andric     if (RParenAfter && !NonEmptyPasteBefore)
5700b57cec5SDimitry Andric       VCtx.hasPlaceholderBeforeRParen();
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric     // If this is on the RHS of a paste operator, we've already copied the
5730b57cec5SDimitry Andric     // paste operator to the ResultToks list, unless the LHS was empty too.
5740b57cec5SDimitry Andric     // Remove it.
5750b57cec5SDimitry Andric     assert(PasteBefore);
5760b57cec5SDimitry Andric     if (NonEmptyPasteBefore) {
5770b57cec5SDimitry Andric       assert(ResultToks.back().is(tok::hashhash));
5780b57cec5SDimitry Andric       // Do not remove the paste operator if it is the one before __VA_OPT__
5790b57cec5SDimitry Andric       // (and we are still processing tokens within VA_OPT).  We handle the case
5800b57cec5SDimitry Andric       // of removing the paste operator if __VA_OPT__ reduces to the notional
5810b57cec5SDimitry Andric       // placemarker above when we encounter the closing paren of VA_OPT.
5820b57cec5SDimitry Andric       if (!VCtx.isInVAOpt() ||
5830b57cec5SDimitry Andric           ResultToks.size() > VCtx.getNumberOfTokensPriorToVAOpt())
5840b57cec5SDimitry Andric         ResultToks.pop_back();
5850b57cec5SDimitry Andric       else
5860b57cec5SDimitry Andric         VCtx.hasPlaceholderAfterHashhashAtStart();
5870b57cec5SDimitry Andric     }
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric     // If this is the __VA_ARGS__ token, and if the argument wasn't provided,
5900b57cec5SDimitry Andric     // and if the macro had at least one real argument, and if the token before
5910b57cec5SDimitry Andric     // the ## was a comma, remove the comma.  This is a GCC extension which is
5920b57cec5SDimitry Andric     // disabled when using -std=c99.
5930b57cec5SDimitry Andric     if (ActualArgs->isVarargsElidedUse())
5940b57cec5SDimitry Andric       MaybeRemoveCommaBeforeVaArgs(ResultToks,
5950b57cec5SDimitry Andric                                    /*HasPasteOperator=*/true,
5960b57cec5SDimitry Andric                                    Macro, ArgNo, PP);
5970b57cec5SDimitry Andric   }
5980b57cec5SDimitry Andric 
5990b57cec5SDimitry Andric   // If anything changed, install this as the new Tokens list.
6000b57cec5SDimitry Andric   if (MadeChange) {
6010b57cec5SDimitry Andric     assert(!OwnsTokens && "This would leak if we already own the token list");
6020b57cec5SDimitry Andric     // This is deleted in the dtor.
6030b57cec5SDimitry Andric     NumTokens = ResultToks.size();
6040b57cec5SDimitry Andric     // The tokens will be added to Preprocessor's cache and will be removed
6050b57cec5SDimitry Andric     // when this TokenLexer finishes lexing them.
6060b57cec5SDimitry Andric     Tokens = PP.cacheMacroExpandedTokens(this, ResultToks);
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric     // The preprocessor cache of macro expanded tokens owns these tokens,not us.
6090b57cec5SDimitry Andric     OwnsTokens = false;
6100b57cec5SDimitry Andric   }
6110b57cec5SDimitry Andric }
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric /// Checks if two tokens form wide string literal.
isWideStringLiteralFromMacro(const Token & FirstTok,const Token & SecondTok)6140b57cec5SDimitry Andric static bool isWideStringLiteralFromMacro(const Token &FirstTok,
6150b57cec5SDimitry Andric                                          const Token &SecondTok) {
6160b57cec5SDimitry Andric   return FirstTok.is(tok::identifier) &&
6170b57cec5SDimitry Andric          FirstTok.getIdentifierInfo()->isStr("L") && SecondTok.isLiteral() &&
6180b57cec5SDimitry Andric          SecondTok.stringifiedInMacro();
6190b57cec5SDimitry Andric }
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric /// Lex - Lex and return a token from this macro stream.
Lex(Token & Tok)6220b57cec5SDimitry Andric bool TokenLexer::Lex(Token &Tok) {
6230b57cec5SDimitry Andric   // Lexing off the end of the macro, pop this macro off the expansion stack.
6240b57cec5SDimitry Andric   if (isAtEnd()) {
6250b57cec5SDimitry Andric     // If this is a macro (not a token stream), mark the macro enabled now
6260b57cec5SDimitry Andric     // that it is no longer being expanded.
6270b57cec5SDimitry Andric     if (Macro) Macro->EnableMacro();
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric     Tok.startToken();
6300b57cec5SDimitry Andric     Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
6310b57cec5SDimitry Andric     Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace || NextTokGetsSpace);
6320b57cec5SDimitry Andric     if (CurTokenIdx == 0)
6330b57cec5SDimitry Andric       Tok.setFlag(Token::LeadingEmptyMacro);
6340b57cec5SDimitry Andric     return PP.HandleEndOfTokenLexer(Tok);
6350b57cec5SDimitry Andric   }
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric   SourceManager &SM = PP.getSourceManager();
6380b57cec5SDimitry Andric 
6390b57cec5SDimitry Andric   // If this is the first token of the expanded result, we inherit spacing
6400b57cec5SDimitry Andric   // properties later.
6410b57cec5SDimitry Andric   bool isFirstToken = CurTokenIdx == 0;
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric   // Get the next token to return.
6440b57cec5SDimitry Andric   Tok = Tokens[CurTokenIdx++];
6450b57cec5SDimitry Andric   if (IsReinject)
6460b57cec5SDimitry Andric     Tok.setFlag(Token::IsReinjected);
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric   bool TokenIsFromPaste = false;
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric   // If this token is followed by a token paste (##) operator, paste the tokens!
6510b57cec5SDimitry Andric   // Note that ## is a normal token when not expanding a macro.
6520b57cec5SDimitry Andric   if (!isAtEnd() && Macro &&
6530b57cec5SDimitry Andric       (Tokens[CurTokenIdx].is(tok::hashhash) ||
6540b57cec5SDimitry Andric        // Special processing of L#x macros in -fms-compatibility mode.
6550b57cec5SDimitry Andric        // Microsoft compiler is able to form a wide string literal from
6560b57cec5SDimitry Andric        // 'L#macro_arg' construct in a function-like macro.
6570b57cec5SDimitry Andric        (PP.getLangOpts().MSVCCompat &&
6580b57cec5SDimitry Andric         isWideStringLiteralFromMacro(Tok, Tokens[CurTokenIdx])))) {
6590b57cec5SDimitry Andric     // When handling the microsoft /##/ extension, the final token is
6600b57cec5SDimitry Andric     // returned by pasteTokens, not the pasted token.
6610b57cec5SDimitry Andric     if (pasteTokens(Tok))
6620b57cec5SDimitry Andric       return true;
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric     TokenIsFromPaste = true;
6650b57cec5SDimitry Andric   }
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric   // The token's current location indicate where the token was lexed from.  We
6680b57cec5SDimitry Andric   // need this information to compute the spelling of the token, but any
6690b57cec5SDimitry Andric   // diagnostics for the expanded token should appear as if they came from
6700b57cec5SDimitry Andric   // ExpansionLoc.  Pull this information together into a new SourceLocation
6710b57cec5SDimitry Andric   // that captures all of this.
6720b57cec5SDimitry Andric   if (ExpandLocStart.isValid() &&   // Don't do this for token streams.
6730b57cec5SDimitry Andric       // Check that the token's location was not already set properly.
6740b57cec5SDimitry Andric       SM.isBeforeInSLocAddrSpace(Tok.getLocation(), MacroStartSLocOffset)) {
6750b57cec5SDimitry Andric     SourceLocation instLoc;
6760b57cec5SDimitry Andric     if (Tok.is(tok::comment)) {
6770b57cec5SDimitry Andric       instLoc = SM.createExpansionLoc(Tok.getLocation(),
6780b57cec5SDimitry Andric                                       ExpandLocStart,
6790b57cec5SDimitry Andric                                       ExpandLocEnd,
6800b57cec5SDimitry Andric                                       Tok.getLength());
6810b57cec5SDimitry Andric     } else {
6820b57cec5SDimitry Andric       instLoc = getExpansionLocForMacroDefLoc(Tok.getLocation());
6830b57cec5SDimitry Andric     }
6840b57cec5SDimitry Andric 
6850b57cec5SDimitry Andric     Tok.setLocation(instLoc);
6860b57cec5SDimitry Andric   }
6870b57cec5SDimitry Andric 
6880b57cec5SDimitry Andric   // If this is the first token, set the lexical properties of the token to
6890b57cec5SDimitry Andric   // match the lexical properties of the macro identifier.
6900b57cec5SDimitry Andric   if (isFirstToken) {
6910b57cec5SDimitry Andric     Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
6920b57cec5SDimitry Andric     Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
6930b57cec5SDimitry Andric   } else {
6940b57cec5SDimitry Andric     // If this is not the first token, we may still need to pass through
6950b57cec5SDimitry Andric     // leading whitespace if we've expanded a macro.
6960b57cec5SDimitry Andric     if (AtStartOfLine) Tok.setFlag(Token::StartOfLine);
6970b57cec5SDimitry Andric     if (HasLeadingSpace) Tok.setFlag(Token::LeadingSpace);
6980b57cec5SDimitry Andric   }
6990b57cec5SDimitry Andric   AtStartOfLine = false;
7000b57cec5SDimitry Andric   HasLeadingSpace = false;
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric   // Handle recursive expansion!
7030b57cec5SDimitry Andric   if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
7040b57cec5SDimitry Andric     // Change the kind of this identifier to the appropriate token kind, e.g.
7050b57cec5SDimitry Andric     // turning "for" into a keyword.
7060b57cec5SDimitry Andric     IdentifierInfo *II = Tok.getIdentifierInfo();
7070b57cec5SDimitry Andric     Tok.setKind(II->getTokenID());
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric     // If this identifier was poisoned and from a paste, emit an error.  This
7100b57cec5SDimitry Andric     // won't be handled by Preprocessor::HandleIdentifier because this is coming
7110b57cec5SDimitry Andric     // from a macro expansion.
7120b57cec5SDimitry Andric     if (II->isPoisoned() && TokenIsFromPaste) {
7130b57cec5SDimitry Andric       PP.HandlePoisonedIdentifier(Tok);
7140b57cec5SDimitry Andric     }
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric     if (!DisableMacroExpansion && II->isHandleIdentifierCase())
7170b57cec5SDimitry Andric       return PP.HandleIdentifier(Tok);
7180b57cec5SDimitry Andric   }
7190b57cec5SDimitry Andric 
7200b57cec5SDimitry Andric   // Otherwise, return a normal token.
7210b57cec5SDimitry Andric   return true;
7220b57cec5SDimitry Andric }
7230b57cec5SDimitry Andric 
pasteTokens(Token & Tok)7240b57cec5SDimitry Andric bool TokenLexer::pasteTokens(Token &Tok) {
725bdd1243dSDimitry Andric   return pasteTokens(Tok, llvm::ArrayRef(Tokens, NumTokens), CurTokenIdx);
7260b57cec5SDimitry Andric }
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric /// LHSTok is the LHS of a ## operator, and CurTokenIdx is the ##
7290b57cec5SDimitry Andric /// operator.  Read the ## and RHS, and paste the LHS/RHS together.  If there
7300b57cec5SDimitry Andric /// are more ## after it, chomp them iteratively.  Return the result as LHSTok.
7310b57cec5SDimitry Andric /// If this returns true, the caller should immediately return the token.
pasteTokens(Token & LHSTok,ArrayRef<Token> TokenStream,unsigned int & CurIdx)7320b57cec5SDimitry Andric bool TokenLexer::pasteTokens(Token &LHSTok, ArrayRef<Token> TokenStream,
7330b57cec5SDimitry Andric                              unsigned int &CurIdx) {
7340b57cec5SDimitry Andric   assert(CurIdx > 0 && "## can not be the first token within tokens");
7350b57cec5SDimitry Andric   assert((TokenStream[CurIdx].is(tok::hashhash) ||
7360b57cec5SDimitry Andric          (PP.getLangOpts().MSVCCompat &&
7370b57cec5SDimitry Andric           isWideStringLiteralFromMacro(LHSTok, TokenStream[CurIdx]))) &&
7380b57cec5SDimitry Andric              "Token at this Index must be ## or part of the MSVC 'L "
7390b57cec5SDimitry Andric              "#macro-arg' pasting pair");
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric   // MSVC: If previous token was pasted, this must be a recovery from an invalid
7420b57cec5SDimitry Andric   // paste operation. Ignore spaces before this token to mimic MSVC output.
7430b57cec5SDimitry Andric   // Required for generating valid UUID strings in some MS headers.
7440b57cec5SDimitry Andric   if (PP.getLangOpts().MicrosoftExt && (CurIdx >= 2) &&
7450b57cec5SDimitry Andric       TokenStream[CurIdx - 2].is(tok::hashhash))
7460b57cec5SDimitry Andric     LHSTok.clearFlag(Token::LeadingSpace);
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric   SmallString<128> Buffer;
7490b57cec5SDimitry Andric   const char *ResultTokStrPtr = nullptr;
7500b57cec5SDimitry Andric   SourceLocation StartLoc = LHSTok.getLocation();
7510b57cec5SDimitry Andric   SourceLocation PasteOpLoc;
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   auto IsAtEnd = [&TokenStream, &CurIdx] {
7540b57cec5SDimitry Andric     return TokenStream.size() == CurIdx;
7550b57cec5SDimitry Andric   };
7560b57cec5SDimitry Andric 
7570b57cec5SDimitry Andric   do {
7580b57cec5SDimitry Andric     // Consume the ## operator if any.
7590b57cec5SDimitry Andric     PasteOpLoc = TokenStream[CurIdx].getLocation();
7600b57cec5SDimitry Andric     if (TokenStream[CurIdx].is(tok::hashhash))
7610b57cec5SDimitry Andric       ++CurIdx;
7620b57cec5SDimitry Andric     assert(!IsAtEnd() && "No token on the RHS of a paste operator!");
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric     // Get the RHS token.
7650b57cec5SDimitry Andric     const Token &RHS = TokenStream[CurIdx];
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric     // Allocate space for the result token.  This is guaranteed to be enough for
7680b57cec5SDimitry Andric     // the two tokens.
7690b57cec5SDimitry Andric     Buffer.resize(LHSTok.getLength() + RHS.getLength());
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric     // Get the spelling of the LHS token in Buffer.
7720b57cec5SDimitry Andric     const char *BufPtr = &Buffer[0];
7730b57cec5SDimitry Andric     bool Invalid = false;
7740b57cec5SDimitry Andric     unsigned LHSLen = PP.getSpelling(LHSTok, BufPtr, &Invalid);
7750b57cec5SDimitry Andric     if (BufPtr != &Buffer[0])   // Really, we want the chars in Buffer!
7760b57cec5SDimitry Andric       memcpy(&Buffer[0], BufPtr, LHSLen);
7770b57cec5SDimitry Andric     if (Invalid)
7780b57cec5SDimitry Andric       return true;
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric     BufPtr = Buffer.data() + LHSLen;
7810b57cec5SDimitry Andric     unsigned RHSLen = PP.getSpelling(RHS, BufPtr, &Invalid);
7820b57cec5SDimitry Andric     if (Invalid)
7830b57cec5SDimitry Andric       return true;
7840b57cec5SDimitry Andric     if (RHSLen && BufPtr != &Buffer[LHSLen])
7850b57cec5SDimitry Andric       // Really, we want the chars in Buffer!
7860b57cec5SDimitry Andric       memcpy(&Buffer[LHSLen], BufPtr, RHSLen);
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric     // Trim excess space.
7890b57cec5SDimitry Andric     Buffer.resize(LHSLen+RHSLen);
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric     // Plop the pasted result (including the trailing newline and null) into a
7920b57cec5SDimitry Andric     // scratch buffer where we can lex it.
7930b57cec5SDimitry Andric     Token ResultTokTmp;
7940b57cec5SDimitry Andric     ResultTokTmp.startToken();
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric     // Claim that the tmp token is a string_literal so that we can get the
7970b57cec5SDimitry Andric     // character pointer back from CreateString in getLiteralData().
7980b57cec5SDimitry Andric     ResultTokTmp.setKind(tok::string_literal);
7990b57cec5SDimitry Andric     PP.CreateString(Buffer, ResultTokTmp);
8000b57cec5SDimitry Andric     SourceLocation ResultTokLoc = ResultTokTmp.getLocation();
8010b57cec5SDimitry Andric     ResultTokStrPtr = ResultTokTmp.getLiteralData();
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric     // Lex the resultant pasted token into Result.
8040b57cec5SDimitry Andric     Token Result;
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric     if (LHSTok.isAnyIdentifier() && RHS.isAnyIdentifier()) {
8070b57cec5SDimitry Andric       // Common paste case: identifier+identifier = identifier.  Avoid creating
8080b57cec5SDimitry Andric       // a lexer and other overhead.
8090b57cec5SDimitry Andric       PP.IncrementPasteCounter(true);
8100b57cec5SDimitry Andric       Result.startToken();
8110b57cec5SDimitry Andric       Result.setKind(tok::raw_identifier);
8120b57cec5SDimitry Andric       Result.setRawIdentifierData(ResultTokStrPtr);
8130b57cec5SDimitry Andric       Result.setLocation(ResultTokLoc);
8140b57cec5SDimitry Andric       Result.setLength(LHSLen+RHSLen);
8150b57cec5SDimitry Andric     } else {
8160b57cec5SDimitry Andric       PP.IncrementPasteCounter(false);
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric       assert(ResultTokLoc.isFileID() &&
8190b57cec5SDimitry Andric              "Should be a raw location into scratch buffer");
8200b57cec5SDimitry Andric       SourceManager &SourceMgr = PP.getSourceManager();
8210b57cec5SDimitry Andric       FileID LocFileID = SourceMgr.getFileID(ResultTokLoc);
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric       bool Invalid = false;
8240b57cec5SDimitry Andric       const char *ScratchBufStart
8250b57cec5SDimitry Andric         = SourceMgr.getBufferData(LocFileID, &Invalid).data();
8260b57cec5SDimitry Andric       if (Invalid)
8270b57cec5SDimitry Andric         return false;
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric       // Make a lexer to lex this string from.  Lex just this one token.
8300b57cec5SDimitry Andric       // Make a lexer object so that we lex and expand the paste result.
8310b57cec5SDimitry Andric       Lexer TL(SourceMgr.getLocForStartOfFile(LocFileID),
8320b57cec5SDimitry Andric                PP.getLangOpts(), ScratchBufStart,
8330b57cec5SDimitry Andric                ResultTokStrPtr, ResultTokStrPtr+LHSLen+RHSLen);
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric       // Lex a token in raw mode.  This way it won't look up identifiers
8360b57cec5SDimitry Andric       // automatically, lexing off the end will return an eof token, and
8370b57cec5SDimitry Andric       // warnings are disabled.  This returns true if the result token is the
8380b57cec5SDimitry Andric       // entire buffer.
8390b57cec5SDimitry Andric       bool isInvalid = !TL.LexFromRawLexer(Result);
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric       // If we got an EOF token, we didn't form even ONE token.  For example, we
8420b57cec5SDimitry Andric       // did "/ ## /" to get "//".
8430b57cec5SDimitry Andric       isInvalid |= Result.is(tok::eof);
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric       // If pasting the two tokens didn't form a full new token, this is an
8460b57cec5SDimitry Andric       // error.  This occurs with "x ## +"  and other stuff.  Return with LHSTok
8470b57cec5SDimitry Andric       // unmodified and with RHS as the next token to lex.
8480b57cec5SDimitry Andric       if (isInvalid) {
8490b57cec5SDimitry Andric         // Explicitly convert the token location to have proper expansion
8500b57cec5SDimitry Andric         // information so that the user knows where it came from.
8510b57cec5SDimitry Andric         SourceManager &SM = PP.getSourceManager();
8520b57cec5SDimitry Andric         SourceLocation Loc =
8530b57cec5SDimitry Andric           SM.createExpansionLoc(PasteOpLoc, ExpandLocStart, ExpandLocEnd, 2);
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric         // Test for the Microsoft extension of /##/ turning into // here on the
8560b57cec5SDimitry Andric         // error path.
8570b57cec5SDimitry Andric         if (PP.getLangOpts().MicrosoftExt && LHSTok.is(tok::slash) &&
8580b57cec5SDimitry Andric             RHS.is(tok::slash)) {
8590b57cec5SDimitry Andric           HandleMicrosoftCommentPaste(LHSTok, Loc);
8600b57cec5SDimitry Andric           return true;
8610b57cec5SDimitry Andric         }
8620b57cec5SDimitry Andric 
8630b57cec5SDimitry Andric         // Do not emit the error when preprocessing assembler code.
8640b57cec5SDimitry Andric         if (!PP.getLangOpts().AsmPreprocessor) {
8650b57cec5SDimitry Andric           // If we're in microsoft extensions mode, downgrade this from a hard
8660b57cec5SDimitry Andric           // error to an extension that defaults to an error.  This allows
8670b57cec5SDimitry Andric           // disabling it.
8680b57cec5SDimitry Andric           PP.Diag(Loc, PP.getLangOpts().MicrosoftExt ? diag::ext_pp_bad_paste_ms
8690b57cec5SDimitry Andric                                                      : diag::err_pp_bad_paste)
8700b57cec5SDimitry Andric               << Buffer;
8710b57cec5SDimitry Andric         }
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric         // An error has occurred so exit loop.
8740b57cec5SDimitry Andric         break;
8750b57cec5SDimitry Andric       }
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric       // Turn ## into 'unknown' to avoid # ## # from looking like a paste
8780b57cec5SDimitry Andric       // operator.
8790b57cec5SDimitry Andric       if (Result.is(tok::hashhash))
8800b57cec5SDimitry Andric         Result.setKind(tok::unknown);
8810b57cec5SDimitry Andric     }
8820b57cec5SDimitry Andric 
8830b57cec5SDimitry Andric     // Transfer properties of the LHS over the Result.
8840b57cec5SDimitry Andric     Result.setFlagValue(Token::StartOfLine , LHSTok.isAtStartOfLine());
8850b57cec5SDimitry Andric     Result.setFlagValue(Token::LeadingSpace, LHSTok.hasLeadingSpace());
8860b57cec5SDimitry Andric 
8870b57cec5SDimitry Andric     // Finally, replace LHS with the result, consume the RHS, and iterate.
8880b57cec5SDimitry Andric     ++CurIdx;
8890b57cec5SDimitry Andric     LHSTok = Result;
8900b57cec5SDimitry Andric   } while (!IsAtEnd() && TokenStream[CurIdx].is(tok::hashhash));
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric   SourceLocation EndLoc = TokenStream[CurIdx - 1].getLocation();
8930b57cec5SDimitry Andric 
8940b57cec5SDimitry Andric   // The token's current location indicate where the token was lexed from.  We
8950b57cec5SDimitry Andric   // need this information to compute the spelling of the token, but any
8960b57cec5SDimitry Andric   // diagnostics for the expanded token should appear as if the token was
8970b57cec5SDimitry Andric   // expanded from the full ## expression. Pull this information together into
8980b57cec5SDimitry Andric   // a new SourceLocation that captures all of this.
8990b57cec5SDimitry Andric   SourceManager &SM = PP.getSourceManager();
9000b57cec5SDimitry Andric   if (StartLoc.isFileID())
9010b57cec5SDimitry Andric     StartLoc = getExpansionLocForMacroDefLoc(StartLoc);
9020b57cec5SDimitry Andric   if (EndLoc.isFileID())
9030b57cec5SDimitry Andric     EndLoc = getExpansionLocForMacroDefLoc(EndLoc);
9040b57cec5SDimitry Andric   FileID MacroFID = SM.getFileID(MacroExpansionStart);
9050b57cec5SDimitry Andric   while (SM.getFileID(StartLoc) != MacroFID)
9060b57cec5SDimitry Andric     StartLoc = SM.getImmediateExpansionRange(StartLoc).getBegin();
9070b57cec5SDimitry Andric   while (SM.getFileID(EndLoc) != MacroFID)
9080b57cec5SDimitry Andric     EndLoc = SM.getImmediateExpansionRange(EndLoc).getEnd();
9090b57cec5SDimitry Andric 
9100b57cec5SDimitry Andric   LHSTok.setLocation(SM.createExpansionLoc(LHSTok.getLocation(), StartLoc, EndLoc,
9110b57cec5SDimitry Andric                                         LHSTok.getLength()));
9120b57cec5SDimitry Andric 
9130b57cec5SDimitry Andric   // Now that we got the result token, it will be subject to expansion.  Since
9140b57cec5SDimitry Andric   // token pasting re-lexes the result token in raw mode, identifier information
9150b57cec5SDimitry Andric   // isn't looked up.  As such, if the result is an identifier, look up id info.
9160b57cec5SDimitry Andric   if (LHSTok.is(tok::raw_identifier)) {
9170b57cec5SDimitry Andric     // Look up the identifier info for the token.  We disabled identifier lookup
9180b57cec5SDimitry Andric     // by saying we're skipping contents, so we need to do this manually.
9190b57cec5SDimitry Andric     PP.LookUpIdentifierInfo(LHSTok);
9200b57cec5SDimitry Andric   }
9210b57cec5SDimitry Andric   return false;
9220b57cec5SDimitry Andric }
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric /// isNextTokenLParen - If the next token lexed will pop this macro off the
9250b57cec5SDimitry Andric /// expansion stack, return 2.  If the next unexpanded token is a '(', return
9260b57cec5SDimitry Andric /// 1, otherwise return 0.
isNextTokenLParen() const9270b57cec5SDimitry Andric unsigned TokenLexer::isNextTokenLParen() const {
9280b57cec5SDimitry Andric   // Out of tokens?
9290b57cec5SDimitry Andric   if (isAtEnd())
9300b57cec5SDimitry Andric     return 2;
9310b57cec5SDimitry Andric   return Tokens[CurTokenIdx].is(tok::l_paren);
9320b57cec5SDimitry Andric }
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric /// isParsingPreprocessorDirective - Return true if we are in the middle of a
9350b57cec5SDimitry Andric /// preprocessor directive.
isParsingPreprocessorDirective() const9360b57cec5SDimitry Andric bool TokenLexer::isParsingPreprocessorDirective() const {
9370b57cec5SDimitry Andric   return Tokens[NumTokens-1].is(tok::eod) && !isAtEnd();
9380b57cec5SDimitry Andric }
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric /// HandleMicrosoftCommentPaste - In microsoft compatibility mode, /##/ pastes
9410b57cec5SDimitry Andric /// together to form a comment that comments out everything in the current
9420b57cec5SDimitry Andric /// macro, other active macros, and anything left on the current physical
9430b57cec5SDimitry Andric /// source line of the expanded buffer.  Handle this by returning the
9440b57cec5SDimitry Andric /// first token on the next line.
HandleMicrosoftCommentPaste(Token & Tok,SourceLocation OpLoc)9450b57cec5SDimitry Andric void TokenLexer::HandleMicrosoftCommentPaste(Token &Tok, SourceLocation OpLoc) {
9460b57cec5SDimitry Andric   PP.Diag(OpLoc, diag::ext_comment_paste_microsoft);
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric   // We 'comment out' the rest of this macro by just ignoring the rest of the
9490b57cec5SDimitry Andric   // tokens that have not been lexed yet, if any.
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric   // Since this must be a macro, mark the macro enabled now that it is no longer
9520b57cec5SDimitry Andric   // being expanded.
9530b57cec5SDimitry Andric   assert(Macro && "Token streams can't paste comments");
9540b57cec5SDimitry Andric   Macro->EnableMacro();
9550b57cec5SDimitry Andric 
9560b57cec5SDimitry Andric   PP.HandleMicrosoftCommentPaste(Tok);
9570b57cec5SDimitry Andric }
9580b57cec5SDimitry Andric 
9590b57cec5SDimitry Andric /// If \arg loc is a file ID and points inside the current macro
9600b57cec5SDimitry Andric /// definition, returns the appropriate source location pointing at the
9610b57cec5SDimitry Andric /// macro expansion source location entry, otherwise it returns an invalid
9620b57cec5SDimitry Andric /// SourceLocation.
9630b57cec5SDimitry Andric SourceLocation
getExpansionLocForMacroDefLoc(SourceLocation loc) const9640b57cec5SDimitry Andric TokenLexer::getExpansionLocForMacroDefLoc(SourceLocation loc) const {
9650b57cec5SDimitry Andric   assert(ExpandLocStart.isValid() && MacroExpansionStart.isValid() &&
9660b57cec5SDimitry Andric          "Not appropriate for token streams");
9670b57cec5SDimitry Andric   assert(loc.isValid() && loc.isFileID());
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric   SourceManager &SM = PP.getSourceManager();
9700b57cec5SDimitry Andric   assert(SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength) &&
9710b57cec5SDimitry Andric          "Expected loc to come from the macro definition");
9720b57cec5SDimitry Andric 
973fe6060f1SDimitry Andric   SourceLocation::UIntTy relativeOffset = 0;
9740b57cec5SDimitry Andric   SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength, &relativeOffset);
9750b57cec5SDimitry Andric   return MacroExpansionStart.getLocWithOffset(relativeOffset);
9760b57cec5SDimitry Andric }
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric /// Finds the tokens that are consecutive (from the same FileID)
9790b57cec5SDimitry Andric /// creates a single SLocEntry, and assigns SourceLocations to each token that
9800b57cec5SDimitry Andric /// point to that SLocEntry. e.g for
9810b57cec5SDimitry Andric ///   assert(foo == bar);
9820b57cec5SDimitry Andric /// There will be a single SLocEntry for the "foo == bar" chunk and locations
9830b57cec5SDimitry Andric /// for the 'foo', '==', 'bar' tokens will point inside that chunk.
9840b57cec5SDimitry Andric ///
9850b57cec5SDimitry Andric /// \arg begin_tokens will be updated to a position past all the found
9860b57cec5SDimitry Andric /// consecutive tokens.
updateConsecutiveMacroArgTokens(SourceManager & SM,SourceLocation ExpandLoc,Token * & begin_tokens,Token * end_tokens)9870b57cec5SDimitry Andric static void updateConsecutiveMacroArgTokens(SourceManager &SM,
988bdd1243dSDimitry Andric                                             SourceLocation ExpandLoc,
9890b57cec5SDimitry Andric                                             Token *&begin_tokens,
9900b57cec5SDimitry Andric                                             Token * end_tokens) {
991bdd1243dSDimitry Andric   assert(begin_tokens + 1 < end_tokens);
992bdd1243dSDimitry Andric   SourceLocation BeginLoc = begin_tokens->getLocation();
993bdd1243dSDimitry Andric   llvm::MutableArrayRef<Token> All(begin_tokens, end_tokens);
994bdd1243dSDimitry Andric   llvm::MutableArrayRef<Token> Partition;
9950b57cec5SDimitry Andric 
996bdd1243dSDimitry Andric   auto NearLast = [&, Last = BeginLoc](SourceLocation Loc) mutable {
997bdd1243dSDimitry Andric     // The maximum distance between two consecutive tokens in a partition.
998bdd1243dSDimitry Andric     // This is an important trick to avoid using too much SourceLocation address
999bdd1243dSDimitry Andric     // space!
1000bdd1243dSDimitry Andric     static constexpr SourceLocation::IntTy MaxDistance = 50;
1001bdd1243dSDimitry Andric     auto Distance = Loc.getRawEncoding() - Last.getRawEncoding();
1002bdd1243dSDimitry Andric     Last = Loc;
1003bdd1243dSDimitry Andric     return Distance <= MaxDistance;
1004bdd1243dSDimitry Andric   };
10050b57cec5SDimitry Andric 
1006bdd1243dSDimitry Andric   // Partition the tokens by their FileID.
1007bdd1243dSDimitry Andric   // This is a hot function, and calling getFileID can be expensive, the
1008bdd1243dSDimitry Andric   // implementation is optimized by reducing the number of getFileID.
1009bdd1243dSDimitry Andric   if (BeginLoc.isFileID()) {
1010bdd1243dSDimitry Andric     // Consecutive tokens not written in macros must be from the same file.
1011bdd1243dSDimitry Andric     // (Neither #include nor eof can occur inside a macro argument.)
1012bdd1243dSDimitry Andric     Partition = All.take_while([&](const Token &T) {
1013bdd1243dSDimitry Andric       return T.getLocation().isFileID() && NearLast(T.getLocation());
1014bdd1243dSDimitry Andric     });
1015bdd1243dSDimitry Andric   } else {
1016bdd1243dSDimitry Andric     // Call getFileID once to calculate the bounds, and use the cheaper
1017bdd1243dSDimitry Andric     // sourcelocation-against-bounds comparison.
1018bdd1243dSDimitry Andric     FileID BeginFID = SM.getFileID(BeginLoc);
1019bdd1243dSDimitry Andric     SourceLocation Limit =
1020bdd1243dSDimitry Andric         SM.getComposedLoc(BeginFID, SM.getFileIDSize(BeginFID));
1021bdd1243dSDimitry Andric     Partition = All.take_while([&](const Token &T) {
10221ac55f4cSDimitry Andric       // NOTE: the Limit is included! The lexer recovery only ever inserts a
10231ac55f4cSDimitry Andric       // single token past the end of the FileID, specifically the ) when a
10241ac55f4cSDimitry Andric       // macro-arg containing a comma should be guarded by parentheses.
10251ac55f4cSDimitry Andric       //
10261ac55f4cSDimitry Andric       // It is safe to include the Limit here because SourceManager allocates
10271ac55f4cSDimitry Andric       // FileSize + 1 for each SLocEntry.
10281ac55f4cSDimitry Andric       //
10291ac55f4cSDimitry Andric       // See https://github.com/llvm/llvm-project/issues/60722.
10301ac55f4cSDimitry Andric       return T.getLocation() >= BeginLoc && T.getLocation() <= Limit
10311ac55f4cSDimitry Andric          &&  NearLast(T.getLocation());
1032bdd1243dSDimitry Andric     });
10330b57cec5SDimitry Andric   }
1034bdd1243dSDimitry Andric   assert(!Partition.empty());
10350b57cec5SDimitry Andric 
10360b57cec5SDimitry Andric   // For the consecutive tokens, find the length of the SLocEntry to contain
10370b57cec5SDimitry Andric   // all of them.
1038fe6060f1SDimitry Andric   SourceLocation::UIntTy FullLength =
1039bdd1243dSDimitry Andric       Partition.back().getEndLoc().getRawEncoding() -
1040bdd1243dSDimitry Andric       Partition.front().getLocation().getRawEncoding();
10410b57cec5SDimitry Andric   // Create a macro expansion SLocEntry that will "contain" all of the tokens.
10420b57cec5SDimitry Andric   SourceLocation Expansion =
1043bdd1243dSDimitry Andric       SM.createMacroArgExpansionLoc(BeginLoc, ExpandLoc, FullLength);
10440b57cec5SDimitry Andric 
1045bdd1243dSDimitry Andric #ifdef EXPENSIVE_CHECKS
1046bdd1243dSDimitry Andric   assert(llvm::all_of(Partition.drop_front(),
1047bdd1243dSDimitry Andric                       [&SM, ID = SM.getFileID(Partition.front().getLocation())](
1048bdd1243dSDimitry Andric                           const Token &T) {
1049bdd1243dSDimitry Andric                         return ID == SM.getFileID(T.getLocation());
1050bdd1243dSDimitry Andric                       }) &&
1051bdd1243dSDimitry Andric          "Must have the same FIleID!");
1052bdd1243dSDimitry Andric #endif
10530b57cec5SDimitry Andric   // Change the location of the tokens from the spelling location to the new
10540b57cec5SDimitry Andric   // expanded location.
1055bdd1243dSDimitry Andric   for (Token& T : Partition) {
1056bdd1243dSDimitry Andric     SourceLocation::IntTy RelativeOffset =
1057bdd1243dSDimitry Andric         T.getLocation().getRawEncoding() - BeginLoc.getRawEncoding();
1058bdd1243dSDimitry Andric     T.setLocation(Expansion.getLocWithOffset(RelativeOffset));
10590b57cec5SDimitry Andric   }
1060bdd1243dSDimitry Andric   begin_tokens = &Partition.back() + 1;
10610b57cec5SDimitry Andric }
10620b57cec5SDimitry Andric 
10630b57cec5SDimitry Andric /// Creates SLocEntries and updates the locations of macro argument
10640b57cec5SDimitry Andric /// tokens to their new expanded locations.
10650b57cec5SDimitry Andric ///
10660b57cec5SDimitry Andric /// \param ArgIdSpellLoc the location of the macro argument id inside the macro
10670b57cec5SDimitry Andric /// definition.
updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc,Token * begin_tokens,Token * end_tokens)10680b57cec5SDimitry Andric void TokenLexer::updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc,
10690b57cec5SDimitry Andric                                             Token *begin_tokens,
10700b57cec5SDimitry Andric                                             Token *end_tokens) {
10710b57cec5SDimitry Andric   SourceManager &SM = PP.getSourceManager();
10720b57cec5SDimitry Andric 
1073bdd1243dSDimitry Andric   SourceLocation ExpandLoc =
10740b57cec5SDimitry Andric       getExpansionLocForMacroDefLoc(ArgIdSpellLoc);
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric   while (begin_tokens < end_tokens) {
10770b57cec5SDimitry Andric     // If there's only one token just create a SLocEntry for it.
10780b57cec5SDimitry Andric     if (end_tokens - begin_tokens == 1) {
10790b57cec5SDimitry Andric       Token &Tok = *begin_tokens;
10800b57cec5SDimitry Andric       Tok.setLocation(SM.createMacroArgExpansionLoc(Tok.getLocation(),
1081bdd1243dSDimitry Andric                                                     ExpandLoc,
10820b57cec5SDimitry Andric                                                     Tok.getLength()));
10830b57cec5SDimitry Andric       return;
10840b57cec5SDimitry Andric     }
10850b57cec5SDimitry Andric 
1086bdd1243dSDimitry Andric     updateConsecutiveMacroArgTokens(SM, ExpandLoc, begin_tokens, end_tokens);
10870b57cec5SDimitry Andric   }
10880b57cec5SDimitry Andric }
10890b57cec5SDimitry Andric 
PropagateLineStartLeadingSpaceInfo(Token & Result)10900b57cec5SDimitry Andric void TokenLexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
10910b57cec5SDimitry Andric   AtStartOfLine = Result.isAtStartOfLine();
10920b57cec5SDimitry Andric   HasLeadingSpace = Result.hasLeadingSpace();
10930b57cec5SDimitry Andric }
1094