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