xref: /aosp_15_r20/external/clang/lib/Lex/TokenLexer.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- TokenLexer.cpp - Lex from a token stream -------------------------===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This file implements the TokenLexer interface.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li 
14*67e74705SXin Li #include "clang/Lex/TokenLexer.h"
15*67e74705SXin Li #include "clang/Basic/SourceManager.h"
16*67e74705SXin Li #include "clang/Lex/LexDiagnostic.h"
17*67e74705SXin Li #include "clang/Lex/MacroArgs.h"
18*67e74705SXin Li #include "clang/Lex/MacroInfo.h"
19*67e74705SXin Li #include "clang/Lex/Preprocessor.h"
20*67e74705SXin Li #include "llvm/ADT/SmallString.h"
21*67e74705SXin Li 
22*67e74705SXin Li using namespace clang;
23*67e74705SXin Li 
24*67e74705SXin Li /// Create a TokenLexer for the specified macro with the specified actual
25*67e74705SXin Li /// arguments.  Note that this ctor takes ownership of the ActualArgs pointer.
Init(Token & Tok,SourceLocation ELEnd,MacroInfo * MI,MacroArgs * Actuals)26*67e74705SXin Li void TokenLexer::Init(Token &Tok, SourceLocation ELEnd, MacroInfo *MI,
27*67e74705SXin Li                       MacroArgs *Actuals) {
28*67e74705SXin Li   // If the client is reusing a TokenLexer, make sure to free any memory
29*67e74705SXin Li   // associated with it.
30*67e74705SXin Li   destroy();
31*67e74705SXin Li 
32*67e74705SXin Li   Macro = MI;
33*67e74705SXin Li   ActualArgs = Actuals;
34*67e74705SXin Li   CurToken = 0;
35*67e74705SXin Li 
36*67e74705SXin Li   ExpandLocStart = Tok.getLocation();
37*67e74705SXin Li   ExpandLocEnd = ELEnd;
38*67e74705SXin Li   AtStartOfLine = Tok.isAtStartOfLine();
39*67e74705SXin Li   HasLeadingSpace = Tok.hasLeadingSpace();
40*67e74705SXin Li   NextTokGetsSpace = false;
41*67e74705SXin Li   Tokens = &*Macro->tokens_begin();
42*67e74705SXin Li   OwnsTokens = false;
43*67e74705SXin Li   DisableMacroExpansion = false;
44*67e74705SXin Li   NumTokens = Macro->tokens_end()-Macro->tokens_begin();
45*67e74705SXin Li   MacroExpansionStart = SourceLocation();
46*67e74705SXin Li 
47*67e74705SXin Li   SourceManager &SM = PP.getSourceManager();
48*67e74705SXin Li   MacroStartSLocOffset = SM.getNextLocalOffset();
49*67e74705SXin Li 
50*67e74705SXin Li   if (NumTokens > 0) {
51*67e74705SXin Li     assert(Tokens[0].getLocation().isValid());
52*67e74705SXin Li     assert((Tokens[0].getLocation().isFileID() || Tokens[0].is(tok::comment)) &&
53*67e74705SXin Li            "Macro defined in macro?");
54*67e74705SXin Li     assert(ExpandLocStart.isValid());
55*67e74705SXin Li 
56*67e74705SXin Li     // Reserve a source location entry chunk for the length of the macro
57*67e74705SXin Li     // definition. Tokens that get lexed directly from the definition will
58*67e74705SXin Li     // have their locations pointing inside this chunk. This is to avoid
59*67e74705SXin Li     // creating separate source location entries for each token.
60*67e74705SXin Li     MacroDefStart = SM.getExpansionLoc(Tokens[0].getLocation());
61*67e74705SXin Li     MacroDefLength = Macro->getDefinitionLength(SM);
62*67e74705SXin Li     MacroExpansionStart = SM.createExpansionLoc(MacroDefStart,
63*67e74705SXin Li                                                 ExpandLocStart,
64*67e74705SXin Li                                                 ExpandLocEnd,
65*67e74705SXin Li                                                 MacroDefLength);
66*67e74705SXin Li   }
67*67e74705SXin Li 
68*67e74705SXin Li   // If this is a function-like macro, expand the arguments and change
69*67e74705SXin Li   // Tokens to point to the expanded tokens.
70*67e74705SXin Li   if (Macro->isFunctionLike() && Macro->getNumArgs())
71*67e74705SXin Li     ExpandFunctionArguments();
72*67e74705SXin Li 
73*67e74705SXin Li   // Mark the macro as currently disabled, so that it is not recursively
74*67e74705SXin Li   // expanded.  The macro must be disabled only after argument pre-expansion of
75*67e74705SXin Li   // function-like macro arguments occurs.
76*67e74705SXin Li   Macro->DisableMacro();
77*67e74705SXin Li }
78*67e74705SXin Li 
79*67e74705SXin Li /// Create a TokenLexer for the specified token stream.  This does not
80*67e74705SXin Li /// take ownership of the specified token vector.
Init(const Token * TokArray,unsigned NumToks,bool disableMacroExpansion,bool ownsTokens)81*67e74705SXin Li void TokenLexer::Init(const Token *TokArray, unsigned NumToks,
82*67e74705SXin Li                       bool disableMacroExpansion, bool ownsTokens) {
83*67e74705SXin Li   // If the client is reusing a TokenLexer, make sure to free any memory
84*67e74705SXin Li   // associated with it.
85*67e74705SXin Li   destroy();
86*67e74705SXin Li 
87*67e74705SXin Li   Macro = nullptr;
88*67e74705SXin Li   ActualArgs = nullptr;
89*67e74705SXin Li   Tokens = TokArray;
90*67e74705SXin Li   OwnsTokens = ownsTokens;
91*67e74705SXin Li   DisableMacroExpansion = disableMacroExpansion;
92*67e74705SXin Li   NumTokens = NumToks;
93*67e74705SXin Li   CurToken = 0;
94*67e74705SXin Li   ExpandLocStart = ExpandLocEnd = SourceLocation();
95*67e74705SXin Li   AtStartOfLine = false;
96*67e74705SXin Li   HasLeadingSpace = false;
97*67e74705SXin Li   NextTokGetsSpace = false;
98*67e74705SXin Li   MacroExpansionStart = SourceLocation();
99*67e74705SXin Li 
100*67e74705SXin Li   // Set HasLeadingSpace/AtStartOfLine so that the first token will be
101*67e74705SXin Li   // returned unmodified.
102*67e74705SXin Li   if (NumToks != 0) {
103*67e74705SXin Li     AtStartOfLine   = TokArray[0].isAtStartOfLine();
104*67e74705SXin Li     HasLeadingSpace = TokArray[0].hasLeadingSpace();
105*67e74705SXin Li   }
106*67e74705SXin Li }
107*67e74705SXin Li 
destroy()108*67e74705SXin Li void TokenLexer::destroy() {
109*67e74705SXin Li   // If this was a function-like macro that actually uses its arguments, delete
110*67e74705SXin Li   // the expanded tokens.
111*67e74705SXin Li   if (OwnsTokens) {
112*67e74705SXin Li     delete [] Tokens;
113*67e74705SXin Li     Tokens = nullptr;
114*67e74705SXin Li     OwnsTokens = false;
115*67e74705SXin Li   }
116*67e74705SXin Li 
117*67e74705SXin Li   // TokenLexer owns its formal arguments.
118*67e74705SXin Li   if (ActualArgs) ActualArgs->destroy(PP);
119*67e74705SXin Li }
120*67e74705SXin Li 
MaybeRemoveCommaBeforeVaArgs(SmallVectorImpl<Token> & ResultToks,bool HasPasteOperator,MacroInfo * Macro,unsigned MacroArgNo,Preprocessor & PP)121*67e74705SXin Li bool TokenLexer::MaybeRemoveCommaBeforeVaArgs(
122*67e74705SXin Li     SmallVectorImpl<Token> &ResultToks, bool HasPasteOperator, MacroInfo *Macro,
123*67e74705SXin Li     unsigned MacroArgNo, Preprocessor &PP) {
124*67e74705SXin Li   // Is the macro argument __VA_ARGS__?
125*67e74705SXin Li   if (!Macro->isVariadic() || MacroArgNo != Macro->getNumArgs()-1)
126*67e74705SXin Li     return false;
127*67e74705SXin Li 
128*67e74705SXin Li   // In Microsoft-compatibility mode, a comma is removed in the expansion
129*67e74705SXin Li   // of " ... , __VA_ARGS__ " if __VA_ARGS__ is empty.  This extension is
130*67e74705SXin Li   // not supported by gcc.
131*67e74705SXin Li   if (!HasPasteOperator && !PP.getLangOpts().MSVCCompat)
132*67e74705SXin Li     return false;
133*67e74705SXin Li 
134*67e74705SXin Li   // GCC removes the comma in the expansion of " ... , ## __VA_ARGS__ " if
135*67e74705SXin Li   // __VA_ARGS__ is empty, but not in strict C99 mode where there are no
136*67e74705SXin Li   // named arguments, where it remains.  In all other modes, including C99
137*67e74705SXin Li   // with GNU extensions, it is removed regardless of named arguments.
138*67e74705SXin Li   // Microsoft also appears to support this extension, unofficially.
139*67e74705SXin Li   if (PP.getLangOpts().C99 && !PP.getLangOpts().GNUMode
140*67e74705SXin Li         && Macro->getNumArgs() < 2)
141*67e74705SXin Li     return false;
142*67e74705SXin Li 
143*67e74705SXin Li   // Is a comma available to be removed?
144*67e74705SXin Li   if (ResultToks.empty() || !ResultToks.back().is(tok::comma))
145*67e74705SXin Li     return false;
146*67e74705SXin Li 
147*67e74705SXin Li   // Issue an extension diagnostic for the paste operator.
148*67e74705SXin Li   if (HasPasteOperator)
149*67e74705SXin Li     PP.Diag(ResultToks.back().getLocation(), diag::ext_paste_comma);
150*67e74705SXin Li 
151*67e74705SXin Li   // Remove the comma.
152*67e74705SXin Li   ResultToks.pop_back();
153*67e74705SXin Li 
154*67e74705SXin Li   if (!ResultToks.empty()) {
155*67e74705SXin Li     // If the comma was right after another paste (e.g. "X##,##__VA_ARGS__"),
156*67e74705SXin Li     // then removal of the comma should produce a placemarker token (in C99
157*67e74705SXin Li     // terms) which we model by popping off the previous ##, giving us a plain
158*67e74705SXin Li     // "X" when __VA_ARGS__ is empty.
159*67e74705SXin Li     if (ResultToks.back().is(tok::hashhash))
160*67e74705SXin Li       ResultToks.pop_back();
161*67e74705SXin Li 
162*67e74705SXin Li     // Remember that this comma was elided.
163*67e74705SXin Li     ResultToks.back().setFlag(Token::CommaAfterElided);
164*67e74705SXin Li   }
165*67e74705SXin Li 
166*67e74705SXin Li   // Never add a space, even if the comma, ##, or arg had a space.
167*67e74705SXin Li   NextTokGetsSpace = false;
168*67e74705SXin Li   return true;
169*67e74705SXin Li }
170*67e74705SXin Li 
171*67e74705SXin Li /// Expand the arguments of a function-like macro so that we can quickly
172*67e74705SXin Li /// return preexpanded tokens from Tokens.
ExpandFunctionArguments()173*67e74705SXin Li void TokenLexer::ExpandFunctionArguments() {
174*67e74705SXin Li   SmallVector<Token, 128> ResultToks;
175*67e74705SXin Li 
176*67e74705SXin Li   // Loop through 'Tokens', expanding them into ResultToks.  Keep
177*67e74705SXin Li   // track of whether we change anything.  If not, no need to keep them.  If so,
178*67e74705SXin Li   // we install the newly expanded sequence as the new 'Tokens' list.
179*67e74705SXin Li   bool MadeChange = false;
180*67e74705SXin Li 
181*67e74705SXin Li   for (unsigned i = 0, e = NumTokens; i != e; ++i) {
182*67e74705SXin Li     // If we found the stringify operator, get the argument stringified.  The
183*67e74705SXin Li     // preprocessor already verified that the following token is a macro name
184*67e74705SXin Li     // when the #define was parsed.
185*67e74705SXin Li     const Token &CurTok = Tokens[i];
186*67e74705SXin Li     if (i != 0 && !Tokens[i-1].is(tok::hashhash) && CurTok.hasLeadingSpace())
187*67e74705SXin Li       NextTokGetsSpace = true;
188*67e74705SXin Li 
189*67e74705SXin Li     if (CurTok.isOneOf(tok::hash, tok::hashat)) {
190*67e74705SXin Li       int ArgNo = Macro->getArgumentNum(Tokens[i+1].getIdentifierInfo());
191*67e74705SXin Li       assert(ArgNo != -1 && "Token following # is not an argument?");
192*67e74705SXin Li 
193*67e74705SXin Li       SourceLocation ExpansionLocStart =
194*67e74705SXin Li           getExpansionLocForMacroDefLoc(CurTok.getLocation());
195*67e74705SXin Li       SourceLocation ExpansionLocEnd =
196*67e74705SXin Li           getExpansionLocForMacroDefLoc(Tokens[i+1].getLocation());
197*67e74705SXin Li 
198*67e74705SXin Li       Token Res;
199*67e74705SXin Li       if (CurTok.is(tok::hash))  // Stringify
200*67e74705SXin Li         Res = ActualArgs->getStringifiedArgument(ArgNo, PP,
201*67e74705SXin Li                                                  ExpansionLocStart,
202*67e74705SXin Li                                                  ExpansionLocEnd);
203*67e74705SXin Li       else {
204*67e74705SXin Li         // 'charify': don't bother caching these.
205*67e74705SXin Li         Res = MacroArgs::StringifyArgument(ActualArgs->getUnexpArgument(ArgNo),
206*67e74705SXin Li                                            PP, true,
207*67e74705SXin Li                                            ExpansionLocStart,
208*67e74705SXin Li                                            ExpansionLocEnd);
209*67e74705SXin Li       }
210*67e74705SXin Li       Res.setFlag(Token::StringifiedInMacro);
211*67e74705SXin Li 
212*67e74705SXin Li       // The stringified/charified string leading space flag gets set to match
213*67e74705SXin Li       // the #/#@ operator.
214*67e74705SXin Li       if (NextTokGetsSpace)
215*67e74705SXin Li         Res.setFlag(Token::LeadingSpace);
216*67e74705SXin Li 
217*67e74705SXin Li       ResultToks.push_back(Res);
218*67e74705SXin Li       MadeChange = true;
219*67e74705SXin Li       ++i;  // Skip arg name.
220*67e74705SXin Li       NextTokGetsSpace = false;
221*67e74705SXin Li       continue;
222*67e74705SXin Li     }
223*67e74705SXin Li 
224*67e74705SXin Li     // Find out if there is a paste (##) operator before or after the token.
225*67e74705SXin Li     bool NonEmptyPasteBefore =
226*67e74705SXin Li       !ResultToks.empty() && ResultToks.back().is(tok::hashhash);
227*67e74705SXin Li     bool PasteBefore = i != 0 && Tokens[i-1].is(tok::hashhash);
228*67e74705SXin Li     bool PasteAfter = i+1 != e && Tokens[i+1].is(tok::hashhash);
229*67e74705SXin Li     assert(!NonEmptyPasteBefore || PasteBefore);
230*67e74705SXin Li 
231*67e74705SXin Li     // Otherwise, if this is not an argument token, just add the token to the
232*67e74705SXin Li     // output buffer.
233*67e74705SXin Li     IdentifierInfo *II = CurTok.getIdentifierInfo();
234*67e74705SXin Li     int ArgNo = II ? Macro->getArgumentNum(II) : -1;
235*67e74705SXin Li     if (ArgNo == -1) {
236*67e74705SXin Li       // This isn't an argument, just add it.
237*67e74705SXin Li       ResultToks.push_back(CurTok);
238*67e74705SXin Li 
239*67e74705SXin Li       if (NextTokGetsSpace) {
240*67e74705SXin Li         ResultToks.back().setFlag(Token::LeadingSpace);
241*67e74705SXin Li         NextTokGetsSpace = false;
242*67e74705SXin Li       } else if (PasteBefore && !NonEmptyPasteBefore)
243*67e74705SXin Li         ResultToks.back().clearFlag(Token::LeadingSpace);
244*67e74705SXin Li 
245*67e74705SXin Li       continue;
246*67e74705SXin Li     }
247*67e74705SXin Li 
248*67e74705SXin Li     // An argument is expanded somehow, the result is different than the
249*67e74705SXin Li     // input.
250*67e74705SXin Li     MadeChange = true;
251*67e74705SXin Li 
252*67e74705SXin Li     // Otherwise, this is a use of the argument.
253*67e74705SXin Li 
254*67e74705SXin Li     // In Microsoft mode, remove the comma before __VA_ARGS__ to ensure there
255*67e74705SXin Li     // are no trailing commas if __VA_ARGS__ is empty.
256*67e74705SXin Li     if (!PasteBefore && ActualArgs->isVarargsElidedUse() &&
257*67e74705SXin Li         MaybeRemoveCommaBeforeVaArgs(ResultToks,
258*67e74705SXin Li                                      /*HasPasteOperator=*/false,
259*67e74705SXin Li                                      Macro, ArgNo, PP))
260*67e74705SXin Li       continue;
261*67e74705SXin Li 
262*67e74705SXin Li     // If it is not the LHS/RHS of a ## operator, we must pre-expand the
263*67e74705SXin Li     // argument and substitute the expanded tokens into the result.  This is
264*67e74705SXin Li     // C99 6.10.3.1p1.
265*67e74705SXin Li     if (!PasteBefore && !PasteAfter) {
266*67e74705SXin Li       const Token *ResultArgToks;
267*67e74705SXin Li 
268*67e74705SXin Li       // Only preexpand the argument if it could possibly need it.  This
269*67e74705SXin Li       // avoids some work in common cases.
270*67e74705SXin Li       const Token *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
271*67e74705SXin Li       if (ActualArgs->ArgNeedsPreexpansion(ArgTok, PP))
272*67e74705SXin Li         ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, Macro, PP)[0];
273*67e74705SXin Li       else
274*67e74705SXin Li         ResultArgToks = ArgTok;  // Use non-preexpanded tokens.
275*67e74705SXin Li 
276*67e74705SXin Li       // If the arg token expanded into anything, append it.
277*67e74705SXin Li       if (ResultArgToks->isNot(tok::eof)) {
278*67e74705SXin Li         unsigned FirstResult = ResultToks.size();
279*67e74705SXin Li         unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
280*67e74705SXin Li         ResultToks.append(ResultArgToks, ResultArgToks+NumToks);
281*67e74705SXin Li 
282*67e74705SXin Li         // In Microsoft-compatibility mode, we follow MSVC's preprocessing
283*67e74705SXin Li         // behavior by not considering single commas from nested macro
284*67e74705SXin Li         // expansions as argument separators. Set a flag on the token so we can
285*67e74705SXin Li         // test for this later when the macro expansion is processed.
286*67e74705SXin Li         if (PP.getLangOpts().MSVCCompat && NumToks == 1 &&
287*67e74705SXin Li             ResultToks.back().is(tok::comma))
288*67e74705SXin Li           ResultToks.back().setFlag(Token::IgnoredComma);
289*67e74705SXin Li 
290*67e74705SXin Li         // If the '##' came from expanding an argument, turn it into 'unknown'
291*67e74705SXin Li         // to avoid pasting.
292*67e74705SXin Li         for (unsigned i = FirstResult, e = ResultToks.size(); i != e; ++i) {
293*67e74705SXin Li           Token &Tok = ResultToks[i];
294*67e74705SXin Li           if (Tok.is(tok::hashhash))
295*67e74705SXin Li             Tok.setKind(tok::unknown);
296*67e74705SXin Li         }
297*67e74705SXin Li 
298*67e74705SXin Li         if(ExpandLocStart.isValid()) {
299*67e74705SXin Li           updateLocForMacroArgTokens(CurTok.getLocation(),
300*67e74705SXin Li                                      ResultToks.begin()+FirstResult,
301*67e74705SXin Li                                      ResultToks.end());
302*67e74705SXin Li         }
303*67e74705SXin Li 
304*67e74705SXin Li         // If any tokens were substituted from the argument, the whitespace
305*67e74705SXin Li         // before the first token should match the whitespace of the arg
306*67e74705SXin Li         // identifier.
307*67e74705SXin Li         ResultToks[FirstResult].setFlagValue(Token::LeadingSpace,
308*67e74705SXin Li                                              NextTokGetsSpace);
309*67e74705SXin Li         ResultToks[FirstResult].setFlagValue(Token::StartOfLine, false);
310*67e74705SXin Li         NextTokGetsSpace = false;
311*67e74705SXin Li       }
312*67e74705SXin Li       continue;
313*67e74705SXin Li     }
314*67e74705SXin Li 
315*67e74705SXin Li     // Okay, we have a token that is either the LHS or RHS of a paste (##)
316*67e74705SXin Li     // argument.  It gets substituted as its non-pre-expanded tokens.
317*67e74705SXin Li     const Token *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
318*67e74705SXin Li     unsigned NumToks = MacroArgs::getArgLength(ArgToks);
319*67e74705SXin Li     if (NumToks) {  // Not an empty argument?
320*67e74705SXin Li       // If this is the GNU ", ## __VA_ARGS__" extension, and we just learned
321*67e74705SXin Li       // that __VA_ARGS__ expands to multiple tokens, avoid a pasting error when
322*67e74705SXin Li       // the expander trys to paste ',' with the first token of the __VA_ARGS__
323*67e74705SXin Li       // expansion.
324*67e74705SXin Li       if (NonEmptyPasteBefore && ResultToks.size() >= 2 &&
325*67e74705SXin Li           ResultToks[ResultToks.size()-2].is(tok::comma) &&
326*67e74705SXin Li           (unsigned)ArgNo == Macro->getNumArgs()-1 &&
327*67e74705SXin Li           Macro->isVariadic()) {
328*67e74705SXin Li         // Remove the paste operator, report use of the extension.
329*67e74705SXin Li         PP.Diag(ResultToks.pop_back_val().getLocation(), diag::ext_paste_comma);
330*67e74705SXin Li       }
331*67e74705SXin Li 
332*67e74705SXin Li       ResultToks.append(ArgToks, ArgToks+NumToks);
333*67e74705SXin Li 
334*67e74705SXin Li       // If the '##' came from expanding an argument, turn it into 'unknown'
335*67e74705SXin Li       // to avoid pasting.
336*67e74705SXin Li       for (unsigned i = ResultToks.size() - NumToks, e = ResultToks.size();
337*67e74705SXin Li              i != e; ++i) {
338*67e74705SXin Li         Token &Tok = ResultToks[i];
339*67e74705SXin Li         if (Tok.is(tok::hashhash))
340*67e74705SXin Li           Tok.setKind(tok::unknown);
341*67e74705SXin Li       }
342*67e74705SXin Li 
343*67e74705SXin Li       if (ExpandLocStart.isValid()) {
344*67e74705SXin Li         updateLocForMacroArgTokens(CurTok.getLocation(),
345*67e74705SXin Li                                    ResultToks.end()-NumToks, ResultToks.end());
346*67e74705SXin Li       }
347*67e74705SXin Li 
348*67e74705SXin Li       // If this token (the macro argument) was supposed to get leading
349*67e74705SXin Li       // whitespace, transfer this information onto the first token of the
350*67e74705SXin Li       // expansion.
351*67e74705SXin Li       //
352*67e74705SXin Li       // Do not do this if the paste operator occurs before the macro argument,
353*67e74705SXin Li       // as in "A ## MACROARG".  In valid code, the first token will get
354*67e74705SXin Li       // smooshed onto the preceding one anyway (forming AMACROARG).  In
355*67e74705SXin Li       // assembler-with-cpp mode, invalid pastes are allowed through: in this
356*67e74705SXin Li       // case, we do not want the extra whitespace to be added.  For example,
357*67e74705SXin Li       // we want ". ## foo" -> ".foo" not ". foo".
358*67e74705SXin Li       if (NextTokGetsSpace)
359*67e74705SXin Li         ResultToks[ResultToks.size()-NumToks].setFlag(Token::LeadingSpace);
360*67e74705SXin Li 
361*67e74705SXin Li       NextTokGetsSpace = false;
362*67e74705SXin Li       continue;
363*67e74705SXin Li     }
364*67e74705SXin Li 
365*67e74705SXin Li     // If an empty argument is on the LHS or RHS of a paste, the standard (C99
366*67e74705SXin Li     // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur.  We
367*67e74705SXin Li     // implement this by eating ## operators when a LHS or RHS expands to
368*67e74705SXin Li     // empty.
369*67e74705SXin Li     if (PasteAfter) {
370*67e74705SXin Li       // Discard the argument token and skip (don't copy to the expansion
371*67e74705SXin Li       // buffer) the paste operator after it.
372*67e74705SXin Li       ++i;
373*67e74705SXin Li       continue;
374*67e74705SXin Li     }
375*67e74705SXin Li 
376*67e74705SXin Li     // If this is on the RHS of a paste operator, we've already copied the
377*67e74705SXin Li     // paste operator to the ResultToks list, unless the LHS was empty too.
378*67e74705SXin Li     // Remove it.
379*67e74705SXin Li     assert(PasteBefore);
380*67e74705SXin Li     if (NonEmptyPasteBefore) {
381*67e74705SXin Li       assert(ResultToks.back().is(tok::hashhash));
382*67e74705SXin Li       ResultToks.pop_back();
383*67e74705SXin Li     }
384*67e74705SXin Li 
385*67e74705SXin Li     // If this is the __VA_ARGS__ token, and if the argument wasn't provided,
386*67e74705SXin Li     // and if the macro had at least one real argument, and if the token before
387*67e74705SXin Li     // the ## was a comma, remove the comma.  This is a GCC extension which is
388*67e74705SXin Li     // disabled when using -std=c99.
389*67e74705SXin Li     if (ActualArgs->isVarargsElidedUse())
390*67e74705SXin Li       MaybeRemoveCommaBeforeVaArgs(ResultToks,
391*67e74705SXin Li                                    /*HasPasteOperator=*/true,
392*67e74705SXin Li                                    Macro, ArgNo, PP);
393*67e74705SXin Li   }
394*67e74705SXin Li 
395*67e74705SXin Li   // If anything changed, install this as the new Tokens list.
396*67e74705SXin Li   if (MadeChange) {
397*67e74705SXin Li     assert(!OwnsTokens && "This would leak if we already own the token list");
398*67e74705SXin Li     // This is deleted in the dtor.
399*67e74705SXin Li     NumTokens = ResultToks.size();
400*67e74705SXin Li     // The tokens will be added to Preprocessor's cache and will be removed
401*67e74705SXin Li     // when this TokenLexer finishes lexing them.
402*67e74705SXin Li     Tokens = PP.cacheMacroExpandedTokens(this, ResultToks);
403*67e74705SXin Li 
404*67e74705SXin Li     // The preprocessor cache of macro expanded tokens owns these tokens,not us.
405*67e74705SXin Li     OwnsTokens = false;
406*67e74705SXin Li   }
407*67e74705SXin Li }
408*67e74705SXin Li 
409*67e74705SXin Li /// \brief Checks if two tokens form wide string literal.
isWideStringLiteralFromMacro(const Token & FirstTok,const Token & SecondTok)410*67e74705SXin Li static bool isWideStringLiteralFromMacro(const Token &FirstTok,
411*67e74705SXin Li                                          const Token &SecondTok) {
412*67e74705SXin Li   return FirstTok.is(tok::identifier) &&
413*67e74705SXin Li          FirstTok.getIdentifierInfo()->isStr("L") && SecondTok.isLiteral() &&
414*67e74705SXin Li          SecondTok.stringifiedInMacro();
415*67e74705SXin Li }
416*67e74705SXin Li 
417*67e74705SXin Li /// Lex - Lex and return a token from this macro stream.
418*67e74705SXin Li ///
Lex(Token & Tok)419*67e74705SXin Li bool TokenLexer::Lex(Token &Tok) {
420*67e74705SXin Li   // Lexing off the end of the macro, pop this macro off the expansion stack.
421*67e74705SXin Li   if (isAtEnd()) {
422*67e74705SXin Li     // If this is a macro (not a token stream), mark the macro enabled now
423*67e74705SXin Li     // that it is no longer being expanded.
424*67e74705SXin Li     if (Macro) Macro->EnableMacro();
425*67e74705SXin Li 
426*67e74705SXin Li     Tok.startToken();
427*67e74705SXin Li     Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
428*67e74705SXin Li     Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace || NextTokGetsSpace);
429*67e74705SXin Li     if (CurToken == 0)
430*67e74705SXin Li       Tok.setFlag(Token::LeadingEmptyMacro);
431*67e74705SXin Li     return PP.HandleEndOfTokenLexer(Tok);
432*67e74705SXin Li   }
433*67e74705SXin Li 
434*67e74705SXin Li   SourceManager &SM = PP.getSourceManager();
435*67e74705SXin Li 
436*67e74705SXin Li   // If this is the first token of the expanded result, we inherit spacing
437*67e74705SXin Li   // properties later.
438*67e74705SXin Li   bool isFirstToken = CurToken == 0;
439*67e74705SXin Li 
440*67e74705SXin Li   // Get the next token to return.
441*67e74705SXin Li   Tok = Tokens[CurToken++];
442*67e74705SXin Li 
443*67e74705SXin Li   bool TokenIsFromPaste = false;
444*67e74705SXin Li 
445*67e74705SXin Li   // If this token is followed by a token paste (##) operator, paste the tokens!
446*67e74705SXin Li   // Note that ## is a normal token when not expanding a macro.
447*67e74705SXin Li   if (!isAtEnd() && Macro &&
448*67e74705SXin Li       (Tokens[CurToken].is(tok::hashhash) ||
449*67e74705SXin Li        // Special processing of L#x macros in -fms-compatibility mode.
450*67e74705SXin Li        // Microsoft compiler is able to form a wide string literal from
451*67e74705SXin Li        // 'L#macro_arg' construct in a function-like macro.
452*67e74705SXin Li        (PP.getLangOpts().MSVCCompat &&
453*67e74705SXin Li         isWideStringLiteralFromMacro(Tok, Tokens[CurToken])))) {
454*67e74705SXin Li     // When handling the microsoft /##/ extension, the final token is
455*67e74705SXin Li     // returned by PasteTokens, not the pasted token.
456*67e74705SXin Li     if (PasteTokens(Tok))
457*67e74705SXin Li       return true;
458*67e74705SXin Li 
459*67e74705SXin Li     TokenIsFromPaste = true;
460*67e74705SXin Li   }
461*67e74705SXin Li 
462*67e74705SXin Li   // The token's current location indicate where the token was lexed from.  We
463*67e74705SXin Li   // need this information to compute the spelling of the token, but any
464*67e74705SXin Li   // diagnostics for the expanded token should appear as if they came from
465*67e74705SXin Li   // ExpansionLoc.  Pull this information together into a new SourceLocation
466*67e74705SXin Li   // that captures all of this.
467*67e74705SXin Li   if (ExpandLocStart.isValid() &&   // Don't do this for token streams.
468*67e74705SXin Li       // Check that the token's location was not already set properly.
469*67e74705SXin Li       SM.isBeforeInSLocAddrSpace(Tok.getLocation(), MacroStartSLocOffset)) {
470*67e74705SXin Li     SourceLocation instLoc;
471*67e74705SXin Li     if (Tok.is(tok::comment)) {
472*67e74705SXin Li       instLoc = SM.createExpansionLoc(Tok.getLocation(),
473*67e74705SXin Li                                       ExpandLocStart,
474*67e74705SXin Li                                       ExpandLocEnd,
475*67e74705SXin Li                                       Tok.getLength());
476*67e74705SXin Li     } else {
477*67e74705SXin Li       instLoc = getExpansionLocForMacroDefLoc(Tok.getLocation());
478*67e74705SXin Li     }
479*67e74705SXin Li 
480*67e74705SXin Li     Tok.setLocation(instLoc);
481*67e74705SXin Li   }
482*67e74705SXin Li 
483*67e74705SXin Li   // If this is the first token, set the lexical properties of the token to
484*67e74705SXin Li   // match the lexical properties of the macro identifier.
485*67e74705SXin Li   if (isFirstToken) {
486*67e74705SXin Li     Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
487*67e74705SXin Li     Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
488*67e74705SXin Li   } else {
489*67e74705SXin Li     // If this is not the first token, we may still need to pass through
490*67e74705SXin Li     // leading whitespace if we've expanded a macro.
491*67e74705SXin Li     if (AtStartOfLine) Tok.setFlag(Token::StartOfLine);
492*67e74705SXin Li     if (HasLeadingSpace) Tok.setFlag(Token::LeadingSpace);
493*67e74705SXin Li   }
494*67e74705SXin Li   AtStartOfLine = false;
495*67e74705SXin Li   HasLeadingSpace = false;
496*67e74705SXin Li 
497*67e74705SXin Li   // Handle recursive expansion!
498*67e74705SXin Li   if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
499*67e74705SXin Li     // Change the kind of this identifier to the appropriate token kind, e.g.
500*67e74705SXin Li     // turning "for" into a keyword.
501*67e74705SXin Li     IdentifierInfo *II = Tok.getIdentifierInfo();
502*67e74705SXin Li     Tok.setKind(II->getTokenID());
503*67e74705SXin Li 
504*67e74705SXin Li     // If this identifier was poisoned and from a paste, emit an error.  This
505*67e74705SXin Li     // won't be handled by Preprocessor::HandleIdentifier because this is coming
506*67e74705SXin Li     // from a macro expansion.
507*67e74705SXin Li     if (II->isPoisoned() && TokenIsFromPaste) {
508*67e74705SXin Li       PP.HandlePoisonedIdentifier(Tok);
509*67e74705SXin Li     }
510*67e74705SXin Li 
511*67e74705SXin Li     if (!DisableMacroExpansion && II->isHandleIdentifierCase())
512*67e74705SXin Li       return PP.HandleIdentifier(Tok);
513*67e74705SXin Li   }
514*67e74705SXin Li 
515*67e74705SXin Li   // Otherwise, return a normal token.
516*67e74705SXin Li   return true;
517*67e74705SXin Li }
518*67e74705SXin Li 
519*67e74705SXin Li /// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ##
520*67e74705SXin Li /// operator.  Read the ## and RHS, and paste the LHS/RHS together.  If there
521*67e74705SXin Li /// are more ## after it, chomp them iteratively.  Return the result as Tok.
522*67e74705SXin Li /// If this returns true, the caller should immediately return the token.
PasteTokens(Token & Tok)523*67e74705SXin Li bool TokenLexer::PasteTokens(Token &Tok) {
524*67e74705SXin Li   // MSVC: If previous token was pasted, this must be a recovery from an invalid
525*67e74705SXin Li   // paste operation. Ignore spaces before this token to mimic MSVC output.
526*67e74705SXin Li   // Required for generating valid UUID strings in some MS headers.
527*67e74705SXin Li   if (PP.getLangOpts().MicrosoftExt && (CurToken >= 2) &&
528*67e74705SXin Li       Tokens[CurToken - 2].is(tok::hashhash))
529*67e74705SXin Li     Tok.clearFlag(Token::LeadingSpace);
530*67e74705SXin Li 
531*67e74705SXin Li   SmallString<128> Buffer;
532*67e74705SXin Li   const char *ResultTokStrPtr = nullptr;
533*67e74705SXin Li   SourceLocation StartLoc = Tok.getLocation();
534*67e74705SXin Li   SourceLocation PasteOpLoc;
535*67e74705SXin Li   do {
536*67e74705SXin Li     // Consume the ## operator if any.
537*67e74705SXin Li     PasteOpLoc = Tokens[CurToken].getLocation();
538*67e74705SXin Li     if (Tokens[CurToken].is(tok::hashhash))
539*67e74705SXin Li       ++CurToken;
540*67e74705SXin Li     assert(!isAtEnd() && "No token on the RHS of a paste operator!");
541*67e74705SXin Li 
542*67e74705SXin Li     // Get the RHS token.
543*67e74705SXin Li     const Token &RHS = Tokens[CurToken];
544*67e74705SXin Li 
545*67e74705SXin Li     // Allocate space for the result token.  This is guaranteed to be enough for
546*67e74705SXin Li     // the two tokens.
547*67e74705SXin Li     Buffer.resize(Tok.getLength() + RHS.getLength());
548*67e74705SXin Li 
549*67e74705SXin Li     // Get the spelling of the LHS token in Buffer.
550*67e74705SXin Li     const char *BufPtr = &Buffer[0];
551*67e74705SXin Li     bool Invalid = false;
552*67e74705SXin Li     unsigned LHSLen = PP.getSpelling(Tok, BufPtr, &Invalid);
553*67e74705SXin Li     if (BufPtr != &Buffer[0])   // Really, we want the chars in Buffer!
554*67e74705SXin Li       memcpy(&Buffer[0], BufPtr, LHSLen);
555*67e74705SXin Li     if (Invalid)
556*67e74705SXin Li       return true;
557*67e74705SXin Li 
558*67e74705SXin Li     BufPtr = Buffer.data() + LHSLen;
559*67e74705SXin Li     unsigned RHSLen = PP.getSpelling(RHS, BufPtr, &Invalid);
560*67e74705SXin Li     if (Invalid)
561*67e74705SXin Li       return true;
562*67e74705SXin Li     if (RHSLen && BufPtr != &Buffer[LHSLen])
563*67e74705SXin Li       // Really, we want the chars in Buffer!
564*67e74705SXin Li       memcpy(&Buffer[LHSLen], BufPtr, RHSLen);
565*67e74705SXin Li 
566*67e74705SXin Li     // Trim excess space.
567*67e74705SXin Li     Buffer.resize(LHSLen+RHSLen);
568*67e74705SXin Li 
569*67e74705SXin Li     // Plop the pasted result (including the trailing newline and null) into a
570*67e74705SXin Li     // scratch buffer where we can lex it.
571*67e74705SXin Li     Token ResultTokTmp;
572*67e74705SXin Li     ResultTokTmp.startToken();
573*67e74705SXin Li 
574*67e74705SXin Li     // Claim that the tmp token is a string_literal so that we can get the
575*67e74705SXin Li     // character pointer back from CreateString in getLiteralData().
576*67e74705SXin Li     ResultTokTmp.setKind(tok::string_literal);
577*67e74705SXin Li     PP.CreateString(Buffer, ResultTokTmp);
578*67e74705SXin Li     SourceLocation ResultTokLoc = ResultTokTmp.getLocation();
579*67e74705SXin Li     ResultTokStrPtr = ResultTokTmp.getLiteralData();
580*67e74705SXin Li 
581*67e74705SXin Li     // Lex the resultant pasted token into Result.
582*67e74705SXin Li     Token Result;
583*67e74705SXin Li 
584*67e74705SXin Li     if (Tok.isAnyIdentifier() && RHS.isAnyIdentifier()) {
585*67e74705SXin Li       // Common paste case: identifier+identifier = identifier.  Avoid creating
586*67e74705SXin Li       // a lexer and other overhead.
587*67e74705SXin Li       PP.IncrementPasteCounter(true);
588*67e74705SXin Li       Result.startToken();
589*67e74705SXin Li       Result.setKind(tok::raw_identifier);
590*67e74705SXin Li       Result.setRawIdentifierData(ResultTokStrPtr);
591*67e74705SXin Li       Result.setLocation(ResultTokLoc);
592*67e74705SXin Li       Result.setLength(LHSLen+RHSLen);
593*67e74705SXin Li     } else {
594*67e74705SXin Li       PP.IncrementPasteCounter(false);
595*67e74705SXin Li 
596*67e74705SXin Li       assert(ResultTokLoc.isFileID() &&
597*67e74705SXin Li              "Should be a raw location into scratch buffer");
598*67e74705SXin Li       SourceManager &SourceMgr = PP.getSourceManager();
599*67e74705SXin Li       FileID LocFileID = SourceMgr.getFileID(ResultTokLoc);
600*67e74705SXin Li 
601*67e74705SXin Li       bool Invalid = false;
602*67e74705SXin Li       const char *ScratchBufStart
603*67e74705SXin Li         = SourceMgr.getBufferData(LocFileID, &Invalid).data();
604*67e74705SXin Li       if (Invalid)
605*67e74705SXin Li         return false;
606*67e74705SXin Li 
607*67e74705SXin Li       // Make a lexer to lex this string from.  Lex just this one token.
608*67e74705SXin Li       // Make a lexer object so that we lex and expand the paste result.
609*67e74705SXin Li       Lexer TL(SourceMgr.getLocForStartOfFile(LocFileID),
610*67e74705SXin Li                PP.getLangOpts(), ScratchBufStart,
611*67e74705SXin Li                ResultTokStrPtr, ResultTokStrPtr+LHSLen+RHSLen);
612*67e74705SXin Li 
613*67e74705SXin Li       // Lex a token in raw mode.  This way it won't look up identifiers
614*67e74705SXin Li       // automatically, lexing off the end will return an eof token, and
615*67e74705SXin Li       // warnings are disabled.  This returns true if the result token is the
616*67e74705SXin Li       // entire buffer.
617*67e74705SXin Li       bool isInvalid = !TL.LexFromRawLexer(Result);
618*67e74705SXin Li 
619*67e74705SXin Li       // If we got an EOF token, we didn't form even ONE token.  For example, we
620*67e74705SXin Li       // did "/ ## /" to get "//".
621*67e74705SXin Li       isInvalid |= Result.is(tok::eof);
622*67e74705SXin Li 
623*67e74705SXin Li       // If pasting the two tokens didn't form a full new token, this is an
624*67e74705SXin Li       // error.  This occurs with "x ## +"  and other stuff.  Return with Tok
625*67e74705SXin Li       // unmodified and with RHS as the next token to lex.
626*67e74705SXin Li       if (isInvalid) {
627*67e74705SXin Li         // Explicitly convert the token location to have proper expansion
628*67e74705SXin Li         // information so that the user knows where it came from.
629*67e74705SXin Li         SourceManager &SM = PP.getSourceManager();
630*67e74705SXin Li         SourceLocation Loc =
631*67e74705SXin Li           SM.createExpansionLoc(PasteOpLoc, ExpandLocStart, ExpandLocEnd, 2);
632*67e74705SXin Li 
633*67e74705SXin Li         // Test for the Microsoft extension of /##/ turning into // here on the
634*67e74705SXin Li         // error path.
635*67e74705SXin Li         if (PP.getLangOpts().MicrosoftExt && Tok.is(tok::slash) &&
636*67e74705SXin Li             RHS.is(tok::slash)) {
637*67e74705SXin Li           HandleMicrosoftCommentPaste(Tok, Loc);
638*67e74705SXin Li           return true;
639*67e74705SXin Li         }
640*67e74705SXin Li 
641*67e74705SXin Li         // Do not emit the error when preprocessing assembler code.
642*67e74705SXin Li         if (!PP.getLangOpts().AsmPreprocessor) {
643*67e74705SXin Li           // If we're in microsoft extensions mode, downgrade this from a hard
644*67e74705SXin Li           // error to an extension that defaults to an error.  This allows
645*67e74705SXin Li           // disabling it.
646*67e74705SXin Li           PP.Diag(Loc, PP.getLangOpts().MicrosoftExt ? diag::ext_pp_bad_paste_ms
647*67e74705SXin Li                                                      : diag::err_pp_bad_paste)
648*67e74705SXin Li               << Buffer;
649*67e74705SXin Li         }
650*67e74705SXin Li 
651*67e74705SXin Li         // An error has occurred so exit loop.
652*67e74705SXin Li         break;
653*67e74705SXin Li       }
654*67e74705SXin Li 
655*67e74705SXin Li       // Turn ## into 'unknown' to avoid # ## # from looking like a paste
656*67e74705SXin Li       // operator.
657*67e74705SXin Li       if (Result.is(tok::hashhash))
658*67e74705SXin Li         Result.setKind(tok::unknown);
659*67e74705SXin Li     }
660*67e74705SXin Li 
661*67e74705SXin Li     // Transfer properties of the LHS over the Result.
662*67e74705SXin Li     Result.setFlagValue(Token::StartOfLine , Tok.isAtStartOfLine());
663*67e74705SXin Li     Result.setFlagValue(Token::LeadingSpace, Tok.hasLeadingSpace());
664*67e74705SXin Li 
665*67e74705SXin Li     // Finally, replace LHS with the result, consume the RHS, and iterate.
666*67e74705SXin Li     ++CurToken;
667*67e74705SXin Li     Tok = Result;
668*67e74705SXin Li   } while (!isAtEnd() && Tokens[CurToken].is(tok::hashhash));
669*67e74705SXin Li 
670*67e74705SXin Li   SourceLocation EndLoc = Tokens[CurToken - 1].getLocation();
671*67e74705SXin Li 
672*67e74705SXin Li   // The token's current location indicate where the token was lexed from.  We
673*67e74705SXin Li   // need this information to compute the spelling of the token, but any
674*67e74705SXin Li   // diagnostics for the expanded token should appear as if the token was
675*67e74705SXin Li   // expanded from the full ## expression. Pull this information together into
676*67e74705SXin Li   // a new SourceLocation that captures all of this.
677*67e74705SXin Li   SourceManager &SM = PP.getSourceManager();
678*67e74705SXin Li   if (StartLoc.isFileID())
679*67e74705SXin Li     StartLoc = getExpansionLocForMacroDefLoc(StartLoc);
680*67e74705SXin Li   if (EndLoc.isFileID())
681*67e74705SXin Li     EndLoc = getExpansionLocForMacroDefLoc(EndLoc);
682*67e74705SXin Li   FileID MacroFID = SM.getFileID(MacroExpansionStart);
683*67e74705SXin Li   while (SM.getFileID(StartLoc) != MacroFID)
684*67e74705SXin Li     StartLoc = SM.getImmediateExpansionRange(StartLoc).first;
685*67e74705SXin Li   while (SM.getFileID(EndLoc) != MacroFID)
686*67e74705SXin Li     EndLoc = SM.getImmediateExpansionRange(EndLoc).second;
687*67e74705SXin Li 
688*67e74705SXin Li   Tok.setLocation(SM.createExpansionLoc(Tok.getLocation(), StartLoc, EndLoc,
689*67e74705SXin Li                                         Tok.getLength()));
690*67e74705SXin Li 
691*67e74705SXin Li   // Now that we got the result token, it will be subject to expansion.  Since
692*67e74705SXin Li   // token pasting re-lexes the result token in raw mode, identifier information
693*67e74705SXin Li   // isn't looked up.  As such, if the result is an identifier, look up id info.
694*67e74705SXin Li   if (Tok.is(tok::raw_identifier)) {
695*67e74705SXin Li     // Look up the identifier info for the token.  We disabled identifier lookup
696*67e74705SXin Li     // by saying we're skipping contents, so we need to do this manually.
697*67e74705SXin Li     PP.LookUpIdentifierInfo(Tok);
698*67e74705SXin Li   }
699*67e74705SXin Li   return false;
700*67e74705SXin Li }
701*67e74705SXin Li 
702*67e74705SXin Li /// isNextTokenLParen - If the next token lexed will pop this macro off the
703*67e74705SXin Li /// expansion stack, return 2.  If the next unexpanded token is a '(', return
704*67e74705SXin Li /// 1, otherwise return 0.
isNextTokenLParen() const705*67e74705SXin Li unsigned TokenLexer::isNextTokenLParen() const {
706*67e74705SXin Li   // Out of tokens?
707*67e74705SXin Li   if (isAtEnd())
708*67e74705SXin Li     return 2;
709*67e74705SXin Li   return Tokens[CurToken].is(tok::l_paren);
710*67e74705SXin Li }
711*67e74705SXin Li 
712*67e74705SXin Li /// isParsingPreprocessorDirective - Return true if we are in the middle of a
713*67e74705SXin Li /// preprocessor directive.
isParsingPreprocessorDirective() const714*67e74705SXin Li bool TokenLexer::isParsingPreprocessorDirective() const {
715*67e74705SXin Li   return Tokens[NumTokens-1].is(tok::eod) && !isAtEnd();
716*67e74705SXin Li }
717*67e74705SXin Li 
718*67e74705SXin Li /// HandleMicrosoftCommentPaste - In microsoft compatibility mode, /##/ pastes
719*67e74705SXin Li /// together to form a comment that comments out everything in the current
720*67e74705SXin Li /// macro, other active macros, and anything left on the current physical
721*67e74705SXin Li /// source line of the expanded buffer.  Handle this by returning the
722*67e74705SXin Li /// first token on the next line.
HandleMicrosoftCommentPaste(Token & Tok,SourceLocation OpLoc)723*67e74705SXin Li void TokenLexer::HandleMicrosoftCommentPaste(Token &Tok, SourceLocation OpLoc) {
724*67e74705SXin Li   PP.Diag(OpLoc, diag::ext_comment_paste_microsoft);
725*67e74705SXin Li 
726*67e74705SXin Li   // We 'comment out' the rest of this macro by just ignoring the rest of the
727*67e74705SXin Li   // tokens that have not been lexed yet, if any.
728*67e74705SXin Li 
729*67e74705SXin Li   // Since this must be a macro, mark the macro enabled now that it is no longer
730*67e74705SXin Li   // being expanded.
731*67e74705SXin Li   assert(Macro && "Token streams can't paste comments");
732*67e74705SXin Li   Macro->EnableMacro();
733*67e74705SXin Li 
734*67e74705SXin Li   PP.HandleMicrosoftCommentPaste(Tok);
735*67e74705SXin Li }
736*67e74705SXin Li 
737*67e74705SXin Li /// \brief If \arg loc is a file ID and points inside the current macro
738*67e74705SXin Li /// definition, returns the appropriate source location pointing at the
739*67e74705SXin Li /// macro expansion source location entry, otherwise it returns an invalid
740*67e74705SXin Li /// SourceLocation.
741*67e74705SXin Li SourceLocation
getExpansionLocForMacroDefLoc(SourceLocation loc) const742*67e74705SXin Li TokenLexer::getExpansionLocForMacroDefLoc(SourceLocation loc) const {
743*67e74705SXin Li   assert(ExpandLocStart.isValid() && MacroExpansionStart.isValid() &&
744*67e74705SXin Li          "Not appropriate for token streams");
745*67e74705SXin Li   assert(loc.isValid() && loc.isFileID());
746*67e74705SXin Li 
747*67e74705SXin Li   SourceManager &SM = PP.getSourceManager();
748*67e74705SXin Li   assert(SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength) &&
749*67e74705SXin Li          "Expected loc to come from the macro definition");
750*67e74705SXin Li 
751*67e74705SXin Li   unsigned relativeOffset = 0;
752*67e74705SXin Li   SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength, &relativeOffset);
753*67e74705SXin Li   return MacroExpansionStart.getLocWithOffset(relativeOffset);
754*67e74705SXin Li }
755*67e74705SXin Li 
756*67e74705SXin Li /// \brief Finds the tokens that are consecutive (from the same FileID)
757*67e74705SXin Li /// creates a single SLocEntry, and assigns SourceLocations to each token that
758*67e74705SXin Li /// point to that SLocEntry. e.g for
759*67e74705SXin Li ///   assert(foo == bar);
760*67e74705SXin Li /// There will be a single SLocEntry for the "foo == bar" chunk and locations
761*67e74705SXin Li /// for the 'foo', '==', 'bar' tokens will point inside that chunk.
762*67e74705SXin Li ///
763*67e74705SXin Li /// \arg begin_tokens will be updated to a position past all the found
764*67e74705SXin Li /// consecutive tokens.
updateConsecutiveMacroArgTokens(SourceManager & SM,SourceLocation InstLoc,Token * & begin_tokens,Token * end_tokens)765*67e74705SXin Li static void updateConsecutiveMacroArgTokens(SourceManager &SM,
766*67e74705SXin Li                                             SourceLocation InstLoc,
767*67e74705SXin Li                                             Token *&begin_tokens,
768*67e74705SXin Li                                             Token * end_tokens) {
769*67e74705SXin Li   assert(begin_tokens < end_tokens);
770*67e74705SXin Li 
771*67e74705SXin Li   SourceLocation FirstLoc = begin_tokens->getLocation();
772*67e74705SXin Li   SourceLocation CurLoc = FirstLoc;
773*67e74705SXin Li 
774*67e74705SXin Li   // Compare the source location offset of tokens and group together tokens that
775*67e74705SXin Li   // are close, even if their locations point to different FileIDs. e.g.
776*67e74705SXin Li   //
777*67e74705SXin Li   //  |bar    |  foo | cake   |  (3 tokens from 3 consecutive FileIDs)
778*67e74705SXin Li   //  ^                    ^
779*67e74705SXin Li   //  |bar       foo   cake|     (one SLocEntry chunk for all tokens)
780*67e74705SXin Li   //
781*67e74705SXin Li   // we can perform this "merge" since the token's spelling location depends
782*67e74705SXin Li   // on the relative offset.
783*67e74705SXin Li 
784*67e74705SXin Li   Token *NextTok = begin_tokens + 1;
785*67e74705SXin Li   for (; NextTok < end_tokens; ++NextTok) {
786*67e74705SXin Li     SourceLocation NextLoc = NextTok->getLocation();
787*67e74705SXin Li     if (CurLoc.isFileID() != NextLoc.isFileID())
788*67e74705SXin Li       break; // Token from different kind of FileID.
789*67e74705SXin Li 
790*67e74705SXin Li     int RelOffs;
791*67e74705SXin Li     if (!SM.isInSameSLocAddrSpace(CurLoc, NextLoc, &RelOffs))
792*67e74705SXin Li       break; // Token from different local/loaded location.
793*67e74705SXin Li     // Check that token is not before the previous token or more than 50
794*67e74705SXin Li     // "characters" away.
795*67e74705SXin Li     if (RelOffs < 0 || RelOffs > 50)
796*67e74705SXin Li       break;
797*67e74705SXin Li 
798*67e74705SXin Li     if (CurLoc.isMacroID() && !SM.isWrittenInSameFile(CurLoc, NextLoc))
799*67e74705SXin Li       break; // Token from a different macro.
800*67e74705SXin Li 
801*67e74705SXin Li     CurLoc = NextLoc;
802*67e74705SXin Li   }
803*67e74705SXin Li 
804*67e74705SXin Li   // For the consecutive tokens, find the length of the SLocEntry to contain
805*67e74705SXin Li   // all of them.
806*67e74705SXin Li   Token &LastConsecutiveTok = *(NextTok-1);
807*67e74705SXin Li   int LastRelOffs = 0;
808*67e74705SXin Li   SM.isInSameSLocAddrSpace(FirstLoc, LastConsecutiveTok.getLocation(),
809*67e74705SXin Li                            &LastRelOffs);
810*67e74705SXin Li   unsigned FullLength = LastRelOffs + LastConsecutiveTok.getLength();
811*67e74705SXin Li 
812*67e74705SXin Li   // Create a macro expansion SLocEntry that will "contain" all of the tokens.
813*67e74705SXin Li   SourceLocation Expansion =
814*67e74705SXin Li       SM.createMacroArgExpansionLoc(FirstLoc, InstLoc,FullLength);
815*67e74705SXin Li 
816*67e74705SXin Li   // Change the location of the tokens from the spelling location to the new
817*67e74705SXin Li   // expanded location.
818*67e74705SXin Li   for (; begin_tokens < NextTok; ++begin_tokens) {
819*67e74705SXin Li     Token &Tok = *begin_tokens;
820*67e74705SXin Li     int RelOffs = 0;
821*67e74705SXin Li     SM.isInSameSLocAddrSpace(FirstLoc, Tok.getLocation(), &RelOffs);
822*67e74705SXin Li     Tok.setLocation(Expansion.getLocWithOffset(RelOffs));
823*67e74705SXin Li   }
824*67e74705SXin Li }
825*67e74705SXin Li 
826*67e74705SXin Li /// \brief Creates SLocEntries and updates the locations of macro argument
827*67e74705SXin Li /// tokens to their new expanded locations.
828*67e74705SXin Li ///
829*67e74705SXin Li /// \param ArgIdDefLoc the location of the macro argument id inside the macro
830*67e74705SXin Li /// definition.
831*67e74705SXin Li /// \param Tokens the macro argument tokens to update.
updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc,Token * begin_tokens,Token * end_tokens)832*67e74705SXin Li void TokenLexer::updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc,
833*67e74705SXin Li                                             Token *begin_tokens,
834*67e74705SXin Li                                             Token *end_tokens) {
835*67e74705SXin Li   SourceManager &SM = PP.getSourceManager();
836*67e74705SXin Li 
837*67e74705SXin Li   SourceLocation InstLoc =
838*67e74705SXin Li       getExpansionLocForMacroDefLoc(ArgIdSpellLoc);
839*67e74705SXin Li 
840*67e74705SXin Li   while (begin_tokens < end_tokens) {
841*67e74705SXin Li     // If there's only one token just create a SLocEntry for it.
842*67e74705SXin Li     if (end_tokens - begin_tokens == 1) {
843*67e74705SXin Li       Token &Tok = *begin_tokens;
844*67e74705SXin Li       Tok.setLocation(SM.createMacroArgExpansionLoc(Tok.getLocation(),
845*67e74705SXin Li                                                     InstLoc,
846*67e74705SXin Li                                                     Tok.getLength()));
847*67e74705SXin Li       return;
848*67e74705SXin Li     }
849*67e74705SXin Li 
850*67e74705SXin Li     updateConsecutiveMacroArgTokens(SM, InstLoc, begin_tokens, end_tokens);
851*67e74705SXin Li   }
852*67e74705SXin Li }
853*67e74705SXin Li 
PropagateLineStartLeadingSpaceInfo(Token & Result)854*67e74705SXin Li void TokenLexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
855*67e74705SXin Li   AtStartOfLine = Result.isAtStartOfLine();
856*67e74705SXin Li   HasLeadingSpace = Result.hasLeadingSpace();
857*67e74705SXin Li }
858