clang API Documentation

PPLexerChange.cpp
Go to the documentation of this file.
00001 //===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements pieces of the Preprocessor interface that manage the
00011 // current lexer stack.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Lex/Preprocessor.h"
00016 #include "clang/Basic/FileManager.h"
00017 #include "clang/Basic/SourceManager.h"
00018 #include "clang/Lex/HeaderSearch.h"
00019 #include "clang/Lex/LexDiagnostic.h"
00020 #include "clang/Lex/MacroInfo.h"
00021 #include "llvm/ADT/StringSwitch.h"
00022 #include "llvm/Support/FileSystem.h"
00023 #include "llvm/Support/MemoryBuffer.h"
00024 #include "llvm/Support/Path.h"
00025 using namespace clang;
00026 
00027 PPCallbacks::~PPCallbacks() {}
00028 
00029 //===----------------------------------------------------------------------===//
00030 // Miscellaneous Methods.
00031 //===----------------------------------------------------------------------===//
00032 
00033 /// isInPrimaryFile - Return true if we're in the top-level file, not in a
00034 /// \#include.  This looks through macro expansions and active _Pragma lexers.
00035 bool Preprocessor::isInPrimaryFile() const {
00036   if (IsFileLexer())
00037     return IncludeMacroStack.empty();
00038 
00039   // If there are any stacked lexers, we're in a #include.
00040   assert(IsFileLexer(IncludeMacroStack[0]) &&
00041          "Top level include stack isn't our primary lexer?");
00042   for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
00043     if (IsFileLexer(IncludeMacroStack[i]))
00044       return false;
00045   return true;
00046 }
00047 
00048 /// getCurrentLexer - Return the current file lexer being lexed from.  Note
00049 /// that this ignores any potentially active macro expansions and _Pragma
00050 /// expansions going on at the time.
00051 PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
00052   if (IsFileLexer())
00053     return CurPPLexer;
00054 
00055   // Look for a stacked lexer.
00056   for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
00057     const IncludeStackInfo& ISI = IncludeMacroStack[i-1];
00058     if (IsFileLexer(ISI))
00059       return ISI.ThePPLexer;
00060   }
00061   return nullptr;
00062 }
00063 
00064 
00065 //===----------------------------------------------------------------------===//
00066 // Methods for Entering and Callbacks for leaving various contexts
00067 //===----------------------------------------------------------------------===//
00068 
00069 /// EnterSourceFile - Add a source file to the top of the include stack and
00070 /// start lexing tokens from it instead of the current buffer.
00071 bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
00072                                    SourceLocation Loc) {
00073   assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
00074   ++NumEnteredSourceFiles;
00075 
00076   if (MaxIncludeStackDepth < IncludeMacroStack.size())
00077     MaxIncludeStackDepth = IncludeMacroStack.size();
00078 
00079   if (PTH) {
00080     if (PTHLexer *PL = PTH->CreateLexer(FID)) {
00081       EnterSourceFileWithPTH(PL, CurDir);
00082       return false;
00083     }
00084   }
00085   
00086   // Get the MemoryBuffer for this FID, if it fails, we fail.
00087   bool Invalid = false;
00088   const llvm::MemoryBuffer *InputFile = 
00089     getSourceManager().getBuffer(FID, Loc, &Invalid);
00090   if (Invalid) {
00091     SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
00092     Diag(Loc, diag::err_pp_error_opening_file)
00093       << std::string(SourceMgr.getBufferName(FileStart)) << "";
00094     return true;
00095   }
00096 
00097   if (isCodeCompletionEnabled() &&
00098       SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
00099     CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
00100     CodeCompletionLoc =
00101         CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
00102   }
00103 
00104   EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
00105   return false;
00106 }
00107 
00108 /// EnterSourceFileWithLexer - Add a source file to the top of the include stack
00109 ///  and start lexing tokens from it instead of the current buffer.
00110 void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
00111                                             const DirectoryLookup *CurDir) {
00112 
00113   // Add the current lexer to the include stack.
00114   if (CurPPLexer || CurTokenLexer)
00115     PushIncludeMacroStack();
00116 
00117   CurLexer.reset(TheLexer);
00118   CurPPLexer = TheLexer;
00119   CurDirLookup = CurDir;
00120   CurSubmodule = nullptr;
00121   if (CurLexerKind != CLK_LexAfterModuleImport)
00122     CurLexerKind = CLK_Lexer;
00123   
00124   // Notify the client, if desired, that we are in a new source file.
00125   if (Callbacks && !CurLexer->Is_PragmaLexer) {
00126     SrcMgr::CharacteristicKind FileType =
00127        SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
00128 
00129     Callbacks->FileChanged(CurLexer->getFileLoc(),
00130                            PPCallbacks::EnterFile, FileType);
00131   }
00132 }
00133 
00134 /// EnterSourceFileWithPTH - Add a source file to the top of the include stack
00135 /// and start getting tokens from it using the PTH cache.
00136 void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
00137                                           const DirectoryLookup *CurDir) {
00138 
00139   if (CurPPLexer || CurTokenLexer)
00140     PushIncludeMacroStack();
00141 
00142   CurDirLookup = CurDir;
00143   CurPTHLexer.reset(PL);
00144   CurPPLexer = CurPTHLexer.get();
00145   CurSubmodule = nullptr;
00146   if (CurLexerKind != CLK_LexAfterModuleImport)
00147     CurLexerKind = CLK_PTHLexer;
00148   
00149   // Notify the client, if desired, that we are in a new source file.
00150   if (Callbacks) {
00151     FileID FID = CurPPLexer->getFileID();
00152     SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
00153     SrcMgr::CharacteristicKind FileType =
00154       SourceMgr.getFileCharacteristic(EnterLoc);
00155     Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
00156   }
00157 }
00158 
00159 /// EnterMacro - Add a Macro to the top of the include stack and start lexing
00160 /// tokens from it instead of the current buffer.
00161 void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
00162                               MacroInfo *Macro, MacroArgs *Args) {
00163   std::unique_ptr<TokenLexer> TokLexer;
00164   if (NumCachedTokenLexers == 0) {
00165     TokLexer = llvm::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);
00166   } else {
00167     TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
00168     TokLexer->Init(Tok, ILEnd, Macro, Args);
00169   }
00170 
00171   PushIncludeMacroStack();
00172   CurDirLookup = nullptr;
00173   CurTokenLexer = std::move(TokLexer);
00174   if (CurLexerKind != CLK_LexAfterModuleImport)
00175     CurLexerKind = CLK_TokenLexer;
00176 }
00177 
00178 /// EnterTokenStream - Add a "macro" context to the top of the include stack,
00179 /// which will cause the lexer to start returning the specified tokens.
00180 ///
00181 /// If DisableMacroExpansion is true, tokens lexed from the token stream will
00182 /// not be subject to further macro expansion.  Otherwise, these tokens will
00183 /// be re-macro-expanded when/if expansion is enabled.
00184 ///
00185 /// If OwnsTokens is false, this method assumes that the specified stream of
00186 /// tokens has a permanent owner somewhere, so they do not need to be copied.
00187 /// If it is true, it assumes the array of tokens is allocated with new[] and
00188 /// must be freed.
00189 ///
00190 void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
00191                                     bool DisableMacroExpansion,
00192                                     bool OwnsTokens) {
00193   if (CurLexerKind == CLK_CachingLexer) {
00194     if (CachedLexPos < CachedTokens.size()) {
00195       // We're entering tokens into the middle of our cached token stream. We
00196       // can't represent that, so just insert the tokens into the buffer.
00197       CachedTokens.insert(CachedTokens.begin() + CachedLexPos,
00198                           Toks, Toks + NumToks);
00199       if (OwnsTokens)
00200         delete [] Toks;
00201       return;
00202     }
00203 
00204     // New tokens are at the end of the cached token sequnece; insert the
00205     // token stream underneath the caching lexer.
00206     ExitCachingLexMode();
00207     EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
00208     EnterCachingLexMode();
00209     return;
00210   }
00211 
00212   // Create a macro expander to expand from the specified token stream.
00213   std::unique_ptr<TokenLexer> TokLexer;
00214   if (NumCachedTokenLexers == 0) {
00215     TokLexer = llvm::make_unique<TokenLexer>(
00216         Toks, NumToks, DisableMacroExpansion, OwnsTokens, *this);
00217   } else {
00218     TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
00219     TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
00220   }
00221 
00222   // Save our current state.
00223   PushIncludeMacroStack();
00224   CurDirLookup = nullptr;
00225   CurTokenLexer = std::move(TokLexer);
00226   if (CurLexerKind != CLK_LexAfterModuleImport)
00227     CurLexerKind = CLK_TokenLexer;
00228 }
00229 
00230 /// \brief Compute the relative path that names the given file relative to
00231 /// the given directory.
00232 static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
00233                                 const FileEntry *File,
00234                                 SmallString<128> &Result) {
00235   Result.clear();
00236 
00237   StringRef FilePath = File->getDir()->getName();
00238   StringRef Path = FilePath;
00239   while (!Path.empty()) {
00240     if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
00241       if (CurDir == Dir) {
00242         Result = FilePath.substr(Path.size());
00243         llvm::sys::path::append(Result, 
00244                                 llvm::sys::path::filename(File->getName()));
00245         return;
00246       }
00247     }
00248     
00249     Path = llvm::sys::path::parent_path(Path);
00250   }
00251   
00252   Result = File->getName();
00253 }
00254 
00255 void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
00256   if (CurTokenLexer) {
00257     CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
00258     return;
00259   }
00260   if (CurLexer) {
00261     CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
00262     return;
00263   }
00264   // FIXME: Handle other kinds of lexers?  It generally shouldn't matter,
00265   // but it might if they're empty?
00266 }
00267 
00268 /// \brief Determine the location to use as the end of the buffer for a lexer.
00269 ///
00270 /// If the file ends with a newline, form the EOF token on the newline itself,
00271 /// rather than "on the line following it", which doesn't exist.  This makes
00272 /// diagnostics relating to the end of file include the last file that the user
00273 /// actually typed, which is goodness.
00274 const char *Preprocessor::getCurLexerEndPos() {
00275   const char *EndPos = CurLexer->BufferEnd;
00276   if (EndPos != CurLexer->BufferStart &&
00277       (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
00278     --EndPos;
00279 
00280     // Handle \n\r and \r\n:
00281     if (EndPos != CurLexer->BufferStart &&
00282         (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
00283         EndPos[-1] != EndPos[0])
00284       --EndPos;
00285   }
00286 
00287   return EndPos;
00288 }
00289 
00290 
00291 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
00292 /// the current file.  This either returns the EOF token or pops a level off
00293 /// the include stack and keeps going.
00294 bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
00295   assert(!CurTokenLexer &&
00296          "Ending a file when currently in a macro!");
00297 
00298   // See if this file had a controlling macro.
00299   if (CurPPLexer) {  // Not ending a macro, ignore it.
00300     if (const IdentifierInfo *ControllingMacro =
00301           CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
00302       // Okay, this has a controlling macro, remember in HeaderFileInfo.
00303       if (const FileEntry *FE =
00304             SourceMgr.getFileEntryForID(CurPPLexer->getFileID())) {
00305         HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
00306         if (MacroInfo *MI =
00307               getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro))) {
00308           MI->UsedForHeaderGuard = true;
00309         }
00310         if (const IdentifierInfo *DefinedMacro =
00311               CurPPLexer->MIOpt.GetDefinedMacro()) {
00312           if (!ControllingMacro->hasMacroDefinition() &&
00313               DefinedMacro != ControllingMacro &&
00314               HeaderInfo.FirstTimeLexingFile(FE)) {
00315 
00316             // If the edit distance between the two macros is more than 50%,
00317             // DefinedMacro may not be header guard, or can be header guard of
00318             // another header file. Therefore, it maybe defining something
00319             // completely different. This can be observed in the wild when
00320             // handling feature macros or header guards in different files.
00321 
00322             const StringRef ControllingMacroName = ControllingMacro->getName();
00323             const StringRef DefinedMacroName = DefinedMacro->getName();
00324             const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
00325                                                   DefinedMacroName.size()) / 2;
00326             const unsigned ED = ControllingMacroName.edit_distance(
00327                 DefinedMacroName, true, MaxHalfLength);
00328             if (ED <= MaxHalfLength) {
00329               // Emit a warning for a bad header guard.
00330               Diag(CurPPLexer->MIOpt.GetMacroLocation(),
00331                    diag::warn_header_guard)
00332                   << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
00333               Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
00334                    diag::note_header_guard)
00335                   << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
00336                   << ControllingMacro
00337                   << FixItHint::CreateReplacement(
00338                          CurPPLexer->MIOpt.GetDefinedLocation(),
00339                          ControllingMacro->getName());
00340             }
00341           }
00342         }
00343       }
00344     }
00345   }
00346 
00347   // Complain about reaching a true EOF within arc_cf_code_audited.
00348   // We don't want to complain about reaching the end of a macro
00349   // instantiation or a _Pragma.
00350   if (PragmaARCCFCodeAuditedLoc.isValid() &&
00351       !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
00352     Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
00353 
00354     // Recover by leaving immediately.
00355     PragmaARCCFCodeAuditedLoc = SourceLocation();
00356   }
00357 
00358   // If this is a #include'd file, pop it off the include stack and continue
00359   // lexing the #includer file.
00360   if (!IncludeMacroStack.empty()) {
00361 
00362     // If we lexed the code-completion file, act as if we reached EOF.
00363     if (isCodeCompletionEnabled() && CurPPLexer &&
00364         SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
00365             CodeCompletionFileLoc) {
00366       if (CurLexer) {
00367         Result.startToken();
00368         CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
00369         CurLexer.reset();
00370       } else {
00371         assert(CurPTHLexer && "Got EOF but no current lexer set!");
00372         CurPTHLexer->getEOF(Result);
00373         CurPTHLexer.reset();
00374       }
00375 
00376       CurPPLexer = nullptr;
00377       return true;
00378     }
00379 
00380     if (!isEndOfMacro && CurPPLexer &&
00381         SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
00382       // Notify SourceManager to record the number of FileIDs that were created
00383       // during lexing of the #include'd file.
00384       unsigned NumFIDs =
00385           SourceMgr.local_sloc_entry_size() -
00386           CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
00387       SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
00388     }
00389 
00390     FileID ExitedFID;
00391     if (Callbacks && !isEndOfMacro && CurPPLexer)
00392       ExitedFID = CurPPLexer->getFileID();
00393 
00394     bool LeavingSubmodule = CurSubmodule && CurLexer;
00395     if (LeavingSubmodule) {
00396       // Notify the parser that we've left the module.
00397       const char *EndPos = getCurLexerEndPos();
00398       Result.startToken();
00399       CurLexer->BufferPtr = EndPos;
00400       CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
00401       Result.setAnnotationEndLoc(Result.getLocation());
00402       Result.setAnnotationValue(CurSubmodule);
00403     }
00404 
00405     // We're done with the #included file.
00406     RemoveTopOfLexerStack();
00407 
00408     // Propagate info about start-of-line/leading white-space/etc.
00409     PropagateLineStartLeadingSpaceInfo(Result);
00410 
00411     // Notify the client, if desired, that we are in a new source file.
00412     if (Callbacks && !isEndOfMacro && CurPPLexer) {
00413       SrcMgr::CharacteristicKind FileType =
00414         SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
00415       Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
00416                              PPCallbacks::ExitFile, FileType, ExitedFID);
00417     }
00418 
00419     // Client should lex another token unless we generated an EOM.
00420     return LeavingSubmodule;
00421   }
00422 
00423   // If this is the end of the main file, form an EOF token.
00424   if (CurLexer) {
00425     const char *EndPos = getCurLexerEndPos();
00426     Result.startToken();
00427     CurLexer->BufferPtr = EndPos;
00428     CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
00429 
00430     if (isCodeCompletionEnabled()) {
00431       // Inserting the code-completion point increases the source buffer by 1,
00432       // but the main FileID was created before inserting the point.
00433       // Compensate by reducing the EOF location by 1, otherwise the location
00434       // will point to the next FileID.
00435       // FIXME: This is hacky, the code-completion point should probably be
00436       // inserted before the main FileID is created.
00437       if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
00438         Result.setLocation(Result.getLocation().getLocWithOffset(-1));
00439     }
00440 
00441     if (!isIncrementalProcessingEnabled())
00442       // We're done with lexing.
00443       CurLexer.reset();
00444   } else {
00445     assert(CurPTHLexer && "Got EOF but no current lexer set!");
00446     CurPTHLexer->getEOF(Result);
00447     CurPTHLexer.reset();
00448   }
00449   
00450   if (!isIncrementalProcessingEnabled())
00451     CurPPLexer = nullptr;
00452 
00453   if (TUKind == TU_Complete) {
00454     // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
00455     // collected all macro locations that we need to warn because they are not
00456     // used.
00457     for (WarnUnusedMacroLocsTy::iterator
00458            I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
00459            I!=E; ++I)
00460       Diag(*I, diag::pp_macro_not_used);
00461   }
00462 
00463   // If we are building a module that has an umbrella header, make sure that
00464   // each of the headers within the directory covered by the umbrella header
00465   // was actually included by the umbrella header.
00466   if (Module *Mod = getCurrentModule()) {
00467     if (Mod->getUmbrellaHeader()) {
00468       SourceLocation StartLoc
00469         = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
00470 
00471       if (!getDiagnostics().isIgnored(diag::warn_uncovered_module_header,
00472                                       StartLoc)) {
00473         ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
00474         const DirectoryEntry *Dir = Mod->getUmbrellaDir();
00475         vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
00476         std::error_code EC;
00477         for (vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC), End;
00478              Entry != End && !EC; Entry.increment(EC)) {
00479           using llvm::StringSwitch;
00480           
00481           // Check whether this entry has an extension typically associated with
00482           // headers.
00483           if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->getName()))
00484                  .Cases(".h", ".H", ".hh", ".hpp", true)
00485                  .Default(false))
00486             continue;
00487 
00488           if (const FileEntry *Header =
00489                   getFileManager().getFile(Entry->getName()))
00490             if (!getSourceManager().hasFileInfo(Header)) {
00491               if (!ModMap.isHeaderInUnavailableModule(Header)) {
00492                 // Find the relative path that would access this header.
00493                 SmallString<128> RelativePath;
00494                 computeRelativePath(FileMgr, Dir, Header, RelativePath);              
00495                 Diag(StartLoc, diag::warn_uncovered_module_header)
00496                   << Mod->getFullModuleName() << RelativePath;
00497               }
00498             }
00499         }
00500       }
00501     }
00502   }
00503 
00504   return true;
00505 }
00506 
00507 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
00508 /// hits the end of its token stream.
00509 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
00510   assert(CurTokenLexer && !CurPPLexer &&
00511          "Ending a macro when currently in a #include file!");
00512 
00513   if (!MacroExpandingLexersStack.empty() &&
00514       MacroExpandingLexersStack.back().first == CurTokenLexer.get())
00515     removeCachedMacroExpandedTokensOfLastLexer();
00516 
00517   // Delete or cache the now-dead macro expander.
00518   if (NumCachedTokenLexers == TokenLexerCacheSize)
00519     CurTokenLexer.reset();
00520   else
00521     TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
00522 
00523   // Handle this like a #include file being popped off the stack.
00524   return HandleEndOfFile(Result, true);
00525 }
00526 
00527 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
00528 /// lexer stack.  This should only be used in situations where the current
00529 /// state of the top-of-stack lexer is unknown.
00530 void Preprocessor::RemoveTopOfLexerStack() {
00531   assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
00532 
00533   if (CurTokenLexer) {
00534     // Delete or cache the now-dead macro expander.
00535     if (NumCachedTokenLexers == TokenLexerCacheSize)
00536       CurTokenLexer.reset();
00537     else
00538       TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
00539   }
00540 
00541   PopIncludeMacroStack();
00542 }
00543 
00544 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
00545 /// comment (/##/) in microsoft mode, this method handles updating the current
00546 /// state, returning the token on the next source line.
00547 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
00548   assert(CurTokenLexer && !CurPPLexer &&
00549          "Pasted comment can only be formed from macro");
00550 
00551   // We handle this by scanning for the closest real lexer, switching it to
00552   // raw mode and preprocessor mode.  This will cause it to return \n as an
00553   // explicit EOD token.
00554   PreprocessorLexer *FoundLexer = nullptr;
00555   bool LexerWasInPPMode = false;
00556   for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
00557     IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
00558     if (ISI.ThePPLexer == nullptr) continue;  // Scan for a real lexer.
00559 
00560     // Once we find a real lexer, mark it as raw mode (disabling macro
00561     // expansions) and preprocessor mode (return EOD).  We know that the lexer
00562     // was *not* in raw mode before, because the macro that the comment came
00563     // from was expanded.  However, it could have already been in preprocessor
00564     // mode (#if COMMENT) in which case we have to return it to that mode and
00565     // return EOD.
00566     FoundLexer = ISI.ThePPLexer;
00567     FoundLexer->LexingRawMode = true;
00568     LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
00569     FoundLexer->ParsingPreprocessorDirective = true;
00570     break;
00571   }
00572 
00573   // Okay, we either found and switched over the lexer, or we didn't find a
00574   // lexer.  In either case, finish off the macro the comment came from, getting
00575   // the next token.
00576   if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
00577 
00578   // Discarding comments as long as we don't have EOF or EOD.  This 'comments
00579   // out' the rest of the line, including any tokens that came from other macros
00580   // that were active, as in:
00581   //  #define submacro a COMMENT b
00582   //    submacro c
00583   // which should lex to 'a' only: 'b' and 'c' should be removed.
00584   while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
00585     Lex(Tok);
00586 
00587   // If we got an eod token, then we successfully found the end of the line.
00588   if (Tok.is(tok::eod)) {
00589     assert(FoundLexer && "Can't get end of line without an active lexer");
00590     // Restore the lexer back to normal mode instead of raw mode.
00591     FoundLexer->LexingRawMode = false;
00592 
00593     // If the lexer was already in preprocessor mode, just return the EOD token
00594     // to finish the preprocessor line.
00595     if (LexerWasInPPMode) return;
00596 
00597     // Otherwise, switch out of PP mode and return the next lexed token.
00598     FoundLexer->ParsingPreprocessorDirective = false;
00599     return Lex(Tok);
00600   }
00601 
00602   // If we got an EOF token, then we reached the end of the token stream but
00603   // didn't find an explicit \n.  This can only happen if there was no lexer
00604   // active (an active lexer would return EOD at EOF if there was no \n in
00605   // preprocessor directive mode), so just return EOF as our token.
00606   assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
00607 }