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 if (isCodeCompletionEnabled() && 94 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) { 95 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID); 96 CodeCompletionLoc = 97 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset); 98 } 99 100 EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir); 101 return; 102 } 103 104 /// EnterSourceFileWithLexer - Add a source file to the top of the include stack 105 /// and start lexing tokens from it instead of the current buffer. 106 void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer, 107 const DirectoryLookup *CurDir) { 108 109 // Add the current lexer to the include stack. 110 if (CurPPLexer || CurTokenLexer) 111 PushIncludeMacroStack(); 112 113 CurLexer.reset(TheLexer); 114 CurPPLexer = TheLexer; 115 CurDirLookup = CurDir; 116 if (CurLexerKind != CLK_LexAfterModuleImport) 117 CurLexerKind = CLK_Lexer; 118 119 // Notify the client, if desired, that we are in a new source file. 120 if (Callbacks && !CurLexer->Is_PragmaLexer) { 121 SrcMgr::CharacteristicKind FileType = 122 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc()); 123 124 Callbacks->FileChanged(CurLexer->getFileLoc(), 125 PPCallbacks::EnterFile, FileType); 126 } 127 } 128 129 /// EnterSourceFileWithPTH - Add a source file to the top of the include stack 130 /// and start getting tokens from it using the PTH cache. 131 void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL, 132 const DirectoryLookup *CurDir) { 133 134 if (CurPPLexer || CurTokenLexer) 135 PushIncludeMacroStack(); 136 137 CurDirLookup = CurDir; 138 CurPTHLexer.reset(PL); 139 CurPPLexer = CurPTHLexer.get(); 140 if (CurLexerKind != CLK_LexAfterModuleImport) 141 CurLexerKind = CLK_PTHLexer; 142 143 // Notify the client, if desired, that we are in a new source file. 144 if (Callbacks) { 145 FileID FID = CurPPLexer->getFileID(); 146 SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID); 147 SrcMgr::CharacteristicKind FileType = 148 SourceMgr.getFileCharacteristic(EnterLoc); 149 Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType); 150 } 151 } 152 153 /// EnterMacro - Add a Macro to the top of the include stack and start lexing 154 /// tokens from it instead of the current buffer. 155 void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd, 156 MacroArgs *Args) { 157 PushIncludeMacroStack(); 158 CurDirLookup = 0; 159 160 if (NumCachedTokenLexers == 0) { 161 CurTokenLexer.reset(new TokenLexer(Tok, ILEnd, Args, *this)); 162 } else { 163 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]); 164 CurTokenLexer->Init(Tok, ILEnd, Args); 165 } 166 if (CurLexerKind != CLK_LexAfterModuleImport) 167 CurLexerKind = CLK_TokenLexer; 168 } 169 170 /// EnterTokenStream - Add a "macro" context to the top of the include stack, 171 /// which will cause the lexer to start returning the specified tokens. 172 /// 173 /// If DisableMacroExpansion is true, tokens lexed from the token stream will 174 /// not be subject to further macro expansion. Otherwise, these tokens will 175 /// be re-macro-expanded when/if expansion is enabled. 176 /// 177 /// If OwnsTokens is false, this method assumes that the specified stream of 178 /// tokens has a permanent owner somewhere, so they do not need to be copied. 179 /// If it is true, it assumes the array of tokens is allocated with new[] and 180 /// must be freed. 181 /// 182 void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks, 183 bool DisableMacroExpansion, 184 bool OwnsTokens) { 185 // Save our current state. 186 PushIncludeMacroStack(); 187 CurDirLookup = 0; 188 189 // Create a macro expander to expand from the specified token stream. 190 if (NumCachedTokenLexers == 0) { 191 CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion, 192 OwnsTokens, *this)); 193 } else { 194 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]); 195 CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens); 196 } 197 if (CurLexerKind != CLK_LexAfterModuleImport) 198 CurLexerKind = CLK_TokenLexer; 199 } 200 201 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of 202 /// the current file. This either returns the EOF token or pops a level off 203 /// the include stack and keeps going. 204 bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) { 205 assert(!CurTokenLexer && 206 "Ending a file when currently in a macro!"); 207 208 // See if this file had a controlling macro. 209 if (CurPPLexer) { // Not ending a macro, ignore it. 210 if (const IdentifierInfo *ControllingMacro = 211 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) { 212 // Okay, this has a controlling macro, remember in HeaderFileInfo. 213 if (const FileEntry *FE = 214 SourceMgr.getFileEntryForID(CurPPLexer->getFileID())) 215 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro); 216 } 217 } 218 219 // Complain about reaching an EOF within arc_cf_code_audited. 220 if (PragmaARCCFCodeAuditedLoc.isValid()) { 221 Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited); 222 223 // Recover by leaving immediately. 224 PragmaARCCFCodeAuditedLoc = SourceLocation(); 225 } 226 227 // If this is a #include'd file, pop it off the include stack and continue 228 // lexing the #includer file. 229 if (!IncludeMacroStack.empty()) { 230 231 // If we lexed the code-completion file, act as if we reached EOF. 232 if (isCodeCompletionEnabled() && CurPPLexer && 233 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) == 234 CodeCompletionFileLoc) { 235 if (CurLexer) { 236 Result.startToken(); 237 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof); 238 CurLexer.reset(); 239 } else { 240 assert(CurPTHLexer && "Got EOF but no current lexer set!"); 241 CurPTHLexer->getEOF(Result); 242 CurPTHLexer.reset(); 243 } 244 245 CurPPLexer = 0; 246 return true; 247 } 248 249 if (!isEndOfMacro && CurPPLexer && 250 SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) { 251 // Notify SourceManager to record the number of FileIDs that were created 252 // during lexing of the #include'd file. 253 unsigned NumFIDs = 254 SourceMgr.local_sloc_entry_size() - 255 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/; 256 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs); 257 } 258 259 // We're done with the #included file. 260 RemoveTopOfLexerStack(); 261 262 // Notify the client, if desired, that we are in a new source file. 263 if (Callbacks && !isEndOfMacro && CurPPLexer) { 264 SrcMgr::CharacteristicKind FileType = 265 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation()); 266 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), 267 PPCallbacks::ExitFile, FileType); 268 } 269 270 // Client should lex another token. 271 return false; 272 } 273 274 // If the file ends with a newline, form the EOF token on the newline itself, 275 // rather than "on the line following it", which doesn't exist. This makes 276 // diagnostics relating to the end of file include the last file that the user 277 // actually typed, which is goodness. 278 if (CurLexer) { 279 const char *EndPos = CurLexer->BufferEnd; 280 if (EndPos != CurLexer->BufferStart && 281 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) { 282 --EndPos; 283 284 // Handle \n\r and \r\n: 285 if (EndPos != CurLexer->BufferStart && 286 (EndPos[-1] == '\n' || EndPos[-1] == '\r') && 287 EndPos[-1] != EndPos[0]) 288 --EndPos; 289 } 290 291 Result.startToken(); 292 CurLexer->BufferPtr = EndPos; 293 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof); 294 295 // We're done with the #included file. 296 CurLexer.reset(); 297 } else { 298 assert(CurPTHLexer && "Got EOF but no current lexer set!"); 299 CurPTHLexer->getEOF(Result); 300 CurPTHLexer.reset(); 301 } 302 303 CurPPLexer = 0; 304 305 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has collected 306 // all macro locations that we need to warn because they are not used. 307 for (WarnUnusedMacroLocsTy::iterator 308 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end(); I!=E; ++I) 309 Diag(*I, diag::pp_macro_not_used); 310 311 return true; 312 } 313 314 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer 315 /// hits the end of its token stream. 316 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) { 317 assert(CurTokenLexer && !CurPPLexer && 318 "Ending a macro when currently in a #include file!"); 319 320 if (!MacroExpandingLexersStack.empty() && 321 MacroExpandingLexersStack.back().first == CurTokenLexer.get()) 322 removeCachedMacroExpandedTokensOfLastLexer(); 323 324 // Delete or cache the now-dead macro expander. 325 if (NumCachedTokenLexers == TokenLexerCacheSize) 326 CurTokenLexer.reset(); 327 else 328 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take(); 329 330 // Handle this like a #include file being popped off the stack. 331 return HandleEndOfFile(Result, true); 332 } 333 334 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the 335 /// lexer stack. This should only be used in situations where the current 336 /// state of the top-of-stack lexer is unknown. 337 void Preprocessor::RemoveTopOfLexerStack() { 338 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load"); 339 340 if (CurTokenLexer) { 341 // Delete or cache the now-dead macro expander. 342 if (NumCachedTokenLexers == TokenLexerCacheSize) 343 CurTokenLexer.reset(); 344 else 345 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take(); 346 } 347 348 PopIncludeMacroStack(); 349 } 350 351 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a 352 /// comment (/##/) in microsoft mode, this method handles updating the current 353 /// state, returning the token on the next source line. 354 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) { 355 assert(CurTokenLexer && !CurPPLexer && 356 "Pasted comment can only be formed from macro"); 357 358 // We handle this by scanning for the closest real lexer, switching it to 359 // raw mode and preprocessor mode. This will cause it to return \n as an 360 // explicit EOD token. 361 PreprocessorLexer *FoundLexer = 0; 362 bool LexerWasInPPMode = false; 363 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { 364 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1); 365 if (ISI.ThePPLexer == 0) continue; // Scan for a real lexer. 366 367 // Once we find a real lexer, mark it as raw mode (disabling macro 368 // expansions) and preprocessor mode (return EOD). We know that the lexer 369 // was *not* in raw mode before, because the macro that the comment came 370 // from was expanded. However, it could have already been in preprocessor 371 // mode (#if COMMENT) in which case we have to return it to that mode and 372 // return EOD. 373 FoundLexer = ISI.ThePPLexer; 374 FoundLexer->LexingRawMode = true; 375 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective; 376 FoundLexer->ParsingPreprocessorDirective = true; 377 break; 378 } 379 380 // Okay, we either found and switched over the lexer, or we didn't find a 381 // lexer. In either case, finish off the macro the comment came from, getting 382 // the next token. 383 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok); 384 385 // Discarding comments as long as we don't have EOF or EOD. This 'comments 386 // out' the rest of the line, including any tokens that came from other macros 387 // that were active, as in: 388 // #define submacro a COMMENT b 389 // submacro c 390 // which should lex to 'a' only: 'b' and 'c' should be removed. 391 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof)) 392 Lex(Tok); 393 394 // If we got an eod token, then we successfully found the end of the line. 395 if (Tok.is(tok::eod)) { 396 assert(FoundLexer && "Can't get end of line without an active lexer"); 397 // Restore the lexer back to normal mode instead of raw mode. 398 FoundLexer->LexingRawMode = false; 399 400 // If the lexer was already in preprocessor mode, just return the EOD token 401 // to finish the preprocessor line. 402 if (LexerWasInPPMode) return; 403 404 // Otherwise, switch out of PP mode and return the next lexed token. 405 FoundLexer->ParsingPreprocessorDirective = false; 406 return Lex(Tok); 407 } 408 409 // If we got an EOF token, then we reached the end of the token stream but 410 // didn't find an explicit \n. This can only happen if there was no lexer 411 // active (an active lexer would return EOD at EOF if there was no \n in 412 // preprocessor directive mode), so just return EOF as our token. 413 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode"); 414 } 415