1 //===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file 11 /// \brief Implements # directive processing for the Preprocessor. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Basic/CharInfo.h" 16 #include "clang/Basic/FileManager.h" 17 #include "clang/Basic/IdentifierTable.h" 18 #include "clang/Basic/LangOptions.h" 19 #include "clang/Basic/Module.h" 20 #include "clang/Basic/SourceLocation.h" 21 #include "clang/Basic/SourceManager.h" 22 #include "clang/Basic/TokenKinds.h" 23 #include "clang/Lex/CodeCompletionHandler.h" 24 #include "clang/Lex/HeaderSearch.h" 25 #include "clang/Lex/LexDiagnostic.h" 26 #include "clang/Lex/LiteralSupport.h" 27 #include "clang/Lex/MacroInfo.h" 28 #include "clang/Lex/ModuleLoader.h" 29 #include "clang/Lex/ModuleMap.h" 30 #include "clang/Lex/PPCallbacks.h" 31 #include "clang/Lex/Pragma.h" 32 #include "clang/Lex/Preprocessor.h" 33 #include "clang/Lex/PreprocessorOptions.h" 34 #include "clang/Lex/PTHLexer.h" 35 #include "clang/Lex/Token.h" 36 #include "clang/Lex/VariadicMacroSupport.h" 37 #include "llvm/ADT/ArrayRef.h" 38 #include "llvm/ADT/SmallString.h" 39 #include "llvm/ADT/SmallVector.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/StringSwitch.h" 42 #include "llvm/ADT/StringRef.h" 43 #include "llvm/Support/AlignOf.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include "llvm/Support/Path.h" 46 #include <algorithm> 47 #include <cassert> 48 #include <cstring> 49 #include <new> 50 #include <string> 51 #include <utility> 52 53 using namespace clang; 54 55 //===----------------------------------------------------------------------===// 56 // Utility Methods for Preprocessor Directive Handling. 57 //===----------------------------------------------------------------------===// 58 59 MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) { 60 auto *MIChain = new (BP) MacroInfoChain{L, MIChainHead}; 61 MIChainHead = MIChain; 62 return &MIChain->MI; 63 } 64 65 DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, 66 SourceLocation Loc) { 67 return new (BP) DefMacroDirective(MI, Loc); 68 } 69 70 UndefMacroDirective * 71 Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) { 72 return new (BP) UndefMacroDirective(UndefLoc); 73 } 74 75 VisibilityMacroDirective * 76 Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc, 77 bool isPublic) { 78 return new (BP) VisibilityMacroDirective(Loc, isPublic); 79 } 80 81 /// \brief Read and discard all tokens remaining on the current line until 82 /// the tok::eod token is found. 83 void Preprocessor::DiscardUntilEndOfDirective() { 84 Token Tmp; 85 do { 86 LexUnexpandedToken(Tmp); 87 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens"); 88 } while (Tmp.isNot(tok::eod)); 89 } 90 91 /// \brief Enumerates possible cases of #define/#undef a reserved identifier. 92 enum MacroDiag { 93 MD_NoWarn, //> Not a reserved identifier 94 MD_KeywordDef, //> Macro hides keyword, enabled by default 95 MD_ReservedMacro //> #define of #undef reserved id, disabled by default 96 }; 97 98 /// \brief Checks if the specified identifier is reserved in the specified 99 /// language. 100 /// This function does not check if the identifier is a keyword. 101 static bool isReservedId(StringRef Text, const LangOptions &Lang) { 102 // C++ [macro.names], C11 7.1.3: 103 // All identifiers that begin with an underscore and either an uppercase 104 // letter or another underscore are always reserved for any use. 105 if (Text.size() >= 2 && Text[0] == '_' && 106 (isUppercase(Text[1]) || Text[1] == '_')) 107 return true; 108 // C++ [global.names] 109 // Each name that contains a double underscore ... is reserved to the 110 // implementation for any use. 111 if (Lang.CPlusPlus) { 112 if (Text.find("__") != StringRef::npos) 113 return true; 114 } 115 return false; 116 } 117 118 static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) { 119 const LangOptions &Lang = PP.getLangOpts(); 120 StringRef Text = II->getName(); 121 if (isReservedId(Text, Lang)) 122 return MD_ReservedMacro; 123 if (II->isKeyword(Lang)) 124 return MD_KeywordDef; 125 if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final"))) 126 return MD_KeywordDef; 127 return MD_NoWarn; 128 } 129 130 static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) { 131 const LangOptions &Lang = PP.getLangOpts(); 132 StringRef Text = II->getName(); 133 // Do not warn on keyword undef. It is generally harmless and widely used. 134 if (isReservedId(Text, Lang)) 135 return MD_ReservedMacro; 136 return MD_NoWarn; 137 } 138 139 // Return true if we want to issue a diagnostic by default if we 140 // encounter this name in a #include with the wrong case. For now, 141 // this includes the standard C and C++ headers, Posix headers, 142 // and Boost headers. Improper case for these #includes is a 143 // potential portability issue. 144 static bool warnByDefaultOnWrongCase(StringRef Include) { 145 // If the first component of the path is "boost", treat this like a standard header 146 // for the purposes of diagnostics. 147 if (::llvm::sys::path::begin(Include)->equals_lower("boost")) 148 return true; 149 150 // "condition_variable" is the longest standard header name at 18 characters. 151 // If the include file name is longer than that, it can't be a standard header. 152 static const size_t MaxStdHeaderNameLen = 18u; 153 if (Include.size() > MaxStdHeaderNameLen) 154 return false; 155 156 // Lowercase and normalize the search string. 157 SmallString<32> LowerInclude{Include}; 158 for (char &Ch : LowerInclude) { 159 // In the ASCII range? 160 if (static_cast<unsigned char>(Ch) > 0x7f) 161 return false; // Can't be a standard header 162 // ASCII lowercase: 163 if (Ch >= 'A' && Ch <= 'Z') 164 Ch += 'a' - 'A'; 165 // Normalize path separators for comparison purposes. 166 else if (::llvm::sys::path::is_separator(Ch)) 167 Ch = '/'; 168 } 169 170 // The standard C/C++ and Posix headers 171 return llvm::StringSwitch<bool>(LowerInclude) 172 // C library headers 173 .Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true) 174 .Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true) 175 .Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true) 176 .Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true) 177 .Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true) 178 .Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true) 179 180 // C++ headers for C library facilities 181 .Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true) 182 .Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true) 183 .Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true) 184 .Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true) 185 .Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true) 186 .Case("cwctype", true) 187 188 // C++ library headers 189 .Cases("algorithm", "fstream", "list", "regex", "thread", true) 190 .Cases("array", "functional", "locale", "scoped_allocator", "tuple", true) 191 .Cases("atomic", "future", "map", "set", "type_traits", true) 192 .Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true) 193 .Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true) 194 .Cases("codecvt", "ios", "new", "stack", "unordered_map", true) 195 .Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true) 196 .Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true) 197 .Cases("deque", "istream", "queue", "string", "valarray", true) 198 .Cases("exception", "iterator", "random", "strstream", "vector", true) 199 .Cases("forward_list", "limits", "ratio", "system_error", true) 200 201 // POSIX headers (which aren't also C headers) 202 .Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true) 203 .Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true) 204 .Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true) 205 .Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true) 206 .Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true) 207 .Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true) 208 .Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true) 209 .Cases("sys/resource.h", "sys/select.h", "sys/sem.h", "sys/shm.h", "sys/socket.h", true) 210 .Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true) 211 .Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true) 212 .Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true) 213 .Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true) 214 .Default(false); 215 } 216 217 bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef, 218 bool *ShadowFlag) { 219 // Missing macro name? 220 if (MacroNameTok.is(tok::eod)) 221 return Diag(MacroNameTok, diag::err_pp_missing_macro_name); 222 223 IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); 224 if (!II) 225 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier); 226 227 if (II->isCPlusPlusOperatorKeyword()) { 228 // C++ 2.5p2: Alternative tokens behave the same as its primary token 229 // except for their spellings. 230 Diag(MacroNameTok, getLangOpts().MicrosoftExt 231 ? diag::ext_pp_operator_used_as_macro_name 232 : diag::err_pp_operator_used_as_macro_name) 233 << II << MacroNameTok.getKind(); 234 // Allow #defining |and| and friends for Microsoft compatibility or 235 // recovery when legacy C headers are included in C++. 236 } 237 238 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) { 239 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4. 240 return Diag(MacroNameTok, diag::err_defined_macro_name); 241 } 242 243 if (isDefineUndef == MU_Undef) { 244 auto *MI = getMacroInfo(II); 245 if (MI && MI->isBuiltinMacro()) { 246 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4 247 // and C++ [cpp.predefined]p4], but allow it as an extension. 248 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro); 249 } 250 } 251 252 // If defining/undefining reserved identifier or a keyword, we need to issue 253 // a warning. 254 SourceLocation MacroNameLoc = MacroNameTok.getLocation(); 255 if (ShadowFlag) 256 *ShadowFlag = false; 257 if (!SourceMgr.isInSystemHeader(MacroNameLoc) && 258 (SourceMgr.getBufferName(MacroNameLoc) != "<built-in>")) { 259 MacroDiag D = MD_NoWarn; 260 if (isDefineUndef == MU_Define) { 261 D = shouldWarnOnMacroDef(*this, II); 262 } 263 else if (isDefineUndef == MU_Undef) 264 D = shouldWarnOnMacroUndef(*this, II); 265 if (D == MD_KeywordDef) { 266 // We do not want to warn on some patterns widely used in configuration 267 // scripts. This requires analyzing next tokens, so do not issue warnings 268 // now, only inform caller. 269 if (ShadowFlag) 270 *ShadowFlag = true; 271 } 272 if (D == MD_ReservedMacro) 273 Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id); 274 } 275 276 // Okay, we got a good identifier. 277 return false; 278 } 279 280 /// \brief Lex and validate a macro name, which occurs after a 281 /// \#define or \#undef. 282 /// 283 /// This sets the token kind to eod and discards the rest of the macro line if 284 /// the macro name is invalid. 285 /// 286 /// \param MacroNameTok Token that is expected to be a macro name. 287 /// \param isDefineUndef Context in which macro is used. 288 /// \param ShadowFlag Points to a flag that is set if macro shadows a keyword. 289 void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef, 290 bool *ShadowFlag) { 291 // Read the token, don't allow macro expansion on it. 292 LexUnexpandedToken(MacroNameTok); 293 294 if (MacroNameTok.is(tok::code_completion)) { 295 if (CodeComplete) 296 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define); 297 setCodeCompletionReached(); 298 LexUnexpandedToken(MacroNameTok); 299 } 300 301 if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag)) 302 return; 303 304 // Invalid macro name, read and discard the rest of the line and set the 305 // token kind to tok::eod if necessary. 306 if (MacroNameTok.isNot(tok::eod)) { 307 MacroNameTok.setKind(tok::eod); 308 DiscardUntilEndOfDirective(); 309 } 310 } 311 312 /// \brief Ensure that the next token is a tok::eod token. 313 /// 314 /// If not, emit a diagnostic and consume up until the eod. If EnableMacros is 315 /// true, then we consider macros that expand to zero tokens as being ok. 316 void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) { 317 Token Tmp; 318 // Lex unexpanded tokens for most directives: macros might expand to zero 319 // tokens, causing us to miss diagnosing invalid lines. Some directives (like 320 // #line) allow empty macros. 321 if (EnableMacros) 322 Lex(Tmp); 323 else 324 LexUnexpandedToken(Tmp); 325 326 // There should be no tokens after the directive, but we allow them as an 327 // extension. 328 while (Tmp.is(tok::comment)) // Skip comments in -C mode. 329 LexUnexpandedToken(Tmp); 330 331 if (Tmp.isNot(tok::eod)) { 332 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89, 333 // or if this is a macro-style preprocessing directive, because it is more 334 // trouble than it is worth to insert /**/ and check that there is no /**/ 335 // in the range also. 336 FixItHint Hint; 337 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) && 338 !CurTokenLexer) 339 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//"); 340 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint; 341 DiscardUntilEndOfDirective(); 342 } 343 } 344 345 /// SkipExcludedConditionalBlock - We just read a \#if or related directive and 346 /// decided that the subsequent tokens are in the \#if'd out portion of the 347 /// file. Lex the rest of the file, until we see an \#endif. If 348 /// FoundNonSkipPortion is true, then we have already emitted code for part of 349 /// this \#if directive, so \#else/\#elif blocks should never be entered. 350 /// If ElseOk is true, then \#else directives are ok, if not, then we have 351 /// already seen one so a \#else directive is a duplicate. When this returns, 352 /// the caller can lex the first valid token. 353 void Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc, 354 SourceLocation IfTokenLoc, 355 bool FoundNonSkipPortion, 356 bool FoundElse, 357 SourceLocation ElseLoc) { 358 ++NumSkipped; 359 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?"); 360 361 if (PreambleConditionalStack.reachedEOFWhileSkipping()) 362 PreambleConditionalStack.clearSkipInfo(); 363 else 364 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/ false, 365 FoundNonSkipPortion, FoundElse); 366 367 if (CurPTHLexer) { 368 PTHSkipExcludedConditionalBlock(); 369 return; 370 } 371 372 // Enter raw mode to disable identifier lookup (and thus macro expansion), 373 // disabling warnings, etc. 374 CurPPLexer->LexingRawMode = true; 375 Token Tok; 376 while (true) { 377 CurLexer->Lex(Tok); 378 379 if (Tok.is(tok::code_completion)) { 380 if (CodeComplete) 381 CodeComplete->CodeCompleteInConditionalExclusion(); 382 setCodeCompletionReached(); 383 continue; 384 } 385 386 // If this is the end of the buffer, we have an error. 387 if (Tok.is(tok::eof)) { 388 // We don't emit errors for unterminated conditionals here, 389 // Lexer::LexEndOfFile can do that propertly. 390 // Just return and let the caller lex after this #include. 391 if (PreambleConditionalStack.isRecording()) 392 PreambleConditionalStack.SkipInfo.emplace( 393 HashTokenLoc, IfTokenLoc, FoundNonSkipPortion, FoundElse, ElseLoc); 394 break; 395 } 396 397 // If this token is not a preprocessor directive, just skip it. 398 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) 399 continue; 400 401 // We just parsed a # character at the start of a line, so we're in 402 // directive mode. Tell the lexer this so any newlines we see will be 403 // converted into an EOD token (this terminates the macro). 404 CurPPLexer->ParsingPreprocessorDirective = true; 405 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false); 406 407 408 // Read the next token, the directive flavor. 409 LexUnexpandedToken(Tok); 410 411 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or 412 // something bogus), skip it. 413 if (Tok.isNot(tok::raw_identifier)) { 414 CurPPLexer->ParsingPreprocessorDirective = false; 415 // Restore comment saving mode. 416 if (CurLexer) CurLexer->resetExtendedTokenMode(); 417 continue; 418 } 419 420 // If the first letter isn't i or e, it isn't intesting to us. We know that 421 // this is safe in the face of spelling differences, because there is no way 422 // to spell an i/e in a strange way that is another letter. Skipping this 423 // allows us to avoid looking up the identifier info for #define/#undef and 424 // other common directives. 425 StringRef RI = Tok.getRawIdentifier(); 426 427 char FirstChar = RI[0]; 428 if (FirstChar >= 'a' && FirstChar <= 'z' && 429 FirstChar != 'i' && FirstChar != 'e') { 430 CurPPLexer->ParsingPreprocessorDirective = false; 431 // Restore comment saving mode. 432 if (CurLexer) CurLexer->resetExtendedTokenMode(); 433 continue; 434 } 435 436 // Get the identifier name without trigraphs or embedded newlines. Note 437 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled 438 // when skipping. 439 char DirectiveBuf[20]; 440 StringRef Directive; 441 if (!Tok.needsCleaning() && RI.size() < 20) { 442 Directive = RI; 443 } else { 444 std::string DirectiveStr = getSpelling(Tok); 445 size_t IdLen = DirectiveStr.size(); 446 if (IdLen >= 20) { 447 CurPPLexer->ParsingPreprocessorDirective = false; 448 // Restore comment saving mode. 449 if (CurLexer) CurLexer->resetExtendedTokenMode(); 450 continue; 451 } 452 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen); 453 Directive = StringRef(DirectiveBuf, IdLen); 454 } 455 456 if (Directive.startswith("if")) { 457 StringRef Sub = Directive.substr(2); 458 if (Sub.empty() || // "if" 459 Sub == "def" || // "ifdef" 460 Sub == "ndef") { // "ifndef" 461 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't 462 // bother parsing the condition. 463 DiscardUntilEndOfDirective(); 464 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true, 465 /*foundnonskip*/false, 466 /*foundelse*/false); 467 } 468 } else if (Directive[0] == 'e') { 469 StringRef Sub = Directive.substr(1); 470 if (Sub == "ndif") { // "endif" 471 PPConditionalInfo CondInfo; 472 CondInfo.WasSkipping = true; // Silence bogus warning. 473 bool InCond = CurPPLexer->popConditionalLevel(CondInfo); 474 (void)InCond; // Silence warning in no-asserts mode. 475 assert(!InCond && "Can't be skipping if not in a conditional!"); 476 477 // If we popped the outermost skipping block, we're done skipping! 478 if (!CondInfo.WasSkipping) { 479 // Restore the value of LexingRawMode so that trailing comments 480 // are handled correctly, if we've reached the outermost block. 481 CurPPLexer->LexingRawMode = false; 482 CheckEndOfDirective("endif"); 483 CurPPLexer->LexingRawMode = true; 484 if (Callbacks) 485 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc); 486 break; 487 } else { 488 DiscardUntilEndOfDirective(); 489 } 490 } else if (Sub == "lse") { // "else". 491 // #else directive in a skipping conditional. If not in some other 492 // skipping conditional, and if #else hasn't already been seen, enter it 493 // as a non-skipping conditional. 494 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); 495 496 // If this is a #else with a #else before it, report the error. 497 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else); 498 499 // Note that we've seen a #else in this conditional. 500 CondInfo.FoundElse = true; 501 502 // If the conditional is at the top level, and the #if block wasn't 503 // entered, enter the #else block now. 504 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) { 505 CondInfo.FoundNonSkip = true; 506 // Restore the value of LexingRawMode so that trailing comments 507 // are handled correctly. 508 CurPPLexer->LexingRawMode = false; 509 CheckEndOfDirective("else"); 510 CurPPLexer->LexingRawMode = true; 511 if (Callbacks) 512 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc); 513 break; 514 } else { 515 DiscardUntilEndOfDirective(); // C99 6.10p4. 516 } 517 } else if (Sub == "lif") { // "elif". 518 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); 519 520 // If this is a #elif with a #else before it, report the error. 521 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else); 522 523 // If this is in a skipping block or if we're already handled this #if 524 // block, don't bother parsing the condition. 525 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) { 526 DiscardUntilEndOfDirective(); 527 } else { 528 const SourceLocation CondBegin = CurPPLexer->getSourceLocation(); 529 // Restore the value of LexingRawMode so that identifiers are 530 // looked up, etc, inside the #elif expression. 531 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!"); 532 CurPPLexer->LexingRawMode = false; 533 IdentifierInfo *IfNDefMacro = nullptr; 534 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro).Conditional; 535 CurPPLexer->LexingRawMode = true; 536 if (Callbacks) { 537 const SourceLocation CondEnd = CurPPLexer->getSourceLocation(); 538 Callbacks->Elif(Tok.getLocation(), 539 SourceRange(CondBegin, CondEnd), 540 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc); 541 } 542 // If this condition is true, enter it! 543 if (CondValue) { 544 CondInfo.FoundNonSkip = true; 545 break; 546 } 547 } 548 } 549 } 550 551 CurPPLexer->ParsingPreprocessorDirective = false; 552 // Restore comment saving mode. 553 if (CurLexer) CurLexer->resetExtendedTokenMode(); 554 } 555 556 // Finally, if we are out of the conditional (saw an #endif or ran off the end 557 // of the file, just stop skipping and return to lexing whatever came after 558 // the #if block. 559 CurPPLexer->LexingRawMode = false; 560 561 // The last skipped range isn't actually skipped yet if it's truncated 562 // by the end of the preamble; we'll resume parsing after the preamble. 563 if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble())) 564 Callbacks->SourceRangeSkipped( 565 SourceRange(HashTokenLoc, CurPPLexer->getSourceLocation()), 566 Tok.getLocation()); 567 } 568 569 void Preprocessor::PTHSkipExcludedConditionalBlock() { 570 while (true) { 571 assert(CurPTHLexer); 572 assert(CurPTHLexer->LexingRawMode == false); 573 574 // Skip to the next '#else', '#elif', or #endif. 575 if (CurPTHLexer->SkipBlock()) { 576 // We have reached an #endif. Both the '#' and 'endif' tokens 577 // have been consumed by the PTHLexer. Just pop off the condition level. 578 PPConditionalInfo CondInfo; 579 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo); 580 (void)InCond; // Silence warning in no-asserts mode. 581 assert(!InCond && "Can't be skipping if not in a conditional!"); 582 break; 583 } 584 585 // We have reached a '#else' or '#elif'. Lex the next token to get 586 // the directive flavor. 587 Token Tok; 588 LexUnexpandedToken(Tok); 589 590 // We can actually look up the IdentifierInfo here since we aren't in 591 // raw mode. 592 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID(); 593 594 if (K == tok::pp_else) { 595 // #else: Enter the else condition. We aren't in a nested condition 596 // since we skip those. We're always in the one matching the last 597 // blocked we skipped. 598 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel(); 599 // Note that we've seen a #else in this conditional. 600 CondInfo.FoundElse = true; 601 602 // If the #if block wasn't entered then enter the #else block now. 603 if (!CondInfo.FoundNonSkip) { 604 CondInfo.FoundNonSkip = true; 605 606 // Scan until the eod token. 607 CurPTHLexer->ParsingPreprocessorDirective = true; 608 DiscardUntilEndOfDirective(); 609 CurPTHLexer->ParsingPreprocessorDirective = false; 610 611 break; 612 } 613 614 // Otherwise skip this block. 615 continue; 616 } 617 618 assert(K == tok::pp_elif); 619 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel(); 620 621 // If this is a #elif with a #else before it, report the error. 622 if (CondInfo.FoundElse) 623 Diag(Tok, diag::pp_err_elif_after_else); 624 625 // If this is in a skipping block or if we're already handled this #if 626 // block, don't bother parsing the condition. We just skip this block. 627 if (CondInfo.FoundNonSkip) 628 continue; 629 630 // Evaluate the condition of the #elif. 631 IdentifierInfo *IfNDefMacro = nullptr; 632 CurPTHLexer->ParsingPreprocessorDirective = true; 633 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro).Conditional; 634 CurPTHLexer->ParsingPreprocessorDirective = false; 635 636 // If this condition is true, enter it! 637 if (ShouldEnter) { 638 CondInfo.FoundNonSkip = true; 639 break; 640 } 641 642 // Otherwise, skip this block and go to the next one. 643 } 644 } 645 646 Module *Preprocessor::getModuleForLocation(SourceLocation Loc) { 647 if (!SourceMgr.isInMainFile(Loc)) { 648 // Try to determine the module of the include directive. 649 // FIXME: Look into directly passing the FileEntry from LookupFile instead. 650 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc)); 651 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) { 652 // The include comes from an included file. 653 return HeaderInfo.getModuleMap() 654 .findModuleForHeader(EntryOfIncl) 655 .getModule(); 656 } 657 } 658 659 // This is either in the main file or not in a file at all. It belongs 660 // to the current module, if there is one. 661 return getLangOpts().CurrentModule.empty() 662 ? nullptr 663 : HeaderInfo.lookupModule(getLangOpts().CurrentModule); 664 } 665 666 const FileEntry * 667 Preprocessor::getModuleHeaderToIncludeForDiagnostics(SourceLocation IncLoc, 668 Module *M, 669 SourceLocation Loc) { 670 assert(M && "no module to include"); 671 672 // If we have a module import syntax, we shouldn't include a header to 673 // make a particular module visible. 674 if (getLangOpts().ObjC2) 675 return nullptr; 676 677 Module *TopM = M->getTopLevelModule(); 678 Module *IncM = getModuleForLocation(IncLoc); 679 680 // Walk up through the include stack, looking through textual headers of M 681 // until we hit a non-textual header that we can #include. (We assume textual 682 // headers of a module with non-textual headers aren't meant to be used to 683 // import entities from the module.) 684 auto &SM = getSourceManager(); 685 while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) { 686 auto ID = SM.getFileID(SM.getExpansionLoc(Loc)); 687 auto *FE = SM.getFileEntryForID(ID); 688 if (!FE) 689 break; 690 691 bool InTextualHeader = false; 692 for (auto Header : HeaderInfo.getModuleMap().findAllModulesForHeader(FE)) { 693 if (!Header.getModule()->isSubModuleOf(TopM)) 694 continue; 695 696 if (!(Header.getRole() & ModuleMap::TextualHeader)) { 697 // If this is an accessible, non-textual header of M's top-level module 698 // that transitively includes the given location and makes the 699 // corresponding module visible, this is the thing to #include. 700 if (Header.isAccessibleFrom(IncM)) 701 return FE; 702 703 // It's in a private header; we can't #include it. 704 // FIXME: If there's a public header in some module that re-exports it, 705 // then we could suggest including that, but it's not clear that's the 706 // expected way to make this entity visible. 707 continue; 708 } 709 710 InTextualHeader = true; 711 } 712 713 if (!InTextualHeader) 714 break; 715 716 Loc = SM.getIncludeLoc(ID); 717 } 718 719 return nullptr; 720 } 721 722 const FileEntry *Preprocessor::LookupFile( 723 SourceLocation FilenameLoc, StringRef Filename, bool isAngled, 724 const DirectoryLookup *FromDir, const FileEntry *FromFile, 725 const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath, 726 SmallVectorImpl<char> *RelativePath, 727 ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool SkipCache) { 728 Module *RequestingModule = getModuleForLocation(FilenameLoc); 729 bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc); 730 731 // If the header lookup mechanism may be relative to the current inclusion 732 // stack, record the parent #includes. 733 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16> 734 Includers; 735 bool BuildSystemModule = false; 736 if (!FromDir && !FromFile) { 737 FileID FID = getCurrentFileLexer()->getFileID(); 738 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID); 739 740 // If there is no file entry associated with this file, it must be the 741 // predefines buffer or the module includes buffer. Any other file is not 742 // lexed with a normal lexer, so it won't be scanned for preprocessor 743 // directives. 744 // 745 // If we have the predefines buffer, resolve #include references (which come 746 // from the -include command line argument) from the current working 747 // directory instead of relative to the main file. 748 // 749 // If we have the module includes buffer, resolve #include references (which 750 // come from header declarations in the module map) relative to the module 751 // map file. 752 if (!FileEnt) { 753 if (FID == SourceMgr.getMainFileID() && MainFileDir) { 754 Includers.push_back(std::make_pair(nullptr, MainFileDir)); 755 BuildSystemModule = getCurrentModule()->IsSystem; 756 } else if ((FileEnt = 757 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))) 758 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory("."))); 759 } else { 760 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir())); 761 } 762 763 // MSVC searches the current include stack from top to bottom for 764 // headers included by quoted include directives. 765 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx 766 if (LangOpts.MSVCCompat && !isAngled) { 767 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) { 768 if (IsFileLexer(ISEntry)) 769 if ((FileEnt = ISEntry.ThePPLexer->getFileEntry())) 770 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir())); 771 } 772 } 773 } 774 775 CurDir = CurDirLookup; 776 777 if (FromFile) { 778 // We're supposed to start looking from after a particular file. Search 779 // the include path until we find that file or run out of files. 780 const DirectoryLookup *TmpCurDir = CurDir; 781 const DirectoryLookup *TmpFromDir = nullptr; 782 while (const FileEntry *FE = HeaderInfo.LookupFile( 783 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir, 784 Includers, SearchPath, RelativePath, RequestingModule, 785 SuggestedModule, /*IsMapped=*/nullptr, SkipCache)) { 786 // Keep looking as if this file did a #include_next. 787 TmpFromDir = TmpCurDir; 788 ++TmpFromDir; 789 if (FE == FromFile) { 790 // Found it. 791 FromDir = TmpFromDir; 792 CurDir = TmpCurDir; 793 break; 794 } 795 } 796 } 797 798 // Do a standard file entry lookup. 799 const FileEntry *FE = HeaderInfo.LookupFile( 800 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath, 801 RelativePath, RequestingModule, SuggestedModule, IsMapped, SkipCache, 802 BuildSystemModule); 803 if (FE) { 804 if (SuggestedModule && !LangOpts.AsmPreprocessor) 805 HeaderInfo.getModuleMap().diagnoseHeaderInclusion( 806 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc, 807 Filename, FE); 808 return FE; 809 } 810 811 const FileEntry *CurFileEnt; 812 // Otherwise, see if this is a subframework header. If so, this is relative 813 // to one of the headers on the #include stack. Walk the list of the current 814 // headers on the #include stack and pass them to HeaderInfo. 815 if (IsFileLexer()) { 816 if ((CurFileEnt = CurPPLexer->getFileEntry())) { 817 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt, 818 SearchPath, RelativePath, 819 RequestingModule, 820 SuggestedModule))) { 821 if (SuggestedModule && !LangOpts.AsmPreprocessor) 822 HeaderInfo.getModuleMap().diagnoseHeaderInclusion( 823 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc, 824 Filename, FE); 825 return FE; 826 } 827 } 828 } 829 830 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) { 831 if (IsFileLexer(ISEntry)) { 832 if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) { 833 if ((FE = HeaderInfo.LookupSubframeworkHeader( 834 Filename, CurFileEnt, SearchPath, RelativePath, 835 RequestingModule, SuggestedModule))) { 836 if (SuggestedModule && !LangOpts.AsmPreprocessor) 837 HeaderInfo.getModuleMap().diagnoseHeaderInclusion( 838 RequestingModule, RequestingModuleIsModuleInterface, 839 FilenameLoc, Filename, FE); 840 return FE; 841 } 842 } 843 } 844 } 845 846 // Otherwise, we really couldn't find the file. 847 return nullptr; 848 } 849 850 //===----------------------------------------------------------------------===// 851 // Preprocessor Directive Handling. 852 //===----------------------------------------------------------------------===// 853 854 class Preprocessor::ResetMacroExpansionHelper { 855 public: 856 ResetMacroExpansionHelper(Preprocessor *pp) 857 : PP(pp), save(pp->DisableMacroExpansion) { 858 if (pp->MacroExpansionInDirectivesOverride) 859 pp->DisableMacroExpansion = false; 860 } 861 862 ~ResetMacroExpansionHelper() { 863 PP->DisableMacroExpansion = save; 864 } 865 866 private: 867 Preprocessor *PP; 868 bool save; 869 }; 870 871 /// HandleDirective - This callback is invoked when the lexer sees a # token 872 /// at the start of a line. This consumes the directive, modifies the 873 /// lexer/preprocessor state, and advances the lexer(s) so that the next token 874 /// read is the correct one. 875 void Preprocessor::HandleDirective(Token &Result) { 876 // FIXME: Traditional: # with whitespace before it not recognized by K&R? 877 878 // We just parsed a # character at the start of a line, so we're in directive 879 // mode. Tell the lexer this so any newlines we see will be converted into an 880 // EOD token (which terminates the directive). 881 CurPPLexer->ParsingPreprocessorDirective = true; 882 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false); 883 884 bool ImmediatelyAfterTopLevelIfndef = 885 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef(); 886 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef(); 887 888 ++NumDirectives; 889 890 // We are about to read a token. For the multiple-include optimization FA to 891 // work, we have to remember if we had read any tokens *before* this 892 // pp-directive. 893 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal(); 894 895 // Save the '#' token in case we need to return it later. 896 Token SavedHash = Result; 897 898 // Read the next token, the directive flavor. This isn't expanded due to 899 // C99 6.10.3p8. 900 LexUnexpandedToken(Result); 901 902 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.: 903 // #define A(x) #x 904 // A(abc 905 // #warning blah 906 // def) 907 // If so, the user is relying on undefined behavior, emit a diagnostic. Do 908 // not support this for #include-like directives, since that can result in 909 // terrible diagnostics, and does not work in GCC. 910 if (InMacroArgs) { 911 if (IdentifierInfo *II = Result.getIdentifierInfo()) { 912 switch (II->getPPKeywordID()) { 913 case tok::pp_include: 914 case tok::pp_import: 915 case tok::pp_include_next: 916 case tok::pp___include_macros: 917 case tok::pp_pragma: 918 Diag(Result, diag::err_embedded_directive) << II->getName(); 919 DiscardUntilEndOfDirective(); 920 return; 921 default: 922 break; 923 } 924 } 925 Diag(Result, diag::ext_embedded_directive); 926 } 927 928 // Temporarily enable macro expansion if set so 929 // and reset to previous state when returning from this function. 930 ResetMacroExpansionHelper helper(this); 931 932 switch (Result.getKind()) { 933 case tok::eod: 934 return; // null directive. 935 case tok::code_completion: 936 if (CodeComplete) 937 CodeComplete->CodeCompleteDirective( 938 CurPPLexer->getConditionalStackDepth() > 0); 939 setCodeCompletionReached(); 940 return; 941 case tok::numeric_constant: // # 7 GNU line marker directive. 942 if (getLangOpts().AsmPreprocessor) 943 break; // # 4 is not a preprocessor directive in .S files. 944 return HandleDigitDirective(Result); 945 default: 946 IdentifierInfo *II = Result.getIdentifierInfo(); 947 if (!II) break; // Not an identifier. 948 949 // Ask what the preprocessor keyword ID is. 950 switch (II->getPPKeywordID()) { 951 default: break; 952 // C99 6.10.1 - Conditional Inclusion. 953 case tok::pp_if: 954 return HandleIfDirective(Result, SavedHash, ReadAnyTokensBeforeDirective); 955 case tok::pp_ifdef: 956 return HandleIfdefDirective(Result, SavedHash, false, 957 true /*not valid for miopt*/); 958 case tok::pp_ifndef: 959 return HandleIfdefDirective(Result, SavedHash, true, 960 ReadAnyTokensBeforeDirective); 961 case tok::pp_elif: 962 return HandleElifDirective(Result, SavedHash); 963 case tok::pp_else: 964 return HandleElseDirective(Result, SavedHash); 965 case tok::pp_endif: 966 return HandleEndifDirective(Result); 967 968 // C99 6.10.2 - Source File Inclusion. 969 case tok::pp_include: 970 // Handle #include. 971 return HandleIncludeDirective(SavedHash.getLocation(), Result); 972 case tok::pp___include_macros: 973 // Handle -imacros. 974 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result); 975 976 // C99 6.10.3 - Macro Replacement. 977 case tok::pp_define: 978 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef); 979 case tok::pp_undef: 980 return HandleUndefDirective(); 981 982 // C99 6.10.4 - Line Control. 983 case tok::pp_line: 984 return HandleLineDirective(); 985 986 // C99 6.10.5 - Error Directive. 987 case tok::pp_error: 988 return HandleUserDiagnosticDirective(Result, false); 989 990 // C99 6.10.6 - Pragma Directive. 991 case tok::pp_pragma: 992 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma); 993 994 // GNU Extensions. 995 case tok::pp_import: 996 return HandleImportDirective(SavedHash.getLocation(), Result); 997 case tok::pp_include_next: 998 return HandleIncludeNextDirective(SavedHash.getLocation(), Result); 999 1000 case tok::pp_warning: 1001 Diag(Result, diag::ext_pp_warning_directive); 1002 return HandleUserDiagnosticDirective(Result, true); 1003 case tok::pp_ident: 1004 return HandleIdentSCCSDirective(Result); 1005 case tok::pp_sccs: 1006 return HandleIdentSCCSDirective(Result); 1007 case tok::pp_assert: 1008 //isExtension = true; // FIXME: implement #assert 1009 break; 1010 case tok::pp_unassert: 1011 //isExtension = true; // FIXME: implement #unassert 1012 break; 1013 1014 case tok::pp___public_macro: 1015 if (getLangOpts().Modules) 1016 return HandleMacroPublicDirective(Result); 1017 break; 1018 1019 case tok::pp___private_macro: 1020 if (getLangOpts().Modules) 1021 return HandleMacroPrivateDirective(); 1022 break; 1023 } 1024 break; 1025 } 1026 1027 // If this is a .S file, treat unknown # directives as non-preprocessor 1028 // directives. This is important because # may be a comment or introduce 1029 // various pseudo-ops. Just return the # token and push back the following 1030 // token to be lexed next time. 1031 if (getLangOpts().AsmPreprocessor) { 1032 auto Toks = llvm::make_unique<Token[]>(2); 1033 // Return the # and the token after it. 1034 Toks[0] = SavedHash; 1035 Toks[1] = Result; 1036 1037 // If the second token is a hashhash token, then we need to translate it to 1038 // unknown so the token lexer doesn't try to perform token pasting. 1039 if (Result.is(tok::hashhash)) 1040 Toks[1].setKind(tok::unknown); 1041 1042 // Enter this token stream so that we re-lex the tokens. Make sure to 1043 // enable macro expansion, in case the token after the # is an identifier 1044 // that is expanded. 1045 EnterTokenStream(std::move(Toks), 2, false); 1046 return; 1047 } 1048 1049 // If we reached here, the preprocessing token is not valid! 1050 Diag(Result, diag::err_pp_invalid_directive); 1051 1052 // Read the rest of the PP line. 1053 DiscardUntilEndOfDirective(); 1054 1055 // Okay, we're done parsing the directive. 1056 } 1057 1058 /// GetLineValue - Convert a numeric token into an unsigned value, emitting 1059 /// Diagnostic DiagID if it is invalid, and returning the value in Val. 1060 static bool GetLineValue(Token &DigitTok, unsigned &Val, 1061 unsigned DiagID, Preprocessor &PP, 1062 bool IsGNULineDirective=false) { 1063 if (DigitTok.isNot(tok::numeric_constant)) { 1064 PP.Diag(DigitTok, DiagID); 1065 1066 if (DigitTok.isNot(tok::eod)) 1067 PP.DiscardUntilEndOfDirective(); 1068 return true; 1069 } 1070 1071 SmallString<64> IntegerBuffer; 1072 IntegerBuffer.resize(DigitTok.getLength()); 1073 const char *DigitTokBegin = &IntegerBuffer[0]; 1074 bool Invalid = false; 1075 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid); 1076 if (Invalid) 1077 return true; 1078 1079 // Verify that we have a simple digit-sequence, and compute the value. This 1080 // is always a simple digit string computed in decimal, so we do this manually 1081 // here. 1082 Val = 0; 1083 for (unsigned i = 0; i != ActualLength; ++i) { 1084 // C++1y [lex.fcon]p1: 1085 // Optional separating single quotes in a digit-sequence are ignored 1086 if (DigitTokBegin[i] == '\'') 1087 continue; 1088 1089 if (!isDigit(DigitTokBegin[i])) { 1090 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i), 1091 diag::err_pp_line_digit_sequence) << IsGNULineDirective; 1092 PP.DiscardUntilEndOfDirective(); 1093 return true; 1094 } 1095 1096 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0'); 1097 if (NextVal < Val) { // overflow. 1098 PP.Diag(DigitTok, DiagID); 1099 PP.DiscardUntilEndOfDirective(); 1100 return true; 1101 } 1102 Val = NextVal; 1103 } 1104 1105 if (DigitTokBegin[0] == '0' && Val) 1106 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal) 1107 << IsGNULineDirective; 1108 1109 return false; 1110 } 1111 1112 /// \brief Handle a \#line directive: C99 6.10.4. 1113 /// 1114 /// The two acceptable forms are: 1115 /// \verbatim 1116 /// # line digit-sequence 1117 /// # line digit-sequence "s-char-sequence" 1118 /// \endverbatim 1119 void Preprocessor::HandleLineDirective() { 1120 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are 1121 // expanded. 1122 Token DigitTok; 1123 Lex(DigitTok); 1124 1125 // Validate the number and convert it to an unsigned. 1126 unsigned LineNo; 1127 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this)) 1128 return; 1129 1130 if (LineNo == 0) 1131 Diag(DigitTok, diag::ext_pp_line_zero); 1132 1133 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a 1134 // number greater than 2147483647". C90 requires that the line # be <= 32767. 1135 unsigned LineLimit = 32768U; 1136 if (LangOpts.C99 || LangOpts.CPlusPlus11) 1137 LineLimit = 2147483648U; 1138 if (LineNo >= LineLimit) 1139 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit; 1140 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U) 1141 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big); 1142 1143 int FilenameID = -1; 1144 Token StrTok; 1145 Lex(StrTok); 1146 1147 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a 1148 // string followed by eod. 1149 if (StrTok.is(tok::eod)) 1150 ; // ok 1151 else if (StrTok.isNot(tok::string_literal)) { 1152 Diag(StrTok, diag::err_pp_line_invalid_filename); 1153 return DiscardUntilEndOfDirective(); 1154 } else if (StrTok.hasUDSuffix()) { 1155 Diag(StrTok, diag::err_invalid_string_udl); 1156 return DiscardUntilEndOfDirective(); 1157 } else { 1158 // Parse and validate the string, converting it into a unique ID. 1159 StringLiteralParser Literal(StrTok, *this); 1160 assert(Literal.isAscii() && "Didn't allow wide strings in"); 1161 if (Literal.hadError) 1162 return DiscardUntilEndOfDirective(); 1163 if (Literal.Pascal) { 1164 Diag(StrTok, diag::err_pp_linemarker_invalid_filename); 1165 return DiscardUntilEndOfDirective(); 1166 } 1167 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString()); 1168 1169 // Verify that there is nothing after the string, other than EOD. Because 1170 // of C99 6.10.4p5, macros that expand to empty tokens are ok. 1171 CheckEndOfDirective("line", true); 1172 } 1173 1174 // Take the file kind of the file containing the #line directive. #line 1175 // directives are often used for generated sources from the same codebase, so 1176 // the new file should generally be classified the same way as the current 1177 // file. This is visible in GCC's pre-processed output, which rewrites #line 1178 // to GNU line markers. 1179 SrcMgr::CharacteristicKind FileKind = 1180 SourceMgr.getFileCharacteristic(DigitTok.getLocation()); 1181 1182 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false, 1183 false, FileKind); 1184 1185 if (Callbacks) 1186 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), 1187 PPCallbacks::RenameFile, FileKind); 1188 } 1189 1190 /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line 1191 /// marker directive. 1192 static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit, 1193 SrcMgr::CharacteristicKind &FileKind, 1194 Preprocessor &PP) { 1195 unsigned FlagVal; 1196 Token FlagTok; 1197 PP.Lex(FlagTok); 1198 if (FlagTok.is(tok::eod)) return false; 1199 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP)) 1200 return true; 1201 1202 if (FlagVal == 1) { 1203 IsFileEntry = true; 1204 1205 PP.Lex(FlagTok); 1206 if (FlagTok.is(tok::eod)) return false; 1207 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP)) 1208 return true; 1209 } else if (FlagVal == 2) { 1210 IsFileExit = true; 1211 1212 SourceManager &SM = PP.getSourceManager(); 1213 // If we are leaving the current presumed file, check to make sure the 1214 // presumed include stack isn't empty! 1215 FileID CurFileID = 1216 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first; 1217 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation()); 1218 if (PLoc.isInvalid()) 1219 return true; 1220 1221 // If there is no include loc (main file) or if the include loc is in a 1222 // different physical file, then we aren't in a "1" line marker flag region. 1223 SourceLocation IncLoc = PLoc.getIncludeLoc(); 1224 if (IncLoc.isInvalid() || 1225 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) { 1226 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop); 1227 PP.DiscardUntilEndOfDirective(); 1228 return true; 1229 } 1230 1231 PP.Lex(FlagTok); 1232 if (FlagTok.is(tok::eod)) return false; 1233 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP)) 1234 return true; 1235 } 1236 1237 // We must have 3 if there are still flags. 1238 if (FlagVal != 3) { 1239 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); 1240 PP.DiscardUntilEndOfDirective(); 1241 return true; 1242 } 1243 1244 FileKind = SrcMgr::C_System; 1245 1246 PP.Lex(FlagTok); 1247 if (FlagTok.is(tok::eod)) return false; 1248 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP)) 1249 return true; 1250 1251 // We must have 4 if there is yet another flag. 1252 if (FlagVal != 4) { 1253 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); 1254 PP.DiscardUntilEndOfDirective(); 1255 return true; 1256 } 1257 1258 FileKind = SrcMgr::C_ExternCSystem; 1259 1260 PP.Lex(FlagTok); 1261 if (FlagTok.is(tok::eod)) return false; 1262 1263 // There are no more valid flags here. 1264 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); 1265 PP.DiscardUntilEndOfDirective(); 1266 return true; 1267 } 1268 1269 /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is 1270 /// one of the following forms: 1271 /// 1272 /// # 42 1273 /// # 42 "file" ('1' | '2')? 1274 /// # 42 "file" ('1' | '2')? '3' '4'? 1275 /// 1276 void Preprocessor::HandleDigitDirective(Token &DigitTok) { 1277 // Validate the number and convert it to an unsigned. GNU does not have a 1278 // line # limit other than it fit in 32-bits. 1279 unsigned LineNo; 1280 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer, 1281 *this, true)) 1282 return; 1283 1284 Token StrTok; 1285 Lex(StrTok); 1286 1287 bool IsFileEntry = false, IsFileExit = false; 1288 int FilenameID = -1; 1289 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User; 1290 1291 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a 1292 // string followed by eod. 1293 if (StrTok.is(tok::eod)) { 1294 // Treat this like "#line NN", which doesn't change file characteristics. 1295 FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation()); 1296 } else if (StrTok.isNot(tok::string_literal)) { 1297 Diag(StrTok, diag::err_pp_linemarker_invalid_filename); 1298 return DiscardUntilEndOfDirective(); 1299 } else if (StrTok.hasUDSuffix()) { 1300 Diag(StrTok, diag::err_invalid_string_udl); 1301 return DiscardUntilEndOfDirective(); 1302 } else { 1303 // Parse and validate the string, converting it into a unique ID. 1304 StringLiteralParser Literal(StrTok, *this); 1305 assert(Literal.isAscii() && "Didn't allow wide strings in"); 1306 if (Literal.hadError) 1307 return DiscardUntilEndOfDirective(); 1308 if (Literal.Pascal) { 1309 Diag(StrTok, diag::err_pp_linemarker_invalid_filename); 1310 return DiscardUntilEndOfDirective(); 1311 } 1312 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString()); 1313 1314 // If a filename was present, read any flags that are present. 1315 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this)) 1316 return; 1317 } 1318 1319 // Create a line note with this information. 1320 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry, 1321 IsFileExit, FileKind); 1322 1323 // If the preprocessor has callbacks installed, notify them of the #line 1324 // change. This is used so that the line marker comes out in -E mode for 1325 // example. 1326 if (Callbacks) { 1327 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile; 1328 if (IsFileEntry) 1329 Reason = PPCallbacks::EnterFile; 1330 else if (IsFileExit) 1331 Reason = PPCallbacks::ExitFile; 1332 1333 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind); 1334 } 1335 } 1336 1337 /// HandleUserDiagnosticDirective - Handle a #warning or #error directive. 1338 /// 1339 void Preprocessor::HandleUserDiagnosticDirective(Token &Tok, 1340 bool isWarning) { 1341 // PTH doesn't emit #warning or #error directives. 1342 if (CurPTHLexer) 1343 return CurPTHLexer->DiscardToEndOfLine(); 1344 1345 // Read the rest of the line raw. We do this because we don't want macros 1346 // to be expanded and we don't require that the tokens be valid preprocessing 1347 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does 1348 // collapse multiple consequtive white space between tokens, but this isn't 1349 // specified by the standard. 1350 SmallString<128> Message; 1351 CurLexer->ReadToEndOfLine(&Message); 1352 1353 // Find the first non-whitespace character, so that we can make the 1354 // diagnostic more succinct. 1355 StringRef Msg = StringRef(Message).ltrim(' '); 1356 1357 if (isWarning) 1358 Diag(Tok, diag::pp_hash_warning) << Msg; 1359 else 1360 Diag(Tok, diag::err_pp_hash_error) << Msg; 1361 } 1362 1363 /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive. 1364 /// 1365 void Preprocessor::HandleIdentSCCSDirective(Token &Tok) { 1366 // Yes, this directive is an extension. 1367 Diag(Tok, diag::ext_pp_ident_directive); 1368 1369 // Read the string argument. 1370 Token StrTok; 1371 Lex(StrTok); 1372 1373 // If the token kind isn't a string, it's a malformed directive. 1374 if (StrTok.isNot(tok::string_literal) && 1375 StrTok.isNot(tok::wide_string_literal)) { 1376 Diag(StrTok, diag::err_pp_malformed_ident); 1377 if (StrTok.isNot(tok::eod)) 1378 DiscardUntilEndOfDirective(); 1379 return; 1380 } 1381 1382 if (StrTok.hasUDSuffix()) { 1383 Diag(StrTok, diag::err_invalid_string_udl); 1384 return DiscardUntilEndOfDirective(); 1385 } 1386 1387 // Verify that there is nothing after the string, other than EOD. 1388 CheckEndOfDirective("ident"); 1389 1390 if (Callbacks) { 1391 bool Invalid = false; 1392 std::string Str = getSpelling(StrTok, &Invalid); 1393 if (!Invalid) 1394 Callbacks->Ident(Tok.getLocation(), Str); 1395 } 1396 } 1397 1398 /// \brief Handle a #public directive. 1399 void Preprocessor::HandleMacroPublicDirective(Token &Tok) { 1400 Token MacroNameTok; 1401 ReadMacroName(MacroNameTok, MU_Undef); 1402 1403 // Error reading macro name? If so, diagnostic already issued. 1404 if (MacroNameTok.is(tok::eod)) 1405 return; 1406 1407 // Check to see if this is the last token on the #__public_macro line. 1408 CheckEndOfDirective("__public_macro"); 1409 1410 IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); 1411 // Okay, we finally have a valid identifier to undef. 1412 MacroDirective *MD = getLocalMacroDirective(II); 1413 1414 // If the macro is not defined, this is an error. 1415 if (!MD) { 1416 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II; 1417 return; 1418 } 1419 1420 // Note that this macro has now been exported. 1421 appendMacroDirective(II, AllocateVisibilityMacroDirective( 1422 MacroNameTok.getLocation(), /*IsPublic=*/true)); 1423 } 1424 1425 /// \brief Handle a #private directive. 1426 void Preprocessor::HandleMacroPrivateDirective() { 1427 Token MacroNameTok; 1428 ReadMacroName(MacroNameTok, MU_Undef); 1429 1430 // Error reading macro name? If so, diagnostic already issued. 1431 if (MacroNameTok.is(tok::eod)) 1432 return; 1433 1434 // Check to see if this is the last token on the #__private_macro line. 1435 CheckEndOfDirective("__private_macro"); 1436 1437 IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); 1438 // Okay, we finally have a valid identifier to undef. 1439 MacroDirective *MD = getLocalMacroDirective(II); 1440 1441 // If the macro is not defined, this is an error. 1442 if (!MD) { 1443 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II; 1444 return; 1445 } 1446 1447 // Note that this macro has now been marked private. 1448 appendMacroDirective(II, AllocateVisibilityMacroDirective( 1449 MacroNameTok.getLocation(), /*IsPublic=*/false)); 1450 } 1451 1452 //===----------------------------------------------------------------------===// 1453 // Preprocessor Include Directive Handling. 1454 //===----------------------------------------------------------------------===// 1455 1456 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully 1457 /// checked and spelled filename, e.g. as an operand of \#include. This returns 1458 /// true if the input filename was in <>'s or false if it were in ""'s. The 1459 /// caller is expected to provide a buffer that is large enough to hold the 1460 /// spelling of the filename, but is also expected to handle the case when 1461 /// this method decides to use a different buffer. 1462 bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc, 1463 StringRef &Buffer) { 1464 // Get the text form of the filename. 1465 assert(!Buffer.empty() && "Can't have tokens with empty spellings!"); 1466 1467 // Make sure the filename is <x> or "x". 1468 bool isAngled; 1469 if (Buffer[0] == '<') { 1470 if (Buffer.back() != '>') { 1471 Diag(Loc, diag::err_pp_expects_filename); 1472 Buffer = StringRef(); 1473 return true; 1474 } 1475 isAngled = true; 1476 } else if (Buffer[0] == '"') { 1477 if (Buffer.back() != '"') { 1478 Diag(Loc, diag::err_pp_expects_filename); 1479 Buffer = StringRef(); 1480 return true; 1481 } 1482 isAngled = false; 1483 } else { 1484 Diag(Loc, diag::err_pp_expects_filename); 1485 Buffer = StringRef(); 1486 return true; 1487 } 1488 1489 // Diagnose #include "" as invalid. 1490 if (Buffer.size() <= 2) { 1491 Diag(Loc, diag::err_pp_empty_filename); 1492 Buffer = StringRef(); 1493 return true; 1494 } 1495 1496 // Skip the brackets. 1497 Buffer = Buffer.substr(1, Buffer.size()-2); 1498 return isAngled; 1499 } 1500 1501 // \brief Handle cases where the \#include name is expanded from a macro 1502 // as multiple tokens, which need to be glued together. 1503 // 1504 // This occurs for code like: 1505 // \code 1506 // \#define FOO <a/b.h> 1507 // \#include FOO 1508 // \endcode 1509 // because in this case, "<a/b.h>" is returned as 7 tokens, not one. 1510 // 1511 // This code concatenates and consumes tokens up to the '>' token. It returns 1512 // false if the > was found, otherwise it returns true if it finds and consumes 1513 // the EOD marker. 1514 bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer, 1515 SourceLocation &End) { 1516 Token CurTok; 1517 1518 Lex(CurTok); 1519 while (CurTok.isNot(tok::eod)) { 1520 End = CurTok.getLocation(); 1521 1522 // FIXME: Provide code completion for #includes. 1523 if (CurTok.is(tok::code_completion)) { 1524 setCodeCompletionReached(); 1525 Lex(CurTok); 1526 continue; 1527 } 1528 1529 // Append the spelling of this token to the buffer. If there was a space 1530 // before it, add it now. 1531 if (CurTok.hasLeadingSpace()) 1532 FilenameBuffer.push_back(' '); 1533 1534 // Get the spelling of the token, directly into FilenameBuffer if possible. 1535 size_t PreAppendSize = FilenameBuffer.size(); 1536 FilenameBuffer.resize(PreAppendSize+CurTok.getLength()); 1537 1538 const char *BufPtr = &FilenameBuffer[PreAppendSize]; 1539 unsigned ActualLen = getSpelling(CurTok, BufPtr); 1540 1541 // If the token was spelled somewhere else, copy it into FilenameBuffer. 1542 if (BufPtr != &FilenameBuffer[PreAppendSize]) 1543 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen); 1544 1545 // Resize FilenameBuffer to the correct size. 1546 if (CurTok.getLength() != ActualLen) 1547 FilenameBuffer.resize(PreAppendSize+ActualLen); 1548 1549 // If we found the '>' marker, return success. 1550 if (CurTok.is(tok::greater)) 1551 return false; 1552 1553 Lex(CurTok); 1554 } 1555 1556 // If we hit the eod marker, emit an error and return true so that the caller 1557 // knows the EOD has been read. 1558 Diag(CurTok.getLocation(), diag::err_pp_expects_filename); 1559 return true; 1560 } 1561 1562 /// \brief Push a token onto the token stream containing an annotation. 1563 void Preprocessor::EnterAnnotationToken(SourceRange Range, 1564 tok::TokenKind Kind, 1565 void *AnnotationVal) { 1566 // FIXME: Produce this as the current token directly, rather than 1567 // allocating a new token for it. 1568 auto Tok = llvm::make_unique<Token[]>(1); 1569 Tok[0].startToken(); 1570 Tok[0].setKind(Kind); 1571 Tok[0].setLocation(Range.getBegin()); 1572 Tok[0].setAnnotationEndLoc(Range.getEnd()); 1573 Tok[0].setAnnotationValue(AnnotationVal); 1574 EnterTokenStream(std::move(Tok), 1, true); 1575 } 1576 1577 /// \brief Produce a diagnostic informing the user that a #include or similar 1578 /// was implicitly treated as a module import. 1579 static void diagnoseAutoModuleImport( 1580 Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok, 1581 ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path, 1582 SourceLocation PathEnd) { 1583 assert(PP.getLangOpts().ObjC2 && "no import syntax available"); 1584 1585 SmallString<128> PathString; 1586 for (size_t I = 0, N = Path.size(); I != N; ++I) { 1587 if (I) 1588 PathString += '.'; 1589 PathString += Path[I].first->getName(); 1590 } 1591 int IncludeKind = 0; 1592 1593 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) { 1594 case tok::pp_include: 1595 IncludeKind = 0; 1596 break; 1597 1598 case tok::pp_import: 1599 IncludeKind = 1; 1600 break; 1601 1602 case tok::pp_include_next: 1603 IncludeKind = 2; 1604 break; 1605 1606 case tok::pp___include_macros: 1607 IncludeKind = 3; 1608 break; 1609 1610 default: 1611 llvm_unreachable("unknown include directive kind"); 1612 } 1613 1614 CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd), 1615 /*IsTokenRange=*/false); 1616 PP.Diag(HashLoc, diag::warn_auto_module_import) 1617 << IncludeKind << PathString 1618 << FixItHint::CreateReplacement(ReplaceRange, 1619 ("@import " + PathString + ";").str()); 1620 } 1621 1622 // Given a vector of path components and a string containing the real 1623 // path to the file, build a properly-cased replacement in the vector, 1624 // and return true if the replacement should be suggested. 1625 static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components, 1626 StringRef RealPathName) { 1627 auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName); 1628 auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName); 1629 int Cnt = 0; 1630 bool SuggestReplacement = false; 1631 // Below is a best-effort to handle ".." in paths. It is admittedly 1632 // not 100% correct in the presence of symlinks. 1633 for (auto &Component : llvm::reverse(Components)) { 1634 if ("." == Component) { 1635 } else if (".." == Component) { 1636 ++Cnt; 1637 } else if (Cnt) { 1638 --Cnt; 1639 } else if (RealPathComponentIter != RealPathComponentEnd) { 1640 if (Component != *RealPathComponentIter) { 1641 // If these path components differ by more than just case, then we 1642 // may be looking at symlinked paths. Bail on this diagnostic to avoid 1643 // noisy false positives. 1644 SuggestReplacement = RealPathComponentIter->equals_lower(Component); 1645 if (!SuggestReplacement) 1646 break; 1647 Component = *RealPathComponentIter; 1648 } 1649 ++RealPathComponentIter; 1650 } 1651 } 1652 return SuggestReplacement; 1653 } 1654 1655 bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts, 1656 const TargetInfo &TargetInfo, 1657 DiagnosticsEngine &Diags, Module *M) { 1658 Module::Requirement Requirement; 1659 Module::UnresolvedHeaderDirective MissingHeader; 1660 Module *ShadowingModule = nullptr; 1661 if (M->isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader, 1662 ShadowingModule)) 1663 return false; 1664 1665 if (MissingHeader.FileNameLoc.isValid()) { 1666 Diags.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing) 1667 << MissingHeader.IsUmbrella << MissingHeader.FileName; 1668 } else if (ShadowingModule) { 1669 Diags.Report(M->DefinitionLoc, diag::err_module_shadowed) << M->Name; 1670 Diags.Report(ShadowingModule->DefinitionLoc, 1671 diag::note_previous_definition); 1672 } else { 1673 // FIXME: Track the location at which the requirement was specified, and 1674 // use it here. 1675 Diags.Report(M->DefinitionLoc, diag::err_module_unavailable) 1676 << M->getFullModuleName() << Requirement.second << Requirement.first; 1677 } 1678 return true; 1679 } 1680 1681 /// HandleIncludeDirective - The "\#include" tokens have just been read, read 1682 /// the file to be included from the lexer, then include it! This is a common 1683 /// routine with functionality shared between \#include, \#include_next and 1684 /// \#import. LookupFrom is set when this is a \#include_next directive, it 1685 /// specifies the file to start searching from. 1686 void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc, 1687 Token &IncludeTok, 1688 const DirectoryLookup *LookupFrom, 1689 const FileEntry *LookupFromFile, 1690 bool isImport) { 1691 Token FilenameTok; 1692 CurPPLexer->LexIncludeFilename(FilenameTok); 1693 1694 // Reserve a buffer to get the spelling. 1695 SmallString<128> FilenameBuffer; 1696 StringRef Filename; 1697 SourceLocation End; 1698 SourceLocation CharEnd; // the end of this directive, in characters 1699 1700 switch (FilenameTok.getKind()) { 1701 case tok::eod: 1702 // If the token kind is EOD, the error has already been diagnosed. 1703 return; 1704 1705 case tok::angle_string_literal: 1706 case tok::string_literal: 1707 Filename = getSpelling(FilenameTok, FilenameBuffer); 1708 End = FilenameTok.getLocation(); 1709 CharEnd = End.getLocWithOffset(FilenameTok.getLength()); 1710 break; 1711 1712 case tok::less: 1713 // This could be a <foo/bar.h> file coming from a macro expansion. In this 1714 // case, glue the tokens together into FilenameBuffer and interpret those. 1715 FilenameBuffer.push_back('<'); 1716 if (ConcatenateIncludeName(FilenameBuffer, End)) 1717 return; // Found <eod> but no ">"? Diagnostic already emitted. 1718 Filename = FilenameBuffer; 1719 CharEnd = End.getLocWithOffset(1); 1720 break; 1721 default: 1722 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename); 1723 DiscardUntilEndOfDirective(); 1724 return; 1725 } 1726 1727 CharSourceRange FilenameRange 1728 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd); 1729 StringRef OriginalFilename = Filename; 1730 bool isAngled = 1731 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename); 1732 // If GetIncludeFilenameSpelling set the start ptr to null, there was an 1733 // error. 1734 if (Filename.empty()) { 1735 DiscardUntilEndOfDirective(); 1736 return; 1737 } 1738 1739 // Verify that there is nothing after the filename, other than EOD. Note that 1740 // we allow macros that expand to nothing after the filename, because this 1741 // falls into the category of "#include pp-tokens new-line" specified in 1742 // C99 6.10.2p4. 1743 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true); 1744 1745 // Check that we don't have infinite #include recursion. 1746 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) { 1747 Diag(FilenameTok, diag::err_pp_include_too_deep); 1748 return; 1749 } 1750 1751 // Complain about attempts to #include files in an audit pragma. 1752 if (PragmaARCCFCodeAuditedLoc.isValid()) { 1753 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited); 1754 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here); 1755 1756 // Immediately leave the pragma. 1757 PragmaARCCFCodeAuditedLoc = SourceLocation(); 1758 } 1759 1760 // Complain about attempts to #include files in an assume-nonnull pragma. 1761 if (PragmaAssumeNonNullLoc.isValid()) { 1762 Diag(HashLoc, diag::err_pp_include_in_assume_nonnull); 1763 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here); 1764 1765 // Immediately leave the pragma. 1766 PragmaAssumeNonNullLoc = SourceLocation(); 1767 } 1768 1769 if (HeaderInfo.HasIncludeAliasMap()) { 1770 // Map the filename with the brackets still attached. If the name doesn't 1771 // map to anything, fall back on the filename we've already gotten the 1772 // spelling for. 1773 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename); 1774 if (!NewName.empty()) 1775 Filename = NewName; 1776 } 1777 1778 // Search include directories. 1779 bool IsMapped = false; 1780 const DirectoryLookup *CurDir; 1781 SmallString<1024> SearchPath; 1782 SmallString<1024> RelativePath; 1783 // We get the raw path only if we have 'Callbacks' to which we later pass 1784 // the path. 1785 ModuleMap::KnownHeader SuggestedModule; 1786 SourceLocation FilenameLoc = FilenameTok.getLocation(); 1787 SmallString<128> NormalizedPath; 1788 if (LangOpts.MSVCCompat) { 1789 NormalizedPath = Filename.str(); 1790 #ifndef LLVM_ON_WIN32 1791 llvm::sys::path::native(NormalizedPath); 1792 #endif 1793 } 1794 const FileEntry *File = LookupFile( 1795 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, 1796 isAngled, LookupFrom, LookupFromFile, CurDir, 1797 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr, 1798 &SuggestedModule, &IsMapped); 1799 1800 if (!File) { 1801 if (Callbacks) { 1802 // Give the clients a chance to recover. 1803 SmallString<128> RecoveryPath; 1804 if (Callbacks->FileNotFound(Filename, RecoveryPath)) { 1805 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) { 1806 // Add the recovery path to the list of search paths. 1807 DirectoryLookup DL(DE, SrcMgr::C_User, false); 1808 HeaderInfo.AddSearchPath(DL, isAngled); 1809 1810 // Try the lookup again, skipping the cache. 1811 File = LookupFile( 1812 FilenameLoc, 1813 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled, 1814 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr, 1815 &SuggestedModule, &IsMapped, /*SkipCache*/ true); 1816 } 1817 } 1818 } 1819 1820 if (!SuppressIncludeNotFoundError) { 1821 // If the file could not be located and it was included via angle 1822 // brackets, we can attempt a lookup as though it were a quoted path to 1823 // provide the user with a possible fixit. 1824 if (isAngled) { 1825 File = LookupFile( 1826 FilenameLoc, 1827 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false, 1828 LookupFrom, LookupFromFile, CurDir, 1829 Callbacks ? &SearchPath : nullptr, 1830 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped); 1831 if (File) { 1832 SourceRange Range(FilenameTok.getLocation(), CharEnd); 1833 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) << 1834 Filename << 1835 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\""); 1836 } 1837 } 1838 1839 // If the file is still not found, just go with the vanilla diagnostic 1840 if (!File) 1841 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename 1842 << FilenameRange; 1843 } 1844 } 1845 1846 // Should we enter the source file? Set to false if either the source file is 1847 // known to have no effect beyond its effect on module visibility -- that is, 1848 // if it's got an include guard that is already defined or is a modular header 1849 // we've imported or already built. 1850 bool ShouldEnter = true; 1851 1852 if (PPOpts->SingleFileParseMode) 1853 ShouldEnter = false; 1854 1855 // Determine whether we should try to import the module for this #include, if 1856 // there is one. Don't do so if precompiled module support is disabled or we 1857 // are processing this module textually (because we're building the module). 1858 if (ShouldEnter && File && SuggestedModule && getLangOpts().Modules && 1859 SuggestedModule.getModule()->getTopLevelModuleName() != 1860 getLangOpts().CurrentModule) { 1861 // If this include corresponds to a module but that module is 1862 // unavailable, diagnose the situation and bail out. 1863 // FIXME: Remove this; loadModule does the same check (but produces 1864 // slightly worse diagnostics). 1865 if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), getDiagnostics(), 1866 SuggestedModule.getModule())) { 1867 Diag(FilenameTok.getLocation(), 1868 diag::note_implicit_top_level_module_import_here) 1869 << SuggestedModule.getModule()->getTopLevelModuleName(); 1870 return; 1871 } 1872 1873 // Compute the module access path corresponding to this module. 1874 // FIXME: Should we have a second loadModule() overload to avoid this 1875 // extra lookup step? 1876 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 1877 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent) 1878 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name), 1879 FilenameTok.getLocation())); 1880 std::reverse(Path.begin(), Path.end()); 1881 1882 // Warn that we're replacing the include/import with a module import. 1883 // We only do this in Objective-C, where we have a module-import syntax. 1884 if (getLangOpts().ObjC2) 1885 diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd); 1886 1887 // Load the module to import its macros. We'll make the declarations 1888 // visible when the parser gets here. 1889 // FIXME: Pass SuggestedModule in here rather than converting it to a path 1890 // and making the module loader convert it back again. 1891 ModuleLoadResult Imported = TheModuleLoader.loadModule( 1892 IncludeTok.getLocation(), Path, Module::Hidden, 1893 /*IsIncludeDirective=*/true); 1894 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) && 1895 "the imported module is different than the suggested one"); 1896 1897 if (Imported) 1898 ShouldEnter = false; 1899 else if (Imported.isMissingExpected()) { 1900 // We failed to find a submodule that we assumed would exist (because it 1901 // was in the directory of an umbrella header, for instance), but no 1902 // actual module containing it exists (because the umbrella header is 1903 // incomplete). Treat this as a textual inclusion. 1904 SuggestedModule = ModuleMap::KnownHeader(); 1905 } else if (Imported.isConfigMismatch()) { 1906 // On a configuration mismatch, enter the header textually. We still know 1907 // that it's part of the corresponding module. 1908 } else { 1909 // We hit an error processing the import. Bail out. 1910 if (hadModuleLoaderFatalFailure()) { 1911 // With a fatal failure in the module loader, we abort parsing. 1912 Token &Result = IncludeTok; 1913 if (CurLexer) { 1914 Result.startToken(); 1915 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof); 1916 CurLexer->cutOffLexing(); 1917 } else { 1918 assert(CurPTHLexer && "#include but no current lexer set!"); 1919 CurPTHLexer->getEOF(Result); 1920 } 1921 } 1922 return; 1923 } 1924 } 1925 1926 // The #included file will be considered to be a system header if either it is 1927 // in a system include directory, or if the #includer is a system include 1928 // header. 1929 SrcMgr::CharacteristicKind FileCharacter = 1930 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()); 1931 if (File) 1932 FileCharacter = std::max(HeaderInfo.getFileDirFlavor(File), FileCharacter); 1933 1934 // Ask HeaderInfo if we should enter this #include file. If not, #including 1935 // this file will have no effect. 1936 bool SkipHeader = false; 1937 if (ShouldEnter && File && 1938 !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport, 1939 getLangOpts().Modules, 1940 SuggestedModule.getModule())) { 1941 ShouldEnter = false; 1942 SkipHeader = true; 1943 } 1944 1945 if (Callbacks) { 1946 // Notify the callback object that we've seen an inclusion directive. 1947 Callbacks->InclusionDirective( 1948 HashLoc, IncludeTok, 1949 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled, 1950 FilenameRange, File, SearchPath, RelativePath, 1951 ShouldEnter ? nullptr : SuggestedModule.getModule()); 1952 if (SkipHeader && !SuggestedModule.getModule()) 1953 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter); 1954 } 1955 1956 if (!File) 1957 return; 1958 1959 // FIXME: If we have a suggested module, and we've already visited this file, 1960 // don't bother entering it again. We know it has no further effect. 1961 1962 // Issue a diagnostic if the name of the file on disk has a different case 1963 // than the one we're about to open. 1964 const bool CheckIncludePathPortability = 1965 !IsMapped && File && !File->tryGetRealPathName().empty(); 1966 1967 if (CheckIncludePathPortability) { 1968 StringRef Name = LangOpts.MSVCCompat ? NormalizedPath.str() : Filename; 1969 StringRef RealPathName = File->tryGetRealPathName(); 1970 SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name), 1971 llvm::sys::path::end(Name)); 1972 1973 if (trySimplifyPath(Components, RealPathName)) { 1974 SmallString<128> Path; 1975 Path.reserve(Name.size()+2); 1976 Path.push_back(isAngled ? '<' : '"'); 1977 bool isLeadingSeparator = llvm::sys::path::is_absolute(Name); 1978 for (auto Component : Components) { 1979 if (isLeadingSeparator) 1980 isLeadingSeparator = false; 1981 else 1982 Path.append(Component); 1983 // Append the separator the user used, or the close quote 1984 Path.push_back( 1985 Path.size() <= Filename.size() ? Filename[Path.size()-1] : 1986 (isAngled ? '>' : '"')); 1987 } 1988 // For user files and known standard headers, by default we issue a diagnostic. 1989 // For other system headers, we don't. They can be controlled separately. 1990 auto DiagId = (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name)) ? 1991 diag::pp_nonportable_path : diag::pp_nonportable_system_path; 1992 SourceRange Range(FilenameTok.getLocation(), CharEnd); 1993 Diag(FilenameTok, DiagId) << Path << 1994 FixItHint::CreateReplacement(Range, Path); 1995 } 1996 } 1997 1998 // If we don't need to enter the file, stop now. 1999 if (!ShouldEnter) { 2000 // If this is a module import, make it visible if needed. 2001 if (auto *M = SuggestedModule.getModule()) { 2002 // When building a pch, -fmodule-name tells the compiler to textually 2003 // include headers in the specified module. But it is possible that 2004 // ShouldEnter is false because we are skipping the header. In that 2005 // case, We are not importing the specified module. 2006 if (SkipHeader && getLangOpts().CompilingPCH && 2007 M->getTopLevelModuleName() == getLangOpts().CurrentModule) 2008 return; 2009 2010 makeModuleVisible(M, HashLoc); 2011 2012 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() != 2013 tok::pp___include_macros) 2014 EnterAnnotationToken(SourceRange(HashLoc, End), 2015 tok::annot_module_include, M); 2016 } 2017 return; 2018 } 2019 2020 // Look up the file, create a File ID for it. 2021 SourceLocation IncludePos = End; 2022 // If the filename string was the result of macro expansions, set the include 2023 // position on the file where it will be included and after the expansions. 2024 if (IncludePos.isMacroID()) 2025 IncludePos = SourceMgr.getExpansionRange(IncludePos).second; 2026 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter); 2027 assert(FID.isValid() && "Expected valid file ID"); 2028 2029 // If all is good, enter the new file! 2030 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation())) 2031 return; 2032 2033 // Determine if we're switching to building a new submodule, and which one. 2034 if (auto *M = SuggestedModule.getModule()) { 2035 if (M->getTopLevelModule()->ShadowingModule) { 2036 // We are building a submodule that belongs to a shadowed module. This 2037 // means we find header files in the shadowed module. 2038 Diag(M->DefinitionLoc, diag::err_module_build_shadowed_submodule) 2039 << M->getFullModuleName(); 2040 Diag(M->getTopLevelModule()->ShadowingModule->DefinitionLoc, 2041 diag::note_previous_definition); 2042 return; 2043 } 2044 // When building a pch, -fmodule-name tells the compiler to textually 2045 // include headers in the specified module. We are not building the 2046 // specified module. 2047 if (getLangOpts().CompilingPCH && 2048 M->getTopLevelModuleName() == getLangOpts().CurrentModule) 2049 return; 2050 2051 assert(!CurLexerSubmodule && "should not have marked this as a module yet"); 2052 CurLexerSubmodule = M; 2053 2054 // Let the macro handling code know that any future macros are within 2055 // the new submodule. 2056 EnterSubmodule(M, HashLoc, /*ForPragma*/false); 2057 2058 // Let the parser know that any future declarations are within the new 2059 // submodule. 2060 // FIXME: There's no point doing this if we're handling a #__include_macros 2061 // directive. 2062 EnterAnnotationToken(SourceRange(HashLoc, End), tok::annot_module_begin, M); 2063 } 2064 } 2065 2066 /// HandleIncludeNextDirective - Implements \#include_next. 2067 /// 2068 void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc, 2069 Token &IncludeNextTok) { 2070 Diag(IncludeNextTok, diag::ext_pp_include_next_directive); 2071 2072 // #include_next is like #include, except that we start searching after 2073 // the current found directory. If we can't do this, issue a 2074 // diagnostic. 2075 const DirectoryLookup *Lookup = CurDirLookup; 2076 const FileEntry *LookupFromFile = nullptr; 2077 if (isInPrimaryFile() && LangOpts.IsHeaderFile) { 2078 // If the main file is a header, then it's either for PCH/AST generation, 2079 // or libclang opened it. Either way, handle it as a normal include below 2080 // and do not complain about include_next. 2081 } else if (isInPrimaryFile()) { 2082 Lookup = nullptr; 2083 Diag(IncludeNextTok, diag::pp_include_next_in_primary); 2084 } else if (CurLexerSubmodule) { 2085 // Start looking up in the directory *after* the one in which the current 2086 // file would be found, if any. 2087 assert(CurPPLexer && "#include_next directive in macro?"); 2088 LookupFromFile = CurPPLexer->getFileEntry(); 2089 Lookup = nullptr; 2090 } else if (!Lookup) { 2091 Diag(IncludeNextTok, diag::pp_include_next_absolute_path); 2092 } else { 2093 // Start looking up in the next directory. 2094 ++Lookup; 2095 } 2096 2097 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup, 2098 LookupFromFile); 2099 } 2100 2101 /// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode 2102 void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) { 2103 // The Microsoft #import directive takes a type library and generates header 2104 // files from it, and includes those. This is beyond the scope of what clang 2105 // does, so we ignore it and error out. However, #import can optionally have 2106 // trailing attributes that span multiple lines. We're going to eat those 2107 // so we can continue processing from there. 2108 Diag(Tok, diag::err_pp_import_directive_ms ); 2109 2110 // Read tokens until we get to the end of the directive. Note that the 2111 // directive can be split over multiple lines using the backslash character. 2112 DiscardUntilEndOfDirective(); 2113 } 2114 2115 /// HandleImportDirective - Implements \#import. 2116 /// 2117 void Preprocessor::HandleImportDirective(SourceLocation HashLoc, 2118 Token &ImportTok) { 2119 if (!LangOpts.ObjC1) { // #import is standard for ObjC. 2120 if (LangOpts.MSVCCompat) 2121 return HandleMicrosoftImportDirective(ImportTok); 2122 Diag(ImportTok, diag::ext_pp_import_directive); 2123 } 2124 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true); 2125 } 2126 2127 /// HandleIncludeMacrosDirective - The -imacros command line option turns into a 2128 /// pseudo directive in the predefines buffer. This handles it by sucking all 2129 /// tokens through the preprocessor and discarding them (only keeping the side 2130 /// effects on the preprocessor). 2131 void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc, 2132 Token &IncludeMacrosTok) { 2133 // This directive should only occur in the predefines buffer. If not, emit an 2134 // error and reject it. 2135 SourceLocation Loc = IncludeMacrosTok.getLocation(); 2136 if (SourceMgr.getBufferName(Loc) != "<built-in>") { 2137 Diag(IncludeMacrosTok.getLocation(), 2138 diag::pp_include_macros_out_of_predefines); 2139 DiscardUntilEndOfDirective(); 2140 return; 2141 } 2142 2143 // Treat this as a normal #include for checking purposes. If this is 2144 // successful, it will push a new lexer onto the include stack. 2145 HandleIncludeDirective(HashLoc, IncludeMacrosTok); 2146 2147 Token TmpTok; 2148 do { 2149 Lex(TmpTok); 2150 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!"); 2151 } while (TmpTok.isNot(tok::hashhash)); 2152 } 2153 2154 //===----------------------------------------------------------------------===// 2155 // Preprocessor Macro Directive Handling. 2156 //===----------------------------------------------------------------------===// 2157 2158 /// ReadMacroParameterList - The ( starting a parameter list of a macro 2159 /// definition has just been read. Lex the rest of the parameters and the 2160 /// closing ), updating MI with what we learn. Return true if an error occurs 2161 /// parsing the param list. 2162 bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) { 2163 SmallVector<IdentifierInfo*, 32> Parameters; 2164 2165 while (true) { 2166 LexUnexpandedToken(Tok); 2167 switch (Tok.getKind()) { 2168 case tok::r_paren: 2169 // Found the end of the parameter list. 2170 if (Parameters.empty()) // #define FOO() 2171 return false; 2172 // Otherwise we have #define FOO(A,) 2173 Diag(Tok, diag::err_pp_expected_ident_in_arg_list); 2174 return true; 2175 case tok::ellipsis: // #define X(... -> C99 varargs 2176 if (!LangOpts.C99) 2177 Diag(Tok, LangOpts.CPlusPlus11 ? 2178 diag::warn_cxx98_compat_variadic_macro : 2179 diag::ext_variadic_macro); 2180 2181 // OpenCL v1.2 s6.9.e: variadic macros are not supported. 2182 if (LangOpts.OpenCL) { 2183 Diag(Tok, diag::err_pp_opencl_variadic_macros); 2184 return true; 2185 } 2186 2187 // Lex the token after the identifier. 2188 LexUnexpandedToken(Tok); 2189 if (Tok.isNot(tok::r_paren)) { 2190 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); 2191 return true; 2192 } 2193 // Add the __VA_ARGS__ identifier as a parameter. 2194 Parameters.push_back(Ident__VA_ARGS__); 2195 MI->setIsC99Varargs(); 2196 MI->setParameterList(Parameters, BP); 2197 return false; 2198 case tok::eod: // #define X( 2199 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); 2200 return true; 2201 default: 2202 // Handle keywords and identifiers here to accept things like 2203 // #define Foo(for) for. 2204 IdentifierInfo *II = Tok.getIdentifierInfo(); 2205 if (!II) { 2206 // #define X(1 2207 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list); 2208 return true; 2209 } 2210 2211 // If this is already used as a parameter, it is used multiple times (e.g. 2212 // #define X(A,A. 2213 if (std::find(Parameters.begin(), Parameters.end(), II) != 2214 Parameters.end()) { // C99 6.10.3p6 2215 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II; 2216 return true; 2217 } 2218 2219 // Add the parameter to the macro info. 2220 Parameters.push_back(II); 2221 2222 // Lex the token after the identifier. 2223 LexUnexpandedToken(Tok); 2224 2225 switch (Tok.getKind()) { 2226 default: // #define X(A B 2227 Diag(Tok, diag::err_pp_expected_comma_in_arg_list); 2228 return true; 2229 case tok::r_paren: // #define X(A) 2230 MI->setParameterList(Parameters, BP); 2231 return false; 2232 case tok::comma: // #define X(A, 2233 break; 2234 case tok::ellipsis: // #define X(A... -> GCC extension 2235 // Diagnose extension. 2236 Diag(Tok, diag::ext_named_variadic_macro); 2237 2238 // Lex the token after the identifier. 2239 LexUnexpandedToken(Tok); 2240 if (Tok.isNot(tok::r_paren)) { 2241 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); 2242 return true; 2243 } 2244 2245 MI->setIsGNUVarargs(); 2246 MI->setParameterList(Parameters, BP); 2247 return false; 2248 } 2249 } 2250 } 2251 } 2252 2253 static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI, 2254 const LangOptions &LOptions) { 2255 if (MI->getNumTokens() == 1) { 2256 const Token &Value = MI->getReplacementToken(0); 2257 2258 // Macro that is identity, like '#define inline inline' is a valid pattern. 2259 if (MacroName.getKind() == Value.getKind()) 2260 return true; 2261 2262 // Macro that maps a keyword to the same keyword decorated with leading/ 2263 // trailing underscores is a valid pattern: 2264 // #define inline __inline 2265 // #define inline __inline__ 2266 // #define inline _inline (in MS compatibility mode) 2267 StringRef MacroText = MacroName.getIdentifierInfo()->getName(); 2268 if (IdentifierInfo *II = Value.getIdentifierInfo()) { 2269 if (!II->isKeyword(LOptions)) 2270 return false; 2271 StringRef ValueText = II->getName(); 2272 StringRef TrimmedValue = ValueText; 2273 if (!ValueText.startswith("__")) { 2274 if (ValueText.startswith("_")) 2275 TrimmedValue = TrimmedValue.drop_front(1); 2276 else 2277 return false; 2278 } else { 2279 TrimmedValue = TrimmedValue.drop_front(2); 2280 if (TrimmedValue.endswith("__")) 2281 TrimmedValue = TrimmedValue.drop_back(2); 2282 } 2283 return TrimmedValue.equals(MacroText); 2284 } else { 2285 return false; 2286 } 2287 } 2288 2289 // #define inline 2290 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static, 2291 tok::kw_const) && 2292 MI->getNumTokens() == 0; 2293 } 2294 2295 // ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the 2296 // entire line) of the macro's tokens and adds them to MacroInfo, and while 2297 // doing so performs certain validity checks including (but not limited to): 2298 // - # (stringization) is followed by a macro parameter 2299 // 2300 // Returns a nullptr if an invalid sequence of tokens is encountered or returns 2301 // a pointer to a MacroInfo object. 2302 2303 MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody( 2304 const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) { 2305 2306 Token LastTok = MacroNameTok; 2307 // Create the new macro. 2308 MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation()); 2309 2310 Token Tok; 2311 LexUnexpandedToken(Tok); 2312 2313 // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk 2314 // within their appropriate context. 2315 VariadicMacroScopeGuard VariadicMacroScopeGuard(*this); 2316 2317 // If this is a function-like macro definition, parse the argument list, 2318 // marking each of the identifiers as being used as macro arguments. Also, 2319 // check other constraints on the first token of the macro body. 2320 if (Tok.is(tok::eod)) { 2321 if (ImmediatelyAfterHeaderGuard) { 2322 // Save this macro information since it may part of a header guard. 2323 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(), 2324 MacroNameTok.getLocation()); 2325 } 2326 // If there is no body to this macro, we have no special handling here. 2327 } else if (Tok.hasLeadingSpace()) { 2328 // This is a normal token with leading space. Clear the leading space 2329 // marker on the first token to get proper expansion. 2330 Tok.clearFlag(Token::LeadingSpace); 2331 } else if (Tok.is(tok::l_paren)) { 2332 // This is a function-like macro definition. Read the argument list. 2333 MI->setIsFunctionLike(); 2334 if (ReadMacroParameterList(MI, LastTok)) { 2335 // Throw away the rest of the line. 2336 if (CurPPLexer->ParsingPreprocessorDirective) 2337 DiscardUntilEndOfDirective(); 2338 return nullptr; 2339 } 2340 2341 // If this is a definition of an ISO C/C++ variadic function-like macro (not 2342 // using the GNU named varargs extension) inform our variadic scope guard 2343 // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__) 2344 // allowed only within the definition of a variadic macro. 2345 2346 if (MI->isC99Varargs()) { 2347 VariadicMacroScopeGuard.enterScope(); 2348 } 2349 2350 // Read the first token after the arg list for down below. 2351 LexUnexpandedToken(Tok); 2352 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) { 2353 // C99 requires whitespace between the macro definition and the body. Emit 2354 // a diagnostic for something like "#define X+". 2355 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name); 2356 } else { 2357 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the 2358 // first character of a replacement list is not a character required by 2359 // subclause 5.2.1, then there shall be white-space separation between the 2360 // identifier and the replacement list.". 5.2.1 lists this set: 2361 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which 2362 // is irrelevant here. 2363 bool isInvalid = false; 2364 if (Tok.is(tok::at)) // @ is not in the list above. 2365 isInvalid = true; 2366 else if (Tok.is(tok::unknown)) { 2367 // If we have an unknown token, it is something strange like "`". Since 2368 // all of valid characters would have lexed into a single character 2369 // token of some sort, we know this is not a valid case. 2370 isInvalid = true; 2371 } 2372 if (isInvalid) 2373 Diag(Tok, diag::ext_missing_whitespace_after_macro_name); 2374 else 2375 Diag(Tok, diag::warn_missing_whitespace_after_macro_name); 2376 } 2377 2378 if (!Tok.is(tok::eod)) 2379 LastTok = Tok; 2380 2381 // Read the rest of the macro body. 2382 if (MI->isObjectLike()) { 2383 // Object-like macros are very simple, just read their body. 2384 while (Tok.isNot(tok::eod)) { 2385 LastTok = Tok; 2386 MI->AddTokenToBody(Tok); 2387 // Get the next token of the macro. 2388 LexUnexpandedToken(Tok); 2389 } 2390 } else { 2391 // Otherwise, read the body of a function-like macro. While we are at it, 2392 // check C99 6.10.3.2p1: ensure that # operators are followed by macro 2393 // parameters in function-like macro expansions. 2394 2395 VAOptDefinitionContext VAOCtx(*this); 2396 2397 while (Tok.isNot(tok::eod)) { 2398 LastTok = Tok; 2399 2400 if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) { 2401 MI->AddTokenToBody(Tok); 2402 2403 if (VAOCtx.isVAOptToken(Tok)) { 2404 // If we're already within a VAOPT, emit an error. 2405 if (VAOCtx.isInVAOpt()) { 2406 Diag(Tok, diag::err_pp_vaopt_nested_use); 2407 return nullptr; 2408 } 2409 // Ensure VAOPT is followed by a '(' . 2410 LexUnexpandedToken(Tok); 2411 if (Tok.isNot(tok::l_paren)) { 2412 Diag(Tok, diag::err_pp_missing_lparen_in_vaopt_use); 2413 return nullptr; 2414 } 2415 MI->AddTokenToBody(Tok); 2416 VAOCtx.sawVAOptFollowedByOpeningParens(Tok.getLocation()); 2417 LexUnexpandedToken(Tok); 2418 if (Tok.is(tok::hashhash)) { 2419 Diag(Tok, diag::err_vaopt_paste_at_start); 2420 return nullptr; 2421 } 2422 continue; 2423 } else if (VAOCtx.isInVAOpt()) { 2424 if (Tok.is(tok::r_paren)) { 2425 if (VAOCtx.sawClosingParen()) { 2426 const unsigned NumTokens = MI->getNumTokens(); 2427 assert(NumTokens >= 3 && "Must have seen at least __VA_OPT__( " 2428 "and a subsequent tok::r_paren"); 2429 if (MI->getReplacementToken(NumTokens - 2).is(tok::hashhash)) { 2430 Diag(Tok, diag::err_vaopt_paste_at_end); 2431 return nullptr; 2432 } 2433 } 2434 } else if (Tok.is(tok::l_paren)) { 2435 VAOCtx.sawOpeningParen(Tok.getLocation()); 2436 } 2437 } 2438 // Get the next token of the macro. 2439 LexUnexpandedToken(Tok); 2440 continue; 2441 } 2442 2443 // If we're in -traditional mode, then we should ignore stringification 2444 // and token pasting. Mark the tokens as unknown so as not to confuse 2445 // things. 2446 if (getLangOpts().TraditionalCPP) { 2447 Tok.setKind(tok::unknown); 2448 MI->AddTokenToBody(Tok); 2449 2450 // Get the next token of the macro. 2451 LexUnexpandedToken(Tok); 2452 continue; 2453 } 2454 2455 if (Tok.is(tok::hashhash)) { 2456 // If we see token pasting, check if it looks like the gcc comma 2457 // pasting extension. We'll use this information to suppress 2458 // diagnostics later on. 2459 2460 // Get the next token of the macro. 2461 LexUnexpandedToken(Tok); 2462 2463 if (Tok.is(tok::eod)) { 2464 MI->AddTokenToBody(LastTok); 2465 break; 2466 } 2467 2468 unsigned NumTokens = MI->getNumTokens(); 2469 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ && 2470 MI->getReplacementToken(NumTokens-1).is(tok::comma)) 2471 MI->setHasCommaPasting(); 2472 2473 // Things look ok, add the '##' token to the macro. 2474 MI->AddTokenToBody(LastTok); 2475 continue; 2476 } 2477 2478 // Our Token is a stringization operator. 2479 // Get the next token of the macro. 2480 LexUnexpandedToken(Tok); 2481 2482 // Check for a valid macro arg identifier or __VA_OPT__. 2483 if (!VAOCtx.isVAOptToken(Tok) && 2484 (Tok.getIdentifierInfo() == nullptr || 2485 MI->getParameterNum(Tok.getIdentifierInfo()) == -1)) { 2486 2487 // If this is assembler-with-cpp mode, we accept random gibberish after 2488 // the '#' because '#' is often a comment character. However, change 2489 // the kind of the token to tok::unknown so that the preprocessor isn't 2490 // confused. 2491 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) { 2492 LastTok.setKind(tok::unknown); 2493 MI->AddTokenToBody(LastTok); 2494 continue; 2495 } else { 2496 Diag(Tok, diag::err_pp_stringize_not_parameter) 2497 << LastTok.is(tok::hashat); 2498 return nullptr; 2499 } 2500 } 2501 2502 // Things look ok, add the '#' and param name tokens to the macro. 2503 MI->AddTokenToBody(LastTok); 2504 2505 // If the token following '#' is VAOPT, let the next iteration handle it 2506 // and check it for correctness, otherwise add the token and prime the 2507 // loop with the next one. 2508 if (!VAOCtx.isVAOptToken(Tok)) { 2509 MI->AddTokenToBody(Tok); 2510 LastTok = Tok; 2511 2512 // Get the next token of the macro. 2513 LexUnexpandedToken(Tok); 2514 } 2515 } 2516 if (VAOCtx.isInVAOpt()) { 2517 assert(Tok.is(tok::eod) && "Must be at End Of preprocessing Directive"); 2518 Diag(Tok, diag::err_pp_expected_after) 2519 << LastTok.getKind() << tok::r_paren; 2520 Diag(VAOCtx.getUnmatchedOpeningParenLoc(), diag::note_matching) << tok::l_paren; 2521 return nullptr; 2522 } 2523 } 2524 MI->setDefinitionEndLoc(LastTok.getLocation()); 2525 return MI; 2526 } 2527 /// HandleDefineDirective - Implements \#define. This consumes the entire macro 2528 /// line then lets the caller lex the next real token. 2529 void Preprocessor::HandleDefineDirective( 2530 Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) { 2531 ++NumDefined; 2532 2533 Token MacroNameTok; 2534 bool MacroShadowsKeyword; 2535 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword); 2536 2537 // Error reading macro name? If so, diagnostic already issued. 2538 if (MacroNameTok.is(tok::eod)) 2539 return; 2540 2541 // If we are supposed to keep comments in #defines, reenable comment saving 2542 // mode. 2543 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments); 2544 2545 MacroInfo *const MI = ReadOptionalMacroParameterListAndBody( 2546 MacroNameTok, ImmediatelyAfterHeaderGuard); 2547 2548 if (!MI) return; 2549 2550 if (MacroShadowsKeyword && 2551 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) { 2552 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword); 2553 } 2554 // Check that there is no paste (##) operator at the beginning or end of the 2555 // replacement list. 2556 unsigned NumTokens = MI->getNumTokens(); 2557 if (NumTokens != 0) { 2558 if (MI->getReplacementToken(0).is(tok::hashhash)) { 2559 Diag(MI->getReplacementToken(0), diag::err_paste_at_start); 2560 return; 2561 } 2562 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) { 2563 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end); 2564 return; 2565 } 2566 } 2567 2568 2569 2570 // Finally, if this identifier already had a macro defined for it, verify that 2571 // the macro bodies are identical, and issue diagnostics if they are not. 2572 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) { 2573 // In Objective-C, ignore attempts to directly redefine the builtin 2574 // definitions of the ownership qualifiers. It's still possible to 2575 // #undef them. 2576 auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool { 2577 return II->isStr("__strong") || 2578 II->isStr("__weak") || 2579 II->isStr("__unsafe_unretained") || 2580 II->isStr("__autoreleasing"); 2581 }; 2582 if (getLangOpts().ObjC1 && 2583 SourceMgr.getFileID(OtherMI->getDefinitionLoc()) 2584 == getPredefinesFileID() && 2585 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) { 2586 // Warn if it changes the tokens. 2587 if ((!getDiagnostics().getSuppressSystemWarnings() || 2588 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) && 2589 !MI->isIdenticalTo(*OtherMI, *this, 2590 /*Syntactic=*/LangOpts.MicrosoftExt)) { 2591 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored); 2592 } 2593 assert(!OtherMI->isWarnIfUnused()); 2594 return; 2595 } 2596 2597 // It is very common for system headers to have tons of macro redefinitions 2598 // and for warnings to be disabled in system headers. If this is the case, 2599 // then don't bother calling MacroInfo::isIdenticalTo. 2600 if (!getDiagnostics().getSuppressSystemWarnings() || 2601 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) { 2602 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused()) 2603 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used); 2604 2605 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and 2606 // C++ [cpp.predefined]p4, but allow it as an extension. 2607 if (OtherMI->isBuiltinMacro()) 2608 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro); 2609 // Macros must be identical. This means all tokens and whitespace 2610 // separation must be the same. C99 6.10.3p2. 2611 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() && 2612 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) { 2613 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef) 2614 << MacroNameTok.getIdentifierInfo(); 2615 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition); 2616 } 2617 } 2618 if (OtherMI->isWarnIfUnused()) 2619 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc()); 2620 } 2621 2622 DefMacroDirective *MD = 2623 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI); 2624 2625 assert(!MI->isUsed()); 2626 // If we need warning for not using the macro, add its location in the 2627 // warn-because-unused-macro set. If it gets used it will be removed from set. 2628 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) && 2629 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) { 2630 MI->setIsWarnIfUnused(true); 2631 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc()); 2632 } 2633 2634 // If the callbacks want to know, tell them about the macro definition. 2635 if (Callbacks) 2636 Callbacks->MacroDefined(MacroNameTok, MD); 2637 } 2638 2639 /// HandleUndefDirective - Implements \#undef. 2640 /// 2641 void Preprocessor::HandleUndefDirective() { 2642 ++NumUndefined; 2643 2644 Token MacroNameTok; 2645 ReadMacroName(MacroNameTok, MU_Undef); 2646 2647 // Error reading macro name? If so, diagnostic already issued. 2648 if (MacroNameTok.is(tok::eod)) 2649 return; 2650 2651 // Check to see if this is the last token on the #undef line. 2652 CheckEndOfDirective("undef"); 2653 2654 // Okay, we have a valid identifier to undef. 2655 auto *II = MacroNameTok.getIdentifierInfo(); 2656 auto MD = getMacroDefinition(II); 2657 UndefMacroDirective *Undef = nullptr; 2658 2659 // If the macro is not defined, this is a noop undef. 2660 if (const MacroInfo *MI = MD.getMacroInfo()) { 2661 if (!MI->isUsed() && MI->isWarnIfUnused()) 2662 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used); 2663 2664 if (MI->isWarnIfUnused()) 2665 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); 2666 2667 Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation()); 2668 } 2669 2670 // If the callbacks want to know, tell them about the macro #undef. 2671 // Note: no matter if the macro was defined or not. 2672 if (Callbacks) 2673 Callbacks->MacroUndefined(MacroNameTok, MD, Undef); 2674 2675 if (Undef) 2676 appendMacroDirective(II, Undef); 2677 } 2678 2679 //===----------------------------------------------------------------------===// 2680 // Preprocessor Conditional Directive Handling. 2681 //===----------------------------------------------------------------------===// 2682 2683 /// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef 2684 /// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is 2685 /// true if any tokens have been returned or pp-directives activated before this 2686 /// \#ifndef has been lexed. 2687 /// 2688 void Preprocessor::HandleIfdefDirective(Token &Result, 2689 const Token &HashToken, 2690 bool isIfndef, 2691 bool ReadAnyTokensBeforeDirective) { 2692 ++NumIf; 2693 Token DirectiveTok = Result; 2694 2695 Token MacroNameTok; 2696 ReadMacroName(MacroNameTok); 2697 2698 // Error reading macro name? If so, diagnostic already issued. 2699 if (MacroNameTok.is(tok::eod)) { 2700 // Skip code until we get to #endif. This helps with recovery by not 2701 // emitting an error when the #endif is reached. 2702 SkipExcludedConditionalBlock(HashToken.getLocation(), 2703 DirectiveTok.getLocation(), 2704 /*Foundnonskip*/ false, /*FoundElse*/ false); 2705 return; 2706 } 2707 2708 // Check to see if this is the last token on the #if[n]def line. 2709 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef"); 2710 2711 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo(); 2712 auto MD = getMacroDefinition(MII); 2713 MacroInfo *MI = MD.getMacroInfo(); 2714 2715 if (CurPPLexer->getConditionalStackDepth() == 0) { 2716 // If the start of a top-level #ifdef and if the macro is not defined, 2717 // inform MIOpt that this might be the start of a proper include guard. 2718 // Otherwise it is some other form of unknown conditional which we can't 2719 // handle. 2720 if (!ReadAnyTokensBeforeDirective && !MI) { 2721 assert(isIfndef && "#ifdef shouldn't reach here"); 2722 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation()); 2723 } else 2724 CurPPLexer->MIOpt.EnterTopLevelConditional(); 2725 } 2726 2727 // If there is a macro, process it. 2728 if (MI) // Mark it used. 2729 markMacroAsUsed(MI); 2730 2731 if (Callbacks) { 2732 if (isIfndef) 2733 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD); 2734 else 2735 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD); 2736 } 2737 2738 // Should we include the stuff contained by this directive? 2739 if (PPOpts->SingleFileParseMode && !MI) { 2740 // In 'single-file-parse mode' undefined identifiers trigger parsing of all 2741 // the directive blocks. 2742 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), 2743 /*wasskip*/false, /*foundnonskip*/false, 2744 /*foundelse*/false); 2745 } else if (!MI == isIfndef) { 2746 // Yes, remember that we are inside a conditional, then lex the next token. 2747 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), 2748 /*wasskip*/false, /*foundnonskip*/true, 2749 /*foundelse*/false); 2750 } else { 2751 // No, skip the contents of this block. 2752 SkipExcludedConditionalBlock(HashToken.getLocation(), 2753 DirectiveTok.getLocation(), 2754 /*Foundnonskip*/ false, 2755 /*FoundElse*/ false); 2756 } 2757 } 2758 2759 /// HandleIfDirective - Implements the \#if directive. 2760 /// 2761 void Preprocessor::HandleIfDirective(Token &IfToken, 2762 const Token &HashToken, 2763 bool ReadAnyTokensBeforeDirective) { 2764 ++NumIf; 2765 2766 // Parse and evaluate the conditional expression. 2767 IdentifierInfo *IfNDefMacro = nullptr; 2768 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation(); 2769 const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro); 2770 const bool ConditionalTrue = DER.Conditional; 2771 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation(); 2772 2773 // If this condition is equivalent to #ifndef X, and if this is the first 2774 // directive seen, handle it for the multiple-include optimization. 2775 if (CurPPLexer->getConditionalStackDepth() == 0) { 2776 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue) 2777 // FIXME: Pass in the location of the macro name, not the 'if' token. 2778 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation()); 2779 else 2780 CurPPLexer->MIOpt.EnterTopLevelConditional(); 2781 } 2782 2783 if (Callbacks) 2784 Callbacks->If(IfToken.getLocation(), 2785 SourceRange(ConditionalBegin, ConditionalEnd), 2786 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False)); 2787 2788 // Should we include the stuff contained by this directive? 2789 if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) { 2790 // In 'single-file-parse mode' undefined identifiers trigger parsing of all 2791 // the directive blocks. 2792 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false, 2793 /*foundnonskip*/false, /*foundelse*/false); 2794 } else if (ConditionalTrue) { 2795 // Yes, remember that we are inside a conditional, then lex the next token. 2796 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false, 2797 /*foundnonskip*/true, /*foundelse*/false); 2798 } else { 2799 // No, skip the contents of this block. 2800 SkipExcludedConditionalBlock(HashToken.getLocation(), IfToken.getLocation(), 2801 /*Foundnonskip*/ false, 2802 /*FoundElse*/ false); 2803 } 2804 } 2805 2806 /// HandleEndifDirective - Implements the \#endif directive. 2807 /// 2808 void Preprocessor::HandleEndifDirective(Token &EndifToken) { 2809 ++NumEndif; 2810 2811 // Check that this is the whole directive. 2812 CheckEndOfDirective("endif"); 2813 2814 PPConditionalInfo CondInfo; 2815 if (CurPPLexer->popConditionalLevel(CondInfo)) { 2816 // No conditionals on the stack: this is an #endif without an #if. 2817 Diag(EndifToken, diag::err_pp_endif_without_if); 2818 return; 2819 } 2820 2821 // If this the end of a top-level #endif, inform MIOpt. 2822 if (CurPPLexer->getConditionalStackDepth() == 0) 2823 CurPPLexer->MIOpt.ExitTopLevelConditional(); 2824 2825 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode && 2826 "This code should only be reachable in the non-skipping case!"); 2827 2828 if (Callbacks) 2829 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc); 2830 } 2831 2832 /// HandleElseDirective - Implements the \#else directive. 2833 /// 2834 void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) { 2835 ++NumElse; 2836 2837 // #else directive in a non-skipping conditional... start skipping. 2838 CheckEndOfDirective("else"); 2839 2840 PPConditionalInfo CI; 2841 if (CurPPLexer->popConditionalLevel(CI)) { 2842 Diag(Result, diag::pp_err_else_without_if); 2843 return; 2844 } 2845 2846 // If this is a top-level #else, inform the MIOpt. 2847 if (CurPPLexer->getConditionalStackDepth() == 0) 2848 CurPPLexer->MIOpt.EnterTopLevelConditional(); 2849 2850 // If this is a #else with a #else before it, report the error. 2851 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else); 2852 2853 if (Callbacks) 2854 Callbacks->Else(Result.getLocation(), CI.IfLoc); 2855 2856 if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) { 2857 // In 'single-file-parse mode' undefined identifiers trigger parsing of all 2858 // the directive blocks. 2859 CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false, 2860 /*foundnonskip*/false, /*foundelse*/true); 2861 return; 2862 } 2863 2864 // Finally, skip the rest of the contents of this block. 2865 SkipExcludedConditionalBlock(HashToken.getLocation(), CI.IfLoc, 2866 /*Foundnonskip*/ true, 2867 /*FoundElse*/ true, Result.getLocation()); 2868 } 2869 2870 /// HandleElifDirective - Implements the \#elif directive. 2871 /// 2872 void Preprocessor::HandleElifDirective(Token &ElifToken, 2873 const Token &HashToken) { 2874 ++NumElse; 2875 2876 // #elif directive in a non-skipping conditional... start skipping. 2877 // We don't care what the condition is, because we will always skip it (since 2878 // the block immediately before it was included). 2879 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation(); 2880 DiscardUntilEndOfDirective(); 2881 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation(); 2882 2883 PPConditionalInfo CI; 2884 if (CurPPLexer->popConditionalLevel(CI)) { 2885 Diag(ElifToken, diag::pp_err_elif_without_if); 2886 return; 2887 } 2888 2889 // If this is a top-level #elif, inform the MIOpt. 2890 if (CurPPLexer->getConditionalStackDepth() == 0) 2891 CurPPLexer->MIOpt.EnterTopLevelConditional(); 2892 2893 // If this is a #elif with a #else before it, report the error. 2894 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else); 2895 2896 if (Callbacks) 2897 Callbacks->Elif(ElifToken.getLocation(), 2898 SourceRange(ConditionalBegin, ConditionalEnd), 2899 PPCallbacks::CVK_NotEvaluated, CI.IfLoc); 2900 2901 if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) { 2902 // In 'single-file-parse mode' undefined identifiers trigger parsing of all 2903 // the directive blocks. 2904 CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false, 2905 /*foundnonskip*/false, /*foundelse*/false); 2906 return; 2907 } 2908 2909 // Finally, skip the rest of the contents of this block. 2910 SkipExcludedConditionalBlock( 2911 HashToken.getLocation(), CI.IfLoc, /*Foundnonskip*/ true, 2912 /*FoundElse*/ CI.FoundElse, ElifToken.getLocation()); 2913 } 2914