Home | History | Annotate | Download | only in Lex
      1 //===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
      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 pieces of the Preprocessor interface that manage the
     11 // current lexer stack.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "clang/Lex/Preprocessor.h"
     16 #include "clang/Lex/HeaderSearch.h"
     17 #include "clang/Lex/MacroInfo.h"
     18 #include "clang/Lex/LexDiagnostic.h"
     19 #include "clang/Basic/SourceManager.h"
     20 #include "llvm/Support/MemoryBuffer.h"
     21 using namespace clang;
     22 
     23 PPCallbacks::~PPCallbacks() {}
     24 
     25 //===----------------------------------------------------------------------===//
     26 // Miscellaneous Methods.
     27 //===----------------------------------------------------------------------===//
     28 
     29 /// isInPrimaryFile - Return true if we're in the top-level file, not in a
     30 /// #include.  This looks through macro expansions and active _Pragma lexers.
     31 bool Preprocessor::isInPrimaryFile() const {
     32   if (IsFileLexer())
     33     return IncludeMacroStack.empty();
     34 
     35   // If there are any stacked lexers, we're in a #include.
     36   assert(IsFileLexer(IncludeMacroStack[0]) &&
     37          "Top level include stack isn't our primary lexer?");
     38   for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
     39     if (IsFileLexer(IncludeMacroStack[i]))
     40       return false;
     41   return true;
     42 }
     43 
     44 /// getCurrentLexer - Return the current file lexer being lexed from.  Note
     45 /// that this ignores any potentially active macro expansions and _Pragma
     46 /// expansions going on at the time.
     47 PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
     48   if (IsFileLexer())
     49     return CurPPLexer;
     50 
     51   // Look for a stacked lexer.
     52   for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
     53     const IncludeStackInfo& ISI = IncludeMacroStack[i-1];
     54     if (IsFileLexer(ISI))
     55       return ISI.ThePPLexer;
     56   }
     57   return 0;
     58 }
     59 
     60 
     61 //===----------------------------------------------------------------------===//
     62 // Methods for Entering and Callbacks for leaving various contexts
     63 //===----------------------------------------------------------------------===//
     64 
     65 /// EnterSourceFile - Add a source file to the top of the include stack and
     66 /// start lexing tokens from it instead of the current buffer.
     67 void Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
     68                                    SourceLocation Loc) {
     69   assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!");
     70   ++NumEnteredSourceFiles;
     71 
     72   if (MaxIncludeStackDepth < IncludeMacroStack.size())
     73     MaxIncludeStackDepth = IncludeMacroStack.size();
     74 
     75   if (PTH) {
     76     if (PTHLexer *PL = PTH->CreateLexer(FID)) {
     77       EnterSourceFileWithPTH(PL, CurDir);
     78       return;
     79     }
     80   }
     81 
     82   // Get the MemoryBuffer for this FID, if it fails, we fail.
     83   bool Invalid = false;
     84   const llvm::MemoryBuffer *InputFile =
     85     getSourceManager().getBuffer(FID, Loc, &Invalid);
     86   if (Invalid) {
     87     SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
     88     Diag(Loc, diag::err_pp_error_opening_file)
     89       << std::string(SourceMgr.getBufferName(FileStart)) << "";
     90     return;
     91   }
     92 
     93   EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
     94   return;
     95 }
     96 
     97 /// EnterSourceFileWithLexer - Add a source file to the top of the include stack
     98 ///  and start lexing tokens from it instead of the current buffer.
     99 void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
    100                                             const DirectoryLookup *CurDir) {
    101 
    102   // Add the current lexer to the include stack.
    103   if (CurPPLexer || CurTokenLexer)
    104     PushIncludeMacroStack();
    105 
    106   CurLexer.reset(TheLexer);
    107   CurPPLexer = TheLexer;
    108   CurDirLookup = CurDir;
    109 
    110   // Notify the client, if desired, that we are in a new source file.
    111   if (Callbacks && !CurLexer->Is_PragmaLexer) {
    112     SrcMgr::CharacteristicKind FileType =
    113        SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
    114 
    115     Callbacks->FileChanged(CurLexer->getFileLoc(),
    116                            PPCallbacks::EnterFile, FileType);
    117   }
    118 }
    119 
    120 /// EnterSourceFileWithPTH - Add a source file to the top of the include stack
    121 /// and start getting tokens from it using the PTH cache.
    122 void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
    123                                           const DirectoryLookup *CurDir) {
    124 
    125   if (CurPPLexer || CurTokenLexer)
    126     PushIncludeMacroStack();
    127 
    128   CurDirLookup = CurDir;
    129   CurPTHLexer.reset(PL);
    130   CurPPLexer = CurPTHLexer.get();
    131 
    132   // Notify the client, if desired, that we are in a new source file.
    133   if (Callbacks) {
    134     FileID FID = CurPPLexer->getFileID();
    135     SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
    136     SrcMgr::CharacteristicKind FileType =
    137       SourceMgr.getFileCharacteristic(EnterLoc);
    138     Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
    139   }
    140 }
    141 
    142 /// EnterMacro - Add a Macro to the top of the include stack and start lexing
    143 /// tokens from it instead of the current buffer.
    144 void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
    145                               MacroArgs *Args) {
    146   PushIncludeMacroStack();
    147   CurDirLookup = 0;
    148 
    149   if (NumCachedTokenLexers == 0) {
    150     CurTokenLexer.reset(new TokenLexer(Tok, ILEnd, Args, *this));
    151   } else {
    152     CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
    153     CurTokenLexer->Init(Tok, ILEnd, Args);
    154   }
    155 }
    156 
    157 /// EnterTokenStream - Add a "macro" context to the top of the include stack,
    158 /// which will cause the lexer to start returning the specified tokens.
    159 ///
    160 /// If DisableMacroExpansion is true, tokens lexed from the token stream will
    161 /// not be subject to further macro expansion.  Otherwise, these tokens will
    162 /// be re-macro-expanded when/if expansion is enabled.
    163 ///
    164 /// If OwnsTokens is false, this method assumes that the specified stream of
    165 /// tokens has a permanent owner somewhere, so they do not need to be copied.
    166 /// If it is true, it assumes the array of tokens is allocated with new[] and
    167 /// must be freed.
    168 ///
    169 void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
    170                                     bool DisableMacroExpansion,
    171                                     bool OwnsTokens) {
    172   // Save our current state.
    173   PushIncludeMacroStack();
    174   CurDirLookup = 0;
    175 
    176   // Create a macro expander to expand from the specified token stream.
    177   if (NumCachedTokenLexers == 0) {
    178     CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion,
    179                                        OwnsTokens, *this));
    180   } else {
    181     CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
    182     CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
    183   }
    184 }
    185 
    186 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
    187 /// the current file.  This either returns the EOF token or pops a level off
    188 /// the include stack and keeps going.
    189 bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
    190   assert(!CurTokenLexer &&
    191          "Ending a file when currently in a macro!");
    192 
    193   // See if this file had a controlling macro.
    194   if (CurPPLexer) {  // Not ending a macro, ignore it.
    195     if (const IdentifierInfo *ControllingMacro =
    196           CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
    197       // Okay, this has a controlling macro, remember in HeaderFileInfo.
    198       if (const FileEntry *FE =
    199             SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))
    200         HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
    201     }
    202   }
    203 
    204   // If this is a #include'd file, pop it off the include stack and continue
    205   // lexing the #includer file.
    206   if (!IncludeMacroStack.empty()) {
    207     // We're done with the #included file.
    208     RemoveTopOfLexerStack();
    209 
    210     // Notify the client, if desired, that we are in a new source file.
    211     if (Callbacks && !isEndOfMacro && CurPPLexer) {
    212       SrcMgr::CharacteristicKind FileType =
    213         SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
    214       Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
    215                              PPCallbacks::ExitFile, FileType);
    216     }
    217 
    218     // Client should lex another token.
    219     return false;
    220   }
    221 
    222   // If the file ends with a newline, form the EOF token on the newline itself,
    223   // rather than "on the line following it", which doesn't exist.  This makes
    224   // diagnostics relating to the end of file include the last file that the user
    225   // actually typed, which is goodness.
    226   if (CurLexer) {
    227     const char *EndPos = CurLexer->BufferEnd;
    228     if (EndPos != CurLexer->BufferStart &&
    229         (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
    230       --EndPos;
    231 
    232       // Handle \n\r and \r\n:
    233       if (EndPos != CurLexer->BufferStart &&
    234           (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
    235           EndPos[-1] != EndPos[0])
    236         --EndPos;
    237     }
    238 
    239     Result.startToken();
    240     CurLexer->BufferPtr = EndPos;
    241     CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
    242 
    243     // We're done with the #included file.
    244     CurLexer.reset();
    245   } else {
    246     assert(CurPTHLexer && "Got EOF but no current lexer set!");
    247     CurPTHLexer->getEOF(Result);
    248     CurPTHLexer.reset();
    249   }
    250 
    251   CurPPLexer = 0;
    252 
    253   // This is the end of the top-level file. 'WarnUnusedMacroLocs' has collected
    254   // all macro locations that we need to warn because they are not used.
    255   for (WarnUnusedMacroLocsTy::iterator
    256          I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end(); I!=E; ++I)
    257     Diag(*I, diag::pp_macro_not_used);
    258 
    259   return true;
    260 }
    261 
    262 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
    263 /// hits the end of its token stream.
    264 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
    265   assert(CurTokenLexer && !CurPPLexer &&
    266          "Ending a macro when currently in a #include file!");
    267 
    268   if (!MacroExpandingLexersStack.empty() &&
    269       MacroExpandingLexersStack.back().first == CurTokenLexer.get())
    270     removeCachedMacroExpandedTokensOfLastLexer();
    271 
    272   // Delete or cache the now-dead macro expander.
    273   if (NumCachedTokenLexers == TokenLexerCacheSize)
    274     CurTokenLexer.reset();
    275   else
    276     TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
    277 
    278   // Handle this like a #include file being popped off the stack.
    279   return HandleEndOfFile(Result, true);
    280 }
    281 
    282 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
    283 /// lexer stack.  This should only be used in situations where the current
    284 /// state of the top-of-stack lexer is unknown.
    285 void Preprocessor::RemoveTopOfLexerStack() {
    286   assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
    287 
    288   if (CurTokenLexer) {
    289     // Delete or cache the now-dead macro expander.
    290     if (NumCachedTokenLexers == TokenLexerCacheSize)
    291       CurTokenLexer.reset();
    292     else
    293       TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
    294   }
    295 
    296   PopIncludeMacroStack();
    297 }
    298 
    299 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
    300 /// comment (/##/) in microsoft mode, this method handles updating the current
    301 /// state, returning the token on the next source line.
    302 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
    303   assert(CurTokenLexer && !CurPPLexer &&
    304          "Pasted comment can only be formed from macro");
    305 
    306   // We handle this by scanning for the closest real lexer, switching it to
    307   // raw mode and preprocessor mode.  This will cause it to return \n as an
    308   // explicit EOD token.
    309   PreprocessorLexer *FoundLexer = 0;
    310   bool LexerWasInPPMode = false;
    311   for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
    312     IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
    313     if (ISI.ThePPLexer == 0) continue;  // Scan for a real lexer.
    314 
    315     // Once we find a real lexer, mark it as raw mode (disabling macro
    316     // expansions) and preprocessor mode (return EOD).  We know that the lexer
    317     // was *not* in raw mode before, because the macro that the comment came
    318     // from was expanded.  However, it could have already been in preprocessor
    319     // mode (#if COMMENT) in which case we have to return it to that mode and
    320     // return EOD.
    321     FoundLexer = ISI.ThePPLexer;
    322     FoundLexer->LexingRawMode = true;
    323     LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
    324     FoundLexer->ParsingPreprocessorDirective = true;
    325     break;
    326   }
    327 
    328   // Okay, we either found and switched over the lexer, or we didn't find a
    329   // lexer.  In either case, finish off the macro the comment came from, getting
    330   // the next token.
    331   if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
    332 
    333   // Discarding comments as long as we don't have EOF or EOD.  This 'comments
    334   // out' the rest of the line, including any tokens that came from other macros
    335   // that were active, as in:
    336   //  #define submacro a COMMENT b
    337   //    submacro c
    338   // which should lex to 'a' only: 'b' and 'c' should be removed.
    339   while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
    340     Lex(Tok);
    341 
    342   // If we got an eod token, then we successfully found the end of the line.
    343   if (Tok.is(tok::eod)) {
    344     assert(FoundLexer && "Can't get end of line without an active lexer");
    345     // Restore the lexer back to normal mode instead of raw mode.
    346     FoundLexer->LexingRawMode = false;
    347 
    348     // If the lexer was already in preprocessor mode, just return the EOD token
    349     // to finish the preprocessor line.
    350     if (LexerWasInPPMode) return;
    351 
    352     // Otherwise, switch out of PP mode and return the next lexed token.
    353     FoundLexer->ParsingPreprocessorDirective = false;
    354     return Lex(Tok);
    355   }
    356 
    357   // If we got an EOF token, then we reached the end of the token stream but
    358   // didn't find an explicit \n.  This can only happen if there was no lexer
    359   // active (an active lexer would return EOD at EOF if there was no \n in
    360   // preprocessor directive mode), so just return EOF as our token.
    361   assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
    362 }
    363