Preprocessor.cpp revision 6be16fe900bdd1e5f677d23ae34fffead5bcfc77
1//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===// 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 the Preprocessor interface. 11// 12//===----------------------------------------------------------------------===// 13// 14// Options to support: 15// -H - Print the name of each header file used. 16// -d[DNI] - Dump various things. 17// -fworking-directory - #line's with preprocessor's working dir. 18// -fpreprocessed 19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD 20// -W* 21// -w 22// 23// Messages to emit: 24// "Multiple include guards may be useful for:\n" 25// 26//===----------------------------------------------------------------------===// 27 28#include "clang/Lex/Preprocessor.h" 29#include "MacroArgs.h" 30#include "clang/Lex/ExternalPreprocessorSource.h" 31#include "clang/Lex/HeaderSearch.h" 32#include "clang/Lex/MacroInfo.h" 33#include "clang/Lex/Pragma.h" 34#include "clang/Lex/PreprocessingRecord.h" 35#include "clang/Lex/ScratchBuffer.h" 36#include "clang/Lex/LexDiagnostic.h" 37#include "clang/Lex/CodeCompletionHandler.h" 38#include "clang/Lex/ModuleLoader.h" 39#include "clang/Basic/SourceManager.h" 40#include "clang/Basic/FileManager.h" 41#include "clang/Basic/TargetInfo.h" 42#include "llvm/ADT/APFloat.h" 43#include "llvm/ADT/SmallVector.h" 44#include "llvm/Support/MemoryBuffer.h" 45#include "llvm/Support/raw_ostream.h" 46#include "llvm/Support/Capacity.h" 47using namespace clang; 48 49//===----------------------------------------------------------------------===// 50ExternalPreprocessorSource::~ExternalPreprocessorSource() { } 51 52Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts, 53 const TargetInfo &target, SourceManager &SM, 54 HeaderSearch &Headers, ModuleLoader &TheModuleLoader, 55 IdentifierInfoLookup* IILookup, 56 bool OwnsHeaders) 57 : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()), 58 SourceMgr(SM), HeaderInfo(Headers), TheModuleLoader(TheModuleLoader), 59 ExternalSource(0), 60 Identifiers(opts, IILookup), BuiltinInfo(Target), CodeComplete(0), 61 CodeCompletionFile(0), SkipMainFilePreamble(0, true), CurPPLexer(0), 62 CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0), 63 MICache(0) { 64 ScratchBuf = new ScratchBuffer(SourceMgr); 65 CounterValue = 0; // __COUNTER__ starts at 0. 66 OwnsHeaderSearch = OwnsHeaders; 67 68 // Clear stats. 69 NumDirectives = NumDefined = NumUndefined = NumPragma = 0; 70 NumIf = NumElse = NumEndif = 0; 71 NumEnteredSourceFiles = 0; 72 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0; 73 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0; 74 MaxIncludeStackDepth = 0; 75 NumSkipped = 0; 76 77 // Default to discarding comments. 78 KeepComments = false; 79 KeepMacroComments = false; 80 81 // Macro expansion is enabled. 82 DisableMacroExpansion = false; 83 InMacroArgs = false; 84 NumCachedTokenLexers = 0; 85 86 CachedLexPos = 0; 87 88 // We haven't read anything from the external source. 89 ReadMacrosFromExternalSource = false; 90 91 LexDepth = 0; 92 93 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. 94 // This gets unpoisoned where it is allowed. 95 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned(); 96 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use); 97 98 // Initialize the pragma handlers. 99 PragmaHandlers = new PragmaNamespace(StringRef()); 100 RegisterBuiltinPragmas(); 101 102 // Initialize builtin macros like __LINE__ and friends. 103 RegisterBuiltinMacros(); 104 105 if(Features.Borland) { 106 Ident__exception_info = getIdentifierInfo("_exception_info"); 107 Ident___exception_info = getIdentifierInfo("__exception_info"); 108 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation"); 109 Ident__exception_code = getIdentifierInfo("_exception_code"); 110 Ident___exception_code = getIdentifierInfo("__exception_code"); 111 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode"); 112 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination"); 113 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination"); 114 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination"); 115 } else { 116 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0; 117 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0; 118 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0; 119 } 120 121} 122 123Preprocessor::~Preprocessor() { 124 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!"); 125 assert(MacroExpandingLexersStack.empty() && MacroExpandedTokens.empty() && 126 "Preprocessor::HandleEndOfTokenLexer should have cleared those"); 127 128 while (!IncludeMacroStack.empty()) { 129 delete IncludeMacroStack.back().TheLexer; 130 delete IncludeMacroStack.back().TheTokenLexer; 131 IncludeMacroStack.pop_back(); 132 } 133 134 // Free any macro definitions. 135 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next) 136 I->MI.Destroy(); 137 138 // Free any cached macro expanders. 139 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i) 140 delete TokenLexerCache[i]; 141 142 // Free any cached MacroArgs. 143 for (MacroArgs *ArgList = MacroArgCache; ArgList; ) 144 ArgList = ArgList->deallocate(); 145 146 // Release pragma information. 147 delete PragmaHandlers; 148 149 // Delete the scratch buffer info. 150 delete ScratchBuf; 151 152 // Delete the header search info, if we own it. 153 if (OwnsHeaderSearch) 154 delete &HeaderInfo; 155 156 delete Callbacks; 157} 158 159void Preprocessor::setPTHManager(PTHManager* pm) { 160 PTH.reset(pm); 161 FileMgr.addStatCache(PTH->createStatCache()); 162} 163 164void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const { 165 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '" 166 << getSpelling(Tok) << "'"; 167 168 if (!DumpFlags) return; 169 170 llvm::errs() << "\t"; 171 if (Tok.isAtStartOfLine()) 172 llvm::errs() << " [StartOfLine]"; 173 if (Tok.hasLeadingSpace()) 174 llvm::errs() << " [LeadingSpace]"; 175 if (Tok.isExpandDisabled()) 176 llvm::errs() << " [ExpandDisabled]"; 177 if (Tok.needsCleaning()) { 178 const char *Start = SourceMgr.getCharacterData(Tok.getLocation()); 179 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength()) 180 << "']"; 181 } 182 183 llvm::errs() << "\tLoc=<"; 184 DumpLocation(Tok.getLocation()); 185 llvm::errs() << ">"; 186} 187 188void Preprocessor::DumpLocation(SourceLocation Loc) const { 189 Loc.dump(SourceMgr); 190} 191 192void Preprocessor::DumpMacro(const MacroInfo &MI) const { 193 llvm::errs() << "MACRO: "; 194 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) { 195 DumpToken(MI.getReplacementToken(i)); 196 llvm::errs() << " "; 197 } 198 llvm::errs() << "\n"; 199} 200 201void Preprocessor::PrintStats() { 202 llvm::errs() << "\n*** Preprocessor Stats:\n"; 203 llvm::errs() << NumDirectives << " directives found:\n"; 204 llvm::errs() << " " << NumDefined << " #define.\n"; 205 llvm::errs() << " " << NumUndefined << " #undef.\n"; 206 llvm::errs() << " #include/#include_next/#import:\n"; 207 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n"; 208 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n"; 209 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n"; 210 llvm::errs() << " " << NumElse << " #else/#elif.\n"; 211 llvm::errs() << " " << NumEndif << " #endif.\n"; 212 llvm::errs() << " " << NumPragma << " #pragma.\n"; 213 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n"; 214 215 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/" 216 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, " 217 << NumFastMacroExpanded << " on the fast path.\n"; 218 llvm::errs() << (NumFastTokenPaste+NumTokenPaste) 219 << " token paste (##) operations performed, " 220 << NumFastTokenPaste << " on the fast path.\n"; 221} 222 223Preprocessor::macro_iterator 224Preprocessor::macro_begin(bool IncludeExternalMacros) const { 225 if (IncludeExternalMacros && ExternalSource && 226 !ReadMacrosFromExternalSource) { 227 ReadMacrosFromExternalSource = true; 228 ExternalSource->ReadDefinedMacros(); 229 } 230 231 return Macros.begin(); 232} 233 234size_t Preprocessor::getTotalMemory() const { 235 return BP.getTotalMemory() 236 + llvm::capacity_in_bytes(MacroExpandedTokens) 237 + Predefines.capacity() /* Predefines buffer. */ 238 + llvm::capacity_in_bytes(Macros) 239 + llvm::capacity_in_bytes(PragmaPushMacroInfo) 240 + llvm::capacity_in_bytes(PoisonReasons) 241 + llvm::capacity_in_bytes(CommentHandlers); 242} 243 244Preprocessor::macro_iterator 245Preprocessor::macro_end(bool IncludeExternalMacros) const { 246 if (IncludeExternalMacros && ExternalSource && 247 !ReadMacrosFromExternalSource) { 248 ReadMacrosFromExternalSource = true; 249 ExternalSource->ReadDefinedMacros(); 250 } 251 252 return Macros.end(); 253} 254 255bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File, 256 unsigned TruncateAtLine, 257 unsigned TruncateAtColumn) { 258 using llvm::MemoryBuffer; 259 260 CodeCompletionFile = File; 261 262 // Okay to clear out the code-completion point by passing NULL. 263 if (!CodeCompletionFile) 264 return false; 265 266 // Load the actual file's contents. 267 bool Invalid = false; 268 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid); 269 if (Invalid) 270 return true; 271 272 // Find the byte position of the truncation point. 273 const char *Position = Buffer->getBufferStart(); 274 for (unsigned Line = 1; Line < TruncateAtLine; ++Line) { 275 for (; *Position; ++Position) { 276 if (*Position != '\r' && *Position != '\n') 277 continue; 278 279 // Eat \r\n or \n\r as a single line. 280 if ((Position[1] == '\r' || Position[1] == '\n') && 281 Position[0] != Position[1]) 282 ++Position; 283 ++Position; 284 break; 285 } 286 } 287 288 Position += TruncateAtColumn - 1; 289 290 // Truncate the buffer. 291 if (Position < Buffer->getBufferEnd()) { 292 StringRef Data(Buffer->getBufferStart(), 293 Position-Buffer->getBufferStart()); 294 MemoryBuffer *TruncatedBuffer 295 = MemoryBuffer::getMemBufferCopy(Data, Buffer->getBufferIdentifier()); 296 SourceMgr.overrideFileContents(File, TruncatedBuffer); 297 } 298 299 return false; 300} 301 302bool Preprocessor::isCodeCompletionFile(SourceLocation FileLoc) const { 303 return CodeCompletionFile && FileLoc.isFileID() && 304 SourceMgr.getFileEntryForID(SourceMgr.getFileID(FileLoc)) 305 == CodeCompletionFile; 306} 307 308void Preprocessor::CodeCompleteNaturalLanguage() { 309 SetCodeCompletionPoint(0, 0, 0); 310 getDiagnostics().setSuppressAllDiagnostics(true); 311 if (CodeComplete) 312 CodeComplete->CodeCompleteNaturalLanguage(); 313} 314 315/// getSpelling - This method is used to get the spelling of a token into a 316/// SmallVector. Note that the returned StringRef may not point to the 317/// supplied buffer if a copy can be avoided. 318StringRef Preprocessor::getSpelling(const Token &Tok, 319 SmallVectorImpl<char> &Buffer, 320 bool *Invalid) const { 321 // NOTE: this has to be checked *before* testing for an IdentifierInfo. 322 if (Tok.isNot(tok::raw_identifier)) { 323 // Try the fast path. 324 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) 325 return II->getName(); 326 } 327 328 // Resize the buffer if we need to copy into it. 329 if (Tok.needsCleaning()) 330 Buffer.resize(Tok.getLength()); 331 332 const char *Ptr = Buffer.data(); 333 unsigned Len = getSpelling(Tok, Ptr, Invalid); 334 return StringRef(Ptr, Len); 335} 336 337/// CreateString - Plop the specified string into a scratch buffer and return a 338/// location for it. If specified, the source location provides a source 339/// location for the token. 340void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok, 341 SourceLocation ExpansionLoc) { 342 Tok.setLength(Len); 343 344 const char *DestPtr; 345 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr); 346 347 if (ExpansionLoc.isValid()) 348 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLoc, ExpansionLoc, Len); 349 Tok.setLocation(Loc); 350 351 // If this is a raw identifier or a literal token, set the pointer data. 352 if (Tok.is(tok::raw_identifier)) 353 Tok.setRawIdentifierData(DestPtr); 354 else if (Tok.isLiteral()) 355 Tok.setLiteralData(DestPtr); 356} 357 358 359 360//===----------------------------------------------------------------------===// 361// Preprocessor Initialization Methods 362//===----------------------------------------------------------------------===// 363 364 365/// EnterMainSourceFile - Enter the specified FileID as the main source file, 366/// which implicitly adds the builtin defines etc. 367void Preprocessor::EnterMainSourceFile() { 368 // We do not allow the preprocessor to reenter the main file. Doing so will 369 // cause FileID's to accumulate information from both runs (e.g. #line 370 // information) and predefined macros aren't guaranteed to be set properly. 371 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!"); 372 FileID MainFileID = SourceMgr.getMainFileID(); 373 374 // Enter the main file source buffer. 375 EnterSourceFile(MainFileID, 0, SourceLocation()); 376 377 // If we've been asked to skip bytes in the main file (e.g., as part of a 378 // precompiled preamble), do so now. 379 if (SkipMainFilePreamble.first > 0) 380 CurLexer->SkipBytes(SkipMainFilePreamble.first, 381 SkipMainFilePreamble.second); 382 383 // Tell the header info that the main file was entered. If the file is later 384 // #imported, it won't be re-entered. 385 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID)) 386 HeaderInfo.IncrementIncludeCount(FE); 387 388 // Preprocess Predefines to populate the initial preprocessor state. 389 llvm::MemoryBuffer *SB = 390 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>"); 391 assert(SB && "Cannot create predefined source buffer"); 392 FileID FID = SourceMgr.createFileIDForMemBuffer(SB); 393 assert(!FID.isInvalid() && "Could not create FileID for predefines?"); 394 395 // Start parsing the predefines. 396 EnterSourceFile(FID, 0, SourceLocation()); 397} 398 399void Preprocessor::EndSourceFile() { 400 // Notify the client that we reached the end of the source file. 401 if (Callbacks) 402 Callbacks->EndOfMainFile(); 403} 404 405//===----------------------------------------------------------------------===// 406// Lexer Event Handling. 407//===----------------------------------------------------------------------===// 408 409/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the 410/// identifier information for the token and install it into the token, 411/// updating the token kind accordingly. 412IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const { 413 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!"); 414 415 // Look up this token, see if it is a macro, or if it is a language keyword. 416 IdentifierInfo *II; 417 if (!Identifier.needsCleaning()) { 418 // No cleaning needed, just use the characters from the lexed buffer. 419 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(), 420 Identifier.getLength())); 421 } else { 422 // Cleaning needed, alloca a buffer, clean into it, then use the buffer. 423 llvm::SmallString<64> IdentifierBuffer; 424 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer); 425 II = getIdentifierInfo(CleanedStr); 426 } 427 428 // Update the token info (identifier info and appropriate token kind). 429 Identifier.setIdentifierInfo(II); 430 Identifier.setKind(II->getTokenID()); 431 432 return II; 433} 434 435void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) { 436 PoisonReasons[II] = DiagID; 437} 438 439void Preprocessor::PoisonSEHIdentifiers(bool Poison) { 440 assert(Ident__exception_code && Ident__exception_info); 441 assert(Ident___exception_code && Ident___exception_info); 442 Ident__exception_code->setIsPoisoned(Poison); 443 Ident___exception_code->setIsPoisoned(Poison); 444 Ident_GetExceptionCode->setIsPoisoned(Poison); 445 Ident__exception_info->setIsPoisoned(Poison); 446 Ident___exception_info->setIsPoisoned(Poison); 447 Ident_GetExceptionInfo->setIsPoisoned(Poison); 448 Ident__abnormal_termination->setIsPoisoned(Poison); 449 Ident___abnormal_termination->setIsPoisoned(Poison); 450 Ident_AbnormalTermination->setIsPoisoned(Poison); 451} 452 453void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) { 454 assert(Identifier.getIdentifierInfo() && 455 "Can't handle identifiers without identifier info!"); 456 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it = 457 PoisonReasons.find(Identifier.getIdentifierInfo()); 458 if(it == PoisonReasons.end()) 459 Diag(Identifier, diag::err_pp_used_poisoned_id); 460 else 461 Diag(Identifier,it->second) << Identifier.getIdentifierInfo(); 462} 463 464/// HandleIdentifier - This callback is invoked when the lexer reads an 465/// identifier. This callback looks up the identifier in the map and/or 466/// potentially macro expands it or turns it into a named token (like 'for'). 467/// 468/// Note that callers of this method are guarded by checking the 469/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the 470/// IdentifierInfo methods that compute these properties will need to change to 471/// match. 472void Preprocessor::HandleIdentifier(Token &Identifier) { 473 assert(Identifier.getIdentifierInfo() && 474 "Can't handle identifiers without identifier info!"); 475 476 IdentifierInfo &II = *Identifier.getIdentifierInfo(); 477 478 // If this identifier was poisoned, and if it was not produced from a macro 479 // expansion, emit an error. 480 if (II.isPoisoned() && CurPPLexer) { 481 HandlePoisonedIdentifier(Identifier); 482 } 483 484 // If this is a macro to be expanded, do it. 485 if (MacroInfo *MI = getMacroInfo(&II)) { 486 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) { 487 if (MI->isEnabled()) { 488 if (!HandleMacroExpandedIdentifier(Identifier, MI)) 489 return; 490 } else { 491 // C99 6.10.3.4p2 says that a disabled macro may never again be 492 // expanded, even if it's in a context where it could be expanded in the 493 // future. 494 Identifier.setFlag(Token::DisableExpand); 495 } 496 } 497 } 498 499 // C++ 2.11p2: If this is an alternative representation of a C++ operator, 500 // then we act as if it is the actual operator and not the textual 501 // representation of it. 502 if (II.isCPlusPlusOperatorKeyword()) 503 Identifier.setIdentifierInfo(0); 504 505 // If this is an extension token, diagnose its use. 506 // We avoid diagnosing tokens that originate from macro definitions. 507 // FIXME: This warning is disabled in cases where it shouldn't be, 508 // like "#define TY typeof", "TY(1) x". 509 if (II.isExtensionToken() && !DisableMacroExpansion) 510 Diag(Identifier, diag::ext_token_used); 511} 512 513void Preprocessor::HandleModuleImport(Token &Import) { 514 // The token sequence 515 // 516 // __import__ identifier 517 // 518 // indicates a module import directive. We load the module and then 519 // leave the token sequence for the parser. 520 Token ModuleNameTok = LookAhead(0); 521 if (ModuleNameTok.getKind() != tok::identifier) 522 return; 523 524 (void)TheModuleLoader.loadModule(Import.getLocation(), 525 *ModuleNameTok.getIdentifierInfo(), 526 ModuleNameTok.getLocation()); 527 528 // FIXME: Transmogrify __import__ into some kind of AST-only __import__ that 529 // is not recognized by the preprocessor but is recognized by the parser. 530 // It would also be useful to stash the ModuleKey somewhere, so we don't try 531 // to load the module twice. 532} 533 534void Preprocessor::AddCommentHandler(CommentHandler *Handler) { 535 assert(Handler && "NULL comment handler"); 536 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) == 537 CommentHandlers.end() && "Comment handler already registered"); 538 CommentHandlers.push_back(Handler); 539} 540 541void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) { 542 std::vector<CommentHandler *>::iterator Pos 543 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler); 544 assert(Pos != CommentHandlers.end() && "Comment handler not registered"); 545 CommentHandlers.erase(Pos); 546} 547 548bool Preprocessor::HandleComment(Token &result, SourceRange Comment) { 549 bool AnyPendingTokens = false; 550 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(), 551 HEnd = CommentHandlers.end(); 552 H != HEnd; ++H) { 553 if ((*H)->HandleComment(*this, Comment)) 554 AnyPendingTokens = true; 555 } 556 if (!AnyPendingTokens || getCommentRetentionState()) 557 return false; 558 Lex(result); 559 return true; 560} 561 562ModuleLoader::~ModuleLoader() { } 563 564CommentHandler::~CommentHandler() { } 565 566CodeCompletionHandler::~CodeCompletionHandler() { } 567 568void Preprocessor::createPreprocessingRecord( 569 bool IncludeNestedMacroExpansions) { 570 if (Record) 571 return; 572 573 Record = new PreprocessingRecord(IncludeNestedMacroExpansions); 574 addPPCallbacks(Record); 575} 576