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