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