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