clang API Documentation
00001 //===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===// 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 /// \file 00011 /// \brief Implements # directive processing for the Preprocessor. 00012 /// 00013 //===----------------------------------------------------------------------===// 00014 00015 #include "clang/Lex/Preprocessor.h" 00016 #include "clang/Basic/FileManager.h" 00017 #include "clang/Basic/SourceManager.h" 00018 #include "clang/Lex/CodeCompletionHandler.h" 00019 #include "clang/Lex/HeaderSearch.h" 00020 #include "clang/Lex/HeaderSearchOptions.h" 00021 #include "clang/Lex/LexDiagnostic.h" 00022 #include "clang/Lex/LiteralSupport.h" 00023 #include "clang/Lex/MacroInfo.h" 00024 #include "clang/Lex/ModuleLoader.h" 00025 #include "clang/Lex/Pragma.h" 00026 #include "llvm/ADT/APInt.h" 00027 #include "llvm/Support/ErrorHandling.h" 00028 #include "llvm/Support/Path.h" 00029 #include "llvm/Support/SaveAndRestore.h" 00030 using namespace clang; 00031 00032 //===----------------------------------------------------------------------===// 00033 // Utility Methods for Preprocessor Directive Handling. 00034 //===----------------------------------------------------------------------===// 00035 00036 MacroInfo *Preprocessor::AllocateMacroInfo() { 00037 MacroInfoChain *MIChain = BP.Allocate<MacroInfoChain>(); 00038 MIChain->Next = MIChainHead; 00039 MIChainHead = MIChain; 00040 return &MIChain->MI; 00041 } 00042 00043 MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) { 00044 MacroInfo *MI = AllocateMacroInfo(); 00045 new (MI) MacroInfo(L); 00046 return MI; 00047 } 00048 00049 MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L, 00050 unsigned SubModuleID) { 00051 static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID), 00052 "alignment for MacroInfo is less than the ID"); 00053 DeserializedMacroInfoChain *MIChain = 00054 BP.Allocate<DeserializedMacroInfoChain>(); 00055 MIChain->Next = DeserialMIChainHead; 00056 DeserialMIChainHead = MIChain; 00057 00058 MacroInfo *MI = &MIChain->MI; 00059 new (MI) MacroInfo(L); 00060 MI->FromASTFile = true; 00061 MI->setOwningModuleID(SubModuleID); 00062 return MI; 00063 } 00064 00065 DefMacroDirective * 00066 Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc, 00067 unsigned ImportedFromModuleID, 00068 ArrayRef<unsigned> Overrides) { 00069 unsigned NumExtra = (ImportedFromModuleID ? 1 : 0) + Overrides.size(); 00070 return new (BP.Allocate(sizeof(DefMacroDirective) + 00071 sizeof(unsigned) * NumExtra, 00072 llvm::alignOf<DefMacroDirective>())) 00073 DefMacroDirective(MI, Loc, ImportedFromModuleID, Overrides); 00074 } 00075 00076 UndefMacroDirective * 00077 Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc, 00078 unsigned ImportedFromModuleID, 00079 ArrayRef<unsigned> Overrides) { 00080 unsigned NumExtra = (ImportedFromModuleID ? 1 : 0) + Overrides.size(); 00081 return new (BP.Allocate(sizeof(UndefMacroDirective) + 00082 sizeof(unsigned) * NumExtra, 00083 llvm::alignOf<UndefMacroDirective>())) 00084 UndefMacroDirective(UndefLoc, ImportedFromModuleID, Overrides); 00085 } 00086 00087 VisibilityMacroDirective * 00088 Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc, 00089 bool isPublic) { 00090 return new (BP) VisibilityMacroDirective(Loc, isPublic); 00091 } 00092 00093 /// \brief Read and discard all tokens remaining on the current line until 00094 /// the tok::eod token is found. 00095 void Preprocessor::DiscardUntilEndOfDirective() { 00096 Token Tmp; 00097 do { 00098 LexUnexpandedToken(Tmp); 00099 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens"); 00100 } while (Tmp.isNot(tok::eod)); 00101 } 00102 00103 bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef) { 00104 // Missing macro name? 00105 if (MacroNameTok.is(tok::eod)) 00106 return Diag(MacroNameTok, diag::err_pp_missing_macro_name); 00107 00108 IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); 00109 if (!II) { 00110 bool Invalid = false; 00111 std::string Spelling = getSpelling(MacroNameTok, &Invalid); 00112 if (Invalid) 00113 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier); 00114 II = getIdentifierInfo(Spelling); 00115 00116 if (!II->isCPlusPlusOperatorKeyword()) 00117 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier); 00118 00119 // C++ 2.5p2: Alternative tokens behave the same as its primary token 00120 // except for their spellings. 00121 Diag(MacroNameTok, getLangOpts().MicrosoftExt 00122 ? diag::ext_pp_operator_used_as_macro_name 00123 : diag::err_pp_operator_used_as_macro_name) 00124 << II << MacroNameTok.getKind(); 00125 00126 // Allow #defining |and| and friends for Microsoft compatibility or 00127 // recovery when legacy C headers are included in C++. 00128 MacroNameTok.setIdentifierInfo(II); 00129 } 00130 00131 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) { 00132 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4. 00133 return Diag(MacroNameTok, diag::err_defined_macro_name); 00134 } 00135 00136 if (isDefineUndef == MU_Undef && II->hasMacroDefinition() && 00137 getMacroInfo(II)->isBuiltinMacro()) { 00138 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4 00139 // and C++ [cpp.predefined]p4], but allow it as an extension. 00140 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro); 00141 } 00142 00143 // Okay, we got a good identifier. 00144 return false; 00145 } 00146 00147 /// \brief Lex and validate a macro name, which occurs after a 00148 /// \#define or \#undef. 00149 /// 00150 /// This sets the token kind to eod and discards the rest of the macro line if 00151 /// the macro name is invalid. 00152 /// 00153 /// \param MacroNameTok Token that is expected to be a macro name. 00154 /// \papam isDefineUndef Context in which macro is used. 00155 void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef) { 00156 // Read the token, don't allow macro expansion on it. 00157 LexUnexpandedToken(MacroNameTok); 00158 00159 if (MacroNameTok.is(tok::code_completion)) { 00160 if (CodeComplete) 00161 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define); 00162 setCodeCompletionReached(); 00163 LexUnexpandedToken(MacroNameTok); 00164 } 00165 00166 if (!CheckMacroName(MacroNameTok, isDefineUndef)) 00167 return; 00168 00169 // Invalid macro name, read and discard the rest of the line and set the 00170 // token kind to tok::eod if necessary. 00171 if (MacroNameTok.isNot(tok::eod)) { 00172 MacroNameTok.setKind(tok::eod); 00173 DiscardUntilEndOfDirective(); 00174 } 00175 } 00176 00177 /// \brief Ensure that the next token is a tok::eod token. 00178 /// 00179 /// If not, emit a diagnostic and consume up until the eod. If EnableMacros is 00180 /// true, then we consider macros that expand to zero tokens as being ok. 00181 void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) { 00182 Token Tmp; 00183 // Lex unexpanded tokens for most directives: macros might expand to zero 00184 // tokens, causing us to miss diagnosing invalid lines. Some directives (like 00185 // #line) allow empty macros. 00186 if (EnableMacros) 00187 Lex(Tmp); 00188 else 00189 LexUnexpandedToken(Tmp); 00190 00191 // There should be no tokens after the directive, but we allow them as an 00192 // extension. 00193 while (Tmp.is(tok::comment)) // Skip comments in -C mode. 00194 LexUnexpandedToken(Tmp); 00195 00196 if (Tmp.isNot(tok::eod)) { 00197 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89, 00198 // or if this is a macro-style preprocessing directive, because it is more 00199 // trouble than it is worth to insert /**/ and check that there is no /**/ 00200 // in the range also. 00201 FixItHint Hint; 00202 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) && 00203 !CurTokenLexer) 00204 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//"); 00205 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint; 00206 DiscardUntilEndOfDirective(); 00207 } 00208 } 00209 00210 00211 00212 /// SkipExcludedConditionalBlock - We just read a \#if or related directive and 00213 /// decided that the subsequent tokens are in the \#if'd out portion of the 00214 /// file. Lex the rest of the file, until we see an \#endif. If 00215 /// FoundNonSkipPortion is true, then we have already emitted code for part of 00216 /// this \#if directive, so \#else/\#elif blocks should never be entered. 00217 /// If ElseOk is true, then \#else directives are ok, if not, then we have 00218 /// already seen one so a \#else directive is a duplicate. When this returns, 00219 /// the caller can lex the first valid token. 00220 void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, 00221 bool FoundNonSkipPortion, 00222 bool FoundElse, 00223 SourceLocation ElseLoc) { 00224 ++NumSkipped; 00225 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?"); 00226 00227 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false, 00228 FoundNonSkipPortion, FoundElse); 00229 00230 if (CurPTHLexer) { 00231 PTHSkipExcludedConditionalBlock(); 00232 return; 00233 } 00234 00235 // Enter raw mode to disable identifier lookup (and thus macro expansion), 00236 // disabling warnings, etc. 00237 CurPPLexer->LexingRawMode = true; 00238 Token Tok; 00239 while (1) { 00240 CurLexer->Lex(Tok); 00241 00242 if (Tok.is(tok::code_completion)) { 00243 if (CodeComplete) 00244 CodeComplete->CodeCompleteInConditionalExclusion(); 00245 setCodeCompletionReached(); 00246 continue; 00247 } 00248 00249 // If this is the end of the buffer, we have an error. 00250 if (Tok.is(tok::eof)) { 00251 // Emit errors for each unterminated conditional on the stack, including 00252 // the current one. 00253 while (!CurPPLexer->ConditionalStack.empty()) { 00254 if (CurLexer->getFileLoc() != CodeCompletionFileLoc) 00255 Diag(CurPPLexer->ConditionalStack.back().IfLoc, 00256 diag::err_pp_unterminated_conditional); 00257 CurPPLexer->ConditionalStack.pop_back(); 00258 } 00259 00260 // Just return and let the caller lex after this #include. 00261 break; 00262 } 00263 00264 // If this token is not a preprocessor directive, just skip it. 00265 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) 00266 continue; 00267 00268 // We just parsed a # character at the start of a line, so we're in 00269 // directive mode. Tell the lexer this so any newlines we see will be 00270 // converted into an EOD token (this terminates the macro). 00271 CurPPLexer->ParsingPreprocessorDirective = true; 00272 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false); 00273 00274 00275 // Read the next token, the directive flavor. 00276 LexUnexpandedToken(Tok); 00277 00278 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or 00279 // something bogus), skip it. 00280 if (Tok.isNot(tok::raw_identifier)) { 00281 CurPPLexer->ParsingPreprocessorDirective = false; 00282 // Restore comment saving mode. 00283 if (CurLexer) CurLexer->resetExtendedTokenMode(); 00284 continue; 00285 } 00286 00287 // If the first letter isn't i or e, it isn't intesting to us. We know that 00288 // this is safe in the face of spelling differences, because there is no way 00289 // to spell an i/e in a strange way that is another letter. Skipping this 00290 // allows us to avoid looking up the identifier info for #define/#undef and 00291 // other common directives. 00292 StringRef RI = Tok.getRawIdentifier(); 00293 00294 char FirstChar = RI[0]; 00295 if (FirstChar >= 'a' && FirstChar <= 'z' && 00296 FirstChar != 'i' && FirstChar != 'e') { 00297 CurPPLexer->ParsingPreprocessorDirective = false; 00298 // Restore comment saving mode. 00299 if (CurLexer) CurLexer->resetExtendedTokenMode(); 00300 continue; 00301 } 00302 00303 // Get the identifier name without trigraphs or embedded newlines. Note 00304 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled 00305 // when skipping. 00306 char DirectiveBuf[20]; 00307 StringRef Directive; 00308 if (!Tok.needsCleaning() && RI.size() < 20) { 00309 Directive = RI; 00310 } else { 00311 std::string DirectiveStr = getSpelling(Tok); 00312 unsigned IdLen = DirectiveStr.size(); 00313 if (IdLen >= 20) { 00314 CurPPLexer->ParsingPreprocessorDirective = false; 00315 // Restore comment saving mode. 00316 if (CurLexer) CurLexer->resetExtendedTokenMode(); 00317 continue; 00318 } 00319 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen); 00320 Directive = StringRef(DirectiveBuf, IdLen); 00321 } 00322 00323 if (Directive.startswith("if")) { 00324 StringRef Sub = Directive.substr(2); 00325 if (Sub.empty() || // "if" 00326 Sub == "def" || // "ifdef" 00327 Sub == "ndef") { // "ifndef" 00328 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't 00329 // bother parsing the condition. 00330 DiscardUntilEndOfDirective(); 00331 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true, 00332 /*foundnonskip*/false, 00333 /*foundelse*/false); 00334 } 00335 } else if (Directive[0] == 'e') { 00336 StringRef Sub = Directive.substr(1); 00337 if (Sub == "ndif") { // "endif" 00338 PPConditionalInfo CondInfo; 00339 CondInfo.WasSkipping = true; // Silence bogus warning. 00340 bool InCond = CurPPLexer->popConditionalLevel(CondInfo); 00341 (void)InCond; // Silence warning in no-asserts mode. 00342 assert(!InCond && "Can't be skipping if not in a conditional!"); 00343 00344 // If we popped the outermost skipping block, we're done skipping! 00345 if (!CondInfo.WasSkipping) { 00346 // Restore the value of LexingRawMode so that trailing comments 00347 // are handled correctly, if we've reached the outermost block. 00348 CurPPLexer->LexingRawMode = false; 00349 CheckEndOfDirective("endif"); 00350 CurPPLexer->LexingRawMode = true; 00351 if (Callbacks) 00352 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc); 00353 break; 00354 } else { 00355 DiscardUntilEndOfDirective(); 00356 } 00357 } else if (Sub == "lse") { // "else". 00358 // #else directive in a skipping conditional. If not in some other 00359 // skipping conditional, and if #else hasn't already been seen, enter it 00360 // as a non-skipping conditional. 00361 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); 00362 00363 // If this is a #else with a #else before it, report the error. 00364 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else); 00365 00366 // Note that we've seen a #else in this conditional. 00367 CondInfo.FoundElse = true; 00368 00369 // If the conditional is at the top level, and the #if block wasn't 00370 // entered, enter the #else block now. 00371 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) { 00372 CondInfo.FoundNonSkip = true; 00373 // Restore the value of LexingRawMode so that trailing comments 00374 // are handled correctly. 00375 CurPPLexer->LexingRawMode = false; 00376 CheckEndOfDirective("else"); 00377 CurPPLexer->LexingRawMode = true; 00378 if (Callbacks) 00379 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc); 00380 break; 00381 } else { 00382 DiscardUntilEndOfDirective(); // C99 6.10p4. 00383 } 00384 } else if (Sub == "lif") { // "elif". 00385 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); 00386 00387 // If this is a #elif with a #else before it, report the error. 00388 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else); 00389 00390 // If this is in a skipping block or if we're already handled this #if 00391 // block, don't bother parsing the condition. 00392 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) { 00393 DiscardUntilEndOfDirective(); 00394 } else { 00395 const SourceLocation CondBegin = CurPPLexer->getSourceLocation(); 00396 // Restore the value of LexingRawMode so that identifiers are 00397 // looked up, etc, inside the #elif expression. 00398 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!"); 00399 CurPPLexer->LexingRawMode = false; 00400 IdentifierInfo *IfNDefMacro = nullptr; 00401 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro); 00402 CurPPLexer->LexingRawMode = true; 00403 if (Callbacks) { 00404 const SourceLocation CondEnd = CurPPLexer->getSourceLocation(); 00405 Callbacks->Elif(Tok.getLocation(), 00406 SourceRange(CondBegin, CondEnd), 00407 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc); 00408 } 00409 // If this condition is true, enter it! 00410 if (CondValue) { 00411 CondInfo.FoundNonSkip = true; 00412 break; 00413 } 00414 } 00415 } 00416 } 00417 00418 CurPPLexer->ParsingPreprocessorDirective = false; 00419 // Restore comment saving mode. 00420 if (CurLexer) CurLexer->resetExtendedTokenMode(); 00421 } 00422 00423 // Finally, if we are out of the conditional (saw an #endif or ran off the end 00424 // of the file, just stop skipping and return to lexing whatever came after 00425 // the #if block. 00426 CurPPLexer->LexingRawMode = false; 00427 00428 if (Callbacks) { 00429 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc; 00430 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation())); 00431 } 00432 } 00433 00434 void Preprocessor::PTHSkipExcludedConditionalBlock() { 00435 00436 while (1) { 00437 assert(CurPTHLexer); 00438 assert(CurPTHLexer->LexingRawMode == false); 00439 00440 // Skip to the next '#else', '#elif', or #endif. 00441 if (CurPTHLexer->SkipBlock()) { 00442 // We have reached an #endif. Both the '#' and 'endif' tokens 00443 // have been consumed by the PTHLexer. Just pop off the condition level. 00444 PPConditionalInfo CondInfo; 00445 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo); 00446 (void)InCond; // Silence warning in no-asserts mode. 00447 assert(!InCond && "Can't be skipping if not in a conditional!"); 00448 break; 00449 } 00450 00451 // We have reached a '#else' or '#elif'. Lex the next token to get 00452 // the directive flavor. 00453 Token Tok; 00454 LexUnexpandedToken(Tok); 00455 00456 // We can actually look up the IdentifierInfo here since we aren't in 00457 // raw mode. 00458 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID(); 00459 00460 if (K == tok::pp_else) { 00461 // #else: Enter the else condition. We aren't in a nested condition 00462 // since we skip those. We're always in the one matching the last 00463 // blocked we skipped. 00464 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel(); 00465 // Note that we've seen a #else in this conditional. 00466 CondInfo.FoundElse = true; 00467 00468 // If the #if block wasn't entered then enter the #else block now. 00469 if (!CondInfo.FoundNonSkip) { 00470 CondInfo.FoundNonSkip = true; 00471 00472 // Scan until the eod token. 00473 CurPTHLexer->ParsingPreprocessorDirective = true; 00474 DiscardUntilEndOfDirective(); 00475 CurPTHLexer->ParsingPreprocessorDirective = false; 00476 00477 break; 00478 } 00479 00480 // Otherwise skip this block. 00481 continue; 00482 } 00483 00484 assert(K == tok::pp_elif); 00485 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel(); 00486 00487 // If this is a #elif with a #else before it, report the error. 00488 if (CondInfo.FoundElse) 00489 Diag(Tok, diag::pp_err_elif_after_else); 00490 00491 // If this is in a skipping block or if we're already handled this #if 00492 // block, don't bother parsing the condition. We just skip this block. 00493 if (CondInfo.FoundNonSkip) 00494 continue; 00495 00496 // Evaluate the condition of the #elif. 00497 IdentifierInfo *IfNDefMacro = nullptr; 00498 CurPTHLexer->ParsingPreprocessorDirective = true; 00499 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro); 00500 CurPTHLexer->ParsingPreprocessorDirective = false; 00501 00502 // If this condition is true, enter it! 00503 if (ShouldEnter) { 00504 CondInfo.FoundNonSkip = true; 00505 break; 00506 } 00507 00508 // Otherwise, skip this block and go to the next one. 00509 continue; 00510 } 00511 } 00512 00513 Module *Preprocessor::getModuleForLocation(SourceLocation FilenameLoc) { 00514 ModuleMap &ModMap = HeaderInfo.getModuleMap(); 00515 if (SourceMgr.isInMainFile(FilenameLoc)) { 00516 if (Module *CurMod = getCurrentModule()) 00517 return CurMod; // Compiling a module. 00518 return HeaderInfo.getModuleMap().SourceModule; // Compiling a source. 00519 } 00520 // Try to determine the module of the include directive. 00521 // FIXME: Look into directly passing the FileEntry from LookupFile instead. 00522 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(FilenameLoc)); 00523 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) { 00524 // The include comes from a file. 00525 return ModMap.findModuleForHeader(EntryOfIncl).getModule(); 00526 } else { 00527 // The include does not come from a file, 00528 // so it is probably a module compilation. 00529 return getCurrentModule(); 00530 } 00531 } 00532 00533 const FileEntry *Preprocessor::LookupFile( 00534 SourceLocation FilenameLoc, 00535 StringRef Filename, 00536 bool isAngled, 00537 const DirectoryLookup *FromDir, 00538 const FileEntry *FromFile, 00539 const DirectoryLookup *&CurDir, 00540 SmallVectorImpl<char> *SearchPath, 00541 SmallVectorImpl<char> *RelativePath, 00542 ModuleMap::KnownHeader *SuggestedModule, 00543 bool SkipCache) { 00544 // If the header lookup mechanism may be relative to the current inclusion 00545 // stack, record the parent #includes. 00546 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16> 00547 Includers; 00548 if (!FromDir && !FromFile) { 00549 FileID FID = getCurrentFileLexer()->getFileID(); 00550 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID); 00551 00552 // If there is no file entry associated with this file, it must be the 00553 // predefines buffer. Any other file is not lexed with a normal lexer, so 00554 // it won't be scanned for preprocessor directives. If we have the 00555 // predefines buffer, resolve #include references (which come from the 00556 // -include command line argument) from the current working directory 00557 // instead of relative to the main file. 00558 if (!FileEnt) { 00559 FileEnt = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()); 00560 if (FileEnt) 00561 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory("."))); 00562 } else { 00563 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir())); 00564 } 00565 00566 // MSVC searches the current include stack from top to bottom for 00567 // headers included by quoted include directives. 00568 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx 00569 if (LangOpts.MSVCCompat && !isAngled) { 00570 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { 00571 IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1]; 00572 if (IsFileLexer(ISEntry)) 00573 if ((FileEnt = SourceMgr.getFileEntryForID( 00574 ISEntry.ThePPLexer->getFileID()))) 00575 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir())); 00576 } 00577 } 00578 } 00579 00580 CurDir = CurDirLookup; 00581 00582 if (FromFile) { 00583 // We're supposed to start looking from after a particular file. Search 00584 // the include path until we find that file or run out of files. 00585 const DirectoryLookup *TmpCurDir = CurDir; 00586 const DirectoryLookup *TmpFromDir = nullptr; 00587 while (const FileEntry *FE = HeaderInfo.LookupFile( 00588 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir, 00589 Includers, SearchPath, RelativePath, SuggestedModule, 00590 SkipCache)) { 00591 // Keep looking as if this file did a #include_next. 00592 TmpFromDir = TmpCurDir; 00593 ++TmpFromDir; 00594 if (FE == FromFile) { 00595 // Found it. 00596 FromDir = TmpFromDir; 00597 CurDir = TmpCurDir; 00598 break; 00599 } 00600 } 00601 } 00602 00603 // Do a standard file entry lookup. 00604 const FileEntry *FE = HeaderInfo.LookupFile( 00605 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath, 00606 RelativePath, SuggestedModule, SkipCache); 00607 if (FE) { 00608 if (SuggestedModule && !LangOpts.AsmPreprocessor) 00609 HeaderInfo.getModuleMap().diagnoseHeaderInclusion( 00610 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE); 00611 return FE; 00612 } 00613 00614 const FileEntry *CurFileEnt; 00615 // Otherwise, see if this is a subframework header. If so, this is relative 00616 // to one of the headers on the #include stack. Walk the list of the current 00617 // headers on the #include stack and pass them to HeaderInfo. 00618 if (IsFileLexer()) { 00619 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))) { 00620 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt, 00621 SearchPath, RelativePath, 00622 SuggestedModule))) { 00623 if (SuggestedModule && !LangOpts.AsmPreprocessor) 00624 HeaderInfo.getModuleMap().diagnoseHeaderInclusion( 00625 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE); 00626 return FE; 00627 } 00628 } 00629 } 00630 00631 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { 00632 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1]; 00633 if (IsFileLexer(ISEntry)) { 00634 if ((CurFileEnt = 00635 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID()))) { 00636 if ((FE = HeaderInfo.LookupSubframeworkHeader( 00637 Filename, CurFileEnt, SearchPath, RelativePath, 00638 SuggestedModule))) { 00639 if (SuggestedModule && !LangOpts.AsmPreprocessor) 00640 HeaderInfo.getModuleMap().diagnoseHeaderInclusion( 00641 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE); 00642 return FE; 00643 } 00644 } 00645 } 00646 } 00647 00648 // Otherwise, we really couldn't find the file. 00649 return nullptr; 00650 } 00651 00652 00653 //===----------------------------------------------------------------------===// 00654 // Preprocessor Directive Handling. 00655 //===----------------------------------------------------------------------===// 00656 00657 class Preprocessor::ResetMacroExpansionHelper { 00658 public: 00659 ResetMacroExpansionHelper(Preprocessor *pp) 00660 : PP(pp), save(pp->DisableMacroExpansion) { 00661 if (pp->MacroExpansionInDirectivesOverride) 00662 pp->DisableMacroExpansion = false; 00663 } 00664 ~ResetMacroExpansionHelper() { 00665 PP->DisableMacroExpansion = save; 00666 } 00667 private: 00668 Preprocessor *PP; 00669 bool save; 00670 }; 00671 00672 /// HandleDirective - This callback is invoked when the lexer sees a # token 00673 /// at the start of a line. This consumes the directive, modifies the 00674 /// lexer/preprocessor state, and advances the lexer(s) so that the next token 00675 /// read is the correct one. 00676 void Preprocessor::HandleDirective(Token &Result) { 00677 // FIXME: Traditional: # with whitespace before it not recognized by K&R? 00678 00679 // We just parsed a # character at the start of a line, so we're in directive 00680 // mode. Tell the lexer this so any newlines we see will be converted into an 00681 // EOD token (which terminates the directive). 00682 CurPPLexer->ParsingPreprocessorDirective = true; 00683 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false); 00684 00685 bool ImmediatelyAfterTopLevelIfndef = 00686 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef(); 00687 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef(); 00688 00689 ++NumDirectives; 00690 00691 // We are about to read a token. For the multiple-include optimization FA to 00692 // work, we have to remember if we had read any tokens *before* this 00693 // pp-directive. 00694 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal(); 00695 00696 // Save the '#' token in case we need to return it later. 00697 Token SavedHash = Result; 00698 00699 // Read the next token, the directive flavor. This isn't expanded due to 00700 // C99 6.10.3p8. 00701 LexUnexpandedToken(Result); 00702 00703 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.: 00704 // #define A(x) #x 00705 // A(abc 00706 // #warning blah 00707 // def) 00708 // If so, the user is relying on undefined behavior, emit a diagnostic. Do 00709 // not support this for #include-like directives, since that can result in 00710 // terrible diagnostics, and does not work in GCC. 00711 if (InMacroArgs) { 00712 if (IdentifierInfo *II = Result.getIdentifierInfo()) { 00713 switch (II->getPPKeywordID()) { 00714 case tok::pp_include: 00715 case tok::pp_import: 00716 case tok::pp_include_next: 00717 case tok::pp___include_macros: 00718 Diag(Result, diag::err_embedded_include) << II->getName(); 00719 DiscardUntilEndOfDirective(); 00720 return; 00721 default: 00722 break; 00723 } 00724 } 00725 Diag(Result, diag::ext_embedded_directive); 00726 } 00727 00728 // Temporarily enable macro expansion if set so 00729 // and reset to previous state when returning from this function. 00730 ResetMacroExpansionHelper helper(this); 00731 00732 switch (Result.getKind()) { 00733 case tok::eod: 00734 return; // null directive. 00735 case tok::code_completion: 00736 if (CodeComplete) 00737 CodeComplete->CodeCompleteDirective( 00738 CurPPLexer->getConditionalStackDepth() > 0); 00739 setCodeCompletionReached(); 00740 return; 00741 case tok::numeric_constant: // # 7 GNU line marker directive. 00742 if (getLangOpts().AsmPreprocessor) 00743 break; // # 4 is not a preprocessor directive in .S files. 00744 return HandleDigitDirective(Result); 00745 default: 00746 IdentifierInfo *II = Result.getIdentifierInfo(); 00747 if (!II) break; // Not an identifier. 00748 00749 // Ask what the preprocessor keyword ID is. 00750 switch (II->getPPKeywordID()) { 00751 default: break; 00752 // C99 6.10.1 - Conditional Inclusion. 00753 case tok::pp_if: 00754 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective); 00755 case tok::pp_ifdef: 00756 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/); 00757 case tok::pp_ifndef: 00758 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective); 00759 case tok::pp_elif: 00760 return HandleElifDirective(Result); 00761 case tok::pp_else: 00762 return HandleElseDirective(Result); 00763 case tok::pp_endif: 00764 return HandleEndifDirective(Result); 00765 00766 // C99 6.10.2 - Source File Inclusion. 00767 case tok::pp_include: 00768 // Handle #include. 00769 return HandleIncludeDirective(SavedHash.getLocation(), Result); 00770 case tok::pp___include_macros: 00771 // Handle -imacros. 00772 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result); 00773 00774 // C99 6.10.3 - Macro Replacement. 00775 case tok::pp_define: 00776 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef); 00777 case tok::pp_undef: 00778 return HandleUndefDirective(Result); 00779 00780 // C99 6.10.4 - Line Control. 00781 case tok::pp_line: 00782 return HandleLineDirective(Result); 00783 00784 // C99 6.10.5 - Error Directive. 00785 case tok::pp_error: 00786 return HandleUserDiagnosticDirective(Result, false); 00787 00788 // C99 6.10.6 - Pragma Directive. 00789 case tok::pp_pragma: 00790 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma); 00791 00792 // GNU Extensions. 00793 case tok::pp_import: 00794 return HandleImportDirective(SavedHash.getLocation(), Result); 00795 case tok::pp_include_next: 00796 return HandleIncludeNextDirective(SavedHash.getLocation(), Result); 00797 00798 case tok::pp_warning: 00799 Diag(Result, diag::ext_pp_warning_directive); 00800 return HandleUserDiagnosticDirective(Result, true); 00801 case tok::pp_ident: 00802 return HandleIdentSCCSDirective(Result); 00803 case tok::pp_sccs: 00804 return HandleIdentSCCSDirective(Result); 00805 case tok::pp_assert: 00806 //isExtension = true; // FIXME: implement #assert 00807 break; 00808 case tok::pp_unassert: 00809 //isExtension = true; // FIXME: implement #unassert 00810 break; 00811 00812 case tok::pp___public_macro: 00813 if (getLangOpts().Modules) 00814 return HandleMacroPublicDirective(Result); 00815 break; 00816 00817 case tok::pp___private_macro: 00818 if (getLangOpts().Modules) 00819 return HandleMacroPrivateDirective(Result); 00820 break; 00821 } 00822 break; 00823 } 00824 00825 // If this is a .S file, treat unknown # directives as non-preprocessor 00826 // directives. This is important because # may be a comment or introduce 00827 // various pseudo-ops. Just return the # token and push back the following 00828 // token to be lexed next time. 00829 if (getLangOpts().AsmPreprocessor) { 00830 Token *Toks = new Token[2]; 00831 // Return the # and the token after it. 00832 Toks[0] = SavedHash; 00833 Toks[1] = Result; 00834 00835 // If the second token is a hashhash token, then we need to translate it to 00836 // unknown so the token lexer doesn't try to perform token pasting. 00837 if (Result.is(tok::hashhash)) 00838 Toks[1].setKind(tok::unknown); 00839 00840 // Enter this token stream so that we re-lex the tokens. Make sure to 00841 // enable macro expansion, in case the token after the # is an identifier 00842 // that is expanded. 00843 EnterTokenStream(Toks, 2, false, true); 00844 return; 00845 } 00846 00847 // If we reached here, the preprocessing token is not valid! 00848 Diag(Result, diag::err_pp_invalid_directive); 00849 00850 // Read the rest of the PP line. 00851 DiscardUntilEndOfDirective(); 00852 00853 // Okay, we're done parsing the directive. 00854 } 00855 00856 /// GetLineValue - Convert a numeric token into an unsigned value, emitting 00857 /// Diagnostic DiagID if it is invalid, and returning the value in Val. 00858 static bool GetLineValue(Token &DigitTok, unsigned &Val, 00859 unsigned DiagID, Preprocessor &PP, 00860 bool IsGNULineDirective=false) { 00861 if (DigitTok.isNot(tok::numeric_constant)) { 00862 PP.Diag(DigitTok, DiagID); 00863 00864 if (DigitTok.isNot(tok::eod)) 00865 PP.DiscardUntilEndOfDirective(); 00866 return true; 00867 } 00868 00869 SmallString<64> IntegerBuffer; 00870 IntegerBuffer.resize(DigitTok.getLength()); 00871 const char *DigitTokBegin = &IntegerBuffer[0]; 00872 bool Invalid = false; 00873 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid); 00874 if (Invalid) 00875 return true; 00876 00877 // Verify that we have a simple digit-sequence, and compute the value. This 00878 // is always a simple digit string computed in decimal, so we do this manually 00879 // here. 00880 Val = 0; 00881 for (unsigned i = 0; i != ActualLength; ++i) { 00882 // C++1y [lex.fcon]p1: 00883 // Optional separating single quotes in a digit-sequence are ignored 00884 if (DigitTokBegin[i] == '\'') 00885 continue; 00886 00887 if (!isDigit(DigitTokBegin[i])) { 00888 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i), 00889 diag::err_pp_line_digit_sequence) << IsGNULineDirective; 00890 PP.DiscardUntilEndOfDirective(); 00891 return true; 00892 } 00893 00894 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0'); 00895 if (NextVal < Val) { // overflow. 00896 PP.Diag(DigitTok, DiagID); 00897 PP.DiscardUntilEndOfDirective(); 00898 return true; 00899 } 00900 Val = NextVal; 00901 } 00902 00903 if (DigitTokBegin[0] == '0' && Val) 00904 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal) 00905 << IsGNULineDirective; 00906 00907 return false; 00908 } 00909 00910 /// \brief Handle a \#line directive: C99 6.10.4. 00911 /// 00912 /// The two acceptable forms are: 00913 /// \verbatim 00914 /// # line digit-sequence 00915 /// # line digit-sequence "s-char-sequence" 00916 /// \endverbatim 00917 void Preprocessor::HandleLineDirective(Token &Tok) { 00918 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are 00919 // expanded. 00920 Token DigitTok; 00921 Lex(DigitTok); 00922 00923 // Validate the number and convert it to an unsigned. 00924 unsigned LineNo; 00925 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this)) 00926 return; 00927 00928 if (LineNo == 0) 00929 Diag(DigitTok, diag::ext_pp_line_zero); 00930 00931 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a 00932 // number greater than 2147483647". C90 requires that the line # be <= 32767. 00933 unsigned LineLimit = 32768U; 00934 if (LangOpts.C99 || LangOpts.CPlusPlus11) 00935 LineLimit = 2147483648U; 00936 if (LineNo >= LineLimit) 00937 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit; 00938 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U) 00939 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big); 00940 00941 int FilenameID = -1; 00942 Token StrTok; 00943 Lex(StrTok); 00944 00945 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a 00946 // string followed by eod. 00947 if (StrTok.is(tok::eod)) 00948 ; // ok 00949 else if (StrTok.isNot(tok::string_literal)) { 00950 Diag(StrTok, diag::err_pp_line_invalid_filename); 00951 return DiscardUntilEndOfDirective(); 00952 } else if (StrTok.hasUDSuffix()) { 00953 Diag(StrTok, diag::err_invalid_string_udl); 00954 return DiscardUntilEndOfDirective(); 00955 } else { 00956 // Parse and validate the string, converting it into a unique ID. 00957 StringLiteralParser Literal(StrTok, *this); 00958 assert(Literal.isAscii() && "Didn't allow wide strings in"); 00959 if (Literal.hadError) 00960 return DiscardUntilEndOfDirective(); 00961 if (Literal.Pascal) { 00962 Diag(StrTok, diag::err_pp_linemarker_invalid_filename); 00963 return DiscardUntilEndOfDirective(); 00964 } 00965 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString()); 00966 00967 // Verify that there is nothing after the string, other than EOD. Because 00968 // of C99 6.10.4p5, macros that expand to empty tokens are ok. 00969 CheckEndOfDirective("line", true); 00970 } 00971 00972 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID); 00973 00974 if (Callbacks) 00975 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), 00976 PPCallbacks::RenameFile, 00977 SrcMgr::C_User); 00978 } 00979 00980 /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line 00981 /// marker directive. 00982 static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit, 00983 bool &IsSystemHeader, bool &IsExternCHeader, 00984 Preprocessor &PP) { 00985 unsigned FlagVal; 00986 Token FlagTok; 00987 PP.Lex(FlagTok); 00988 if (FlagTok.is(tok::eod)) return false; 00989 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP)) 00990 return true; 00991 00992 if (FlagVal == 1) { 00993 IsFileEntry = true; 00994 00995 PP.Lex(FlagTok); 00996 if (FlagTok.is(tok::eod)) return false; 00997 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP)) 00998 return true; 00999 } else if (FlagVal == 2) { 01000 IsFileExit = true; 01001 01002 SourceManager &SM = PP.getSourceManager(); 01003 // If we are leaving the current presumed file, check to make sure the 01004 // presumed include stack isn't empty! 01005 FileID CurFileID = 01006 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first; 01007 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation()); 01008 if (PLoc.isInvalid()) 01009 return true; 01010 01011 // If there is no include loc (main file) or if the include loc is in a 01012 // different physical file, then we aren't in a "1" line marker flag region. 01013 SourceLocation IncLoc = PLoc.getIncludeLoc(); 01014 if (IncLoc.isInvalid() || 01015 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) { 01016 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop); 01017 PP.DiscardUntilEndOfDirective(); 01018 return true; 01019 } 01020 01021 PP.Lex(FlagTok); 01022 if (FlagTok.is(tok::eod)) return false; 01023 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP)) 01024 return true; 01025 } 01026 01027 // We must have 3 if there are still flags. 01028 if (FlagVal != 3) { 01029 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); 01030 PP.DiscardUntilEndOfDirective(); 01031 return true; 01032 } 01033 01034 IsSystemHeader = true; 01035 01036 PP.Lex(FlagTok); 01037 if (FlagTok.is(tok::eod)) return false; 01038 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP)) 01039 return true; 01040 01041 // We must have 4 if there is yet another flag. 01042 if (FlagVal != 4) { 01043 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); 01044 PP.DiscardUntilEndOfDirective(); 01045 return true; 01046 } 01047 01048 IsExternCHeader = true; 01049 01050 PP.Lex(FlagTok); 01051 if (FlagTok.is(tok::eod)) return false; 01052 01053 // There are no more valid flags here. 01054 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); 01055 PP.DiscardUntilEndOfDirective(); 01056 return true; 01057 } 01058 01059 /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is 01060 /// one of the following forms: 01061 /// 01062 /// # 42 01063 /// # 42 "file" ('1' | '2')? 01064 /// # 42 "file" ('1' | '2')? '3' '4'? 01065 /// 01066 void Preprocessor::HandleDigitDirective(Token &DigitTok) { 01067 // Validate the number and convert it to an unsigned. GNU does not have a 01068 // line # limit other than it fit in 32-bits. 01069 unsigned LineNo; 01070 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer, 01071 *this, true)) 01072 return; 01073 01074 Token StrTok; 01075 Lex(StrTok); 01076 01077 bool IsFileEntry = false, IsFileExit = false; 01078 bool IsSystemHeader = false, IsExternCHeader = false; 01079 int FilenameID = -1; 01080 01081 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a 01082 // string followed by eod. 01083 if (StrTok.is(tok::eod)) 01084 ; // ok 01085 else if (StrTok.isNot(tok::string_literal)) { 01086 Diag(StrTok, diag::err_pp_linemarker_invalid_filename); 01087 return DiscardUntilEndOfDirective(); 01088 } else if (StrTok.hasUDSuffix()) { 01089 Diag(StrTok, diag::err_invalid_string_udl); 01090 return DiscardUntilEndOfDirective(); 01091 } else { 01092 // Parse and validate the string, converting it into a unique ID. 01093 StringLiteralParser Literal(StrTok, *this); 01094 assert(Literal.isAscii() && "Didn't allow wide strings in"); 01095 if (Literal.hadError) 01096 return DiscardUntilEndOfDirective(); 01097 if (Literal.Pascal) { 01098 Diag(StrTok, diag::err_pp_linemarker_invalid_filename); 01099 return DiscardUntilEndOfDirective(); 01100 } 01101 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString()); 01102 01103 // If a filename was present, read any flags that are present. 01104 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, 01105 IsSystemHeader, IsExternCHeader, *this)) 01106 return; 01107 } 01108 01109 // Create a line note with this information. 01110 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, 01111 IsFileEntry, IsFileExit, 01112 IsSystemHeader, IsExternCHeader); 01113 01114 // If the preprocessor has callbacks installed, notify them of the #line 01115 // change. This is used so that the line marker comes out in -E mode for 01116 // example. 01117 if (Callbacks) { 01118 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile; 01119 if (IsFileEntry) 01120 Reason = PPCallbacks::EnterFile; 01121 else if (IsFileExit) 01122 Reason = PPCallbacks::ExitFile; 01123 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User; 01124 if (IsExternCHeader) 01125 FileKind = SrcMgr::C_ExternCSystem; 01126 else if (IsSystemHeader) 01127 FileKind = SrcMgr::C_System; 01128 01129 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind); 01130 } 01131 } 01132 01133 01134 /// HandleUserDiagnosticDirective - Handle a #warning or #error directive. 01135 /// 01136 void Preprocessor::HandleUserDiagnosticDirective(Token &Tok, 01137 bool isWarning) { 01138 // PTH doesn't emit #warning or #error directives. 01139 if (CurPTHLexer) 01140 return CurPTHLexer->DiscardToEndOfLine(); 01141 01142 // Read the rest of the line raw. We do this because we don't want macros 01143 // to be expanded and we don't require that the tokens be valid preprocessing 01144 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does 01145 // collapse multiple consequtive white space between tokens, but this isn't 01146 // specified by the standard. 01147 SmallString<128> Message; 01148 CurLexer->ReadToEndOfLine(&Message); 01149 01150 // Find the first non-whitespace character, so that we can make the 01151 // diagnostic more succinct. 01152 StringRef Msg = Message.str().ltrim(" "); 01153 01154 if (isWarning) 01155 Diag(Tok, diag::pp_hash_warning) << Msg; 01156 else 01157 Diag(Tok, diag::err_pp_hash_error) << Msg; 01158 } 01159 01160 /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive. 01161 /// 01162 void Preprocessor::HandleIdentSCCSDirective(Token &Tok) { 01163 // Yes, this directive is an extension. 01164 Diag(Tok, diag::ext_pp_ident_directive); 01165 01166 // Read the string argument. 01167 Token StrTok; 01168 Lex(StrTok); 01169 01170 // If the token kind isn't a string, it's a malformed directive. 01171 if (StrTok.isNot(tok::string_literal) && 01172 StrTok.isNot(tok::wide_string_literal)) { 01173 Diag(StrTok, diag::err_pp_malformed_ident); 01174 if (StrTok.isNot(tok::eod)) 01175 DiscardUntilEndOfDirective(); 01176 return; 01177 } 01178 01179 if (StrTok.hasUDSuffix()) { 01180 Diag(StrTok, diag::err_invalid_string_udl); 01181 return DiscardUntilEndOfDirective(); 01182 } 01183 01184 // Verify that there is nothing after the string, other than EOD. 01185 CheckEndOfDirective("ident"); 01186 01187 if (Callbacks) { 01188 bool Invalid = false; 01189 std::string Str = getSpelling(StrTok, &Invalid); 01190 if (!Invalid) 01191 Callbacks->Ident(Tok.getLocation(), Str); 01192 } 01193 } 01194 01195 /// \brief Handle a #public directive. 01196 void Preprocessor::HandleMacroPublicDirective(Token &Tok) { 01197 Token MacroNameTok; 01198 ReadMacroName(MacroNameTok, MU_Undef); 01199 01200 // Error reading macro name? If so, diagnostic already issued. 01201 if (MacroNameTok.is(tok::eod)) 01202 return; 01203 01204 // Check to see if this is the last token on the #__public_macro line. 01205 CheckEndOfDirective("__public_macro"); 01206 01207 IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); 01208 // Okay, we finally have a valid identifier to undef. 01209 MacroDirective *MD = getMacroDirective(II); 01210 01211 // If the macro is not defined, this is an error. 01212 if (!MD) { 01213 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II; 01214 return; 01215 } 01216 01217 // Note that this macro has now been exported. 01218 appendMacroDirective(II, AllocateVisibilityMacroDirective( 01219 MacroNameTok.getLocation(), /*IsPublic=*/true)); 01220 } 01221 01222 /// \brief Handle a #private directive. 01223 void Preprocessor::HandleMacroPrivateDirective(Token &Tok) { 01224 Token MacroNameTok; 01225 ReadMacroName(MacroNameTok, MU_Undef); 01226 01227 // Error reading macro name? If so, diagnostic already issued. 01228 if (MacroNameTok.is(tok::eod)) 01229 return; 01230 01231 // Check to see if this is the last token on the #__private_macro line. 01232 CheckEndOfDirective("__private_macro"); 01233 01234 IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); 01235 // Okay, we finally have a valid identifier to undef. 01236 MacroDirective *MD = getMacroDirective(II); 01237 01238 // If the macro is not defined, this is an error. 01239 if (!MD) { 01240 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II; 01241 return; 01242 } 01243 01244 // Note that this macro has now been marked private. 01245 appendMacroDirective(II, AllocateVisibilityMacroDirective( 01246 MacroNameTok.getLocation(), /*IsPublic=*/false)); 01247 } 01248 01249 //===----------------------------------------------------------------------===// 01250 // Preprocessor Include Directive Handling. 01251 //===----------------------------------------------------------------------===// 01252 01253 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully 01254 /// checked and spelled filename, e.g. as an operand of \#include. This returns 01255 /// true if the input filename was in <>'s or false if it were in ""'s. The 01256 /// caller is expected to provide a buffer that is large enough to hold the 01257 /// spelling of the filename, but is also expected to handle the case when 01258 /// this method decides to use a different buffer. 01259 bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc, 01260 StringRef &Buffer) { 01261 // Get the text form of the filename. 01262 assert(!Buffer.empty() && "Can't have tokens with empty spellings!"); 01263 01264 // Make sure the filename is <x> or "x". 01265 bool isAngled; 01266 if (Buffer[0] == '<') { 01267 if (Buffer.back() != '>') { 01268 Diag(Loc, diag::err_pp_expects_filename); 01269 Buffer = StringRef(); 01270 return true; 01271 } 01272 isAngled = true; 01273 } else if (Buffer[0] == '"') { 01274 if (Buffer.back() != '"') { 01275 Diag(Loc, diag::err_pp_expects_filename); 01276 Buffer = StringRef(); 01277 return true; 01278 } 01279 isAngled = false; 01280 } else { 01281 Diag(Loc, diag::err_pp_expects_filename); 01282 Buffer = StringRef(); 01283 return true; 01284 } 01285 01286 // Diagnose #include "" as invalid. 01287 if (Buffer.size() <= 2) { 01288 Diag(Loc, diag::err_pp_empty_filename); 01289 Buffer = StringRef(); 01290 return true; 01291 } 01292 01293 // Skip the brackets. 01294 Buffer = Buffer.substr(1, Buffer.size()-2); 01295 return isAngled; 01296 } 01297 01298 // \brief Handle cases where the \#include name is expanded from a macro 01299 // as multiple tokens, which need to be glued together. 01300 // 01301 // This occurs for code like: 01302 // \code 01303 // \#define FOO <a/b.h> 01304 // \#include FOO 01305 // \endcode 01306 // because in this case, "<a/b.h>" is returned as 7 tokens, not one. 01307 // 01308 // This code concatenates and consumes tokens up to the '>' token. It returns 01309 // false if the > was found, otherwise it returns true if it finds and consumes 01310 // the EOD marker. 01311 bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer, 01312 SourceLocation &End) { 01313 Token CurTok; 01314 01315 Lex(CurTok); 01316 while (CurTok.isNot(tok::eod)) { 01317 End = CurTok.getLocation(); 01318 01319 // FIXME: Provide code completion for #includes. 01320 if (CurTok.is(tok::code_completion)) { 01321 setCodeCompletionReached(); 01322 Lex(CurTok); 01323 continue; 01324 } 01325 01326 // Append the spelling of this token to the buffer. If there was a space 01327 // before it, add it now. 01328 if (CurTok.hasLeadingSpace()) 01329 FilenameBuffer.push_back(' '); 01330 01331 // Get the spelling of the token, directly into FilenameBuffer if possible. 01332 unsigned PreAppendSize = FilenameBuffer.size(); 01333 FilenameBuffer.resize(PreAppendSize+CurTok.getLength()); 01334 01335 const char *BufPtr = &FilenameBuffer[PreAppendSize]; 01336 unsigned ActualLen = getSpelling(CurTok, BufPtr); 01337 01338 // If the token was spelled somewhere else, copy it into FilenameBuffer. 01339 if (BufPtr != &FilenameBuffer[PreAppendSize]) 01340 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen); 01341 01342 // Resize FilenameBuffer to the correct size. 01343 if (CurTok.getLength() != ActualLen) 01344 FilenameBuffer.resize(PreAppendSize+ActualLen); 01345 01346 // If we found the '>' marker, return success. 01347 if (CurTok.is(tok::greater)) 01348 return false; 01349 01350 Lex(CurTok); 01351 } 01352 01353 // If we hit the eod marker, emit an error and return true so that the caller 01354 // knows the EOD has been read. 01355 Diag(CurTok.getLocation(), diag::err_pp_expects_filename); 01356 return true; 01357 } 01358 01359 /// \brief Push a token onto the token stream containing an annotation. 01360 static void EnterAnnotationToken(Preprocessor &PP, 01361 SourceLocation Begin, SourceLocation End, 01362 tok::TokenKind Kind, void *AnnotationVal) { 01363 Token *Tok = new Token[1]; 01364 Tok[0].startToken(); 01365 Tok[0].setKind(Kind); 01366 Tok[0].setLocation(Begin); 01367 Tok[0].setAnnotationEndLoc(End); 01368 Tok[0].setAnnotationValue(AnnotationVal); 01369 PP.EnterTokenStream(Tok, 1, true, true); 01370 } 01371 01372 /// HandleIncludeDirective - The "\#include" tokens have just been read, read 01373 /// the file to be included from the lexer, then include it! This is a common 01374 /// routine with functionality shared between \#include, \#include_next and 01375 /// \#import. LookupFrom is set when this is a \#include_next directive, it 01376 /// specifies the file to start searching from. 01377 void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc, 01378 Token &IncludeTok, 01379 const DirectoryLookup *LookupFrom, 01380 const FileEntry *LookupFromFile, 01381 bool isImport) { 01382 01383 Token FilenameTok; 01384 CurPPLexer->LexIncludeFilename(FilenameTok); 01385 01386 // Reserve a buffer to get the spelling. 01387 SmallString<128> FilenameBuffer; 01388 StringRef Filename; 01389 SourceLocation End; 01390 SourceLocation CharEnd; // the end of this directive, in characters 01391 01392 switch (FilenameTok.getKind()) { 01393 case tok::eod: 01394 // If the token kind is EOD, the error has already been diagnosed. 01395 return; 01396 01397 case tok::angle_string_literal: 01398 case tok::string_literal: 01399 Filename = getSpelling(FilenameTok, FilenameBuffer); 01400 End = FilenameTok.getLocation(); 01401 CharEnd = End.getLocWithOffset(FilenameTok.getLength()); 01402 break; 01403 01404 case tok::less: 01405 // This could be a <foo/bar.h> file coming from a macro expansion. In this 01406 // case, glue the tokens together into FilenameBuffer and interpret those. 01407 FilenameBuffer.push_back('<'); 01408 if (ConcatenateIncludeName(FilenameBuffer, End)) 01409 return; // Found <eod> but no ">"? Diagnostic already emitted. 01410 Filename = FilenameBuffer.str(); 01411 CharEnd = End.getLocWithOffset(1); 01412 break; 01413 default: 01414 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename); 01415 DiscardUntilEndOfDirective(); 01416 return; 01417 } 01418 01419 CharSourceRange FilenameRange 01420 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd); 01421 StringRef OriginalFilename = Filename; 01422 bool isAngled = 01423 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename); 01424 // If GetIncludeFilenameSpelling set the start ptr to null, there was an 01425 // error. 01426 if (Filename.empty()) { 01427 DiscardUntilEndOfDirective(); 01428 return; 01429 } 01430 01431 // Verify that there is nothing after the filename, other than EOD. Note that 01432 // we allow macros that expand to nothing after the filename, because this 01433 // falls into the category of "#include pp-tokens new-line" specified in 01434 // C99 6.10.2p4. 01435 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true); 01436 01437 // Check that we don't have infinite #include recursion. 01438 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) { 01439 Diag(FilenameTok, diag::err_pp_include_too_deep); 01440 return; 01441 } 01442 01443 // Complain about attempts to #include files in an audit pragma. 01444 if (PragmaARCCFCodeAuditedLoc.isValid()) { 01445 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited); 01446 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here); 01447 01448 // Immediately leave the pragma. 01449 PragmaARCCFCodeAuditedLoc = SourceLocation(); 01450 } 01451 01452 if (HeaderInfo.HasIncludeAliasMap()) { 01453 // Map the filename with the brackets still attached. If the name doesn't 01454 // map to anything, fall back on the filename we've already gotten the 01455 // spelling for. 01456 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename); 01457 if (!NewName.empty()) 01458 Filename = NewName; 01459 } 01460 01461 // Search include directories. 01462 const DirectoryLookup *CurDir; 01463 SmallString<1024> SearchPath; 01464 SmallString<1024> RelativePath; 01465 // We get the raw path only if we have 'Callbacks' to which we later pass 01466 // the path. 01467 ModuleMap::KnownHeader SuggestedModule; 01468 SourceLocation FilenameLoc = FilenameTok.getLocation(); 01469 SmallString<128> NormalizedPath; 01470 if (LangOpts.MSVCCompat) { 01471 NormalizedPath = Filename.str(); 01472 #ifndef LLVM_ON_WIN32 01473 llvm::sys::path::native(NormalizedPath); 01474 #endif 01475 } 01476 const FileEntry *File = LookupFile( 01477 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, 01478 isAngled, LookupFrom, LookupFromFile, CurDir, 01479 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr, 01480 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule : nullptr); 01481 01482 if (Callbacks) { 01483 if (!File) { 01484 // Give the clients a chance to recover. 01485 SmallString<128> RecoveryPath; 01486 if (Callbacks->FileNotFound(Filename, RecoveryPath)) { 01487 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) { 01488 // Add the recovery path to the list of search paths. 01489 DirectoryLookup DL(DE, SrcMgr::C_User, false); 01490 HeaderInfo.AddSearchPath(DL, isAngled); 01491 01492 // Try the lookup again, skipping the cache. 01493 File = LookupFile( 01494 FilenameLoc, 01495 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled, 01496 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr, 01497 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule 01498 : nullptr, 01499 /*SkipCache*/ true); 01500 } 01501 } 01502 } 01503 01504 if (!SuggestedModule || !getLangOpts().Modules) { 01505 // Notify the callback object that we've seen an inclusion directive. 01506 Callbacks->InclusionDirective(HashLoc, IncludeTok, 01507 LangOpts.MSVCCompat ? NormalizedPath.c_str() 01508 : Filename, 01509 isAngled, FilenameRange, File, SearchPath, 01510 RelativePath, /*ImportedModule=*/nullptr); 01511 } 01512 } 01513 01514 if (!File) { 01515 if (!SuppressIncludeNotFoundError) { 01516 // If the file could not be located and it was included via angle 01517 // brackets, we can attempt a lookup as though it were a quoted path to 01518 // provide the user with a possible fixit. 01519 if (isAngled) { 01520 File = LookupFile( 01521 FilenameLoc, 01522 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false, 01523 LookupFrom, LookupFromFile, CurDir, 01524 Callbacks ? &SearchPath : nullptr, 01525 Callbacks ? &RelativePath : nullptr, 01526 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule 01527 : nullptr); 01528 if (File) { 01529 SourceRange Range(FilenameTok.getLocation(), CharEnd); 01530 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) << 01531 Filename << 01532 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\""); 01533 } 01534 } 01535 // If the file is still not found, just go with the vanilla diagnostic 01536 if (!File) 01537 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename; 01538 } 01539 if (!File) 01540 return; 01541 } 01542 01543 // If we are supposed to import a module rather than including the header, 01544 // do so now. 01545 if (SuggestedModule && getLangOpts().Modules && 01546 SuggestedModule.getModule()->getTopLevelModuleName() != 01547 getLangOpts().ImplementationOfModule) { 01548 // Compute the module access path corresponding to this module. 01549 // FIXME: Should we have a second loadModule() overload to avoid this 01550 // extra lookup step? 01551 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 01552 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent) 01553 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name), 01554 FilenameTok.getLocation())); 01555 std::reverse(Path.begin(), Path.end()); 01556 01557 // Warn that we're replacing the include/import with a module import. 01558 SmallString<128> PathString; 01559 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 01560 if (I) 01561 PathString += '.'; 01562 PathString += Path[I].first->getName(); 01563 } 01564 int IncludeKind = 0; 01565 01566 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) { 01567 case tok::pp_include: 01568 IncludeKind = 0; 01569 break; 01570 01571 case tok::pp_import: 01572 IncludeKind = 1; 01573 break; 01574 01575 case tok::pp_include_next: 01576 IncludeKind = 2; 01577 break; 01578 01579 case tok::pp___include_macros: 01580 IncludeKind = 3; 01581 break; 01582 01583 default: 01584 llvm_unreachable("unknown include directive kind"); 01585 } 01586 01587 // Determine whether we are actually building the module that this 01588 // include directive maps to. 01589 bool BuildingImportedModule 01590 = Path[0].first->getName() == getLangOpts().CurrentModule; 01591 01592 if (!BuildingImportedModule && getLangOpts().ObjC2) { 01593 // If we're not building the imported module, warn that we're going 01594 // to automatically turn this inclusion directive into a module import. 01595 // We only do this in Objective-C, where we have a module-import syntax. 01596 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd), 01597 /*IsTokenRange=*/false); 01598 Diag(HashLoc, diag::warn_auto_module_import) 01599 << IncludeKind << PathString 01600 << FixItHint::CreateReplacement(ReplaceRange, 01601 "@import " + PathString.str().str() + ";"); 01602 } 01603 01604 // Load the module. Only make macros visible. We'll make the declarations 01605 // visible when the parser gets here. 01606 Module::NameVisibilityKind Visibility = Module::MacrosVisible; 01607 ModuleLoadResult Imported 01608 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility, 01609 /*IsIncludeDirective=*/true); 01610 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) && 01611 "the imported module is different than the suggested one"); 01612 01613 if (!Imported && hadModuleLoaderFatalFailure()) { 01614 // With a fatal failure in the module loader, we abort parsing. 01615 Token &Result = IncludeTok; 01616 if (CurLexer) { 01617 Result.startToken(); 01618 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof); 01619 CurLexer->cutOffLexing(); 01620 } else { 01621 assert(CurPTHLexer && "#include but no current lexer set!"); 01622 CurPTHLexer->getEOF(Result); 01623 } 01624 return; 01625 } 01626 01627 // If this header isn't part of the module we're building, we're done. 01628 if (!BuildingImportedModule && Imported) { 01629 if (Callbacks) { 01630 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, 01631 FilenameRange, File, 01632 SearchPath, RelativePath, Imported); 01633 } 01634 01635 if (IncludeKind != 3) { 01636 // Let the parser know that we hit a module import, and it should 01637 // make the module visible. 01638 // FIXME: Produce this as the current token directly, rather than 01639 // allocating a new token for it. 01640 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include, 01641 Imported); 01642 } 01643 return; 01644 } 01645 01646 // If we failed to find a submodule that we expected to find, we can 01647 // continue. Otherwise, there's an error in the included file, so we 01648 // don't want to include it. 01649 if (!BuildingImportedModule && !Imported.isMissingExpected()) { 01650 return; 01651 } 01652 } 01653 01654 if (Callbacks && SuggestedModule) { 01655 // We didn't notify the callback object that we've seen an inclusion 01656 // directive before. Now that we are parsing the include normally and not 01657 // turning it to a module import, notify the callback object. 01658 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, 01659 FilenameRange, File, 01660 SearchPath, RelativePath, 01661 /*ImportedModule=*/nullptr); 01662 } 01663 01664 // The #included file will be considered to be a system header if either it is 01665 // in a system include directory, or if the #includer is a system include 01666 // header. 01667 SrcMgr::CharacteristicKind FileCharacter = 01668 std::max(HeaderInfo.getFileDirFlavor(File), 01669 SourceMgr.getFileCharacteristic(FilenameTok.getLocation())); 01670 01671 // Ask HeaderInfo if we should enter this #include file. If not, #including 01672 // this file will have no effect. 01673 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) { 01674 if (Callbacks) 01675 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter); 01676 return; 01677 } 01678 01679 // Look up the file, create a File ID for it. 01680 SourceLocation IncludePos = End; 01681 // If the filename string was the result of macro expansions, set the include 01682 // position on the file where it will be included and after the expansions. 01683 if (IncludePos.isMacroID()) 01684 IncludePos = SourceMgr.getExpansionRange(IncludePos).second; 01685 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter); 01686 assert(!FID.isInvalid() && "Expected valid file ID"); 01687 01688 // Determine if we're switching to building a new submodule, and which one. 01689 ModuleMap::KnownHeader BuildingModule; 01690 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) { 01691 Module *RequestingModule = getModuleForLocation(FilenameLoc); 01692 BuildingModule = 01693 HeaderInfo.getModuleMap().findModuleForHeader(File, RequestingModule); 01694 } 01695 01696 // If all is good, enter the new file! 01697 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation())) 01698 return; 01699 01700 // If we're walking into another part of the same module, let the parser 01701 // know that any future declarations are within that other submodule. 01702 if (BuildingModule) { 01703 assert(!CurSubmodule && "should not have marked this as a module yet"); 01704 CurSubmodule = BuildingModule.getModule(); 01705 01706 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin, 01707 CurSubmodule); 01708 } 01709 } 01710 01711 /// HandleIncludeNextDirective - Implements \#include_next. 01712 /// 01713 void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc, 01714 Token &IncludeNextTok) { 01715 Diag(IncludeNextTok, diag::ext_pp_include_next_directive); 01716 01717 // #include_next is like #include, except that we start searching after 01718 // the current found directory. If we can't do this, issue a 01719 // diagnostic. 01720 const DirectoryLookup *Lookup = CurDirLookup; 01721 const FileEntry *LookupFromFile = nullptr; 01722 if (isInPrimaryFile()) { 01723 Lookup = nullptr; 01724 Diag(IncludeNextTok, diag::pp_include_next_in_primary); 01725 } else if (CurSubmodule) { 01726 // Start looking up in the directory *after* the one in which the current 01727 // file would be found, if any. 01728 assert(CurPPLexer && "#include_next directive in macro?"); 01729 LookupFromFile = CurPPLexer->getFileEntry(); 01730 Lookup = nullptr; 01731 } else if (!Lookup) { 01732 Diag(IncludeNextTok, diag::pp_include_next_absolute_path); 01733 } else { 01734 // Start looking up in the next directory. 01735 ++Lookup; 01736 } 01737 01738 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup, 01739 LookupFromFile); 01740 } 01741 01742 /// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode 01743 void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) { 01744 // The Microsoft #import directive takes a type library and generates header 01745 // files from it, and includes those. This is beyond the scope of what clang 01746 // does, so we ignore it and error out. However, #import can optionally have 01747 // trailing attributes that span multiple lines. We're going to eat those 01748 // so we can continue processing from there. 01749 Diag(Tok, diag::err_pp_import_directive_ms ); 01750 01751 // Read tokens until we get to the end of the directive. Note that the 01752 // directive can be split over multiple lines using the backslash character. 01753 DiscardUntilEndOfDirective(); 01754 } 01755 01756 /// HandleImportDirective - Implements \#import. 01757 /// 01758 void Preprocessor::HandleImportDirective(SourceLocation HashLoc, 01759 Token &ImportTok) { 01760 if (!LangOpts.ObjC1) { // #import is standard for ObjC. 01761 if (LangOpts.MSVCCompat) 01762 return HandleMicrosoftImportDirective(ImportTok); 01763 Diag(ImportTok, diag::ext_pp_import_directive); 01764 } 01765 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true); 01766 } 01767 01768 /// HandleIncludeMacrosDirective - The -imacros command line option turns into a 01769 /// pseudo directive in the predefines buffer. This handles it by sucking all 01770 /// tokens through the preprocessor and discarding them (only keeping the side 01771 /// effects on the preprocessor). 01772 void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc, 01773 Token &IncludeMacrosTok) { 01774 // This directive should only occur in the predefines buffer. If not, emit an 01775 // error and reject it. 01776 SourceLocation Loc = IncludeMacrosTok.getLocation(); 01777 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) { 01778 Diag(IncludeMacrosTok.getLocation(), 01779 diag::pp_include_macros_out_of_predefines); 01780 DiscardUntilEndOfDirective(); 01781 return; 01782 } 01783 01784 // Treat this as a normal #include for checking purposes. If this is 01785 // successful, it will push a new lexer onto the include stack. 01786 HandleIncludeDirective(HashLoc, IncludeMacrosTok); 01787 01788 Token TmpTok; 01789 do { 01790 Lex(TmpTok); 01791 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!"); 01792 } while (TmpTok.isNot(tok::hashhash)); 01793 } 01794 01795 //===----------------------------------------------------------------------===// 01796 // Preprocessor Macro Directive Handling. 01797 //===----------------------------------------------------------------------===// 01798 01799 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro 01800 /// definition has just been read. Lex the rest of the arguments and the 01801 /// closing ), updating MI with what we learn. Return true if an error occurs 01802 /// parsing the arg list. 01803 bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) { 01804 SmallVector<IdentifierInfo*, 32> Arguments; 01805 01806 while (1) { 01807 LexUnexpandedToken(Tok); 01808 switch (Tok.getKind()) { 01809 case tok::r_paren: 01810 // Found the end of the argument list. 01811 if (Arguments.empty()) // #define FOO() 01812 return false; 01813 // Otherwise we have #define FOO(A,) 01814 Diag(Tok, diag::err_pp_expected_ident_in_arg_list); 01815 return true; 01816 case tok::ellipsis: // #define X(... -> C99 varargs 01817 if (!LangOpts.C99) 01818 Diag(Tok, LangOpts.CPlusPlus11 ? 01819 diag::warn_cxx98_compat_variadic_macro : 01820 diag::ext_variadic_macro); 01821 01822 // OpenCL v1.2 s6.9.e: variadic macros are not supported. 01823 if (LangOpts.OpenCL) { 01824 Diag(Tok, diag::err_pp_opencl_variadic_macros); 01825 return true; 01826 } 01827 01828 // Lex the token after the identifier. 01829 LexUnexpandedToken(Tok); 01830 if (Tok.isNot(tok::r_paren)) { 01831 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); 01832 return true; 01833 } 01834 // Add the __VA_ARGS__ identifier as an argument. 01835 Arguments.push_back(Ident__VA_ARGS__); 01836 MI->setIsC99Varargs(); 01837 MI->setArgumentList(&Arguments[0], Arguments.size(), BP); 01838 return false; 01839 case tok::eod: // #define X( 01840 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); 01841 return true; 01842 default: 01843 // Handle keywords and identifiers here to accept things like 01844 // #define Foo(for) for. 01845 IdentifierInfo *II = Tok.getIdentifierInfo(); 01846 if (!II) { 01847 // #define X(1 01848 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list); 01849 return true; 01850 } 01851 01852 // If this is already used as an argument, it is used multiple times (e.g. 01853 // #define X(A,A. 01854 if (std::find(Arguments.begin(), Arguments.end(), II) != 01855 Arguments.end()) { // C99 6.10.3p6 01856 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II; 01857 return true; 01858 } 01859 01860 // Add the argument to the macro info. 01861 Arguments.push_back(II); 01862 01863 // Lex the token after the identifier. 01864 LexUnexpandedToken(Tok); 01865 01866 switch (Tok.getKind()) { 01867 default: // #define X(A B 01868 Diag(Tok, diag::err_pp_expected_comma_in_arg_list); 01869 return true; 01870 case tok::r_paren: // #define X(A) 01871 MI->setArgumentList(&Arguments[0], Arguments.size(), BP); 01872 return false; 01873 case tok::comma: // #define X(A, 01874 break; 01875 case tok::ellipsis: // #define X(A... -> GCC extension 01876 // Diagnose extension. 01877 Diag(Tok, diag::ext_named_variadic_macro); 01878 01879 // Lex the token after the identifier. 01880 LexUnexpandedToken(Tok); 01881 if (Tok.isNot(tok::r_paren)) { 01882 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); 01883 return true; 01884 } 01885 01886 MI->setIsGNUVarargs(); 01887 MI->setArgumentList(&Arguments[0], Arguments.size(), BP); 01888 return false; 01889 } 01890 } 01891 } 01892 } 01893 01894 /// HandleDefineDirective - Implements \#define. This consumes the entire macro 01895 /// line then lets the caller lex the next real token. 01896 void Preprocessor::HandleDefineDirective(Token &DefineTok, 01897 bool ImmediatelyAfterHeaderGuard) { 01898 ++NumDefined; 01899 01900 Token MacroNameTok; 01901 ReadMacroName(MacroNameTok, MU_Define); 01902 01903 // Error reading macro name? If so, diagnostic already issued. 01904 if (MacroNameTok.is(tok::eod)) 01905 return; 01906 01907 Token LastTok = MacroNameTok; 01908 01909 // If we are supposed to keep comments in #defines, reenable comment saving 01910 // mode. 01911 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments); 01912 01913 // Create the new macro. 01914 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation()); 01915 01916 Token Tok; 01917 LexUnexpandedToken(Tok); 01918 01919 // If this is a function-like macro definition, parse the argument list, 01920 // marking each of the identifiers as being used as macro arguments. Also, 01921 // check other constraints on the first token of the macro body. 01922 if (Tok.is(tok::eod)) { 01923 if (ImmediatelyAfterHeaderGuard) { 01924 // Save this macro information since it may part of a header guard. 01925 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(), 01926 MacroNameTok.getLocation()); 01927 } 01928 // If there is no body to this macro, we have no special handling here. 01929 } else if (Tok.hasLeadingSpace()) { 01930 // This is a normal token with leading space. Clear the leading space 01931 // marker on the first token to get proper expansion. 01932 Tok.clearFlag(Token::LeadingSpace); 01933 } else if (Tok.is(tok::l_paren)) { 01934 // This is a function-like macro definition. Read the argument list. 01935 MI->setIsFunctionLike(); 01936 if (ReadMacroDefinitionArgList(MI, LastTok)) { 01937 // Throw away the rest of the line. 01938 if (CurPPLexer->ParsingPreprocessorDirective) 01939 DiscardUntilEndOfDirective(); 01940 return; 01941 } 01942 01943 // If this is a definition of a variadic C99 function-like macro, not using 01944 // the GNU named varargs extension, enabled __VA_ARGS__. 01945 01946 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. 01947 // This gets unpoisoned where it is allowed. 01948 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!"); 01949 if (MI->isC99Varargs()) 01950 Ident__VA_ARGS__->setIsPoisoned(false); 01951 01952 // Read the first token after the arg list for down below. 01953 LexUnexpandedToken(Tok); 01954 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) { 01955 // C99 requires whitespace between the macro definition and the body. Emit 01956 // a diagnostic for something like "#define X+". 01957 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name); 01958 } else { 01959 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the 01960 // first character of a replacement list is not a character required by 01961 // subclause 5.2.1, then there shall be white-space separation between the 01962 // identifier and the replacement list.". 5.2.1 lists this set: 01963 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which 01964 // is irrelevant here. 01965 bool isInvalid = false; 01966 if (Tok.is(tok::at)) // @ is not in the list above. 01967 isInvalid = true; 01968 else if (Tok.is(tok::unknown)) { 01969 // If we have an unknown token, it is something strange like "`". Since 01970 // all of valid characters would have lexed into a single character 01971 // token of some sort, we know this is not a valid case. 01972 isInvalid = true; 01973 } 01974 if (isInvalid) 01975 Diag(Tok, diag::ext_missing_whitespace_after_macro_name); 01976 else 01977 Diag(Tok, diag::warn_missing_whitespace_after_macro_name); 01978 } 01979 01980 if (!Tok.is(tok::eod)) 01981 LastTok = Tok; 01982 01983 // Read the rest of the macro body. 01984 if (MI->isObjectLike()) { 01985 // Object-like macros are very simple, just read their body. 01986 while (Tok.isNot(tok::eod)) { 01987 LastTok = Tok; 01988 MI->AddTokenToBody(Tok); 01989 // Get the next token of the macro. 01990 LexUnexpandedToken(Tok); 01991 } 01992 01993 } else { 01994 // Otherwise, read the body of a function-like macro. While we are at it, 01995 // check C99 6.10.3.2p1: ensure that # operators are followed by macro 01996 // parameters in function-like macro expansions. 01997 while (Tok.isNot(tok::eod)) { 01998 LastTok = Tok; 01999 02000 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) { 02001 MI->AddTokenToBody(Tok); 02002 02003 // Get the next token of the macro. 02004 LexUnexpandedToken(Tok); 02005 continue; 02006 } 02007 02008 // If we're in -traditional mode, then we should ignore stringification 02009 // and token pasting. Mark the tokens as unknown so as not to confuse 02010 // things. 02011 if (getLangOpts().TraditionalCPP) { 02012 Tok.setKind(tok::unknown); 02013 MI->AddTokenToBody(Tok); 02014 02015 // Get the next token of the macro. 02016 LexUnexpandedToken(Tok); 02017 continue; 02018 } 02019 02020 if (Tok.is(tok::hashhash)) { 02021 02022 // If we see token pasting, check if it looks like the gcc comma 02023 // pasting extension. We'll use this information to suppress 02024 // diagnostics later on. 02025 02026 // Get the next token of the macro. 02027 LexUnexpandedToken(Tok); 02028 02029 if (Tok.is(tok::eod)) { 02030 MI->AddTokenToBody(LastTok); 02031 break; 02032 } 02033 02034 unsigned NumTokens = MI->getNumTokens(); 02035 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ && 02036 MI->getReplacementToken(NumTokens-1).is(tok::comma)) 02037 MI->setHasCommaPasting(); 02038 02039 // Things look ok, add the '##' token to the macro. 02040 MI->AddTokenToBody(LastTok); 02041 continue; 02042 } 02043 02044 // Get the next token of the macro. 02045 LexUnexpandedToken(Tok); 02046 02047 // Check for a valid macro arg identifier. 02048 if (Tok.getIdentifierInfo() == nullptr || 02049 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) { 02050 02051 // If this is assembler-with-cpp mode, we accept random gibberish after 02052 // the '#' because '#' is often a comment character. However, change 02053 // the kind of the token to tok::unknown so that the preprocessor isn't 02054 // confused. 02055 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) { 02056 LastTok.setKind(tok::unknown); 02057 MI->AddTokenToBody(LastTok); 02058 continue; 02059 } else { 02060 Diag(Tok, diag::err_pp_stringize_not_parameter); 02061 02062 // Disable __VA_ARGS__ again. 02063 Ident__VA_ARGS__->setIsPoisoned(true); 02064 return; 02065 } 02066 } 02067 02068 // Things look ok, add the '#' and param name tokens to the macro. 02069 MI->AddTokenToBody(LastTok); 02070 MI->AddTokenToBody(Tok); 02071 LastTok = Tok; 02072 02073 // Get the next token of the macro. 02074 LexUnexpandedToken(Tok); 02075 } 02076 } 02077 02078 02079 // Disable __VA_ARGS__ again. 02080 Ident__VA_ARGS__->setIsPoisoned(true); 02081 02082 // Check that there is no paste (##) operator at the beginning or end of the 02083 // replacement list. 02084 unsigned NumTokens = MI->getNumTokens(); 02085 if (NumTokens != 0) { 02086 if (MI->getReplacementToken(0).is(tok::hashhash)) { 02087 Diag(MI->getReplacementToken(0), diag::err_paste_at_start); 02088 return; 02089 } 02090 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) { 02091 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end); 02092 return; 02093 } 02094 } 02095 02096 MI->setDefinitionEndLoc(LastTok.getLocation()); 02097 02098 // Finally, if this identifier already had a macro defined for it, verify that 02099 // the macro bodies are identical, and issue diagnostics if they are not. 02100 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) { 02101 // It is very common for system headers to have tons of macro redefinitions 02102 // and for warnings to be disabled in system headers. If this is the case, 02103 // then don't bother calling MacroInfo::isIdenticalTo. 02104 if (!getDiagnostics().getSuppressSystemWarnings() || 02105 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) { 02106 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused()) 02107 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used); 02108 02109 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and 02110 // C++ [cpp.predefined]p4, but allow it as an extension. 02111 if (OtherMI->isBuiltinMacro()) 02112 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro); 02113 // Macros must be identical. This means all tokens and whitespace 02114 // separation must be the same. C99 6.10.3p2. 02115 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() && 02116 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) { 02117 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef) 02118 << MacroNameTok.getIdentifierInfo(); 02119 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition); 02120 } 02121 } 02122 if (OtherMI->isWarnIfUnused()) 02123 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc()); 02124 } 02125 02126 DefMacroDirective *MD = 02127 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI); 02128 02129 assert(!MI->isUsed()); 02130 // If we need warning for not using the macro, add its location in the 02131 // warn-because-unused-macro set. If it gets used it will be removed from set. 02132 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) && 02133 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) { 02134 MI->setIsWarnIfUnused(true); 02135 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc()); 02136 } 02137 02138 // If the callbacks want to know, tell them about the macro definition. 02139 if (Callbacks) 02140 Callbacks->MacroDefined(MacroNameTok, MD); 02141 } 02142 02143 /// HandleUndefDirective - Implements \#undef. 02144 /// 02145 void Preprocessor::HandleUndefDirective(Token &UndefTok) { 02146 ++NumUndefined; 02147 02148 Token MacroNameTok; 02149 ReadMacroName(MacroNameTok, MU_Undef); 02150 02151 // Error reading macro name? If so, diagnostic already issued. 02152 if (MacroNameTok.is(tok::eod)) 02153 return; 02154 02155 // Check to see if this is the last token on the #undef line. 02156 CheckEndOfDirective("undef"); 02157 02158 // Okay, we finally have a valid identifier to undef. 02159 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo()); 02160 const MacroInfo *MI = MD ? MD->getMacroInfo() : nullptr; 02161 02162 // If the callbacks want to know, tell them about the macro #undef. 02163 // Note: no matter if the macro was defined or not. 02164 if (Callbacks) 02165 Callbacks->MacroUndefined(MacroNameTok, MD); 02166 02167 // If the macro is not defined, this is a noop undef, just return. 02168 if (!MI) 02169 return; 02170 02171 if (!MI->isUsed() && MI->isWarnIfUnused()) 02172 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used); 02173 02174 if (MI->isWarnIfUnused()) 02175 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); 02176 02177 appendMacroDirective(MacroNameTok.getIdentifierInfo(), 02178 AllocateUndefMacroDirective(MacroNameTok.getLocation())); 02179 } 02180 02181 02182 //===----------------------------------------------------------------------===// 02183 // Preprocessor Conditional Directive Handling. 02184 //===----------------------------------------------------------------------===// 02185 02186 /// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef 02187 /// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is 02188 /// true if any tokens have been returned or pp-directives activated before this 02189 /// \#ifndef has been lexed. 02190 /// 02191 void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef, 02192 bool ReadAnyTokensBeforeDirective) { 02193 ++NumIf; 02194 Token DirectiveTok = Result; 02195 02196 Token MacroNameTok; 02197 ReadMacroName(MacroNameTok); 02198 02199 // Error reading macro name? If so, diagnostic already issued. 02200 if (MacroNameTok.is(tok::eod)) { 02201 // Skip code until we get to #endif. This helps with recovery by not 02202 // emitting an error when the #endif is reached. 02203 SkipExcludedConditionalBlock(DirectiveTok.getLocation(), 02204 /*Foundnonskip*/false, /*FoundElse*/false); 02205 return; 02206 } 02207 02208 // Check to see if this is the last token on the #if[n]def line. 02209 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef"); 02210 02211 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo(); 02212 MacroDirective *MD = getMacroDirective(MII); 02213 MacroInfo *MI = MD ? MD->getMacroInfo() : nullptr; 02214 02215 if (CurPPLexer->getConditionalStackDepth() == 0) { 02216 // If the start of a top-level #ifdef and if the macro is not defined, 02217 // inform MIOpt that this might be the start of a proper include guard. 02218 // Otherwise it is some other form of unknown conditional which we can't 02219 // handle. 02220 if (!ReadAnyTokensBeforeDirective && !MI) { 02221 assert(isIfndef && "#ifdef shouldn't reach here"); 02222 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation()); 02223 } else 02224 CurPPLexer->MIOpt.EnterTopLevelConditional(); 02225 } 02226 02227 // If there is a macro, process it. 02228 if (MI) // Mark it used. 02229 markMacroAsUsed(MI); 02230 02231 if (Callbacks) { 02232 if (isIfndef) 02233 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD); 02234 else 02235 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD); 02236 } 02237 02238 // Should we include the stuff contained by this directive? 02239 if (!MI == isIfndef) { 02240 // Yes, remember that we are inside a conditional, then lex the next token. 02241 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), 02242 /*wasskip*/false, /*foundnonskip*/true, 02243 /*foundelse*/false); 02244 } else { 02245 // No, skip the contents of this block. 02246 SkipExcludedConditionalBlock(DirectiveTok.getLocation(), 02247 /*Foundnonskip*/false, 02248 /*FoundElse*/false); 02249 } 02250 } 02251 02252 /// HandleIfDirective - Implements the \#if directive. 02253 /// 02254 void Preprocessor::HandleIfDirective(Token &IfToken, 02255 bool ReadAnyTokensBeforeDirective) { 02256 ++NumIf; 02257 02258 // Parse and evaluate the conditional expression. 02259 IdentifierInfo *IfNDefMacro = nullptr; 02260 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation(); 02261 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro); 02262 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation(); 02263 02264 // If this condition is equivalent to #ifndef X, and if this is the first 02265 // directive seen, handle it for the multiple-include optimization. 02266 if (CurPPLexer->getConditionalStackDepth() == 0) { 02267 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue) 02268 // FIXME: Pass in the location of the macro name, not the 'if' token. 02269 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation()); 02270 else 02271 CurPPLexer->MIOpt.EnterTopLevelConditional(); 02272 } 02273 02274 if (Callbacks) 02275 Callbacks->If(IfToken.getLocation(), 02276 SourceRange(ConditionalBegin, ConditionalEnd), 02277 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False)); 02278 02279 // Should we include the stuff contained by this directive? 02280 if (ConditionalTrue) { 02281 // Yes, remember that we are inside a conditional, then lex the next token. 02282 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false, 02283 /*foundnonskip*/true, /*foundelse*/false); 02284 } else { 02285 // No, skip the contents of this block. 02286 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false, 02287 /*FoundElse*/false); 02288 } 02289 } 02290 02291 /// HandleEndifDirective - Implements the \#endif directive. 02292 /// 02293 void Preprocessor::HandleEndifDirective(Token &EndifToken) { 02294 ++NumEndif; 02295 02296 // Check that this is the whole directive. 02297 CheckEndOfDirective("endif"); 02298 02299 PPConditionalInfo CondInfo; 02300 if (CurPPLexer->popConditionalLevel(CondInfo)) { 02301 // No conditionals on the stack: this is an #endif without an #if. 02302 Diag(EndifToken, diag::err_pp_endif_without_if); 02303 return; 02304 } 02305 02306 // If this the end of a top-level #endif, inform MIOpt. 02307 if (CurPPLexer->getConditionalStackDepth() == 0) 02308 CurPPLexer->MIOpt.ExitTopLevelConditional(); 02309 02310 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode && 02311 "This code should only be reachable in the non-skipping case!"); 02312 02313 if (Callbacks) 02314 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc); 02315 } 02316 02317 /// HandleElseDirective - Implements the \#else directive. 02318 /// 02319 void Preprocessor::HandleElseDirective(Token &Result) { 02320 ++NumElse; 02321 02322 // #else directive in a non-skipping conditional... start skipping. 02323 CheckEndOfDirective("else"); 02324 02325 PPConditionalInfo CI; 02326 if (CurPPLexer->popConditionalLevel(CI)) { 02327 Diag(Result, diag::pp_err_else_without_if); 02328 return; 02329 } 02330 02331 // If this is a top-level #else, inform the MIOpt. 02332 if (CurPPLexer->getConditionalStackDepth() == 0) 02333 CurPPLexer->MIOpt.EnterTopLevelConditional(); 02334 02335 // If this is a #else with a #else before it, report the error. 02336 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else); 02337 02338 if (Callbacks) 02339 Callbacks->Else(Result.getLocation(), CI.IfLoc); 02340 02341 // Finally, skip the rest of the contents of this block. 02342 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true, 02343 /*FoundElse*/true, Result.getLocation()); 02344 } 02345 02346 /// HandleElifDirective - Implements the \#elif directive. 02347 /// 02348 void Preprocessor::HandleElifDirective(Token &ElifToken) { 02349 ++NumElse; 02350 02351 // #elif directive in a non-skipping conditional... start skipping. 02352 // We don't care what the condition is, because we will always skip it (since 02353 // the block immediately before it was included). 02354 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation(); 02355 DiscardUntilEndOfDirective(); 02356 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation(); 02357 02358 PPConditionalInfo CI; 02359 if (CurPPLexer->popConditionalLevel(CI)) { 02360 Diag(ElifToken, diag::pp_err_elif_without_if); 02361 return; 02362 } 02363 02364 // If this is a top-level #elif, inform the MIOpt. 02365 if (CurPPLexer->getConditionalStackDepth() == 0) 02366 CurPPLexer->MIOpt.EnterTopLevelConditional(); 02367 02368 // If this is a #elif with a #else before it, report the error. 02369 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else); 02370 02371 if (Callbacks) 02372 Callbacks->Elif(ElifToken.getLocation(), 02373 SourceRange(ConditionalBegin, ConditionalEnd), 02374 PPCallbacks::CVK_NotEvaluated, CI.IfLoc); 02375 02376 // Finally, skip the rest of the contents of this block. 02377 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true, 02378 /*FoundElse*/CI.FoundElse, 02379 ElifToken.getLocation()); 02380 }