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