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