clang API Documentation
00001 //===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===// 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 the Preprocessor interface. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 // 00014 // Options to support: 00015 // -H - Print the name of each header file used. 00016 // -d[DNI] - Dump various things. 00017 // -fworking-directory - #line's with preprocessor's working dir. 00018 // -fpreprocessed 00019 // -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD 00020 // -W* 00021 // -w 00022 // 00023 // Messages to emit: 00024 // "Multiple include guards may be useful for:\n" 00025 // 00026 //===----------------------------------------------------------------------===// 00027 00028 #include "clang/Lex/Preprocessor.h" 00029 #include "MacroArgs.h" 00030 #include "clang/Lex/ExternalPreprocessorSource.h" 00031 #include "clang/Lex/HeaderSearch.h" 00032 #include "clang/Lex/MacroInfo.h" 00033 #include "clang/Lex/Pragma.h" 00034 #include "clang/Lex/PreprocessingRecord.h" 00035 #include "clang/Lex/ScratchBuffer.h" 00036 #include "clang/Lex/LexDiagnostic.h" 00037 #include "clang/Lex/CodeCompletionHandler.h" 00038 #include "clang/Lex/ModuleLoader.h" 00039 #include "clang/Basic/SourceManager.h" 00040 #include "clang/Basic/FileManager.h" 00041 #include "clang/Basic/TargetInfo.h" 00042 #include "llvm/ADT/APFloat.h" 00043 #include "llvm/ADT/SmallString.h" 00044 #include "llvm/Support/MemoryBuffer.h" 00045 #include "llvm/Support/raw_ostream.h" 00046 #include "llvm/Support/Capacity.h" 00047 using namespace clang; 00048 00049 //===----------------------------------------------------------------------===// 00050 ExternalPreprocessorSource::~ExternalPreprocessorSource() { } 00051 00052 Preprocessor::Preprocessor(DiagnosticsEngine &diags, LangOptions &opts, 00053 const TargetInfo *target, SourceManager &SM, 00054 HeaderSearch &Headers, ModuleLoader &TheModuleLoader, 00055 IdentifierInfoLookup* IILookup, 00056 bool OwnsHeaders, 00057 bool DelayInitialization, 00058 bool IncrProcessing) 00059 : Diags(&diags), LangOpts(opts), Target(target),FileMgr(Headers.getFileMgr()), 00060 SourceMgr(SM), HeaderInfo(Headers), TheModuleLoader(TheModuleLoader), 00061 ExternalSource(0), Identifiers(opts, IILookup), 00062 IncrementalProcessing(IncrProcessing), CodeComplete(0), 00063 CodeCompletionFile(0), CodeCompletionOffset(0), CodeCompletionReached(0), 00064 SkipMainFilePreamble(0, true), CurPPLexer(0), 00065 CurDirLookup(0), CurLexerKind(CLK_Lexer), Callbacks(0), MacroArgCache(0), 00066 Record(0), MIChainHead(0), MICache(0) 00067 { 00068 OwnsHeaderSearch = OwnsHeaders; 00069 00070 if (!DelayInitialization) { 00071 assert(Target && "Must provide target information for PP initialization"); 00072 Initialize(*Target); 00073 } 00074 } 00075 00076 Preprocessor::~Preprocessor() { 00077 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!"); 00078 00079 while (!IncludeMacroStack.empty()) { 00080 delete IncludeMacroStack.back().TheLexer; 00081 delete IncludeMacroStack.back().TheTokenLexer; 00082 IncludeMacroStack.pop_back(); 00083 } 00084 00085 // Free any macro definitions. 00086 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next) 00087 I->MI.Destroy(); 00088 00089 // Free any cached macro expanders. 00090 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i) 00091 delete TokenLexerCache[i]; 00092 00093 // Free any cached MacroArgs. 00094 for (MacroArgs *ArgList = MacroArgCache; ArgList; ) 00095 ArgList = ArgList->deallocate(); 00096 00097 // Release pragma information. 00098 delete PragmaHandlers; 00099 00100 // Delete the scratch buffer info. 00101 delete ScratchBuf; 00102 00103 // Delete the header search info, if we own it. 00104 if (OwnsHeaderSearch) 00105 delete &HeaderInfo; 00106 00107 delete Callbacks; 00108 } 00109 00110 void Preprocessor::Initialize(const TargetInfo &Target) { 00111 assert((!this->Target || this->Target == &Target) && 00112 "Invalid override of target information"); 00113 this->Target = &Target; 00114 00115 // Initialize information about built-ins. 00116 BuiltinInfo.InitializeTarget(Target); 00117 00118 ScratchBuf = new ScratchBuffer(SourceMgr); 00119 CounterValue = 0; // __COUNTER__ starts at 0. 00120 00121 // Clear stats. 00122 NumDirectives = NumDefined = NumUndefined = NumPragma = 0; 00123 NumIf = NumElse = NumEndif = 0; 00124 NumEnteredSourceFiles = 0; 00125 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0; 00126 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0; 00127 MaxIncludeStackDepth = 0; 00128 NumSkipped = 0; 00129 00130 // Default to discarding comments. 00131 KeepComments = false; 00132 KeepMacroComments = false; 00133 SuppressIncludeNotFoundError = false; 00134 00135 // Macro expansion is enabled. 00136 DisableMacroExpansion = false; 00137 InMacroArgs = false; 00138 InMacroArgPreExpansion = false; 00139 NumCachedTokenLexers = 0; 00140 00141 CachedLexPos = 0; 00142 00143 // We haven't read anything from the external source. 00144 ReadMacrosFromExternalSource = false; 00145 00146 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. 00147 // This gets unpoisoned where it is allowed. 00148 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned(); 00149 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use); 00150 00151 // Initialize the pragma handlers. 00152 PragmaHandlers = new PragmaNamespace(StringRef()); 00153 RegisterBuiltinPragmas(); 00154 00155 // Initialize builtin macros like __LINE__ and friends. 00156 RegisterBuiltinMacros(); 00157 00158 if(LangOpts.Borland) { 00159 Ident__exception_info = getIdentifierInfo("_exception_info"); 00160 Ident___exception_info = getIdentifierInfo("__exception_info"); 00161 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation"); 00162 Ident__exception_code = getIdentifierInfo("_exception_code"); 00163 Ident___exception_code = getIdentifierInfo("__exception_code"); 00164 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode"); 00165 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination"); 00166 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination"); 00167 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination"); 00168 } else { 00169 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0; 00170 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0; 00171 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0; 00172 } 00173 00174 HeaderInfo.setTarget(Target); 00175 } 00176 00177 void Preprocessor::setPTHManager(PTHManager* pm) { 00178 PTH.reset(pm); 00179 FileMgr.addStatCache(PTH->createStatCache()); 00180 } 00181 00182 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const { 00183 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '" 00184 << getSpelling(Tok) << "'"; 00185 00186 if (!DumpFlags) return; 00187 00188 llvm::errs() << "\t"; 00189 if (Tok.isAtStartOfLine()) 00190 llvm::errs() << " [StartOfLine]"; 00191 if (Tok.hasLeadingSpace()) 00192 llvm::errs() << " [LeadingSpace]"; 00193 if (Tok.isExpandDisabled()) 00194 llvm::errs() << " [ExpandDisabled]"; 00195 if (Tok.needsCleaning()) { 00196 const char *Start = SourceMgr.getCharacterData(Tok.getLocation()); 00197 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength()) 00198 << "']"; 00199 } 00200 00201 llvm::errs() << "\tLoc=<"; 00202 DumpLocation(Tok.getLocation()); 00203 llvm::errs() << ">"; 00204 } 00205 00206 void Preprocessor::DumpLocation(SourceLocation Loc) const { 00207 Loc.dump(SourceMgr); 00208 } 00209 00210 void Preprocessor::DumpMacro(const MacroInfo &MI) const { 00211 llvm::errs() << "MACRO: "; 00212 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) { 00213 DumpToken(MI.getReplacementToken(i)); 00214 llvm::errs() << " "; 00215 } 00216 llvm::errs() << "\n"; 00217 } 00218 00219 void Preprocessor::PrintStats() { 00220 llvm::errs() << "\n*** Preprocessor Stats:\n"; 00221 llvm::errs() << NumDirectives << " directives found:\n"; 00222 llvm::errs() << " " << NumDefined << " #define.\n"; 00223 llvm::errs() << " " << NumUndefined << " #undef.\n"; 00224 llvm::errs() << " #include/#include_next/#import:\n"; 00225 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n"; 00226 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n"; 00227 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n"; 00228 llvm::errs() << " " << NumElse << " #else/#elif.\n"; 00229 llvm::errs() << " " << NumEndif << " #endif.\n"; 00230 llvm::errs() << " " << NumPragma << " #pragma.\n"; 00231 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n"; 00232 00233 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/" 00234 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, " 00235 << NumFastMacroExpanded << " on the fast path.\n"; 00236 llvm::errs() << (NumFastTokenPaste+NumTokenPaste) 00237 << " token paste (##) operations performed, " 00238 << NumFastTokenPaste << " on the fast path.\n"; 00239 } 00240 00241 Preprocessor::macro_iterator 00242 Preprocessor::macro_begin(bool IncludeExternalMacros) const { 00243 if (IncludeExternalMacros && ExternalSource && 00244 !ReadMacrosFromExternalSource) { 00245 ReadMacrosFromExternalSource = true; 00246 ExternalSource->ReadDefinedMacros(); 00247 } 00248 00249 return Macros.begin(); 00250 } 00251 00252 size_t Preprocessor::getTotalMemory() const { 00253 return BP.getTotalMemory() 00254 + llvm::capacity_in_bytes(MacroExpandedTokens) 00255 + Predefines.capacity() /* Predefines buffer. */ 00256 + llvm::capacity_in_bytes(Macros) 00257 + llvm::capacity_in_bytes(PragmaPushMacroInfo) 00258 + llvm::capacity_in_bytes(PoisonReasons) 00259 + llvm::capacity_in_bytes(CommentHandlers); 00260 } 00261 00262 Preprocessor::macro_iterator 00263 Preprocessor::macro_end(bool IncludeExternalMacros) const { 00264 if (IncludeExternalMacros && ExternalSource && 00265 !ReadMacrosFromExternalSource) { 00266 ReadMacrosFromExternalSource = true; 00267 ExternalSource->ReadDefinedMacros(); 00268 } 00269 00270 return Macros.end(); 00271 } 00272 00273 void Preprocessor::recomputeCurLexerKind() { 00274 if (CurLexer) 00275 CurLexerKind = CLK_Lexer; 00276 else if (CurPTHLexer) 00277 CurLexerKind = CLK_PTHLexer; 00278 else if (CurTokenLexer) 00279 CurLexerKind = CLK_TokenLexer; 00280 else 00281 CurLexerKind = CLK_CachingLexer; 00282 } 00283 00284 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File, 00285 unsigned CompleteLine, 00286 unsigned CompleteColumn) { 00287 assert(File); 00288 assert(CompleteLine && CompleteColumn && "Starts from 1:1"); 00289 assert(!CodeCompletionFile && "Already set"); 00290 00291 using llvm::MemoryBuffer; 00292 00293 // Load the actual file's contents. 00294 bool Invalid = false; 00295 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid); 00296 if (Invalid) 00297 return true; 00298 00299 // Find the byte position of the truncation point. 00300 const char *Position = Buffer->getBufferStart(); 00301 for (unsigned Line = 1; Line < CompleteLine; ++Line) { 00302 for (; *Position; ++Position) { 00303 if (*Position != '\r' && *Position != '\n') 00304 continue; 00305 00306 // Eat \r\n or \n\r as a single line. 00307 if ((Position[1] == '\r' || Position[1] == '\n') && 00308 Position[0] != Position[1]) 00309 ++Position; 00310 ++Position; 00311 break; 00312 } 00313 } 00314 00315 Position += CompleteColumn - 1; 00316 00317 // Insert '\0' at the code-completion point. 00318 if (Position < Buffer->getBufferEnd()) { 00319 CodeCompletionFile = File; 00320 CodeCompletionOffset = Position - Buffer->getBufferStart(); 00321 00322 MemoryBuffer *NewBuffer = 00323 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1, 00324 Buffer->getBufferIdentifier()); 00325 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart()); 00326 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf); 00327 *NewPos = '\0'; 00328 std::copy(Position, Buffer->getBufferEnd(), NewPos+1); 00329 SourceMgr.overrideFileContents(File, NewBuffer); 00330 } 00331 00332 return false; 00333 } 00334 00335 void Preprocessor::CodeCompleteNaturalLanguage() { 00336 if (CodeComplete) 00337 CodeComplete->CodeCompleteNaturalLanguage(); 00338 setCodeCompletionReached(); 00339 } 00340 00341 /// getSpelling - This method is used to get the spelling of a token into a 00342 /// SmallVector. Note that the returned StringRef may not point to the 00343 /// supplied buffer if a copy can be avoided. 00344 StringRef Preprocessor::getSpelling(const Token &Tok, 00345 SmallVectorImpl<char> &Buffer, 00346 bool *Invalid) const { 00347 // NOTE: this has to be checked *before* testing for an IdentifierInfo. 00348 if (Tok.isNot(tok::raw_identifier)) { 00349 // Try the fast path. 00350 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) 00351 return II->getName(); 00352 } 00353 00354 // Resize the buffer if we need to copy into it. 00355 if (Tok.needsCleaning()) 00356 Buffer.resize(Tok.getLength()); 00357 00358 const char *Ptr = Buffer.data(); 00359 unsigned Len = getSpelling(Tok, Ptr, Invalid); 00360 return StringRef(Ptr, Len); 00361 } 00362 00363 /// CreateString - Plop the specified string into a scratch buffer and return a 00364 /// location for it. If specified, the source location provides a source 00365 /// location for the token. 00366 void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok, 00367 SourceLocation ExpansionLocStart, 00368 SourceLocation ExpansionLocEnd) { 00369 Tok.setLength(Len); 00370 00371 const char *DestPtr; 00372 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr); 00373 00374 if (ExpansionLocStart.isValid()) 00375 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart, 00376 ExpansionLocEnd, Len); 00377 Tok.setLocation(Loc); 00378 00379 // If this is a raw identifier or a literal token, set the pointer data. 00380 if (Tok.is(tok::raw_identifier)) 00381 Tok.setRawIdentifierData(DestPtr); 00382 else if (Tok.isLiteral()) 00383 Tok.setLiteralData(DestPtr); 00384 } 00385 00386 Module *Preprocessor::getCurrentModule() { 00387 if (getLangOpts().CurrentModule.empty()) 00388 return 0; 00389 00390 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule); 00391 } 00392 00393 //===----------------------------------------------------------------------===// 00394 // Preprocessor Initialization Methods 00395 //===----------------------------------------------------------------------===// 00396 00397 00398 /// EnterMainSourceFile - Enter the specified FileID as the main source file, 00399 /// which implicitly adds the builtin defines etc. 00400 void Preprocessor::EnterMainSourceFile() { 00401 // We do not allow the preprocessor to reenter the main file. Doing so will 00402 // cause FileID's to accumulate information from both runs (e.g. #line 00403 // information) and predefined macros aren't guaranteed to be set properly. 00404 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!"); 00405 FileID MainFileID = SourceMgr.getMainFileID(); 00406 00407 // If MainFileID is loaded it means we loaded an AST file, no need to enter 00408 // a main file. 00409 if (!SourceMgr.isLoadedFileID(MainFileID)) { 00410 // Enter the main file source buffer. 00411 EnterSourceFile(MainFileID, 0, SourceLocation()); 00412 00413 // If we've been asked to skip bytes in the main file (e.g., as part of a 00414 // precompiled preamble), do so now. 00415 if (SkipMainFilePreamble.first > 0) 00416 CurLexer->SkipBytes(SkipMainFilePreamble.first, 00417 SkipMainFilePreamble.second); 00418 00419 // Tell the header info that the main file was entered. If the file is later 00420 // #imported, it won't be re-entered. 00421 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID)) 00422 HeaderInfo.IncrementIncludeCount(FE); 00423 } 00424 00425 // Preprocess Predefines to populate the initial preprocessor state. 00426 llvm::MemoryBuffer *SB = 00427 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>"); 00428 assert(SB && "Cannot create predefined source buffer"); 00429 FileID FID = SourceMgr.createFileIDForMemBuffer(SB); 00430 assert(!FID.isInvalid() && "Could not create FileID for predefines?"); 00431 00432 // Start parsing the predefines. 00433 EnterSourceFile(FID, 0, SourceLocation()); 00434 } 00435 00436 void Preprocessor::EndSourceFile() { 00437 // Notify the client that we reached the end of the source file. 00438 if (Callbacks) 00439 Callbacks->EndOfMainFile(); 00440 } 00441 00442 //===----------------------------------------------------------------------===// 00443 // Lexer Event Handling. 00444 //===----------------------------------------------------------------------===// 00445 00446 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the 00447 /// identifier information for the token and install it into the token, 00448 /// updating the token kind accordingly. 00449 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const { 00450 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!"); 00451 00452 // Look up this token, see if it is a macro, or if it is a language keyword. 00453 IdentifierInfo *II; 00454 if (!Identifier.needsCleaning()) { 00455 // No cleaning needed, just use the characters from the lexed buffer. 00456 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(), 00457 Identifier.getLength())); 00458 } else { 00459 // Cleaning needed, alloca a buffer, clean into it, then use the buffer. 00460 SmallString<64> IdentifierBuffer; 00461 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer); 00462 II = getIdentifierInfo(CleanedStr); 00463 } 00464 00465 // Update the token info (identifier info and appropriate token kind). 00466 Identifier.setIdentifierInfo(II); 00467 Identifier.setKind(II->getTokenID()); 00468 00469 return II; 00470 } 00471 00472 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) { 00473 PoisonReasons[II] = DiagID; 00474 } 00475 00476 void Preprocessor::PoisonSEHIdentifiers(bool Poison) { 00477 assert(Ident__exception_code && Ident__exception_info); 00478 assert(Ident___exception_code && Ident___exception_info); 00479 Ident__exception_code->setIsPoisoned(Poison); 00480 Ident___exception_code->setIsPoisoned(Poison); 00481 Ident_GetExceptionCode->setIsPoisoned(Poison); 00482 Ident__exception_info->setIsPoisoned(Poison); 00483 Ident___exception_info->setIsPoisoned(Poison); 00484 Ident_GetExceptionInfo->setIsPoisoned(Poison); 00485 Ident__abnormal_termination->setIsPoisoned(Poison); 00486 Ident___abnormal_termination->setIsPoisoned(Poison); 00487 Ident_AbnormalTermination->setIsPoisoned(Poison); 00488 } 00489 00490 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) { 00491 assert(Identifier.getIdentifierInfo() && 00492 "Can't handle identifiers without identifier info!"); 00493 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it = 00494 PoisonReasons.find(Identifier.getIdentifierInfo()); 00495 if(it == PoisonReasons.end()) 00496 Diag(Identifier, diag::err_pp_used_poisoned_id); 00497 else 00498 Diag(Identifier,it->second) << Identifier.getIdentifierInfo(); 00499 } 00500 00501 /// HandleIdentifier - This callback is invoked when the lexer reads an 00502 /// identifier. This callback looks up the identifier in the map and/or 00503 /// potentially macro expands it or turns it into a named token (like 'for'). 00504 /// 00505 /// Note that callers of this method are guarded by checking the 00506 /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the 00507 /// IdentifierInfo methods that compute these properties will need to change to 00508 /// match. 00509 void Preprocessor::HandleIdentifier(Token &Identifier) { 00510 assert(Identifier.getIdentifierInfo() && 00511 "Can't handle identifiers without identifier info!"); 00512 00513 IdentifierInfo &II = *Identifier.getIdentifierInfo(); 00514 00515 // If the information about this identifier is out of date, update it from 00516 // the external source. 00517 if (II.isOutOfDate()) { 00518 ExternalSource->updateOutOfDateIdentifier(II); 00519 Identifier.setKind(II.getTokenID()); 00520 } 00521 00522 // If this identifier was poisoned, and if it was not produced from a macro 00523 // expansion, emit an error. 00524 if (II.isPoisoned() && CurPPLexer) { 00525 HandlePoisonedIdentifier(Identifier); 00526 } 00527 00528 // If this is a macro to be expanded, do it. 00529 if (MacroInfo *MI = getMacroInfo(&II)) { 00530 if (!DisableMacroExpansion) { 00531 if (Identifier.isExpandDisabled()) { 00532 Diag(Identifier, diag::pp_disabled_macro_expansion); 00533 } else if (MI->isEnabled()) { 00534 if (!HandleMacroExpandedIdentifier(Identifier, MI)) 00535 return; 00536 } else { 00537 // C99 6.10.3.4p2 says that a disabled macro may never again be 00538 // expanded, even if it's in a context where it could be expanded in the 00539 // future. 00540 Identifier.setFlag(Token::DisableExpand); 00541 Diag(Identifier, diag::pp_disabled_macro_expansion); 00542 } 00543 } 00544 } 00545 00546 // If this identifier is a keyword in C++11, produce a warning. Don't warn if 00547 // we're not considering macro expansion, since this identifier might be the 00548 // name of a macro. 00549 // FIXME: This warning is disabled in cases where it shouldn't be, like 00550 // "#define constexpr constexpr", "int constexpr;" 00551 if (II.isCXX11CompatKeyword() & !DisableMacroExpansion) { 00552 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName(); 00553 // Don't diagnose this keyword again in this translation unit. 00554 II.setIsCXX11CompatKeyword(false); 00555 } 00556 00557 // C++ 2.11p2: If this is an alternative representation of a C++ operator, 00558 // then we act as if it is the actual operator and not the textual 00559 // representation of it. 00560 if (II.isCPlusPlusOperatorKeyword()) 00561 Identifier.setIdentifierInfo(0); 00562 00563 // If this is an extension token, diagnose its use. 00564 // We avoid diagnosing tokens that originate from macro definitions. 00565 // FIXME: This warning is disabled in cases where it shouldn't be, 00566 // like "#define TY typeof", "TY(1) x". 00567 if (II.isExtensionToken() && !DisableMacroExpansion) 00568 Diag(Identifier, diag::ext_token_used); 00569 00570 // If this is the '__experimental_modules_import' contextual keyword, note 00571 // that the next token indicates a module name. 00572 // 00573 // Note that we do not treat '__experimental_modules_import' as a contextual 00574 // keyword when we're in a caching lexer, because caching lexers only get 00575 // used in contexts where import declarations are disallowed. 00576 if (II.isModulesImport() && !InMacroArgs && !DisableMacroExpansion && 00577 getLangOpts().Modules && CurLexerKind != CLK_CachingLexer) { 00578 ModuleImportLoc = Identifier.getLocation(); 00579 ModuleImportPath.clear(); 00580 ModuleImportExpectsIdentifier = true; 00581 CurLexerKind = CLK_LexAfterModuleImport; 00582 } 00583 } 00584 00585 /// \brief Lex a token following the 'import' contextual keyword. 00586 /// 00587 void Preprocessor::LexAfterModuleImport(Token &Result) { 00588 // Figure out what kind of lexer we actually have. 00589 recomputeCurLexerKind(); 00590 00591 // Lex the next token. 00592 Lex(Result); 00593 00594 // The token sequence 00595 // 00596 // import identifier (. identifier)* 00597 // 00598 // indicates a module import directive. We already saw the 'import' 00599 // contextual keyword, so now we're looking for the identifiers. 00600 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) { 00601 // We expected to see an identifier here, and we did; continue handling 00602 // identifiers. 00603 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(), 00604 Result.getLocation())); 00605 ModuleImportExpectsIdentifier = false; 00606 CurLexerKind = CLK_LexAfterModuleImport; 00607 return; 00608 } 00609 00610 // If we're expecting a '.' or a ';', and we got a '.', then wait until we 00611 // see the next identifier. 00612 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) { 00613 ModuleImportExpectsIdentifier = true; 00614 CurLexerKind = CLK_LexAfterModuleImport; 00615 return; 00616 } 00617 00618 // If we have a non-empty module path, load the named module. 00619 if (!ModuleImportPath.empty()) 00620 (void)TheModuleLoader.loadModule(ModuleImportLoc, ModuleImportPath, 00621 Module::MacrosVisible, 00622 /*IsIncludeDirective=*/false); 00623 } 00624 00625 void Preprocessor::AddCommentHandler(CommentHandler *Handler) { 00626 assert(Handler && "NULL comment handler"); 00627 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) == 00628 CommentHandlers.end() && "Comment handler already registered"); 00629 CommentHandlers.push_back(Handler); 00630 } 00631 00632 void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) { 00633 std::vector<CommentHandler *>::iterator Pos 00634 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler); 00635 assert(Pos != CommentHandlers.end() && "Comment handler not registered"); 00636 CommentHandlers.erase(Pos); 00637 } 00638 00639 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) { 00640 bool AnyPendingTokens = false; 00641 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(), 00642 HEnd = CommentHandlers.end(); 00643 H != HEnd; ++H) { 00644 if ((*H)->HandleComment(*this, Comment)) 00645 AnyPendingTokens = true; 00646 } 00647 if (!AnyPendingTokens || getCommentRetentionState()) 00648 return false; 00649 Lex(result); 00650 return true; 00651 } 00652 00653 ModuleLoader::~ModuleLoader() { } 00654 00655 CommentHandler::~CommentHandler() { } 00656 00657 CodeCompletionHandler::~CodeCompletionHandler() { } 00658 00659 void Preprocessor::createPreprocessingRecord(bool RecordConditionalDirectives) { 00660 if (Record) 00661 return; 00662 00663 Record = new PreprocessingRecord(getSourceManager(), 00664 RecordConditionalDirectives); 00665 addPPCallbacks(Record); 00666 }