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