Path: blob/main/contrib/llvm-project/clang/lib/Lex/TokenLexer.cpp
35234 views
//===- TokenLexer.cpp - Lex from a token stream ---------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the TokenLexer interface.9//10//===----------------------------------------------------------------------===//1112#include "clang/Lex/TokenLexer.h"13#include "clang/Basic/Diagnostic.h"14#include "clang/Basic/IdentifierTable.h"15#include "clang/Basic/LangOptions.h"16#include "clang/Basic/SourceLocation.h"17#include "clang/Basic/SourceManager.h"18#include "clang/Basic/TokenKinds.h"19#include "clang/Lex/LexDiagnostic.h"20#include "clang/Lex/Lexer.h"21#include "clang/Lex/MacroArgs.h"22#include "clang/Lex/MacroInfo.h"23#include "clang/Lex/Preprocessor.h"24#include "clang/Lex/Token.h"25#include "clang/Lex/VariadicMacroSupport.h"26#include "llvm/ADT/ArrayRef.h"27#include "llvm/ADT/STLExtras.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#include <optional>3435using namespace clang;3637/// Create a TokenLexer for the specified macro with the specified actual38/// arguments. Note that this ctor takes ownership of the ActualArgs pointer.39void TokenLexer::Init(Token &Tok, SourceLocation ELEnd, MacroInfo *MI,40MacroArgs *Actuals) {41// If the client is reusing a TokenLexer, make sure to free any memory42// associated with it.43destroy();4445Macro = MI;46ActualArgs = Actuals;47CurTokenIdx = 0;4849ExpandLocStart = Tok.getLocation();50ExpandLocEnd = ELEnd;51AtStartOfLine = Tok.isAtStartOfLine();52HasLeadingSpace = Tok.hasLeadingSpace();53NextTokGetsSpace = false;54Tokens = &*Macro->tokens_begin();55OwnsTokens = false;56DisableMacroExpansion = false;57IsReinject = false;58NumTokens = Macro->tokens_end()-Macro->tokens_begin();59MacroExpansionStart = SourceLocation();6061SourceManager &SM = PP.getSourceManager();62MacroStartSLocOffset = SM.getNextLocalOffset();6364if (NumTokens > 0) {65assert(Tokens[0].getLocation().isValid());66assert((Tokens[0].getLocation().isFileID() || Tokens[0].is(tok::comment)) &&67"Macro defined in macro?");68assert(ExpandLocStart.isValid());6970// Reserve a source location entry chunk for the length of the macro71// definition. Tokens that get lexed directly from the definition will72// have their locations pointing inside this chunk. This is to avoid73// creating separate source location entries for each token.74MacroDefStart = SM.getExpansionLoc(Tokens[0].getLocation());75MacroDefLength = Macro->getDefinitionLength(SM);76MacroExpansionStart = SM.createExpansionLoc(MacroDefStart,77ExpandLocStart,78ExpandLocEnd,79MacroDefLength);80}8182// If this is a function-like macro, expand the arguments and change83// Tokens to point to the expanded tokens.84if (Macro->isFunctionLike() && Macro->getNumParams())85ExpandFunctionArguments();8687// Mark the macro as currently disabled, so that it is not recursively88// expanded. The macro must be disabled only after argument pre-expansion of89// function-like macro arguments occurs.90Macro->DisableMacro();91}9293/// Create a TokenLexer for the specified token stream. This does not94/// take ownership of the specified token vector.95void TokenLexer::Init(const Token *TokArray, unsigned NumToks,96bool disableMacroExpansion, bool ownsTokens,97bool isReinject) {98assert(!isReinject || disableMacroExpansion);99// If the client is reusing a TokenLexer, make sure to free any memory100// associated with it.101destroy();102103Macro = nullptr;104ActualArgs = nullptr;105Tokens = TokArray;106OwnsTokens = ownsTokens;107DisableMacroExpansion = disableMacroExpansion;108IsReinject = isReinject;109NumTokens = NumToks;110CurTokenIdx = 0;111ExpandLocStart = ExpandLocEnd = SourceLocation();112AtStartOfLine = false;113HasLeadingSpace = false;114NextTokGetsSpace = false;115MacroExpansionStart = SourceLocation();116117// Set HasLeadingSpace/AtStartOfLine so that the first token will be118// returned unmodified.119if (NumToks != 0) {120AtStartOfLine = TokArray[0].isAtStartOfLine();121HasLeadingSpace = TokArray[0].hasLeadingSpace();122}123}124125void TokenLexer::destroy() {126// If this was a function-like macro that actually uses its arguments, delete127// the expanded tokens.128if (OwnsTokens) {129delete [] Tokens;130Tokens = nullptr;131OwnsTokens = false;132}133134// TokenLexer owns its formal arguments.135if (ActualArgs) ActualArgs->destroy(PP);136}137138bool TokenLexer::MaybeRemoveCommaBeforeVaArgs(139SmallVectorImpl<Token> &ResultToks, bool HasPasteOperator, MacroInfo *Macro,140unsigned MacroArgNo, Preprocessor &PP) {141// Is the macro argument __VA_ARGS__?142if (!Macro->isVariadic() || MacroArgNo != Macro->getNumParams()-1)143return false;144145// In Microsoft-compatibility mode, a comma is removed in the expansion146// of " ... , __VA_ARGS__ " if __VA_ARGS__ is empty. This extension is147// not supported by gcc.148if (!HasPasteOperator && !PP.getLangOpts().MSVCCompat)149return false;150151// GCC removes the comma in the expansion of " ... , ## __VA_ARGS__ " if152// __VA_ARGS__ is empty, but not in strict C99 mode where there are no153// named arguments, where it remains. In all other modes, including C99154// with GNU extensions, it is removed regardless of named arguments.155// Microsoft also appears to support this extension, unofficially.156if (PP.getLangOpts().C99 && !PP.getLangOpts().GNUMode157&& Macro->getNumParams() < 2)158return false;159160// Is a comma available to be removed?161if (ResultToks.empty() || !ResultToks.back().is(tok::comma))162return false;163164// Issue an extension diagnostic for the paste operator.165if (HasPasteOperator)166PP.Diag(ResultToks.back().getLocation(), diag::ext_paste_comma);167168// Remove the comma.169ResultToks.pop_back();170171if (!ResultToks.empty()) {172// If the comma was right after another paste (e.g. "X##,##__VA_ARGS__"),173// then removal of the comma should produce a placemarker token (in C99174// terms) which we model by popping off the previous ##, giving us a plain175// "X" when __VA_ARGS__ is empty.176if (ResultToks.back().is(tok::hashhash))177ResultToks.pop_back();178179// Remember that this comma was elided.180ResultToks.back().setFlag(Token::CommaAfterElided);181}182183// Never add a space, even if the comma, ##, or arg had a space.184NextTokGetsSpace = false;185return true;186}187188void TokenLexer::stringifyVAOPTContents(189SmallVectorImpl<Token> &ResultToks, const VAOptExpansionContext &VCtx,190const SourceLocation VAOPTClosingParenLoc) {191const int NumToksPriorToVAOpt = VCtx.getNumberOfTokensPriorToVAOpt();192const unsigned int NumVAOptTokens = ResultToks.size() - NumToksPriorToVAOpt;193Token *const VAOPTTokens =194NumVAOptTokens ? &ResultToks[NumToksPriorToVAOpt] : nullptr;195196SmallVector<Token, 64> ConcatenatedVAOPTResultToks;197// FIXME: Should we keep track within VCtx that we did or didnot198// encounter pasting - and only then perform this loop.199200// Perform token pasting (concatenation) prior to stringization.201for (unsigned int CurTokenIdx = 0; CurTokenIdx != NumVAOptTokens;202++CurTokenIdx) {203if (VAOPTTokens[CurTokenIdx].is(tok::hashhash)) {204assert(CurTokenIdx != 0 &&205"Can not have __VAOPT__ contents begin with a ##");206Token &LHS = VAOPTTokens[CurTokenIdx - 1];207pasteTokens(LHS, llvm::ArrayRef(VAOPTTokens, NumVAOptTokens),208CurTokenIdx);209// Replace the token prior to the first ## in this iteration.210ConcatenatedVAOPTResultToks.back() = LHS;211if (CurTokenIdx == NumVAOptTokens)212break;213}214ConcatenatedVAOPTResultToks.push_back(VAOPTTokens[CurTokenIdx]);215}216217ConcatenatedVAOPTResultToks.push_back(VCtx.getEOFTok());218// Get the SourceLocation that represents the start location within219// the macro definition that marks where this string is substituted220// into: i.e. the __VA_OPT__ and the ')' within the spelling of the221// macro definition, and use it to indicate that the stringified token222// was generated from that location.223const SourceLocation ExpansionLocStartWithinMacro =224getExpansionLocForMacroDefLoc(VCtx.getVAOptLoc());225const SourceLocation ExpansionLocEndWithinMacro =226getExpansionLocForMacroDefLoc(VAOPTClosingParenLoc);227228Token StringifiedVAOPT = MacroArgs::StringifyArgument(229&ConcatenatedVAOPTResultToks[0], PP, VCtx.hasCharifyBefore() /*Charify*/,230ExpansionLocStartWithinMacro, ExpansionLocEndWithinMacro);231232if (VCtx.getLeadingSpaceForStringifiedToken())233StringifiedVAOPT.setFlag(Token::LeadingSpace);234235StringifiedVAOPT.setFlag(Token::StringifiedInMacro);236// Resize (shrink) the token stream to just capture this stringified token.237ResultToks.resize(NumToksPriorToVAOpt + 1);238ResultToks.back() = StringifiedVAOPT;239}240241/// Expand the arguments of a function-like macro so that we can quickly242/// return preexpanded tokens from Tokens.243void TokenLexer::ExpandFunctionArguments() {244SmallVector<Token, 128> ResultToks;245246// Loop through 'Tokens', expanding them into ResultToks. Keep247// track of whether we change anything. If not, no need to keep them. If so,248// we install the newly expanded sequence as the new 'Tokens' list.249bool MadeChange = false;250251std::optional<bool> CalledWithVariadicArguments;252253VAOptExpansionContext VCtx(PP);254255for (unsigned I = 0, E = NumTokens; I != E; ++I) {256const Token &CurTok = Tokens[I];257// We don't want a space for the next token after a paste258// operator. In valid code, the token will get smooshed onto the259// preceding one anyway. In assembler-with-cpp mode, invalid260// pastes are allowed through: in this case, we do not want the261// extra whitespace to be added. For example, we want ". ## foo"262// -> ".foo" not ". foo".263if (I != 0 && !Tokens[I-1].is(tok::hashhash) && CurTok.hasLeadingSpace())264NextTokGetsSpace = true;265266if (VCtx.isVAOptToken(CurTok)) {267MadeChange = true;268assert(Tokens[I + 1].is(tok::l_paren) &&269"__VA_OPT__ must be followed by '('");270271++I; // Skip the l_paren272VCtx.sawVAOptFollowedByOpeningParens(CurTok.getLocation(),273ResultToks.size());274275continue;276}277278// We have entered into the __VA_OPT__ context, so handle tokens279// appropriately.280if (VCtx.isInVAOpt()) {281// If we are about to process a token that is either an argument to282// __VA_OPT__ or its closing rparen, then:283// 1) If the token is the closing rparen that exits us out of __VA_OPT__,284// perform any necessary stringification or placemarker processing,285// and/or skip to the next token.286// 2) else if macro was invoked without variadic arguments skip this287// token.288// 3) else (macro was invoked with variadic arguments) process the token289// normally.290291if (Tokens[I].is(tok::l_paren))292VCtx.sawOpeningParen(Tokens[I].getLocation());293// Continue skipping tokens within __VA_OPT__ if the macro was not294// called with variadic arguments, else let the rest of the loop handle295// this token. Note sawClosingParen() returns true only if the r_paren matches296// the closing r_paren of the __VA_OPT__.297if (!Tokens[I].is(tok::r_paren) || !VCtx.sawClosingParen()) {298// Lazily expand __VA_ARGS__ when we see the first __VA_OPT__.299if (!CalledWithVariadicArguments) {300CalledWithVariadicArguments =301ActualArgs->invokedWithVariadicArgument(Macro, PP);302}303if (!*CalledWithVariadicArguments) {304// Skip this token.305continue;306}307// ... else the macro was called with variadic arguments, and we do not308// have a closing rparen - so process this token normally.309} else {310// Current token is the closing r_paren which marks the end of the311// __VA_OPT__ invocation, so handle any place-marker pasting (if312// empty) by removing hashhash either before (if exists) or after. And313// also stringify the entire contents if VAOPT was preceded by a hash,314// but do so only after any token concatenation that needs to occur315// within the contents of VAOPT.316317if (VCtx.hasStringifyOrCharifyBefore()) {318// Replace all the tokens just added from within VAOPT into a single319// stringified token. This requires token-pasting to eagerly occur320// within these tokens. If either the contents of VAOPT were empty321// or the macro wasn't called with any variadic arguments, the result322// is a token that represents an empty string.323stringifyVAOPTContents(ResultToks, VCtx,324/*ClosingParenLoc*/ Tokens[I].getLocation());325326} else if (/*No tokens within VAOPT*/327ResultToks.size() == VCtx.getNumberOfTokensPriorToVAOpt()) {328// Treat VAOPT as a placemarker token. Eat either the '##' before the329// RHS/VAOPT (if one exists, suggesting that the LHS (if any) to that330// hashhash was not a placemarker) or the '##'331// after VAOPT, but not both.332333if (ResultToks.size() && ResultToks.back().is(tok::hashhash)) {334ResultToks.pop_back();335} else if ((I + 1 != E) && Tokens[I + 1].is(tok::hashhash)) {336++I; // Skip the following hashhash.337}338} else {339// If there's a ## before the __VA_OPT__, we might have discovered340// that the __VA_OPT__ begins with a placeholder. We delay action on341// that to now to avoid messing up our stashed count of tokens before342// __VA_OPT__.343if (VCtx.beginsWithPlaceholder()) {344assert(VCtx.getNumberOfTokensPriorToVAOpt() > 0 &&345ResultToks.size() >= VCtx.getNumberOfTokensPriorToVAOpt() &&346ResultToks[VCtx.getNumberOfTokensPriorToVAOpt() - 1].is(347tok::hashhash) &&348"no token paste before __VA_OPT__");349ResultToks.erase(ResultToks.begin() +350VCtx.getNumberOfTokensPriorToVAOpt() - 1);351}352// If the expansion of __VA_OPT__ ends with a placeholder, eat any353// following '##' token.354if (VCtx.endsWithPlaceholder() && I + 1 != E &&355Tokens[I + 1].is(tok::hashhash)) {356++I;357}358}359VCtx.reset();360// We processed __VA_OPT__'s closing paren (and the exit out of361// __VA_OPT__), so skip to the next token.362continue;363}364}365366// If we found the stringify operator, get the argument stringified. The367// preprocessor already verified that the following token is a macro368// parameter or __VA_OPT__ when the #define was lexed.369370if (CurTok.isOneOf(tok::hash, tok::hashat)) {371int ArgNo = Macro->getParameterNum(Tokens[I+1].getIdentifierInfo());372assert((ArgNo != -1 || VCtx.isVAOptToken(Tokens[I + 1])) &&373"Token following # is not an argument or __VA_OPT__!");374375if (ArgNo == -1) {376// Handle the __VA_OPT__ case.377VCtx.sawHashOrHashAtBefore(NextTokGetsSpace,378CurTok.is(tok::hashat));379continue;380}381// Else handle the simple argument case.382SourceLocation ExpansionLocStart =383getExpansionLocForMacroDefLoc(CurTok.getLocation());384SourceLocation ExpansionLocEnd =385getExpansionLocForMacroDefLoc(Tokens[I+1].getLocation());386387bool Charify = CurTok.is(tok::hashat);388const Token *UnexpArg = ActualArgs->getUnexpArgument(ArgNo);389Token Res = MacroArgs::StringifyArgument(390UnexpArg, PP, Charify, ExpansionLocStart, ExpansionLocEnd);391Res.setFlag(Token::StringifiedInMacro);392393// The stringified/charified string leading space flag gets set to match394// the #/#@ operator.395if (NextTokGetsSpace)396Res.setFlag(Token::LeadingSpace);397398ResultToks.push_back(Res);399MadeChange = true;400++I; // Skip arg name.401NextTokGetsSpace = false;402continue;403}404405// Find out if there is a paste (##) operator before or after the token.406bool NonEmptyPasteBefore =407!ResultToks.empty() && ResultToks.back().is(tok::hashhash);408bool PasteBefore = I != 0 && Tokens[I-1].is(tok::hashhash);409bool PasteAfter = I+1 != E && Tokens[I+1].is(tok::hashhash);410bool RParenAfter = I+1 != E && Tokens[I+1].is(tok::r_paren);411412assert((!NonEmptyPasteBefore || PasteBefore || VCtx.isInVAOpt()) &&413"unexpected ## in ResultToks");414415// Otherwise, if this is not an argument token, just add the token to the416// output buffer.417IdentifierInfo *II = CurTok.getIdentifierInfo();418int ArgNo = II ? Macro->getParameterNum(II) : -1;419if (ArgNo == -1) {420// This isn't an argument, just add it.421ResultToks.push_back(CurTok);422423if (NextTokGetsSpace) {424ResultToks.back().setFlag(Token::LeadingSpace);425NextTokGetsSpace = false;426} else if (PasteBefore && !NonEmptyPasteBefore)427ResultToks.back().clearFlag(Token::LeadingSpace);428429continue;430}431432// An argument is expanded somehow, the result is different than the433// input.434MadeChange = true;435436// Otherwise, this is a use of the argument.437438// In Microsoft mode, remove the comma before __VA_ARGS__ to ensure there439// are no trailing commas if __VA_ARGS__ is empty.440if (!PasteBefore && ActualArgs->isVarargsElidedUse() &&441MaybeRemoveCommaBeforeVaArgs(ResultToks,442/*HasPasteOperator=*/false,443Macro, ArgNo, PP))444continue;445446// If it is not the LHS/RHS of a ## operator, we must pre-expand the447// argument and substitute the expanded tokens into the result. This is448// C99 6.10.3.1p1.449if (!PasteBefore && !PasteAfter) {450const Token *ResultArgToks;451452// Only preexpand the argument if it could possibly need it. This453// avoids some work in common cases.454const Token *ArgTok = ActualArgs->getUnexpArgument(ArgNo);455if (ActualArgs->ArgNeedsPreexpansion(ArgTok, PP))456ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0];457else458ResultArgToks = ArgTok; // Use non-preexpanded tokens.459460// If the arg token expanded into anything, append it.461if (ResultArgToks->isNot(tok::eof)) {462size_t FirstResult = ResultToks.size();463unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);464ResultToks.append(ResultArgToks, ResultArgToks+NumToks);465466// In Microsoft-compatibility mode, we follow MSVC's preprocessing467// behavior by not considering single commas from nested macro468// expansions as argument separators. Set a flag on the token so we can469// test for this later when the macro expansion is processed.470if (PP.getLangOpts().MSVCCompat && NumToks == 1 &&471ResultToks.back().is(tok::comma))472ResultToks.back().setFlag(Token::IgnoredComma);473474// If the '##' came from expanding an argument, turn it into 'unknown'475// to avoid pasting.476for (Token &Tok : llvm::drop_begin(ResultToks, FirstResult))477if (Tok.is(tok::hashhash))478Tok.setKind(tok::unknown);479480if(ExpandLocStart.isValid()) {481updateLocForMacroArgTokens(CurTok.getLocation(),482ResultToks.begin()+FirstResult,483ResultToks.end());484}485486// If any tokens were substituted from the argument, the whitespace487// before the first token should match the whitespace of the arg488// identifier.489ResultToks[FirstResult].setFlagValue(Token::LeadingSpace,490NextTokGetsSpace);491ResultToks[FirstResult].setFlagValue(Token::StartOfLine, false);492NextTokGetsSpace = 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 a496// __VA_OPT__.497if (NonEmptyPasteBefore) {498// We're imagining a placeholder token is inserted here. If this is499// the first token in a __VA_OPT__ after a ##, delete the ##.500assert(VCtx.isInVAOpt() && "should only happen inside a __VA_OPT__");501VCtx.hasPlaceholderAfterHashhashAtStart();502} else if (RParenAfter)503VCtx.hasPlaceholderBeforeRParen();504}505continue;506}507508// Okay, we have a token that is either the LHS or RHS of a paste (##)509// argument. It gets substituted as its non-pre-expanded tokens.510const Token *ArgToks = ActualArgs->getUnexpArgument(ArgNo);511unsigned NumToks = MacroArgs::getArgLength(ArgToks);512if (NumToks) { // Not an empty argument?513bool VaArgsPseudoPaste = false;514// If this is the GNU ", ## __VA_ARGS__" extension, and we just learned515// that __VA_ARGS__ expands to multiple tokens, avoid a pasting error when516// the expander tries to paste ',' with the first token of the __VA_ARGS__517// expansion.518if (NonEmptyPasteBefore && ResultToks.size() >= 2 &&519ResultToks[ResultToks.size()-2].is(tok::comma) &&520(unsigned)ArgNo == Macro->getNumParams()-1 &&521Macro->isVariadic()) {522VaArgsPseudoPaste = true;523// Remove the paste operator, report use of the extension.524PP.Diag(ResultToks.pop_back_val().getLocation(), diag::ext_paste_comma);525}526527ResultToks.append(ArgToks, ArgToks+NumToks);528529// If the '##' came from expanding an argument, turn it into 'unknown'530// to avoid pasting.531for (Token &Tok : llvm::make_range(ResultToks.end() - NumToks,532ResultToks.end())) {533if (Tok.is(tok::hashhash))534Tok.setKind(tok::unknown);535}536537if (ExpandLocStart.isValid()) {538updateLocForMacroArgTokens(CurTok.getLocation(),539ResultToks.end()-NumToks, ResultToks.end());540}541542// Transfer the leading whitespace information from the token543// (the macro argument) onto the first token of the544// expansion. Note that we don't do this for the GNU545// pseudo-paste extension ", ## __VA_ARGS__".546if (!VaArgsPseudoPaste) {547ResultToks[ResultToks.size() - NumToks].setFlagValue(Token::StartOfLine,548false);549ResultToks[ResultToks.size() - NumToks].setFlagValue(550Token::LeadingSpace, NextTokGetsSpace);551}552553NextTokGetsSpace = false;554continue;555}556557// If an empty argument is on the LHS or RHS of a paste, the standard (C99558// 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur. We559// implement this by eating ## operators when a LHS or RHS expands to560// empty.561if (PasteAfter) {562// Discard the argument token and skip (don't copy to the expansion563// buffer) the paste operator after it.564++I;565continue;566}567568if (RParenAfter && !NonEmptyPasteBefore)569VCtx.hasPlaceholderBeforeRParen();570571// If this is on the RHS of a paste operator, we've already copied the572// paste operator to the ResultToks list, unless the LHS was empty too.573// Remove it.574assert(PasteBefore);575if (NonEmptyPasteBefore) {576assert(ResultToks.back().is(tok::hashhash));577// Do not remove the paste operator if it is the one before __VA_OPT__578// (and we are still processing tokens within VA_OPT). We handle the case579// of removing the paste operator if __VA_OPT__ reduces to the notional580// placemarker above when we encounter the closing paren of VA_OPT.581if (!VCtx.isInVAOpt() ||582ResultToks.size() > VCtx.getNumberOfTokensPriorToVAOpt())583ResultToks.pop_back();584else585VCtx.hasPlaceholderAfterHashhashAtStart();586}587588// If this is the __VA_ARGS__ token, and if the argument wasn't provided,589// and if the macro had at least one real argument, and if the token before590// the ## was a comma, remove the comma. This is a GCC extension which is591// disabled when using -std=c99.592if (ActualArgs->isVarargsElidedUse())593MaybeRemoveCommaBeforeVaArgs(ResultToks,594/*HasPasteOperator=*/true,595Macro, ArgNo, PP);596}597598// If anything changed, install this as the new Tokens list.599if (MadeChange) {600assert(!OwnsTokens && "This would leak if we already own the token list");601// This is deleted in the dtor.602NumTokens = ResultToks.size();603// The tokens will be added to Preprocessor's cache and will be removed604// when this TokenLexer finishes lexing them.605Tokens = PP.cacheMacroExpandedTokens(this, ResultToks);606607// The preprocessor cache of macro expanded tokens owns these tokens,not us.608OwnsTokens = false;609}610}611612/// Checks if two tokens form wide string literal.613static bool isWideStringLiteralFromMacro(const Token &FirstTok,614const Token &SecondTok) {615return FirstTok.is(tok::identifier) &&616FirstTok.getIdentifierInfo()->isStr("L") && SecondTok.isLiteral() &&617SecondTok.stringifiedInMacro();618}619620/// Lex - Lex and return a token from this macro stream.621bool TokenLexer::Lex(Token &Tok) {622// Lexing off the end of the macro, pop this macro off the expansion stack.623if (isAtEnd()) {624// If this is a macro (not a token stream), mark the macro enabled now625// that it is no longer being expanded.626if (Macro) Macro->EnableMacro();627628Tok.startToken();629Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);630Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace || NextTokGetsSpace);631if (CurTokenIdx == 0)632Tok.setFlag(Token::LeadingEmptyMacro);633return PP.HandleEndOfTokenLexer(Tok);634}635636SourceManager &SM = PP.getSourceManager();637638// If this is the first token of the expanded result, we inherit spacing639// properties later.640bool isFirstToken = CurTokenIdx == 0;641642// Get the next token to return.643Tok = Tokens[CurTokenIdx++];644if (IsReinject)645Tok.setFlag(Token::IsReinjected);646647bool TokenIsFromPaste = false;648649// If this token is followed by a token paste (##) operator, paste the tokens!650// Note that ## is a normal token when not expanding a macro.651if (!isAtEnd() && Macro &&652(Tokens[CurTokenIdx].is(tok::hashhash) ||653// Special processing of L#x macros in -fms-compatibility mode.654// Microsoft compiler is able to form a wide string literal from655// 'L#macro_arg' construct in a function-like macro.656(PP.getLangOpts().MSVCCompat &&657isWideStringLiteralFromMacro(Tok, Tokens[CurTokenIdx])))) {658// When handling the microsoft /##/ extension, the final token is659// returned by pasteTokens, not the pasted token.660if (pasteTokens(Tok))661return true;662663TokenIsFromPaste = true;664}665666// The token's current location indicate where the token was lexed from. We667// need this information to compute the spelling of the token, but any668// diagnostics for the expanded token should appear as if they came from669// ExpansionLoc. Pull this information together into a new SourceLocation670// that captures all of this.671if (ExpandLocStart.isValid() && // Don't do this for token streams.672// Check that the token's location was not already set properly.673SM.isBeforeInSLocAddrSpace(Tok.getLocation(), MacroStartSLocOffset)) {674SourceLocation instLoc;675if (Tok.is(tok::comment)) {676instLoc = SM.createExpansionLoc(Tok.getLocation(),677ExpandLocStart,678ExpandLocEnd,679Tok.getLength());680} else {681instLoc = getExpansionLocForMacroDefLoc(Tok.getLocation());682}683684Tok.setLocation(instLoc);685}686687// If this is the first token, set the lexical properties of the token to688// match the lexical properties of the macro identifier.689if (isFirstToken) {690Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);691Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);692} else {693// If this is not the first token, we may still need to pass through694// leading whitespace if we've expanded a macro.695if (AtStartOfLine) Tok.setFlag(Token::StartOfLine);696if (HasLeadingSpace) Tok.setFlag(Token::LeadingSpace);697}698AtStartOfLine = false;699HasLeadingSpace = false;700701// Handle recursive expansion!702if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {703// Change the kind of this identifier to the appropriate token kind, e.g.704// turning "for" into a keyword.705IdentifierInfo *II = Tok.getIdentifierInfo();706Tok.setKind(II->getTokenID());707708// If this identifier was poisoned and from a paste, emit an error. This709// won't be handled by Preprocessor::HandleIdentifier because this is coming710// from a macro expansion.711if (II->isPoisoned() && TokenIsFromPaste) {712PP.HandlePoisonedIdentifier(Tok);713}714715if (!DisableMacroExpansion && II->isHandleIdentifierCase())716return PP.HandleIdentifier(Tok);717}718719// Otherwise, return a normal token.720return true;721}722723bool TokenLexer::pasteTokens(Token &Tok) {724return pasteTokens(Tok, llvm::ArrayRef(Tokens, NumTokens), CurTokenIdx);725}726727/// LHSTok is the LHS of a ## operator, and CurTokenIdx is the ##728/// operator. Read the ## and RHS, and paste the LHS/RHS together. If there729/// are more ## after it, chomp them iteratively. Return the result as LHSTok.730/// If this returns true, the caller should immediately return the token.731bool TokenLexer::pasteTokens(Token &LHSTok, ArrayRef<Token> TokenStream,732unsigned int &CurIdx) {733assert(CurIdx > 0 && "## can not be the first token within tokens");734assert((TokenStream[CurIdx].is(tok::hashhash) ||735(PP.getLangOpts().MSVCCompat &&736isWideStringLiteralFromMacro(LHSTok, TokenStream[CurIdx]))) &&737"Token at this Index must be ## or part of the MSVC 'L "738"#macro-arg' pasting pair");739740// MSVC: If previous token was pasted, this must be a recovery from an invalid741// paste operation. Ignore spaces before this token to mimic MSVC output.742// Required for generating valid UUID strings in some MS headers.743if (PP.getLangOpts().MicrosoftExt && (CurIdx >= 2) &&744TokenStream[CurIdx - 2].is(tok::hashhash))745LHSTok.clearFlag(Token::LeadingSpace);746747SmallString<128> Buffer;748const char *ResultTokStrPtr = nullptr;749SourceLocation StartLoc = LHSTok.getLocation();750SourceLocation PasteOpLoc;751752auto IsAtEnd = [&TokenStream, &CurIdx] {753return TokenStream.size() == CurIdx;754};755756do {757// Consume the ## operator if any.758PasteOpLoc = TokenStream[CurIdx].getLocation();759if (TokenStream[CurIdx].is(tok::hashhash))760++CurIdx;761assert(!IsAtEnd() && "No token on the RHS of a paste operator!");762763// Get the RHS token.764const Token &RHS = TokenStream[CurIdx];765766// Allocate space for the result token. This is guaranteed to be enough for767// the two tokens.768Buffer.resize(LHSTok.getLength() + RHS.getLength());769770// Get the spelling of the LHS token in Buffer.771const char *BufPtr = &Buffer[0];772bool Invalid = false;773unsigned LHSLen = PP.getSpelling(LHSTok, BufPtr, &Invalid);774if (BufPtr != &Buffer[0]) // Really, we want the chars in Buffer!775memcpy(&Buffer[0], BufPtr, LHSLen);776if (Invalid)777return true;778779BufPtr = Buffer.data() + LHSLen;780unsigned RHSLen = PP.getSpelling(RHS, BufPtr, &Invalid);781if (Invalid)782return true;783if (RHSLen && BufPtr != &Buffer[LHSLen])784// Really, we want the chars in Buffer!785memcpy(&Buffer[LHSLen], BufPtr, RHSLen);786787// Trim excess space.788Buffer.resize(LHSLen+RHSLen);789790// Plop the pasted result (including the trailing newline and null) into a791// scratch buffer where we can lex it.792Token ResultTokTmp;793ResultTokTmp.startToken();794795// Claim that the tmp token is a string_literal so that we can get the796// character pointer back from CreateString in getLiteralData().797ResultTokTmp.setKind(tok::string_literal);798PP.CreateString(Buffer, ResultTokTmp);799SourceLocation ResultTokLoc = ResultTokTmp.getLocation();800ResultTokStrPtr = ResultTokTmp.getLiteralData();801802// Lex the resultant pasted token into Result.803Token Result;804805if (LHSTok.isAnyIdentifier() && RHS.isAnyIdentifier()) {806// Common paste case: identifier+identifier = identifier. Avoid creating807// a lexer and other overhead.808PP.IncrementPasteCounter(true);809Result.startToken();810Result.setKind(tok::raw_identifier);811Result.setRawIdentifierData(ResultTokStrPtr);812Result.setLocation(ResultTokLoc);813Result.setLength(LHSLen+RHSLen);814} else {815PP.IncrementPasteCounter(false);816817assert(ResultTokLoc.isFileID() &&818"Should be a raw location into scratch buffer");819SourceManager &SourceMgr = PP.getSourceManager();820FileID LocFileID = SourceMgr.getFileID(ResultTokLoc);821822bool Invalid = false;823const char *ScratchBufStart824= SourceMgr.getBufferData(LocFileID, &Invalid).data();825if (Invalid)826return false;827828// Make a lexer to lex this string from. Lex just this one token.829// Make a lexer object so that we lex and expand the paste result.830Lexer TL(SourceMgr.getLocForStartOfFile(LocFileID),831PP.getLangOpts(), ScratchBufStart,832ResultTokStrPtr, ResultTokStrPtr+LHSLen+RHSLen);833834// Lex a token in raw mode. This way it won't look up identifiers835// automatically, lexing off the end will return an eof token, and836// warnings are disabled. This returns true if the result token is the837// entire buffer.838bool isInvalid = !TL.LexFromRawLexer(Result);839840// If we got an EOF token, we didn't form even ONE token. For example, we841// did "/ ## /" to get "//".842isInvalid |= Result.is(tok::eof);843844// If pasting the two tokens didn't form a full new token, this is an845// error. This occurs with "x ## +" and other stuff. Return with LHSTok846// unmodified and with RHS as the next token to lex.847if (isInvalid) {848// Explicitly convert the token location to have proper expansion849// information so that the user knows where it came from.850SourceManager &SM = PP.getSourceManager();851SourceLocation Loc =852SM.createExpansionLoc(PasteOpLoc, ExpandLocStart, ExpandLocEnd, 2);853854// Test for the Microsoft extension of /##/ turning into // here on the855// error path.856if (PP.getLangOpts().MicrosoftExt && LHSTok.is(tok::slash) &&857RHS.is(tok::slash)) {858HandleMicrosoftCommentPaste(LHSTok, Loc);859return true;860}861862// Do not emit the error when preprocessing assembler code.863if (!PP.getLangOpts().AsmPreprocessor) {864// If we're in microsoft extensions mode, downgrade this from a hard865// error to an extension that defaults to an error. This allows866// disabling it.867PP.Diag(Loc, PP.getLangOpts().MicrosoftExt ? diag::ext_pp_bad_paste_ms868: diag::err_pp_bad_paste)869<< Buffer;870}871872// An error has occurred so exit loop.873break;874}875876// Turn ## into 'unknown' to avoid # ## # from looking like a paste877// operator.878if (Result.is(tok::hashhash))879Result.setKind(tok::unknown);880}881882// Transfer properties of the LHS over the Result.883Result.setFlagValue(Token::StartOfLine , LHSTok.isAtStartOfLine());884Result.setFlagValue(Token::LeadingSpace, LHSTok.hasLeadingSpace());885886// Finally, replace LHS with the result, consume the RHS, and iterate.887++CurIdx;888LHSTok = Result;889} while (!IsAtEnd() && TokenStream[CurIdx].is(tok::hashhash));890891SourceLocation EndLoc = TokenStream[CurIdx - 1].getLocation();892893// The token's current location indicate where the token was lexed from. We894// need this information to compute the spelling of the token, but any895// diagnostics for the expanded token should appear as if the token was896// expanded from the full ## expression. Pull this information together into897// a new SourceLocation that captures all of this.898SourceManager &SM = PP.getSourceManager();899if (StartLoc.isFileID())900StartLoc = getExpansionLocForMacroDefLoc(StartLoc);901if (EndLoc.isFileID())902EndLoc = getExpansionLocForMacroDefLoc(EndLoc);903FileID MacroFID = SM.getFileID(MacroExpansionStart);904while (SM.getFileID(StartLoc) != MacroFID)905StartLoc = SM.getImmediateExpansionRange(StartLoc).getBegin();906while (SM.getFileID(EndLoc) != MacroFID)907EndLoc = SM.getImmediateExpansionRange(EndLoc).getEnd();908909LHSTok.setLocation(SM.createExpansionLoc(LHSTok.getLocation(), StartLoc, EndLoc,910LHSTok.getLength()));911912// Now that we got the result token, it will be subject to expansion. Since913// token pasting re-lexes the result token in raw mode, identifier information914// isn't looked up. As such, if the result is an identifier, look up id info.915if (LHSTok.is(tok::raw_identifier)) {916// Look up the identifier info for the token. We disabled identifier lookup917// by saying we're skipping contents, so we need to do this manually.918PP.LookUpIdentifierInfo(LHSTok);919}920return false;921}922923/// isNextTokenLParen - If the next token lexed will pop this macro off the924/// expansion stack, return 2. If the next unexpanded token is a '(', return925/// 1, otherwise return 0.926unsigned TokenLexer::isNextTokenLParen() const {927// Out of tokens?928if (isAtEnd())929return 2;930return Tokens[CurTokenIdx].is(tok::l_paren);931}932933/// isParsingPreprocessorDirective - Return true if we are in the middle of a934/// preprocessor directive.935bool TokenLexer::isParsingPreprocessorDirective() const {936return Tokens[NumTokens-1].is(tok::eod) && !isAtEnd();937}938939/// HandleMicrosoftCommentPaste - In microsoft compatibility mode, /##/ pastes940/// together to form a comment that comments out everything in the current941/// macro, other active macros, and anything left on the current physical942/// source line of the expanded buffer. Handle this by returning the943/// first token on the next line.944void TokenLexer::HandleMicrosoftCommentPaste(Token &Tok, SourceLocation OpLoc) {945PP.Diag(OpLoc, diag::ext_comment_paste_microsoft);946947// We 'comment out' the rest of this macro by just ignoring the rest of the948// tokens that have not been lexed yet, if any.949950// Since this must be a macro, mark the macro enabled now that it is no longer951// being expanded.952assert(Macro && "Token streams can't paste comments");953Macro->EnableMacro();954955PP.HandleMicrosoftCommentPaste(Tok);956}957958/// If \arg loc is a file ID and points inside the current macro959/// definition, returns the appropriate source location pointing at the960/// macro expansion source location entry, otherwise it returns an invalid961/// SourceLocation.962SourceLocation963TokenLexer::getExpansionLocForMacroDefLoc(SourceLocation loc) const {964assert(ExpandLocStart.isValid() && MacroExpansionStart.isValid() &&965"Not appropriate for token streams");966assert(loc.isValid() && loc.isFileID());967968SourceManager &SM = PP.getSourceManager();969assert(SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength) &&970"Expected loc to come from the macro definition");971972SourceLocation::UIntTy relativeOffset = 0;973SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength, &relativeOffset);974return MacroExpansionStart.getLocWithOffset(relativeOffset);975}976977/// Finds the tokens that are consecutive (from the same FileID)978/// creates a single SLocEntry, and assigns SourceLocations to each token that979/// point to that SLocEntry. e.g for980/// assert(foo == bar);981/// There will be a single SLocEntry for the "foo == bar" chunk and locations982/// for the 'foo', '==', 'bar' tokens will point inside that chunk.983///984/// \arg begin_tokens will be updated to a position past all the found985/// consecutive tokens.986static void updateConsecutiveMacroArgTokens(SourceManager &SM,987SourceLocation ExpandLoc,988Token *&begin_tokens,989Token * end_tokens) {990assert(begin_tokens + 1 < end_tokens);991SourceLocation BeginLoc = begin_tokens->getLocation();992llvm::MutableArrayRef<Token> All(begin_tokens, end_tokens);993llvm::MutableArrayRef<Token> Partition;994995auto NearLast = [&, Last = BeginLoc](SourceLocation Loc) mutable {996// The maximum distance between two consecutive tokens in a partition.997// This is an important trick to avoid using too much SourceLocation address998// space!999static constexpr SourceLocation::IntTy MaxDistance = 50;1000auto Distance = Loc.getRawEncoding() - Last.getRawEncoding();1001Last = Loc;1002return Distance <= MaxDistance;1003};10041005// Partition the tokens by their FileID.1006// This is a hot function, and calling getFileID can be expensive, the1007// implementation is optimized by reducing the number of getFileID.1008if (BeginLoc.isFileID()) {1009// Consecutive tokens not written in macros must be from the same file.1010// (Neither #include nor eof can occur inside a macro argument.)1011Partition = All.take_while([&](const Token &T) {1012return T.getLocation().isFileID() && NearLast(T.getLocation());1013});1014} else {1015// Call getFileID once to calculate the bounds, and use the cheaper1016// sourcelocation-against-bounds comparison.1017FileID BeginFID = SM.getFileID(BeginLoc);1018SourceLocation Limit =1019SM.getComposedLoc(BeginFID, SM.getFileIDSize(BeginFID));1020Partition = All.take_while([&](const Token &T) {1021// NOTE: the Limit is included! The lexer recovery only ever inserts a1022// single token past the end of the FileID, specifically the ) when a1023// macro-arg containing a comma should be guarded by parentheses.1024//1025// It is safe to include the Limit here because SourceManager allocates1026// FileSize + 1 for each SLocEntry.1027//1028// See https://github.com/llvm/llvm-project/issues/60722.1029return T.getLocation() >= BeginLoc && T.getLocation() <= Limit1030&& NearLast(T.getLocation());1031});1032}1033assert(!Partition.empty());10341035// For the consecutive tokens, find the length of the SLocEntry to contain1036// all of them.1037SourceLocation::UIntTy FullLength =1038Partition.back().getEndLoc().getRawEncoding() -1039Partition.front().getLocation().getRawEncoding();1040// Create a macro expansion SLocEntry that will "contain" all of the tokens.1041SourceLocation Expansion =1042SM.createMacroArgExpansionLoc(BeginLoc, ExpandLoc, FullLength);10431044#ifdef EXPENSIVE_CHECKS1045assert(llvm::all_of(Partition.drop_front(),1046[&SM, ID = SM.getFileID(Partition.front().getLocation())](1047const Token &T) {1048return ID == SM.getFileID(T.getLocation());1049}) &&1050"Must have the same FIleID!");1051#endif1052// Change the location of the tokens from the spelling location to the new1053// expanded location.1054for (Token& T : Partition) {1055SourceLocation::IntTy RelativeOffset =1056T.getLocation().getRawEncoding() - BeginLoc.getRawEncoding();1057T.setLocation(Expansion.getLocWithOffset(RelativeOffset));1058}1059begin_tokens = &Partition.back() + 1;1060}10611062/// Creates SLocEntries and updates the locations of macro argument1063/// tokens to their new expanded locations.1064///1065/// \param ArgIdSpellLoc the location of the macro argument id inside the macro1066/// definition.1067void TokenLexer::updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc,1068Token *begin_tokens,1069Token *end_tokens) {1070SourceManager &SM = PP.getSourceManager();10711072SourceLocation ExpandLoc =1073getExpansionLocForMacroDefLoc(ArgIdSpellLoc);10741075while (begin_tokens < end_tokens) {1076// If there's only one token just create a SLocEntry for it.1077if (end_tokens - begin_tokens == 1) {1078Token &Tok = *begin_tokens;1079Tok.setLocation(SM.createMacroArgExpansionLoc(Tok.getLocation(),1080ExpandLoc,1081Tok.getLength()));1082return;1083}10841085updateConsecutiveMacroArgTokens(SM, ExpandLoc, begin_tokens, end_tokens);1086}1087}10881089void TokenLexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {1090AtStartOfLine = Result.isAtStartOfLine();1091HasLeadingSpace = Result.hasLeadingSpace();1092}109310941095