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