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/Basic/FileManager.h" 17 #include "clang/Basic/SourceManager.h" 18 #include "clang/Lex/HeaderSearch.h" 19 #include "clang/Lex/LexDiagnostic.h" 20 #include "clang/Lex/MacroInfo.h" 21 #include "llvm/ADT/StringSwitch.h" 22 #include "llvm/Support/FileSystem.h" 23 #include "llvm/Support/MemoryBuffer.h" 24 #include "llvm/Support/Path.h" 25 using namespace clang; 26 27 PPCallbacks::~PPCallbacks() {} 28 29 //===----------------------------------------------------------------------===// 30 // Miscellaneous Methods. 31 //===----------------------------------------------------------------------===// 32 33 /// isInPrimaryFile - Return true if we're in the top-level file, not in a 34 /// \#include. This looks through macro expansions and active _Pragma lexers. 35 bool Preprocessor::isInPrimaryFile() const { 36 if (IsFileLexer()) 37 return IncludeMacroStack.empty(); 38 39 // If there are any stacked lexers, we're in a #include. 40 assert(IsFileLexer(IncludeMacroStack[0]) && 41 "Top level include stack isn't our primary lexer?"); 42 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i) 43 if (IsFileLexer(IncludeMacroStack[i])) 44 return false; 45 return true; 46 } 47 48 /// getCurrentLexer - Return the current file lexer being lexed from. Note 49 /// that this ignores any potentially active macro expansions and _Pragma 50 /// expansions going on at the time. 51 PreprocessorLexer *Preprocessor::getCurrentFileLexer() const { 52 if (IsFileLexer()) 53 return CurPPLexer; 54 55 // Look for a stacked lexer. 56 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) { 57 const IncludeStackInfo& ISI = IncludeMacroStack[i-1]; 58 if (IsFileLexer(ISI)) 59 return ISI.ThePPLexer; 60 } 61 return 0; 62 } 63 64 65 //===----------------------------------------------------------------------===// 66 // Methods for Entering and Callbacks for leaving various contexts 67 //===----------------------------------------------------------------------===// 68 69 /// EnterSourceFile - Add a source file to the top of the include stack and 70 /// start lexing tokens from it instead of the current buffer. 71 void Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir, 72 SourceLocation Loc) { 73 assert(!CurTokenLexer && "Cannot #include a file inside a macro!"); 74 ++NumEnteredSourceFiles; 75 76 if (MaxIncludeStackDepth < IncludeMacroStack.size()) 77 MaxIncludeStackDepth = IncludeMacroStack.size(); 78 79 if (PTH) { 80 if (PTHLexer *PL = PTH->CreateLexer(FID)) { 81 EnterSourceFileWithPTH(PL, CurDir); 82 return; 83 } 84 } 85 86 // Get the MemoryBuffer for this FID, if it fails, we fail. 87 bool Invalid = false; 88 const llvm::MemoryBuffer *InputFile = 89 getSourceManager().getBuffer(FID, Loc, &Invalid); 90 if (Invalid) { 91 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID); 92 Diag(Loc, diag::err_pp_error_opening_file) 93 << std::string(SourceMgr.getBufferName(FileStart)) << ""; 94 return; 95 } 96 97 if (isCodeCompletionEnabled() && 98 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) { 99 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID); 100 CodeCompletionLoc = 101 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset); 102 } 103 104 EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir); 105 return; 106 } 107 108 /// EnterSourceFileWithLexer - Add a source file to the top of the include stack 109 /// and start lexing tokens from it instead of the current buffer. 110 void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer, 111 const DirectoryLookup *CurDir) { 112 113 // Add the current lexer to the include stack. 114 if (CurPPLexer || CurTokenLexer) 115 PushIncludeMacroStack(); 116 117 CurLexer.reset(TheLexer); 118 CurPPLexer = TheLexer; 119 CurDirLookup = CurDir; 120 if (CurLexerKind != CLK_LexAfterModuleImport) 121 CurLexerKind = CLK_Lexer; 122 123 // Notify the client, if desired, that we are in a new source file. 124 if (Callbacks && !CurLexer->Is_PragmaLexer) { 125 SrcMgr::CharacteristicKind FileType = 126 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc()); 127 128 Callbacks->FileChanged(CurLexer->getFileLoc(), 129 PPCallbacks::EnterFile, FileType); 130 } 131 } 132 133 /// EnterSourceFileWithPTH - Add a source file to the top of the include stack 134 /// and start getting tokens from it using the PTH cache. 135 void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL, 136 const DirectoryLookup *CurDir) { 137 138 if (CurPPLexer || CurTokenLexer) 139 PushIncludeMacroStack(); 140 141 CurDirLookup = CurDir; 142 CurPTHLexer.reset(PL); 143 CurPPLexer = CurPTHLexer.get(); 144 if (CurLexerKind != CLK_LexAfterModuleImport) 145 CurLexerKind = CLK_PTHLexer; 146 147 // Notify the client, if desired, that we are in a new source file. 148 if (Callbacks) { 149 FileID FID = CurPPLexer->getFileID(); 150 SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID); 151 SrcMgr::CharacteristicKind FileType = 152 SourceMgr.getFileCharacteristic(EnterLoc); 153 Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType); 154 } 155 } 156 157 /// EnterMacro - Add a Macro to the top of the include stack and start lexing 158 /// tokens from it instead of the current buffer. 159 void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd, 160 MacroInfo *Macro, MacroArgs *Args) { 161 TokenLexer *TokLexer; 162 if (NumCachedTokenLexers == 0) { 163 TokLexer = new TokenLexer(Tok, ILEnd, Macro, Args, *this); 164 } else { 165 TokLexer = TokenLexerCache[--NumCachedTokenLexers]; 166 TokLexer->Init(Tok, ILEnd, Macro, Args); 167 } 168 169 PushIncludeMacroStack(); 170 CurDirLookup = 0; 171 CurTokenLexer.reset(TokLexer); 172 if (CurLexerKind != CLK_LexAfterModuleImport) 173 CurLexerKind = CLK_TokenLexer; 174 } 175 176 /// EnterTokenStream - Add a "macro" context to the top of the include stack, 177 /// which will cause the lexer to start returning the specified tokens. 178 /// 179 /// If DisableMacroExpansion is true, tokens lexed from the token stream will 180 /// not be subject to further macro expansion. Otherwise, these tokens will 181 /// be re-macro-expanded when/if expansion is enabled. 182 /// 183 /// If OwnsTokens is false, this method assumes that the specified stream of 184 /// tokens has a permanent owner somewhere, so they do not need to be copied. 185 /// If it is true, it assumes the array of tokens is allocated with new[] and 186 /// must be freed. 187 /// 188 void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks, 189 bool DisableMacroExpansion, 190 bool OwnsTokens) { 191 // Create a macro expander to expand from the specified token stream. 192 TokenLexer *TokLexer; 193 if (NumCachedTokenLexers == 0) { 194 TokLexer = new TokenLexer(Toks, NumToks, DisableMacroExpansion, 195 OwnsTokens, *this); 196 } else { 197 TokLexer = TokenLexerCache[--NumCachedTokenLexers]; 198 TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens); 199 } 200 201 // Save our current state. 202 PushIncludeMacroStack(); 203 CurDirLookup = 0; 204 CurTokenLexer.reset(TokLexer); 205 if (CurLexerKind != CLK_LexAfterModuleImport) 206 CurLexerKind = CLK_TokenLexer; 207 } 208 209 /// \brief Compute the relative path that names the given file relative to 210 /// the given directory. 211 static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir, 212 const FileEntry *File, 213 SmallString<128> &Result) { 214 Result.clear(); 215 216 StringRef FilePath = File->getDir()->getName(); 217 StringRef Path = FilePath; 218 while (!Path.empty()) { 219 if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) { 220 if (CurDir == Dir) { 221 Result = FilePath.substr(Path.size()); 222 llvm::sys::path::append(Result, 223 llvm::sys::path::filename(File->getName())); 224 return; 225 } 226 } 227 228 Path = llvm::sys::path::parent_path(Path); 229 } 230 231 Result = File->getName(); 232 } 233 234 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of 235 /// the current file. This either returns the EOF token or pops a level off 236 /// the include stack and keeps going. 237 bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) { 238 assert(!CurTokenLexer && 239 "Ending a file when currently in a macro!"); 240 241 // See if this file had a controlling macro. 242 if (CurPPLexer) { // Not ending a macro, ignore it. 243 if (const IdentifierInfo *ControllingMacro = 244 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) { 245 // Okay, this has a controlling macro, remember in HeaderFileInfo. 246 if (const FileEntry *FE = 247 SourceMgr.getFileEntryForID(CurPPLexer->getFileID())) { 248 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro); 249 if (const IdentifierInfo *DefinedMacro = 250 CurPPLexer->MIOpt.GetDefinedMacro()) { 251 if (!ControllingMacro->hasMacroDefinition() && 252 DefinedMacro != ControllingMacro && 253 HeaderInfo.FirstTimeLexingFile(FE)) { 254 // Emit a warning for a bad header guard. 255 Diag(CurPPLexer->MIOpt.GetMacroLocation(), 256 diag::warn_header_guard) 257 << CurPPLexer->MIOpt.GetMacroLocation() 258 << ControllingMacro; 259 Diag(CurPPLexer->MIOpt.GetDefinedLocation(), 260 diag::note_header_guard) 261 << CurPPLexer->MIOpt.GetDefinedLocation() 262 << DefinedMacro 263 << ControllingMacro 264 << FixItHint::CreateReplacement( 265 CurPPLexer->MIOpt.GetDefinedLocation(), 266 ControllingMacro->getName()); 267 } 268 } 269 } 270 } 271 } 272 273 // Complain about reaching a true EOF within arc_cf_code_audited. 274 // We don't want to complain about reaching the end of a macro 275 // instantiation or a _Pragma. 276 if (PragmaARCCFCodeAuditedLoc.isValid() && 277 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) { 278 Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited); 279 280 // Recover by leaving immediately. 281 PragmaARCCFCodeAuditedLoc = SourceLocation(); 282 } 283 284 // If this is a #include'd file, pop it off the include stack and continue 285 // lexing the #includer file. 286 if (!IncludeMacroStack.empty()) { 287 288 // If we lexed the code-completion file, act as if we reached EOF. 289 if (isCodeCompletionEnabled() && CurPPLexer && 290 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) == 291 CodeCompletionFileLoc) { 292 if (CurLexer) { 293 Result.startToken(); 294 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof); 295 CurLexer.reset(); 296 } else { 297 assert(CurPTHLexer && "Got EOF but no current lexer set!"); 298 CurPTHLexer->getEOF(Result); 299 CurPTHLexer.reset(); 300 } 301 302 CurPPLexer = 0; 303 return true; 304 } 305 306 if (!isEndOfMacro && CurPPLexer && 307 SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) { 308 // Notify SourceManager to record the number of FileIDs that were created 309 // during lexing of the #include'd file. 310 unsigned NumFIDs = 311 SourceMgr.local_sloc_entry_size() - 312 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/; 313 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs); 314 } 315 316 FileID ExitedFID; 317 if (Callbacks && !isEndOfMacro && CurPPLexer) 318 ExitedFID = CurPPLexer->getFileID(); 319 320 // We're done with the #included file. 321 RemoveTopOfLexerStack(); 322 323 // Notify the client, if desired, that we are in a new source file. 324 if (Callbacks && !isEndOfMacro && CurPPLexer) { 325 SrcMgr::CharacteristicKind FileType = 326 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation()); 327 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), 328 PPCallbacks::ExitFile, FileType, ExitedFID); 329 } 330 331 // Client should lex another token. 332 return false; 333 } 334 335 // If the file ends with a newline, form the EOF token on the newline itself, 336 // rather than "on the line following it", which doesn't exist. This makes 337 // diagnostics relating to the end of file include the last file that the user 338 // actually typed, which is goodness. 339 if (CurLexer) { 340 const char *EndPos = CurLexer->BufferEnd; 341 if (EndPos != CurLexer->BufferStart && 342 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) { 343 --EndPos; 344 345 // Handle \n\r and \r\n: 346 if (EndPos != CurLexer->BufferStart && 347 (EndPos[-1] == '\n' || EndPos[-1] == '\r') && 348 EndPos[-1] != EndPos[0]) 349 --EndPos; 350 } 351 352 Result.startToken(); 353 CurLexer->BufferPtr = EndPos; 354 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof); 355 356 if (isCodeCompletionEnabled()) { 357 // Inserting the code-completion point increases the source buffer by 1, 358 // but the main FileID was created before inserting the point. 359 // Compensate by reducing the EOF location by 1, otherwise the location 360 // will point to the next FileID. 361 // FIXME: This is hacky, the code-completion point should probably be 362 // inserted before the main FileID is created. 363 if (CurLexer->getFileLoc() == CodeCompletionFileLoc) 364 Result.setLocation(Result.getLocation().getLocWithOffset(-1)); 365 } 366 367 if (!isIncrementalProcessingEnabled()) 368 // We're done with lexing. 369 CurLexer.reset(); 370 } else { 371 assert(CurPTHLexer && "Got EOF but no current lexer set!"); 372 CurPTHLexer->getEOF(Result); 373 CurPTHLexer.reset(); 374 } 375 376 if (!isIncrementalProcessingEnabled()) 377 CurPPLexer = 0; 378 379 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has collected 380 // all macro locations that we need to warn because they are not used. 381 for (WarnUnusedMacroLocsTy::iterator 382 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end(); I!=E; ++I) 383 Diag(*I, diag::pp_macro_not_used); 384 385 // If we are building a module that has an umbrella header, make sure that 386 // each of the headers within the directory covered by the umbrella header 387 // was actually included by the umbrella header. 388 if (Module *Mod = getCurrentModule()) { 389 if (Mod->getUmbrellaHeader()) { 390 SourceLocation StartLoc 391 = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 392 393 if (getDiagnostics().getDiagnosticLevel( 394 diag::warn_uncovered_module_header, 395 StartLoc) != DiagnosticsEngine::Ignored) { 396 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap(); 397 typedef llvm::sys::fs::recursive_directory_iterator 398 recursive_directory_iterator; 399 const DirectoryEntry *Dir = Mod->getUmbrellaDir(); 400 llvm::error_code EC; 401 for (recursive_directory_iterator Entry(Dir->getName(), EC), End; 402 Entry != End && !EC; Entry.increment(EC)) { 403 using llvm::StringSwitch; 404 405 // Check whether this entry has an extension typically associated with 406 // headers. 407 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path())) 408 .Cases(".h", ".H", ".hh", ".hpp", true) 409 .Default(false)) 410 continue; 411 412 if (const FileEntry *Header = getFileManager().getFile(Entry->path())) 413 if (!getSourceManager().hasFileInfo(Header)) { 414 if (!ModMap.isHeaderInUnavailableModule(Header)) { 415 // Find the relative path that would access this header. 416 SmallString<128> RelativePath; 417 computeRelativePath(FileMgr, Dir, Header, RelativePath); 418 Diag(StartLoc, diag::warn_uncovered_module_header) 419 << Mod->getFullModuleName() << RelativePath; 420 } 421 } 422 } 423 } 424 } 425 426 // Check whether there are any headers that were included, but not 427 // mentioned at all in the module map. Such headers 428 SourceLocation StartLoc 429 = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 430 if (getDiagnostics().getDiagnosticLevel(diag::warn_forgotten_module_header, 431 StartLoc) 432 != DiagnosticsEngine::Ignored) { 433 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap(); 434 for (unsigned I = 0, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) { 435 // We only care about file entries. 436 const SrcMgr::SLocEntry &Entry = SourceMgr.getLocalSLocEntry(I); 437 if (!Entry.isFile()) 438 continue; 439 440 // Dig out the actual file. 441 const FileEntry *File = Entry.getFile().getContentCache()->OrigEntry; 442 if (!File) 443 continue; 444 445 // If it's not part of a module and not unknown, complain. 446 if (!ModMap.findModuleForHeader(File) && 447 !ModMap.isHeaderInUnavailableModule(File)) { 448 Diag(StartLoc, diag::warn_forgotten_module_header) 449 << File->getName() << Mod->getFullModuleName(); 450 } 451 } 452 } 453 } 454 455 return true; 456 } 457 458 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer 459 /// hits the end of its token stream. 460 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) { 461 assert(CurTokenLexer && !CurPPLexer && 462 "Ending a macro when currently in a #include file!"); 463 464 if (!MacroExpandingLexersStack.empty() && 465 MacroExpandingLexersStack.back().first == CurTokenLexer.get()) 466 removeCachedMacroExpandedTokensOfLastLexer(); 467 468 // Delete or cache the now-dead macro expander. 469 if (NumCachedTokenLexers == TokenLexerCacheSize) 470 CurTokenLexer.reset(); 471 else 472 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take(); 473 474 // Handle this like a #include file being popped off the stack. 475 return HandleEndOfFile(Result, true); 476 } 477 478 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the 479 /// lexer stack. This should only be used in situations where the current 480 /// state of the top-of-stack lexer is unknown. 481 void Preprocessor::RemoveTopOfLexerStack() { 482 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load"); 483 484 if (CurTokenLexer) { 485 // Delete or cache the now-dead macro expander. 486 if (NumCachedTokenLexers == TokenLexerCacheSize) 487 CurTokenLexer.reset(); 488 else 489 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take(); 490 } 491 492 PopIncludeMacroStack(); 493 } 494 495 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a 496 /// comment (/##/) in microsoft mode, this method handles updating the current 497 /// state, returning the token on the next source line. 498 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) { 499 assert(CurTokenLexer && !CurPPLexer && 500 "Pasted comment can only be formed from macro"); 501 502 // We handle this by scanning for the closest real lexer, switching it to 503 // raw mode and preprocessor mode. This will cause it to return \n as an 504 // explicit EOD token. 505 PreprocessorLexer *FoundLexer = 0; 506 bool LexerWasInPPMode = false; 507 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { 508 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1); 509 if (ISI.ThePPLexer == 0) continue; // Scan for a real lexer. 510 511 // Once we find a real lexer, mark it as raw mode (disabling macro 512 // expansions) and preprocessor mode (return EOD). We know that the lexer 513 // was *not* in raw mode before, because the macro that the comment came 514 // from was expanded. However, it could have already been in preprocessor 515 // mode (#if COMMENT) in which case we have to return it to that mode and 516 // return EOD. 517 FoundLexer = ISI.ThePPLexer; 518 FoundLexer->LexingRawMode = true; 519 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective; 520 FoundLexer->ParsingPreprocessorDirective = true; 521 break; 522 } 523 524 // Okay, we either found and switched over the lexer, or we didn't find a 525 // lexer. In either case, finish off the macro the comment came from, getting 526 // the next token. 527 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok); 528 529 // Discarding comments as long as we don't have EOF or EOD. This 'comments 530 // out' the rest of the line, including any tokens that came from other macros 531 // that were active, as in: 532 // #define submacro a COMMENT b 533 // submacro c 534 // which should lex to 'a' only: 'b' and 'c' should be removed. 535 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof)) 536 Lex(Tok); 537 538 // If we got an eod token, then we successfully found the end of the line. 539 if (Tok.is(tok::eod)) { 540 assert(FoundLexer && "Can't get end of line without an active lexer"); 541 // Restore the lexer back to normal mode instead of raw mode. 542 FoundLexer->LexingRawMode = false; 543 544 // If the lexer was already in preprocessor mode, just return the EOD token 545 // to finish the preprocessor line. 546 if (LexerWasInPPMode) return; 547 548 // Otherwise, switch out of PP mode and return the next lexed token. 549 FoundLexer->ParsingPreprocessorDirective = false; 550 return Lex(Tok); 551 } 552 553 // If we got an EOF token, then we reached the end of the token stream but 554 // didn't find an explicit \n. This can only happen if there was no lexer 555 // active (an active lexer would return EOD at EOF if there was no \n in 556 // preprocessor directive mode), so just return EOF as our token. 557 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode"); 558 } 559