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