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/Lex/HeaderSearch.h"
00017 #include "clang/Lex/MacroInfo.h"
00018 #include "clang/Lex/LexDiagnostic.h"
00019 #include "clang/Basic/FileManager.h"
00020 #include "clang/Basic/SourceManager.h"
00021 #include "llvm/Support/FileSystem.h"
00022 #include "llvm/Support/MemoryBuffer.h"
00023 #include "llvm/Support/PathV2.h"
00024 #include "llvm/ADT/StringSwitch.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 0;
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 void Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
00072                                    SourceLocation Loc) {
00073   assert(CurTokenLexer == 0 && "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;
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;
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;
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   if (CurLexerKind != CLK_LexAfterModuleImport)
00121     CurLexerKind = CLK_Lexer;
00122   
00123   // Notify the client, if desired, that we are in a new source file.
00124   if (Callbacks && !CurLexer->Is_PragmaLexer) {
00125     SrcMgr::CharacteristicKind FileType =
00126        SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
00127 
00128     Callbacks->FileChanged(CurLexer->getFileLoc(),
00129                            PPCallbacks::EnterFile, FileType);
00130   }
00131 }
00132 
00133 /// EnterSourceFileWithPTH - Add a source file to the top of the include stack
00134 /// and start getting tokens from it using the PTH cache.
00135 void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
00136                                           const DirectoryLookup *CurDir) {
00137 
00138   if (CurPPLexer || CurTokenLexer)
00139     PushIncludeMacroStack();
00140 
00141   CurDirLookup = CurDir;
00142   CurPTHLexer.reset(PL);
00143   CurPPLexer = CurPTHLexer.get();
00144   if (CurLexerKind != CLK_LexAfterModuleImport)
00145     CurLexerKind = CLK_PTHLexer;
00146   
00147   // Notify the client, if desired, that we are in a new source file.
00148   if (Callbacks) {
00149     FileID FID = CurPPLexer->getFileID();
00150     SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
00151     SrcMgr::CharacteristicKind FileType =
00152       SourceMgr.getFileCharacteristic(EnterLoc);
00153     Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
00154   }
00155 }
00156 
00157 /// EnterMacro - Add a Macro to the top of the include stack and start lexing
00158 /// tokens from it instead of the current buffer.
00159 void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
00160                               MacroArgs *Args) {
00161   PushIncludeMacroStack();
00162   CurDirLookup = 0;
00163 
00164   if (NumCachedTokenLexers == 0) {
00165     CurTokenLexer.reset(new TokenLexer(Tok, ILEnd, Args, *this));
00166   } else {
00167     CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
00168     CurTokenLexer->Init(Tok, ILEnd, Args);
00169   }
00170   if (CurLexerKind != CLK_LexAfterModuleImport)
00171     CurLexerKind = CLK_TokenLexer;
00172 }
00173 
00174 /// EnterTokenStream - Add a "macro" context to the top of the include stack,
00175 /// which will cause the lexer to start returning the specified tokens.
00176 ///
00177 /// If DisableMacroExpansion is true, tokens lexed from the token stream will
00178 /// not be subject to further macro expansion.  Otherwise, these tokens will
00179 /// be re-macro-expanded when/if expansion is enabled.
00180 ///
00181 /// If OwnsTokens is false, this method assumes that the specified stream of
00182 /// tokens has a permanent owner somewhere, so they do not need to be copied.
00183 /// If it is true, it assumes the array of tokens is allocated with new[] and
00184 /// must be freed.
00185 ///
00186 void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
00187                                     bool DisableMacroExpansion,
00188                                     bool OwnsTokens) {
00189   // Save our current state.
00190   PushIncludeMacroStack();
00191   CurDirLookup = 0;
00192 
00193   // Create a macro expander to expand from the specified token stream.
00194   if (NumCachedTokenLexers == 0) {
00195     CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion,
00196                                        OwnsTokens, *this));
00197   } else {
00198     CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
00199     CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
00200   }
00201   if (CurLexerKind != CLK_LexAfterModuleImport)
00202     CurLexerKind = CLK_TokenLexer;
00203 }
00204 
00205 /// \brief Compute the relative path that names the given file relative to
00206 /// the given directory.
00207 static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
00208                                 const FileEntry *File,
00209                                 SmallString<128> &Result) {
00210   Result.clear();
00211 
00212   StringRef FilePath = File->getDir()->getName();
00213   StringRef Path = FilePath;
00214   while (!Path.empty()) {
00215     if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
00216       if (CurDir == Dir) {
00217         Result = FilePath.substr(Path.size());
00218         llvm::sys::path::append(Result, 
00219                                 llvm::sys::path::filename(File->getName()));
00220         return;
00221       }
00222     }
00223     
00224     Path = llvm::sys::path::parent_path(Path);
00225   }
00226   
00227   Result = File->getName();
00228 }
00229 
00230 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
00231 /// the current file.  This either returns the EOF token or pops a level off
00232 /// the include stack and keeps going.
00233 bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
00234   assert(!CurTokenLexer &&
00235          "Ending a file when currently in a macro!");
00236 
00237   // See if this file had a controlling macro.
00238   if (CurPPLexer) {  // Not ending a macro, ignore it.
00239     if (const IdentifierInfo *ControllingMacro =
00240           CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
00241       // Okay, this has a controlling macro, remember in HeaderFileInfo.
00242       if (const FileEntry *FE =
00243             SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))
00244         HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
00245     }
00246   }
00247 
00248   // Complain about reaching a true EOF within arc_cf_code_audited.
00249   // We don't want to complain about reaching the end of a macro
00250   // instantiation or a _Pragma.
00251   if (PragmaARCCFCodeAuditedLoc.isValid() &&
00252       !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
00253     Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
00254 
00255     // Recover by leaving immediately.
00256     PragmaARCCFCodeAuditedLoc = SourceLocation();
00257   }
00258 
00259   // If this is a #include'd file, pop it off the include stack and continue
00260   // lexing the #includer file.
00261   if (!IncludeMacroStack.empty()) {
00262 
00263     // If we lexed the code-completion file, act as if we reached EOF.
00264     if (isCodeCompletionEnabled() && CurPPLexer &&
00265         SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
00266             CodeCompletionFileLoc) {
00267       if (CurLexer) {
00268         Result.startToken();
00269         CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
00270         CurLexer.reset();
00271       } else {
00272         assert(CurPTHLexer && "Got EOF but no current lexer set!");
00273         CurPTHLexer->getEOF(Result);
00274         CurPTHLexer.reset();
00275       }
00276 
00277       CurPPLexer = 0;
00278       return true;
00279     }
00280 
00281     if (!isEndOfMacro && CurPPLexer &&
00282         SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
00283       // Notify SourceManager to record the number of FileIDs that were created
00284       // during lexing of the #include'd file.
00285       unsigned NumFIDs =
00286           SourceMgr.local_sloc_entry_size() -
00287           CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
00288       SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
00289     }
00290 
00291     FileID ExitedFID;
00292     if (Callbacks && !isEndOfMacro && CurPPLexer)
00293       ExitedFID = CurPPLexer->getFileID();
00294     
00295     // We're done with the #included file.
00296     RemoveTopOfLexerStack();
00297 
00298     // Notify the client, if desired, that we are in a new source file.
00299     if (Callbacks && !isEndOfMacro && CurPPLexer) {
00300       SrcMgr::CharacteristicKind FileType =
00301         SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
00302       Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
00303                              PPCallbacks::ExitFile, FileType, ExitedFID);
00304     }
00305 
00306     // Client should lex another token.
00307     return false;
00308   }
00309 
00310   // If the file ends with a newline, form the EOF token on the newline itself,
00311   // rather than "on the line following it", which doesn't exist.  This makes
00312   // diagnostics relating to the end of file include the last file that the user
00313   // actually typed, which is goodness.
00314   if (CurLexer) {
00315     const char *EndPos = CurLexer->BufferEnd;
00316     if (EndPos != CurLexer->BufferStart &&
00317         (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
00318       --EndPos;
00319 
00320       // Handle \n\r and \r\n:
00321       if (EndPos != CurLexer->BufferStart &&
00322           (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
00323           EndPos[-1] != EndPos[0])
00324         --EndPos;
00325     }
00326 
00327     Result.startToken();
00328     CurLexer->BufferPtr = EndPos;
00329     CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
00330 
00331     if (!isIncrementalProcessingEnabled())
00332       // We're done with lexing.
00333       CurLexer.reset();
00334   } else {
00335     assert(CurPTHLexer && "Got EOF but no current lexer set!");
00336     CurPTHLexer->getEOF(Result);
00337     CurPTHLexer.reset();
00338   }
00339   
00340   if (!isIncrementalProcessingEnabled())
00341     CurPPLexer = 0;
00342 
00343   // This is the end of the top-level file. 'WarnUnusedMacroLocs' has collected
00344   // all macro locations that we need to warn because they are not used.
00345   for (WarnUnusedMacroLocsTy::iterator
00346          I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end(); I!=E; ++I)
00347     Diag(*I, diag::pp_macro_not_used);
00348 
00349   // If we are building a module that has an umbrella header, make sure that
00350   // each of the headers within the directory covered by the umbrella header
00351   // was actually included by the umbrella header.
00352   if (Module *Mod = getCurrentModule()) {
00353     if (Mod->getUmbrellaHeader()) {
00354       SourceLocation StartLoc
00355         = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
00356 
00357       if (getDiagnostics().getDiagnosticLevel(
00358             diag::warn_uncovered_module_header, 
00359             StartLoc) != DiagnosticsEngine::Ignored) {
00360         ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
00361         typedef llvm::sys::fs::recursive_directory_iterator
00362           recursive_directory_iterator;
00363         const DirectoryEntry *Dir = Mod->getUmbrellaDir();
00364         llvm::error_code EC;
00365         for (recursive_directory_iterator Entry(Dir->getName(), EC), End;
00366              Entry != End && !EC; Entry.increment(EC)) {
00367           using llvm::StringSwitch;
00368           
00369           // Check whether this entry has an extension typically associated with
00370           // headers.
00371           if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
00372                  .Cases(".h", ".H", ".hh", ".hpp", true)
00373                  .Default(false))
00374             continue;
00375 
00376           if (const FileEntry *Header = getFileManager().getFile(Entry->path()))
00377             if (!getSourceManager().hasFileInfo(Header)) {
00378               if (!ModMap.isHeaderInUnavailableModule(Header)) {
00379                 // Find the relative path that would access this header.
00380                 SmallString<128> RelativePath;
00381                 computeRelativePath(FileMgr, Dir, Header, RelativePath);              
00382                 Diag(StartLoc, diag::warn_uncovered_module_header)
00383                   << RelativePath;
00384               }
00385             }
00386         }
00387       }
00388     }
00389   }
00390   
00391   return true;
00392 }
00393 
00394 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
00395 /// hits the end of its token stream.
00396 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
00397   assert(CurTokenLexer && !CurPPLexer &&
00398          "Ending a macro when currently in a #include file!");
00399 
00400   if (!MacroExpandingLexersStack.empty() &&
00401       MacroExpandingLexersStack.back().first == CurTokenLexer.get())
00402     removeCachedMacroExpandedTokensOfLastLexer();
00403 
00404   // Delete or cache the now-dead macro expander.
00405   if (NumCachedTokenLexers == TokenLexerCacheSize)
00406     CurTokenLexer.reset();
00407   else
00408     TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
00409 
00410   // Handle this like a #include file being popped off the stack.
00411   return HandleEndOfFile(Result, true);
00412 }
00413 
00414 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
00415 /// lexer stack.  This should only be used in situations where the current
00416 /// state of the top-of-stack lexer is unknown.
00417 void Preprocessor::RemoveTopOfLexerStack() {
00418   assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
00419 
00420   if (CurTokenLexer) {
00421     // Delete or cache the now-dead macro expander.
00422     if (NumCachedTokenLexers == TokenLexerCacheSize)
00423       CurTokenLexer.reset();
00424     else
00425       TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
00426   }
00427 
00428   PopIncludeMacroStack();
00429 }
00430 
00431 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
00432 /// comment (/##/) in microsoft mode, this method handles updating the current
00433 /// state, returning the token on the next source line.
00434 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
00435   assert(CurTokenLexer && !CurPPLexer &&
00436          "Pasted comment can only be formed from macro");
00437 
00438   // We handle this by scanning for the closest real lexer, switching it to
00439   // raw mode and preprocessor mode.  This will cause it to return \n as an
00440   // explicit EOD token.
00441   PreprocessorLexer *FoundLexer = 0;
00442   bool LexerWasInPPMode = false;
00443   for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
00444     IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
00445     if (ISI.ThePPLexer == 0) continue;  // Scan for a real lexer.
00446 
00447     // Once we find a real lexer, mark it as raw mode (disabling macro
00448     // expansions) and preprocessor mode (return EOD).  We know that the lexer
00449     // was *not* in raw mode before, because the macro that the comment came
00450     // from was expanded.  However, it could have already been in preprocessor
00451     // mode (#if COMMENT) in which case we have to return it to that mode and
00452     // return EOD.
00453     FoundLexer = ISI.ThePPLexer;
00454     FoundLexer->LexingRawMode = true;
00455     LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
00456     FoundLexer->ParsingPreprocessorDirective = true;
00457     break;
00458   }
00459 
00460   // Okay, we either found and switched over the lexer, or we didn't find a
00461   // lexer.  In either case, finish off the macro the comment came from, getting
00462   // the next token.
00463   if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
00464 
00465   // Discarding comments as long as we don't have EOF or EOD.  This 'comments
00466   // out' the rest of the line, including any tokens that came from other macros
00467   // that were active, as in:
00468   //  #define submacro a COMMENT b
00469   //    submacro c
00470   // which should lex to 'a' only: 'b' and 'c' should be removed.
00471   while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
00472     Lex(Tok);
00473 
00474   // If we got an eod token, then we successfully found the end of the line.
00475   if (Tok.is(tok::eod)) {
00476     assert(FoundLexer && "Can't get end of line without an active lexer");
00477     // Restore the lexer back to normal mode instead of raw mode.
00478     FoundLexer->LexingRawMode = false;
00479 
00480     // If the lexer was already in preprocessor mode, just return the EOD token
00481     // to finish the preprocessor line.
00482     if (LexerWasInPPMode) return;
00483 
00484     // Otherwise, switch out of PP mode and return the next lexed token.
00485     FoundLexer->ParsingPreprocessorDirective = false;
00486     return Lex(Tok);
00487   }
00488 
00489   // If we got an EOF token, then we reached the end of the token stream but
00490   // didn't find an explicit \n.  This can only happen if there was no lexer
00491   // active (an active lexer would return EOD at EOF if there was no \n in
00492   // preprocessor directive mode), so just return EOF as our token.
00493   assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
00494 }