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