| 1 | //===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | /// |
| 9 | /// \file |
| 10 | /// Implements # directive processing for the Preprocessor. |
| 11 | /// |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "clang/Basic/AttributeCommonInfo.h" |
| 15 | #include "clang/Basic/Attributes.h" |
| 16 | #include "clang/Basic/CharInfo.h" |
| 17 | #include "clang/Basic/DirectoryEntry.h" |
| 18 | #include "clang/Basic/FileManager.h" |
| 19 | #include "clang/Basic/IdentifierTable.h" |
| 20 | #include "clang/Basic/LangOptions.h" |
| 21 | #include "clang/Basic/Module.h" |
| 22 | #include "clang/Basic/SourceLocation.h" |
| 23 | #include "clang/Basic/SourceManager.h" |
| 24 | #include "clang/Basic/TargetInfo.h" |
| 25 | #include "clang/Basic/TokenKinds.h" |
| 26 | #include "clang/Lex/CodeCompletionHandler.h" |
| 27 | #include "clang/Lex/HeaderSearch.h" |
| 28 | #include "clang/Lex/LexDiagnostic.h" |
| 29 | #include "clang/Lex/LiteralSupport.h" |
| 30 | #include "clang/Lex/MacroInfo.h" |
| 31 | #include "clang/Lex/ModuleLoader.h" |
| 32 | #include "clang/Lex/ModuleMap.h" |
| 33 | #include "clang/Lex/PPCallbacks.h" |
| 34 | #include "clang/Lex/Pragma.h" |
| 35 | #include "clang/Lex/Preprocessor.h" |
| 36 | #include "clang/Lex/PreprocessorOptions.h" |
| 37 | #include "clang/Lex/Token.h" |
| 38 | #include "clang/Lex/VariadicMacroSupport.h" |
| 39 | #include "llvm/ADT/ArrayRef.h" |
| 40 | #include "llvm/ADT/STLExtras.h" |
| 41 | #include "llvm/ADT/ScopeExit.h" |
| 42 | #include "llvm/ADT/SmallVector.h" |
| 43 | #include "llvm/ADT/StringExtras.h" |
| 44 | #include "llvm/ADT/StringRef.h" |
| 45 | #include "llvm/ADT/StringSwitch.h" |
| 46 | #include "llvm/Support/ErrorHandling.h" |
| 47 | #include "llvm/Support/Path.h" |
| 48 | #include "llvm/Support/SaveAndRestore.h" |
| 49 | #include <algorithm> |
| 50 | #include <cassert> |
| 51 | #include <cstddef> |
| 52 | #include <cstring> |
| 53 | #include <optional> |
| 54 | #include <string> |
| 55 | #include <utility> |
| 56 | |
| 57 | using namespace clang; |
| 58 | |
| 59 | //===----------------------------------------------------------------------===// |
| 60 | // Utility Methods for Preprocessor Directive Handling. |
| 61 | //===----------------------------------------------------------------------===// |
| 62 | |
| 63 | MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) { |
| 64 | static_assert(std::is_trivially_destructible_v<MacroInfo>, "" ); |
| 65 | return new (BP) MacroInfo(L); |
| 66 | } |
| 67 | |
| 68 | DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, |
| 69 | SourceLocation Loc) { |
| 70 | return new (BP) DefMacroDirective(MI, Loc); |
| 71 | } |
| 72 | |
| 73 | UndefMacroDirective * |
| 74 | Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) { |
| 75 | return new (BP) UndefMacroDirective(UndefLoc); |
| 76 | } |
| 77 | |
| 78 | VisibilityMacroDirective * |
| 79 | Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc, |
| 80 | bool isPublic) { |
| 81 | return new (BP) VisibilityMacroDirective(Loc, isPublic); |
| 82 | } |
| 83 | |
| 84 | /// Read and discard all tokens remaining on the current line until |
| 85 | /// the tok::eod token is found. |
| 86 | SourceRange Preprocessor::DiscardUntilEndOfDirective( |
| 87 | Token &Tmp, SmallVectorImpl<Token> *DiscardedToks) { |
| 88 | SourceRange Res; |
| 89 | auto ReadNextTok = [&]() { |
| 90 | LexUnexpandedToken(Result&: Tmp); |
| 91 | if (DiscardedToks && Tmp.isNot(K: tok::eod)) |
| 92 | DiscardedToks->push_back(Elt: Tmp); |
| 93 | }; |
| 94 | ReadNextTok(); |
| 95 | Res.setBegin(Tmp.getLocation()); |
| 96 | while (Tmp.isNot(K: tok::eod)) { |
| 97 | assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens" ); |
| 98 | ReadNextTok(); |
| 99 | } |
| 100 | Res.setEnd(Tmp.getLocation()); |
| 101 | return Res; |
| 102 | } |
| 103 | |
| 104 | /// Enumerates possible cases of #define/#undef a reserved identifier. |
| 105 | enum MacroDiag { |
| 106 | MD_NoWarn, //> Not a reserved identifier |
| 107 | MD_KeywordDef, //> Macro hides keyword, enabled by default |
| 108 | MD_ReservedMacro, //> #define of #undef reserved id, disabled by default |
| 109 | MD_ReservedAttributeIdentifier |
| 110 | }; |
| 111 | |
| 112 | /// Enumerates possible %select values for the pp_err_elif_after_else and |
| 113 | /// pp_err_elif_without_if diagnostics. |
| 114 | enum PPElifDiag { |
| 115 | PED_Elif, |
| 116 | PED_Elifdef, |
| 117 | PED_Elifndef |
| 118 | }; |
| 119 | |
| 120 | static bool isFeatureTestMacro(StringRef MacroName) { |
| 121 | // list from: |
| 122 | // * https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_macros.html |
| 123 | // * https://docs.microsoft.com/en-us/cpp/c-runtime-library/security-features-in-the-crt?view=msvc-160 |
| 124 | // * man 7 feature_test_macros |
| 125 | // The list must be sorted for correct binary search. |
| 126 | static constexpr StringRef ReservedMacro[] = { |
| 127 | "_ATFILE_SOURCE" , |
| 128 | "_BSD_SOURCE" , |
| 129 | "_CRT_NONSTDC_NO_WARNINGS" , |
| 130 | "_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES" , |
| 131 | "_CRT_SECURE_NO_WARNINGS" , |
| 132 | "_FILE_OFFSET_BITS" , |
| 133 | "_FORTIFY_SOURCE" , |
| 134 | "_GLIBCXX_ASSERTIONS" , |
| 135 | "_GLIBCXX_CONCEPT_CHECKS" , |
| 136 | "_GLIBCXX_DEBUG" , |
| 137 | "_GLIBCXX_DEBUG_PEDANTIC" , |
| 138 | "_GLIBCXX_PARALLEL" , |
| 139 | "_GLIBCXX_PARALLEL_ASSERTIONS" , |
| 140 | "_GLIBCXX_SANITIZE_VECTOR" , |
| 141 | "_GLIBCXX_USE_CXX11_ABI" , |
| 142 | "_GLIBCXX_USE_DEPRECATED" , |
| 143 | "_GNU_SOURCE" , |
| 144 | "_ISOC11_SOURCE" , |
| 145 | "_ISOC95_SOURCE" , |
| 146 | "_ISOC99_SOURCE" , |
| 147 | "_LARGEFILE64_SOURCE" , |
| 148 | "_POSIX_C_SOURCE" , |
| 149 | "_REENTRANT" , |
| 150 | "_SVID_SOURCE" , |
| 151 | "_THREAD_SAFE" , |
| 152 | "_XOPEN_SOURCE" , |
| 153 | "_XOPEN_SOURCE_EXTENDED" , |
| 154 | "__STDCPP_WANT_MATH_SPEC_FUNCS__" , |
| 155 | "__STDC_FORMAT_MACROS" , |
| 156 | }; |
| 157 | return llvm::binary_search(Range: ReservedMacro, Value&: MacroName); |
| 158 | } |
| 159 | |
| 160 | static bool isLanguageDefinedBuiltin(const SourceManager &SourceMgr, |
| 161 | const MacroInfo *MI, |
| 162 | const StringRef MacroName) { |
| 163 | // If this is a macro with special handling (like __LINE__) then it's language |
| 164 | // defined. |
| 165 | if (MI->isBuiltinMacro()) |
| 166 | return true; |
| 167 | // Builtin macros are defined in the builtin file |
| 168 | if (!SourceMgr.isWrittenInBuiltinFile(Loc: MI->getDefinitionLoc())) |
| 169 | return false; |
| 170 | // C defines macros starting with __STDC, and C++ defines macros starting with |
| 171 | // __STDCPP |
| 172 | if (MacroName.starts_with(Prefix: "__STDC" )) |
| 173 | return true; |
| 174 | // C++ defines the __cplusplus macro |
| 175 | if (MacroName == "__cplusplus" ) |
| 176 | return true; |
| 177 | // C++ defines various feature-test macros starting with __cpp |
| 178 | if (MacroName.starts_with(Prefix: "__cpp" )) |
| 179 | return true; |
| 180 | // Anything else isn't language-defined |
| 181 | return false; |
| 182 | } |
| 183 | |
| 184 | static bool isReservedCXXAttributeName(Preprocessor &PP, IdentifierInfo *II) { |
| 185 | const LangOptions &Lang = PP.getLangOpts(); |
| 186 | if (Lang.CPlusPlus && |
| 187 | hasAttribute(Syntax: AttributeCommonInfo::AS_CXX11, /* Scope*/ nullptr, Attr: II, |
| 188 | Target: PP.getTargetInfo(), LangOpts: Lang, /*CheckPlugins*/ false) > 0) { |
| 189 | AttributeCommonInfo::AttrArgsInfo AttrArgsInfo = |
| 190 | AttributeCommonInfo::getCXX11AttrArgsInfo(Name: II); |
| 191 | if (AttrArgsInfo == AttributeCommonInfo::AttrArgsInfo::Required) |
| 192 | return PP.isNextPPTokenOneOf(Ks: tok::l_paren); |
| 193 | |
| 194 | return !PP.isNextPPTokenOneOf(Ks: tok::l_paren) || |
| 195 | AttrArgsInfo == AttributeCommonInfo::AttrArgsInfo::Optional; |
| 196 | } |
| 197 | return false; |
| 198 | } |
| 199 | |
| 200 | static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) { |
| 201 | const LangOptions &Lang = PP.getLangOpts(); |
| 202 | StringRef Text = II->getName(); |
| 203 | if (isReservedInAllContexts(Status: II->isReserved(LangOpts: Lang))) |
| 204 | return isFeatureTestMacro(MacroName: Text) ? MD_NoWarn : MD_ReservedMacro; |
| 205 | if (II->isKeyword(LangOpts: Lang)) |
| 206 | return MD_KeywordDef; |
| 207 | if (Lang.CPlusPlus11 && (Text == "override" || Text == "final" )) |
| 208 | return MD_KeywordDef; |
| 209 | if (isReservedCXXAttributeName(PP, II)) |
| 210 | return MD_ReservedAttributeIdentifier; |
| 211 | return MD_NoWarn; |
| 212 | } |
| 213 | |
| 214 | static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) { |
| 215 | const LangOptions &Lang = PP.getLangOpts(); |
| 216 | // Do not warn on keyword undef. It is generally harmless and widely used. |
| 217 | if (isReservedInAllContexts(Status: II->isReserved(LangOpts: Lang))) |
| 218 | return MD_ReservedMacro; |
| 219 | if (isReservedCXXAttributeName(PP, II)) |
| 220 | return MD_ReservedAttributeIdentifier; |
| 221 | return MD_NoWarn; |
| 222 | } |
| 223 | |
| 224 | // Return true if we want to issue a diagnostic by default if we |
| 225 | // encounter this name in a #include with the wrong case. For now, |
| 226 | // this includes the standard C and C++ headers, Posix headers, |
| 227 | // and Boost headers. Improper case for these #includes is a |
| 228 | // potential portability issue. |
| 229 | static bool warnByDefaultOnWrongCase(StringRef Include) { |
| 230 | // If the first component of the path is "boost", treat this like a standard header |
| 231 | // for the purposes of diagnostics. |
| 232 | if (::llvm::sys::path::begin(path: Include)->equals_insensitive(RHS: "boost" )) |
| 233 | return true; |
| 234 | |
| 235 | // "condition_variable" is the longest standard header name at 18 characters. |
| 236 | // If the include file name is longer than that, it can't be a standard header. |
| 237 | static const size_t = 18u; |
| 238 | if (Include.size() > MaxStdHeaderNameLen) |
| 239 | return false; |
| 240 | |
| 241 | // Lowercase and normalize the search string. |
| 242 | SmallString<32> LowerInclude{Include}; |
| 243 | for (char &Ch : LowerInclude) { |
| 244 | // In the ASCII range? |
| 245 | if (static_cast<unsigned char>(Ch) > 0x7f) |
| 246 | return false; // Can't be a standard header |
| 247 | // ASCII lowercase: |
| 248 | if (Ch >= 'A' && Ch <= 'Z') |
| 249 | Ch += 'a' - 'A'; |
| 250 | // Normalize path separators for comparison purposes. |
| 251 | else if (::llvm::sys::path::is_separator(value: Ch)) |
| 252 | Ch = '/'; |
| 253 | } |
| 254 | |
| 255 | // The standard C/C++ and Posix headers |
| 256 | return llvm::StringSwitch<bool>(LowerInclude) |
| 257 | // C library headers |
| 258 | .Cases(CaseStrings: {"assert.h" , "complex.h" , "ctype.h" , "errno.h" , "fenv.h" }, Value: true) |
| 259 | .Cases(CaseStrings: {"float.h" , "inttypes.h" , "iso646.h" , "limits.h" , "locale.h" }, |
| 260 | Value: true) |
| 261 | .Cases(CaseStrings: {"math.h" , "setjmp.h" , "signal.h" , "stdalign.h" , "stdarg.h" }, Value: true) |
| 262 | .Cases(CaseStrings: {"stdatomic.h" , "stdbool.h" , "stdckdint.h" , "stdcountof.h" }, Value: true) |
| 263 | .Cases(CaseStrings: {"stddef.h" , "stdint.h" , "stdio.h" , "stdlib.h" , "stdnoreturn.h" }, |
| 264 | Value: true) |
| 265 | .Cases(CaseStrings: {"string.h" , "tgmath.h" , "threads.h" , "time.h" , "uchar.h" }, Value: true) |
| 266 | .Cases(CaseStrings: {"wchar.h" , "wctype.h" }, Value: true) |
| 267 | |
| 268 | // C++ headers for C library facilities |
| 269 | .Cases(CaseStrings: {"cassert" , "ccomplex" , "cctype" , "cerrno" , "cfenv" }, Value: true) |
| 270 | .Cases(CaseStrings: {"cfloat" , "cinttypes" , "ciso646" , "climits" , "clocale" }, Value: true) |
| 271 | .Cases(CaseStrings: {"cmath" , "csetjmp" , "csignal" , "cstdalign" , "cstdarg" }, Value: true) |
| 272 | .Cases(CaseStrings: {"cstdbool" , "cstddef" , "cstdint" , "cstdio" , "cstdlib" }, Value: true) |
| 273 | .Cases(CaseStrings: {"cstring" , "ctgmath" , "ctime" , "cuchar" , "cwchar" }, Value: true) |
| 274 | .Case(S: "cwctype" , Value: true) |
| 275 | |
| 276 | // C++ library headers |
| 277 | .Cases(CaseStrings: {"algorithm" , "fstream" , "list" , "regex" , "thread" }, Value: true) |
| 278 | .Cases(CaseStrings: {"array" , "functional" , "locale" , "scoped_allocator" , "tuple" }, |
| 279 | Value: true) |
| 280 | .Cases(CaseStrings: {"atomic" , "future" , "map" , "set" , "type_traits" }, Value: true) |
| 281 | .Cases( |
| 282 | CaseStrings: {"bitset" , "initializer_list" , "memory" , "shared_mutex" , "typeindex" }, |
| 283 | Value: true) |
| 284 | .Cases(CaseStrings: {"chrono" , "iomanip" , "mutex" , "sstream" , "typeinfo" }, Value: true) |
| 285 | .Cases(CaseStrings: {"codecvt" , "ios" , "new" , "stack" , "unordered_map" }, Value: true) |
| 286 | .Cases(CaseStrings: {"complex" , "iosfwd" , "numeric" , "stdexcept" , "unordered_set" }, |
| 287 | Value: true) |
| 288 | .Cases( |
| 289 | CaseStrings: {"condition_variable" , "iostream" , "ostream" , "streambuf" , "utility" }, |
| 290 | Value: true) |
| 291 | .Cases(CaseStrings: {"deque" , "istream" , "queue" , "string" , "valarray" }, Value: true) |
| 292 | .Cases(CaseStrings: {"exception" , "iterator" , "random" , "strstream" , "vector" }, Value: true) |
| 293 | .Cases(CaseStrings: {"forward_list" , "limits" , "ratio" , "system_error" }, Value: true) |
| 294 | |
| 295 | // POSIX headers (which aren't also C headers) |
| 296 | .Cases(CaseStrings: {"aio.h" , "arpa/inet.h" , "cpio.h" , "dirent.h" , "dlfcn.h" }, Value: true) |
| 297 | .Cases(CaseStrings: {"fcntl.h" , "fmtmsg.h" , "fnmatch.h" , "ftw.h" , "glob.h" }, Value: true) |
| 298 | .Cases(CaseStrings: {"grp.h" , "iconv.h" , "langinfo.h" , "libgen.h" , "monetary.h" }, Value: true) |
| 299 | .Cases(CaseStrings: {"mqueue.h" , "ndbm.h" , "net/if.h" , "netdb.h" , "netinet/in.h" }, |
| 300 | Value: true) |
| 301 | .Cases(CaseStrings: {"netinet/tcp.h" , "nl_types.h" , "poll.h" , "pthread.h" , "pwd.h" }, |
| 302 | Value: true) |
| 303 | .Cases(CaseStrings: {"regex.h" , "sched.h" , "search.h" , "semaphore.h" , "spawn.h" }, Value: true) |
| 304 | .Cases(CaseStrings: {"strings.h" , "stropts.h" , "sys/ipc.h" , "sys/mman.h" , "sys/msg.h" }, |
| 305 | Value: true) |
| 306 | .Cases(CaseStrings: {"sys/resource.h" , "sys/select.h" , "sys/sem.h" , "sys/shm.h" , |
| 307 | "sys/socket.h" }, |
| 308 | Value: true) |
| 309 | .Cases(CaseStrings: {"sys/stat.h" , "sys/statvfs.h" , "sys/time.h" , "sys/times.h" , |
| 310 | "sys/types.h" }, |
| 311 | Value: true) |
| 312 | .Cases( |
| 313 | CaseStrings: {"sys/uio.h" , "sys/un.h" , "sys/utsname.h" , "sys/wait.h" , "syslog.h" }, |
| 314 | Value: true) |
| 315 | .Cases(CaseStrings: {"tar.h" , "termios.h" , "trace.h" , "ulimit.h" }, Value: true) |
| 316 | .Cases(CaseStrings: {"unistd.h" , "utime.h" , "utmpx.h" , "wordexp.h" }, Value: true) |
| 317 | .Default(Value: false); |
| 318 | } |
| 319 | |
| 320 | /// Find a similar string in `Candidates`. |
| 321 | /// |
| 322 | /// \param LHS a string for a similar string in `Candidates` |
| 323 | /// |
| 324 | /// \param Candidates the candidates to find a similar string. |
| 325 | /// |
| 326 | /// \returns a similar string if exists. If no similar string exists, |
| 327 | /// returns std::nullopt. |
| 328 | static std::optional<StringRef> |
| 329 | findSimilarStr(StringRef LHS, const std::vector<StringRef> &Candidates) { |
| 330 | // We need to check if `Candidates` has the exact case-insensitive string |
| 331 | // because the Levenshtein distance match does not care about it. |
| 332 | for (StringRef C : Candidates) { |
| 333 | if (LHS.equals_insensitive(RHS: C)) { |
| 334 | return C; |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | // Keep going with the Levenshtein distance match. |
| 339 | // If the LHS size is less than 3, use the LHS size minus 1 and if not, |
| 340 | // use the LHS size divided by 3. |
| 341 | size_t Length = LHS.size(); |
| 342 | size_t MaxDist = Length < 3 ? Length - 1 : Length / 3; |
| 343 | |
| 344 | std::optional<std::pair<StringRef, size_t>> SimilarStr; |
| 345 | for (StringRef C : Candidates) { |
| 346 | size_t CurDist = LHS.edit_distance(Other: C, AllowReplacements: true); |
| 347 | if (CurDist <= MaxDist) { |
| 348 | if (!SimilarStr) { |
| 349 | // The first similar string found. |
| 350 | SimilarStr = {C, CurDist}; |
| 351 | } else if (CurDist < SimilarStr->second) { |
| 352 | // More similar string found. |
| 353 | SimilarStr = {C, CurDist}; |
| 354 | } |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | if (SimilarStr) { |
| 359 | return SimilarStr->first; |
| 360 | } else { |
| 361 | return std::nullopt; |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef, |
| 366 | bool *ShadowFlag) { |
| 367 | // Missing macro name? |
| 368 | if (MacroNameTok.is(K: tok::eod)) |
| 369 | return Diag(Tok: MacroNameTok, DiagID: diag::err_pp_missing_macro_name); |
| 370 | |
| 371 | IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); |
| 372 | if (!II) |
| 373 | return Diag(Tok: MacroNameTok, DiagID: diag::err_pp_macro_not_identifier); |
| 374 | |
| 375 | if (II->isCPlusPlusOperatorKeyword()) { |
| 376 | // C++ 2.5p2: Alternative tokens behave the same as its primary token |
| 377 | // except for their spellings. |
| 378 | Diag(Tok: MacroNameTok, DiagID: getLangOpts().MicrosoftExt |
| 379 | ? diag::ext_pp_operator_used_as_macro_name |
| 380 | : diag::err_pp_operator_used_as_macro_name) |
| 381 | << II << MacroNameTok.getKind(); |
| 382 | // Allow #defining |and| and friends for Microsoft compatibility or |
| 383 | // recovery when legacy C headers are included in C++. |
| 384 | } |
| 385 | |
| 386 | if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) { |
| 387 | // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4. |
| 388 | return Diag(Tok: MacroNameTok, DiagID: diag::err_defined_macro_name); |
| 389 | } |
| 390 | |
| 391 | // If defining/undefining reserved identifier or a keyword, we need to issue |
| 392 | // a warning. |
| 393 | SourceLocation MacroNameLoc = MacroNameTok.getLocation(); |
| 394 | if (ShadowFlag) |
| 395 | *ShadowFlag = false; |
| 396 | // Macro names with reserved identifiers are accepted if built-in or passed |
| 397 | // through the command line (the later may be present if -dD was used to |
| 398 | // generate the preprocessed file). |
| 399 | // NB: isInPredefinedFile() is relatively expensive, so keep it at the end |
| 400 | // of the condition. |
| 401 | if (!SourceMgr.isInSystemHeader(Loc: MacroNameLoc) && |
| 402 | !SourceMgr.isInPredefinedFile(Loc: MacroNameLoc)) { |
| 403 | MacroDiag D = MD_NoWarn; |
| 404 | if (isDefineUndef == MU_Define) { |
| 405 | D = shouldWarnOnMacroDef(PP&: *this, II); |
| 406 | } |
| 407 | else if (isDefineUndef == MU_Undef) |
| 408 | D = shouldWarnOnMacroUndef(PP&: *this, II); |
| 409 | if (D == MD_KeywordDef) { |
| 410 | // We do not want to warn on some patterns widely used in configuration |
| 411 | // scripts. This requires analyzing next tokens, so do not issue warnings |
| 412 | // now, only inform caller. |
| 413 | if (ShadowFlag) |
| 414 | *ShadowFlag = true; |
| 415 | } |
| 416 | if (D == MD_ReservedMacro) |
| 417 | Diag(Tok: MacroNameTok, DiagID: diag::warn_pp_macro_is_reserved_id); |
| 418 | if (D == MD_ReservedAttributeIdentifier) |
| 419 | Diag(Tok: MacroNameTok, DiagID: diag::warn_pp_macro_is_reserved_attribute_id) |
| 420 | << II->getName(); |
| 421 | } |
| 422 | |
| 423 | // Okay, we got a good identifier. |
| 424 | return false; |
| 425 | } |
| 426 | |
| 427 | /// Lex and validate a macro name, which occurs after a |
| 428 | /// \#define or \#undef. |
| 429 | /// |
| 430 | /// This sets the token kind to eod and discards the rest of the macro line if |
| 431 | /// the macro name is invalid. |
| 432 | /// |
| 433 | /// \param MacroNameTok Token that is expected to be a macro name. |
| 434 | /// \param isDefineUndef Context in which macro is used. |
| 435 | /// \param ShadowFlag Points to a flag that is set if macro shadows a keyword. |
| 436 | void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef, |
| 437 | bool *ShadowFlag) { |
| 438 | // Read the token, don't allow macro expansion on it. |
| 439 | LexUnexpandedToken(Result&: MacroNameTok); |
| 440 | |
| 441 | if (MacroNameTok.is(K: tok::code_completion)) { |
| 442 | if (CodeComplete) |
| 443 | CodeComplete->CodeCompleteMacroName(IsDefinition: isDefineUndef == MU_Define); |
| 444 | setCodeCompletionReached(); |
| 445 | LexUnexpandedToken(Result&: MacroNameTok); |
| 446 | } |
| 447 | |
| 448 | if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag)) |
| 449 | return; |
| 450 | |
| 451 | // Invalid macro name, read and discard the rest of the line and set the |
| 452 | // token kind to tok::eod if necessary. |
| 453 | if (MacroNameTok.isNot(K: tok::eod)) { |
| 454 | MacroNameTok.setKind(tok::eod); |
| 455 | DiscardUntilEndOfDirective(); |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | /// Ensure that the next token is a tok::eod token. |
| 460 | /// |
| 461 | /// If not, emit a diagnostic and consume up until the eod. If EnableMacros is |
| 462 | /// true, then we consider macros that expand to zero tokens as being ok. |
| 463 | /// |
| 464 | /// Returns the location of the end of the directive. |
| 465 | SourceLocation |
| 466 | Preprocessor::CheckEndOfDirective(StringRef DirType, bool EnableMacros, |
| 467 | SmallVectorImpl<Token> *) { |
| 468 | Token Tmp; |
| 469 | auto ReadNextTok = [this, ExtraToks, &Tmp](auto &&LexFn) { |
| 470 | std::invoke(LexFn, this, Tmp); |
| 471 | if (ExtraToks && Tmp.isNot(K: tok::eod)) |
| 472 | ExtraToks->push_back(Elt: Tmp); |
| 473 | }; |
| 474 | // Lex unexpanded tokens for most directives: macros might expand to zero |
| 475 | // tokens, causing us to miss diagnosing invalid lines. Some directives (like |
| 476 | // #line) allow empty macros. |
| 477 | if (EnableMacros) |
| 478 | ReadNextTok(&Preprocessor::Lex); |
| 479 | else |
| 480 | ReadNextTok(&Preprocessor::LexUnexpandedToken); |
| 481 | |
| 482 | // There should be no tokens after the directive, but we allow them as an |
| 483 | // extension. |
| 484 | while (Tmp.is(K: tok::comment)) // Skip comments in -C mode. |
| 485 | ReadNextTok(&Preprocessor::LexUnexpandedToken); |
| 486 | |
| 487 | if (Tmp.is(K: tok::eod)) |
| 488 | return Tmp.getLocation(); |
| 489 | |
| 490 | // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89, |
| 491 | // or if this is a macro-style preprocessing directive, because it is more |
| 492 | // trouble than it is worth to insert /**/ and check that there is no /**/ |
| 493 | // in the range also. |
| 494 | FixItHint Hint; |
| 495 | if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) && |
| 496 | !CurTokenLexer) |
| 497 | Hint = FixItHint::CreateInsertion(InsertionLoc: Tmp.getLocation(),Code: "//" ); |
| 498 | |
| 499 | unsigned DiagID = diag::ext_pp_extra_tokens_at_eol; |
| 500 | // C++20 import or module directive has no '#' prefix. |
| 501 | if (getLangOpts().CPlusPlusModules && |
| 502 | (DirType == "import" || DirType == "module" )) |
| 503 | DiagID = diag::warn_pp_extra_tokens_at_module_directive_eol; |
| 504 | |
| 505 | Diag(Tok: Tmp, DiagID) << DirType << Hint; |
| 506 | return DiscardUntilEndOfDirective(DiscardedToks: ExtraToks).getEnd(); |
| 507 | } |
| 508 | |
| 509 | void Preprocessor::SuggestTypoedDirective(const Token &Tok, |
| 510 | StringRef Directive) const { |
| 511 | // If this is a `.S` file, treat unknown # directives as non-preprocessor |
| 512 | // directives. |
| 513 | if (getLangOpts().AsmPreprocessor) return; |
| 514 | |
| 515 | std::vector<StringRef> Candidates = { |
| 516 | "if" , "ifdef" , "ifndef" , "elif" , "else" , "endif" |
| 517 | }; |
| 518 | if (LangOpts.C23 || LangOpts.CPlusPlus23) |
| 519 | Candidates.insert(position: Candidates.end(), l: {"elifdef" , "elifndef" }); |
| 520 | |
| 521 | if (std::optional<StringRef> Sugg = findSimilarStr(LHS: Directive, Candidates)) { |
| 522 | // Directive cannot be coming from macro. |
| 523 | assert(Tok.getLocation().isFileID()); |
| 524 | CharSourceRange DirectiveRange = CharSourceRange::getCharRange( |
| 525 | B: Tok.getLocation(), |
| 526 | E: Tok.getLocation().getLocWithOffset(Offset: Directive.size())); |
| 527 | StringRef SuggValue = *Sugg; |
| 528 | |
| 529 | auto Hint = FixItHint::CreateReplacement(RemoveRange: DirectiveRange, Code: SuggValue); |
| 530 | Diag(Tok, DiagID: diag::warn_pp_invalid_directive) << 1 << SuggValue << Hint; |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | /// SkipExcludedConditionalBlock - We just read a \#if or related directive and |
| 535 | /// decided that the subsequent tokens are in the \#if'd out portion of the |
| 536 | /// file. Lex the rest of the file, until we see an \#endif. If |
| 537 | /// FoundNonSkipPortion is true, then we have already emitted code for part of |
| 538 | /// this \#if directive, so \#else/\#elif blocks should never be entered. |
| 539 | /// If ElseOk is true, then \#else directives are ok, if not, then we have |
| 540 | /// already seen one so a \#else directive is a duplicate. When this returns, |
| 541 | /// the caller can lex the first valid token. |
| 542 | void Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc, |
| 543 | SourceLocation IfTokenLoc, |
| 544 | bool FoundNonSkipPortion, |
| 545 | bool FoundElse, |
| 546 | SourceLocation ElseLoc) { |
| 547 | // In SkippingRangeStateTy we are depending on SkipExcludedConditionalBlock() |
| 548 | // not getting called recursively by storing the RecordedSkippedRanges |
| 549 | // DenseMap lookup pointer (field SkipRangePtr). SkippingRangeStateTy expects |
| 550 | // that RecordedSkippedRanges won't get modified and SkipRangePtr won't be |
| 551 | // invalidated. If this changes and there is a need to call |
| 552 | // SkipExcludedConditionalBlock() recursively, SkippingRangeStateTy should |
| 553 | // change to do a second lookup in endLexPass function instead of reusing the |
| 554 | // lookup pointer. |
| 555 | assert(!SkippingExcludedConditionalBlock && |
| 556 | "calling SkipExcludedConditionalBlock recursively" ); |
| 557 | llvm::SaveAndRestore SARSkipping(SkippingExcludedConditionalBlock, true); |
| 558 | |
| 559 | ++NumSkipped; |
| 560 | assert(!CurTokenLexer && "Conditional PP block cannot appear in a macro!" ); |
| 561 | assert(CurPPLexer && "Conditional PP block must be in a file!" ); |
| 562 | assert(CurLexer && "Conditional PP block but no current lexer set!" ); |
| 563 | |
| 564 | if (PreambleConditionalStack.reachedEOFWhileSkipping()) |
| 565 | PreambleConditionalStack.clearSkipInfo(); |
| 566 | else |
| 567 | CurPPLexer->pushConditionalLevel(DirectiveStart: IfTokenLoc, /*isSkipping*/ WasSkipping: false, |
| 568 | FoundNonSkip: FoundNonSkipPortion, FoundElse); |
| 569 | |
| 570 | // Enter raw mode to disable identifier lookup (and thus macro expansion), |
| 571 | // disabling warnings, etc. |
| 572 | CurPPLexer->LexingRawMode = true; |
| 573 | Token Tok; |
| 574 | SourceLocation endLoc; |
| 575 | |
| 576 | /// Keeps track and caches skipped ranges and also retrieves a prior skipped |
| 577 | /// range if the same block is re-visited. |
| 578 | struct SkippingRangeStateTy { |
| 579 | Preprocessor &PP; |
| 580 | |
| 581 | const char *BeginPtr = nullptr; |
| 582 | unsigned *SkipRangePtr = nullptr; |
| 583 | |
| 584 | SkippingRangeStateTy(Preprocessor &PP) : PP(PP) {} |
| 585 | |
| 586 | void beginLexPass() { |
| 587 | if (BeginPtr) |
| 588 | return; // continue skipping a block. |
| 589 | |
| 590 | // Initiate a skipping block and adjust the lexer if we already skipped it |
| 591 | // before. |
| 592 | BeginPtr = PP.CurLexer->getBufferLocation(); |
| 593 | SkipRangePtr = &PP.RecordedSkippedRanges[BeginPtr]; |
| 594 | if (*SkipRangePtr) { |
| 595 | PP.CurLexer->seek(Offset: PP.CurLexer->getCurrentBufferOffset() + *SkipRangePtr, |
| 596 | /*IsAtStartOfLine*/ true); |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | void endLexPass(const char *Hashptr) { |
| 601 | if (!BeginPtr) { |
| 602 | // Not doing normal lexing. |
| 603 | assert(PP.CurLexer->isDependencyDirectivesLexer()); |
| 604 | return; |
| 605 | } |
| 606 | |
| 607 | // Finished skipping a block, record the range if it's first time visited. |
| 608 | if (!*SkipRangePtr) { |
| 609 | *SkipRangePtr = Hashptr - BeginPtr; |
| 610 | } |
| 611 | assert(*SkipRangePtr == unsigned(Hashptr - BeginPtr)); |
| 612 | BeginPtr = nullptr; |
| 613 | SkipRangePtr = nullptr; |
| 614 | } |
| 615 | } SkippingRangeState(*this); |
| 616 | |
| 617 | while (true) { |
| 618 | if (CurLexer->isDependencyDirectivesLexer()) { |
| 619 | CurLexer->LexDependencyDirectiveTokenWhileSkipping(Result&: Tok); |
| 620 | } else { |
| 621 | SkippingRangeState.beginLexPass(); |
| 622 | while (true) { |
| 623 | CurLexer->Lex(Result&: Tok); |
| 624 | |
| 625 | if (Tok.is(K: tok::code_completion)) { |
| 626 | setCodeCompletionReached(); |
| 627 | if (CodeComplete) |
| 628 | CodeComplete->CodeCompleteInConditionalExclusion(); |
| 629 | continue; |
| 630 | } |
| 631 | |
| 632 | // There is actually no "skipped block" in the above because the module |
| 633 | // directive is not a text-line (https://wg21.link/cpp.pre#2) nor |
| 634 | // anything else that is allowed in a group |
| 635 | // (https://eel.is/c++draft/cpp.pre#nt:group-part). |
| 636 | // |
| 637 | // A preprocessor diagnostic (effective with -E) that triggers whenever |
| 638 | // a module directive is encountered where a control-line or a text-line |
| 639 | // is required. |
| 640 | if (getLangOpts().CPlusPlusModules && Tok.isAtStartOfLine() && |
| 641 | Tok.is(K: tok::raw_identifier) && |
| 642 | (Tok.getRawIdentifier() == "export" || |
| 643 | Tok.getRawIdentifier() == "module" )) { |
| 644 | llvm::SaveAndRestore ModuleDirectiveSkipping( |
| 645 | LastTokenWasExportKeyword); |
| 646 | LastTokenWasExportKeyword.reset(); |
| 647 | LookUpIdentifierInfo(Identifier&: Tok); |
| 648 | IdentifierInfo *II = Tok.getIdentifierInfo(); |
| 649 | |
| 650 | if (II->getName()[0] == 'e') { // export |
| 651 | HandleModuleContextualKeyword(Result&: Tok, TokAtPhysicalStartOfLine: Tok.isAtStartOfLine()); |
| 652 | CurLexer->Lex(Result&: Tok); |
| 653 | if (Tok.is(K: tok::raw_identifier)) { |
| 654 | LookUpIdentifierInfo(Identifier&: Tok); |
| 655 | II = Tok.getIdentifierInfo(); |
| 656 | } |
| 657 | } |
| 658 | |
| 659 | if (II->getName()[0] == 'm') { // module |
| 660 | // HandleModuleContextualKeyword changes the lexer state, so we need |
| 661 | // to save RawLexingMode |
| 662 | llvm::SaveAndRestore RestoreLexingRawMode(CurPPLexer->LexingRawMode, |
| 663 | false); |
| 664 | if (HandleModuleContextualKeyword(Result&: Tok, TokAtPhysicalStartOfLine: Tok.isAtStartOfLine())) { |
| 665 | // We just parsed a # character at the start of a line, so we're |
| 666 | // in directive mode. Tell the lexer this so any newlines we see |
| 667 | // will be converted into an EOD token (this terminates the |
| 668 | // macro). |
| 669 | CurPPLexer->ParsingPreprocessorDirective = true; |
| 670 | SourceLocation StartLoc = Tok.getLocation(); |
| 671 | SourceLocation End = DiscardUntilEndOfDirective().getEnd(); |
| 672 | Diag(Loc: StartLoc, DiagID: diag::err_pp_cond_span_module_decl) |
| 673 | << SourceRange(StartLoc, End); |
| 674 | CurPPLexer->ParsingPreprocessorDirective = false; |
| 675 | // Restore comment saving mode. |
| 676 | if (CurLexer) |
| 677 | CurLexer->resetExtendedTokenMode(); |
| 678 | continue; |
| 679 | } |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | // If this is the end of the buffer, we have an error. |
| 684 | if (Tok.is(K: tok::eof)) { |
| 685 | // We don't emit errors for unterminated conditionals here, |
| 686 | // Lexer::LexEndOfFile can do that properly. |
| 687 | // Just return and let the caller lex after this #include. |
| 688 | if (PreambleConditionalStack.isRecording()) |
| 689 | PreambleConditionalStack.SkipInfo.emplace(args&: HashTokenLoc, args&: IfTokenLoc, |
| 690 | args&: FoundNonSkipPortion, |
| 691 | args&: FoundElse, args&: ElseLoc); |
| 692 | break; |
| 693 | } |
| 694 | |
| 695 | // If this token is not a preprocessor directive, just skip it. |
| 696 | if (Tok.isNot(K: tok::hash) || !Tok.isAtStartOfLine()) |
| 697 | continue; |
| 698 | |
| 699 | break; |
| 700 | } |
| 701 | } |
| 702 | if (Tok.is(K: tok::eof)) |
| 703 | break; |
| 704 | |
| 705 | // We just parsed a # character at the start of a line, so we're in |
| 706 | // directive mode. Tell the lexer this so any newlines we see will be |
| 707 | // converted into an EOD token (this terminates the macro). |
| 708 | CurPPLexer->ParsingPreprocessorDirective = true; |
| 709 | if (CurLexer) CurLexer->SetKeepWhitespaceMode(false); |
| 710 | |
| 711 | assert(Tok.is(tok::hash)); |
| 712 | const char *Hashptr = CurLexer->getBufferLocation() - Tok.getLength(); |
| 713 | assert(CurLexer->getSourceLocation(Hashptr) == Tok.getLocation()); |
| 714 | |
| 715 | // Read the next token, the directive flavor. |
| 716 | LexUnexpandedToken(Result&: Tok); |
| 717 | |
| 718 | // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or |
| 719 | // something bogus), skip it. |
| 720 | if (Tok.isNot(K: tok::raw_identifier)) { |
| 721 | CurPPLexer->ParsingPreprocessorDirective = false; |
| 722 | // Restore comment saving mode. |
| 723 | if (CurLexer) CurLexer->resetExtendedTokenMode(); |
| 724 | continue; |
| 725 | } |
| 726 | |
| 727 | // If the first letter isn't i or e, it isn't intesting to us. We know that |
| 728 | // this is safe in the face of spelling differences, because there is no way |
| 729 | // to spell an i/e in a strange way that is another letter. Skipping this |
| 730 | // allows us to avoid looking up the identifier info for #define/#undef and |
| 731 | // other common directives. |
| 732 | StringRef RI = Tok.getRawIdentifier(); |
| 733 | |
| 734 | char FirstChar = RI[0]; |
| 735 | if (FirstChar >= 'a' && FirstChar <= 'z' && |
| 736 | FirstChar != 'i' && FirstChar != 'e') { |
| 737 | CurPPLexer->ParsingPreprocessorDirective = false; |
| 738 | // Restore comment saving mode. |
| 739 | if (CurLexer) CurLexer->resetExtendedTokenMode(); |
| 740 | continue; |
| 741 | } |
| 742 | |
| 743 | // Get the identifier name without trigraphs or embedded newlines. Note |
| 744 | // that we can't use Tok.getIdentifierInfo() because its lookup is disabled |
| 745 | // when skipping. |
| 746 | char DirectiveBuf[20]; |
| 747 | StringRef Directive; |
| 748 | if (!Tok.needsCleaning() && RI.size() < 20) { |
| 749 | Directive = RI; |
| 750 | } else { |
| 751 | std::string DirectiveStr = getSpelling(Tok); |
| 752 | size_t IdLen = DirectiveStr.size(); |
| 753 | if (IdLen >= 20) { |
| 754 | CurPPLexer->ParsingPreprocessorDirective = false; |
| 755 | // Restore comment saving mode. |
| 756 | if (CurLexer) CurLexer->resetExtendedTokenMode(); |
| 757 | continue; |
| 758 | } |
| 759 | memcpy(dest: DirectiveBuf, src: &DirectiveStr[0], n: IdLen); |
| 760 | Directive = StringRef(DirectiveBuf, IdLen); |
| 761 | } |
| 762 | |
| 763 | if (Directive.starts_with(Prefix: "if" )) { |
| 764 | StringRef Sub = Directive.substr(Start: 2); |
| 765 | if (Sub.empty() || // "if" |
| 766 | Sub == "def" || // "ifdef" |
| 767 | Sub == "ndef" ) { // "ifndef" |
| 768 | // We know the entire #if/#ifdef/#ifndef block will be skipped, don't |
| 769 | // bother parsing the condition. |
| 770 | DiscardUntilEndOfDirective(); |
| 771 | CurPPLexer->pushConditionalLevel(DirectiveStart: Tok.getLocation(), /*wasskipping*/WasSkipping: true, |
| 772 | /*foundnonskip*/FoundNonSkip: false, |
| 773 | /*foundelse*/FoundElse: false); |
| 774 | } else { |
| 775 | SuggestTypoedDirective(Tok, Directive); |
| 776 | } |
| 777 | } else if (Directive[0] == 'e') { |
| 778 | StringRef Sub = Directive.substr(Start: 1); |
| 779 | if (Sub == "ndif" ) { // "endif" |
| 780 | PPConditionalInfo CondInfo; |
| 781 | CondInfo.WasSkipping = true; // Silence bogus warning. |
| 782 | bool InCond = CurPPLexer->popConditionalLevel(CI&: CondInfo); |
| 783 | (void)InCond; // Silence warning in no-asserts mode. |
| 784 | assert(!InCond && "Can't be skipping if not in a conditional!" ); |
| 785 | |
| 786 | // If we popped the outermost skipping block, we're done skipping! |
| 787 | if (!CondInfo.WasSkipping) { |
| 788 | SkippingRangeState.endLexPass(Hashptr); |
| 789 | // Restore the value of LexingRawMode so that trailing comments |
| 790 | // are handled correctly, if we've reached the outermost block. |
| 791 | CurPPLexer->LexingRawMode = false; |
| 792 | endLoc = CheckEndOfDirective(DirType: "endif" ); |
| 793 | CurPPLexer->LexingRawMode = true; |
| 794 | if (Callbacks) |
| 795 | Callbacks->Endif(Loc: Tok.getLocation(), IfLoc: CondInfo.IfLoc); |
| 796 | break; |
| 797 | } else { |
| 798 | DiscardUntilEndOfDirective(); |
| 799 | } |
| 800 | } else if (Sub == "lse" ) { // "else". |
| 801 | // #else directive in a skipping conditional. If not in some other |
| 802 | // skipping conditional, and if #else hasn't already been seen, enter it |
| 803 | // as a non-skipping conditional. |
| 804 | PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); |
| 805 | |
| 806 | if (!CondInfo.WasSkipping) |
| 807 | SkippingRangeState.endLexPass(Hashptr); |
| 808 | |
| 809 | // If this is a #else with a #else before it, report the error. |
| 810 | if (CondInfo.FoundElse) |
| 811 | Diag(Tok, DiagID: diag::pp_err_else_after_else); |
| 812 | |
| 813 | // Note that we've seen a #else in this conditional. |
| 814 | CondInfo.FoundElse = true; |
| 815 | |
| 816 | // If the conditional is at the top level, and the #if block wasn't |
| 817 | // entered, enter the #else block now. |
| 818 | if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) { |
| 819 | CondInfo.FoundNonSkip = true; |
| 820 | // Restore the value of LexingRawMode so that trailing comments |
| 821 | // are handled correctly. |
| 822 | CurPPLexer->LexingRawMode = false; |
| 823 | endLoc = CheckEndOfDirective(DirType: "else" ); |
| 824 | CurPPLexer->LexingRawMode = true; |
| 825 | if (Callbacks) |
| 826 | Callbacks->Else(Loc: Tok.getLocation(), IfLoc: CondInfo.IfLoc); |
| 827 | break; |
| 828 | } else { |
| 829 | DiscardUntilEndOfDirective(); // C99 6.10p4. |
| 830 | } |
| 831 | } else if (Sub == "lif" ) { // "elif". |
| 832 | PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); |
| 833 | |
| 834 | if (!CondInfo.WasSkipping) |
| 835 | SkippingRangeState.endLexPass(Hashptr); |
| 836 | |
| 837 | // If this is a #elif with a #else before it, report the error. |
| 838 | if (CondInfo.FoundElse) |
| 839 | Diag(Tok, DiagID: diag::pp_err_elif_after_else) << PED_Elif; |
| 840 | |
| 841 | // If this is in a skipping block or if we're already handled this #if |
| 842 | // block, don't bother parsing the condition. |
| 843 | if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) { |
| 844 | // FIXME: We should probably do at least some minimal parsing of the |
| 845 | // condition to verify that it is well-formed. The current state |
| 846 | // allows #elif* directives with completely malformed (or missing) |
| 847 | // conditions. |
| 848 | DiscardUntilEndOfDirective(); |
| 849 | } else { |
| 850 | // Restore the value of LexingRawMode so that identifiers are |
| 851 | // looked up, etc, inside the #elif expression. |
| 852 | assert(CurPPLexer->LexingRawMode && "We have to be skipping here!" ); |
| 853 | CurPPLexer->LexingRawMode = false; |
| 854 | IdentifierInfo *IfNDefMacro = nullptr; |
| 855 | DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro); |
| 856 | // Stop if Lexer became invalid after hitting code completion token. |
| 857 | if (!CurPPLexer) |
| 858 | return; |
| 859 | const bool CondValue = DER.Conditional; |
| 860 | CurPPLexer->LexingRawMode = true; |
| 861 | if (Callbacks) { |
| 862 | Callbacks->Elif( |
| 863 | Loc: Tok.getLocation(), ConditionRange: DER.ExprRange, |
| 864 | ConditionValue: (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), |
| 865 | IfLoc: CondInfo.IfLoc); |
| 866 | } |
| 867 | // If this condition is true, enter it! |
| 868 | if (CondValue) { |
| 869 | CondInfo.FoundNonSkip = true; |
| 870 | break; |
| 871 | } |
| 872 | } |
| 873 | } else if (Sub == "lifdef" || // "elifdef" |
| 874 | Sub == "lifndef" ) { // "elifndef" |
| 875 | bool IsElifDef = Sub == "lifdef" ; |
| 876 | PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); |
| 877 | Token DirectiveToken = Tok; |
| 878 | |
| 879 | if (!CondInfo.WasSkipping) |
| 880 | SkippingRangeState.endLexPass(Hashptr); |
| 881 | |
| 882 | // Warn if using `#elifdef` & `#elifndef` in not C23 & C++23 mode even |
| 883 | // if this branch is in a skipping block. |
| 884 | unsigned DiagID; |
| 885 | if (LangOpts.CPlusPlus) |
| 886 | DiagID = LangOpts.CPlusPlus23 ? diag::warn_cxx23_compat_pp_directive |
| 887 | : diag::ext_cxx23_pp_directive; |
| 888 | else |
| 889 | DiagID = LangOpts.C23 ? diag::warn_c23_compat_pp_directive |
| 890 | : diag::ext_c23_pp_directive; |
| 891 | Diag(Tok, DiagID) << (IsElifDef ? PED_Elifdef : PED_Elifndef); |
| 892 | |
| 893 | // If this is a #elif with a #else before it, report the error. |
| 894 | if (CondInfo.FoundElse) |
| 895 | Diag(Tok, DiagID: diag::pp_err_elif_after_else) |
| 896 | << (IsElifDef ? PED_Elifdef : PED_Elifndef); |
| 897 | |
| 898 | // If this is in a skipping block or if we're already handled this #if |
| 899 | // block, don't bother parsing the condition. |
| 900 | if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) { |
| 901 | // FIXME: We should probably do at least some minimal parsing of the |
| 902 | // condition to verify that it is well-formed. The current state |
| 903 | // allows #elif* directives with completely malformed (or missing) |
| 904 | // conditions. |
| 905 | DiscardUntilEndOfDirective(); |
| 906 | } else { |
| 907 | // Restore the value of LexingRawMode so that identifiers are |
| 908 | // looked up, etc, inside the #elif[n]def expression. |
| 909 | assert(CurPPLexer->LexingRawMode && "We have to be skipping here!" ); |
| 910 | CurPPLexer->LexingRawMode = false; |
| 911 | Token MacroNameTok; |
| 912 | ReadMacroName(MacroNameTok); |
| 913 | CurPPLexer->LexingRawMode = true; |
| 914 | |
| 915 | // If the macro name token is tok::eod, there was an error that was |
| 916 | // already reported. |
| 917 | if (MacroNameTok.is(K: tok::eod)) { |
| 918 | // Skip code until we get to #endif. This helps with recovery by |
| 919 | // not emitting an error when the #endif is reached. |
| 920 | continue; |
| 921 | } |
| 922 | |
| 923 | emitMacroExpansionWarnings(Identifier: MacroNameTok); |
| 924 | |
| 925 | CheckEndOfDirective(DirType: IsElifDef ? "elifdef" : "elifndef" ); |
| 926 | |
| 927 | IdentifierInfo *MII = MacroNameTok.getIdentifierInfo(); |
| 928 | auto MD = getMacroDefinition(II: MII); |
| 929 | MacroInfo *MI = MD.getMacroInfo(); |
| 930 | |
| 931 | if (Callbacks) { |
| 932 | if (IsElifDef) { |
| 933 | Callbacks->Elifdef(Loc: DirectiveToken.getLocation(), MacroNameTok, |
| 934 | MD); |
| 935 | } else { |
| 936 | Callbacks->Elifndef(Loc: DirectiveToken.getLocation(), MacroNameTok, |
| 937 | MD); |
| 938 | } |
| 939 | } |
| 940 | // If this condition is true, enter it! |
| 941 | if (static_cast<bool>(MI) == IsElifDef) { |
| 942 | CondInfo.FoundNonSkip = true; |
| 943 | break; |
| 944 | } |
| 945 | } |
| 946 | } else { |
| 947 | SuggestTypoedDirective(Tok, Directive); |
| 948 | } |
| 949 | } else { |
| 950 | SuggestTypoedDirective(Tok, Directive); |
| 951 | } |
| 952 | |
| 953 | CurPPLexer->ParsingPreprocessorDirective = false; |
| 954 | // Restore comment saving mode. |
| 955 | if (CurLexer) CurLexer->resetExtendedTokenMode(); |
| 956 | } |
| 957 | |
| 958 | // Finally, if we are out of the conditional (saw an #endif or ran off the end |
| 959 | // of the file, just stop skipping and return to lexing whatever came after |
| 960 | // the #if block. |
| 961 | CurPPLexer->LexingRawMode = false; |
| 962 | |
| 963 | // The last skipped range isn't actually skipped yet if it's truncated |
| 964 | // by the end of the preamble; we'll resume parsing after the preamble. |
| 965 | if (Callbacks && (Tok.isNot(K: tok::eof) || !isRecordingPreamble())) |
| 966 | Callbacks->SourceRangeSkipped( |
| 967 | Range: SourceRange(HashTokenLoc, endLoc.isValid() |
| 968 | ? endLoc |
| 969 | : CurPPLexer->getSourceLocation()), |
| 970 | EndifLoc: Tok.getLocation()); |
| 971 | } |
| 972 | |
| 973 | Module *Preprocessor::getModuleForLocation(SourceLocation Loc, |
| 974 | bool AllowTextual) { |
| 975 | if (!SourceMgr.isInMainFile(Loc)) { |
| 976 | // Try to determine the module of the include directive. |
| 977 | // FIXME: Look into directly passing the FileEntry from LookupFile instead. |
| 978 | FileID IDOfIncl = SourceMgr.getFileID(SpellingLoc: SourceMgr.getExpansionLoc(Loc)); |
| 979 | if (auto EntryOfIncl = SourceMgr.getFileEntryRefForID(FID: IDOfIncl)) { |
| 980 | // The include comes from an included file. |
| 981 | return HeaderInfo.getModuleMap() |
| 982 | .findModuleForHeader(File: *EntryOfIncl, AllowTextual) |
| 983 | .getModule(); |
| 984 | } |
| 985 | } |
| 986 | |
| 987 | // This is either in the main file or not in a file at all. It belongs |
| 988 | // to the current module, if there is one. |
| 989 | return getLangOpts().CurrentModule.empty() |
| 990 | ? nullptr |
| 991 | : HeaderInfo.lookupModule(ModuleName: getLangOpts().CurrentModule, ImportLoc: Loc); |
| 992 | } |
| 993 | |
| 994 | OptionalFileEntryRef |
| 995 | Preprocessor::(SourceLocation IncLoc, |
| 996 | SourceLocation Loc) { |
| 997 | Module *IncM = getModuleForLocation( |
| 998 | Loc: IncLoc, AllowTextual: LangOpts.ModulesValidateTextualHeaderIncludes); |
| 999 | |
| 1000 | // Walk up through the include stack, looking through textual headers of M |
| 1001 | // until we hit a non-textual header that we can #include. (We assume textual |
| 1002 | // headers of a module with non-textual headers aren't meant to be used to |
| 1003 | // import entities from the module.) |
| 1004 | auto &SM = getSourceManager(); |
| 1005 | while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) { |
| 1006 | auto ID = SM.getFileID(SpellingLoc: SM.getExpansionLoc(Loc)); |
| 1007 | auto FE = SM.getFileEntryRefForID(FID: ID); |
| 1008 | if (!FE) |
| 1009 | break; |
| 1010 | |
| 1011 | // We want to find all possible modules that might contain this header, so |
| 1012 | // search all enclosing directories for module maps and load them. |
| 1013 | HeaderInfo.hasModuleMap(Filename: FE->getName(), /*Root*/ nullptr, |
| 1014 | IsSystem: SourceMgr.isInSystemHeader(Loc)); |
| 1015 | |
| 1016 | bool = false; |
| 1017 | for (auto : HeaderInfo.findAllModulesForHeader(File: *FE)) { |
| 1018 | if (!Header.isAccessibleFrom(M: IncM)) { |
| 1019 | // It's in a private header; we can't #include it. |
| 1020 | // FIXME: If there's a public header in some module that re-exports it, |
| 1021 | // then we could suggest including that, but it's not clear that's the |
| 1022 | // expected way to make this entity visible. |
| 1023 | InPrivateHeader = true; |
| 1024 | continue; |
| 1025 | } |
| 1026 | |
| 1027 | // Don't suggest explicitly excluded headers. |
| 1028 | if (Header.getRole() == ModuleMap::ExcludedHeader) |
| 1029 | continue; |
| 1030 | |
| 1031 | // We'll suggest including textual headers below if they're |
| 1032 | // include-guarded. |
| 1033 | if (Header.getRole() & ModuleMap::TextualHeader) |
| 1034 | continue; |
| 1035 | |
| 1036 | // If we have a module import syntax, we shouldn't include a header to |
| 1037 | // make a particular module visible. Let the caller know they should |
| 1038 | // suggest an import instead. |
| 1039 | if (getLangOpts().ObjC || getLangOpts().CPlusPlusModules) |
| 1040 | return std::nullopt; |
| 1041 | |
| 1042 | // If this is an accessible, non-textual header of M's top-level module |
| 1043 | // that transitively includes the given location and makes the |
| 1044 | // corresponding module visible, this is the thing to #include. |
| 1045 | return *FE; |
| 1046 | } |
| 1047 | |
| 1048 | // FIXME: If we're bailing out due to a private header, we shouldn't suggest |
| 1049 | // an import either. |
| 1050 | if (InPrivateHeader) |
| 1051 | return std::nullopt; |
| 1052 | |
| 1053 | // If the header is includable and has an include guard, assume the |
| 1054 | // intended way to expose its contents is by #include, not by importing a |
| 1055 | // module that transitively includes it. |
| 1056 | if (getHeaderSearchInfo().isFileMultipleIncludeGuarded(File: *FE)) |
| 1057 | return *FE; |
| 1058 | |
| 1059 | Loc = SM.getIncludeLoc(FID: ID); |
| 1060 | } |
| 1061 | |
| 1062 | return std::nullopt; |
| 1063 | } |
| 1064 | |
| 1065 | OptionalFileEntryRef Preprocessor::LookupFile( |
| 1066 | SourceLocation FilenameLoc, StringRef Filename, bool isAngled, |
| 1067 | ConstSearchDirIterator FromDir, const FileEntry *FromFile, |
| 1068 | ConstSearchDirIterator *CurDirArg, SmallVectorImpl<char> *SearchPath, |
| 1069 | SmallVectorImpl<char> *RelativePath, |
| 1070 | ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, |
| 1071 | bool *IsFrameworkFound, bool SkipCache, bool OpenFile, bool CacheFailures) { |
| 1072 | ConstSearchDirIterator CurDirLocal = nullptr; |
| 1073 | ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal; |
| 1074 | |
| 1075 | Module *RequestingModule = getModuleForLocation( |
| 1076 | Loc: FilenameLoc, AllowTextual: LangOpts.ModulesValidateTextualHeaderIncludes); |
| 1077 | |
| 1078 | // If the header lookup mechanism may be relative to the current inclusion |
| 1079 | // stack, record the parent #includes. |
| 1080 | SmallVector<std::pair<OptionalFileEntryRef, DirectoryEntryRef>, 16> Includers; |
| 1081 | bool BuildSystemModule = false; |
| 1082 | if (!FromDir && !FromFile) { |
| 1083 | FileID FID = getCurrentFileLexer()->getFileID(); |
| 1084 | OptionalFileEntryRef FileEnt = SourceMgr.getFileEntryRefForID(FID); |
| 1085 | |
| 1086 | // If there is no file entry associated with this file, it must be the |
| 1087 | // predefines buffer or the module includes buffer. Any other file is not |
| 1088 | // lexed with a normal lexer, so it won't be scanned for preprocessor |
| 1089 | // directives. |
| 1090 | // |
| 1091 | // If we have the predefines buffer, resolve #include references (which come |
| 1092 | // from the -include command line argument) from the current working |
| 1093 | // directory instead of relative to the main file. |
| 1094 | // |
| 1095 | // If we have the module includes buffer, resolve #include references (which |
| 1096 | // come from header declarations in the module map) relative to the module |
| 1097 | // map file. |
| 1098 | if (!FileEnt) { |
| 1099 | if (FID == SourceMgr.getMainFileID() && MainFileDir) { |
| 1100 | auto IncludeDir = |
| 1101 | HeaderInfo.getModuleMap().shouldImportRelativeToBuiltinIncludeDir( |
| 1102 | FileName: Filename, Module: getCurrentModule()) |
| 1103 | ? HeaderInfo.getModuleMap().getBuiltinDir() |
| 1104 | : MainFileDir; |
| 1105 | Includers.push_back(Elt: std::make_pair(x: std::nullopt, y&: *IncludeDir)); |
| 1106 | BuildSystemModule = getCurrentModule()->IsSystem; |
| 1107 | } else if ((FileEnt = SourceMgr.getFileEntryRefForID( |
| 1108 | FID: SourceMgr.getMainFileID()))) { |
| 1109 | auto CWD = FileMgr.getOptionalDirectoryRef(DirName: "." ); |
| 1110 | Includers.push_back(Elt: std::make_pair(x&: *FileEnt, y&: *CWD)); |
| 1111 | } |
| 1112 | } else { |
| 1113 | Includers.push_back(Elt: std::make_pair(x&: *FileEnt, y: FileEnt->getDir())); |
| 1114 | } |
| 1115 | |
| 1116 | // MSVC searches the current include stack from top to bottom for |
| 1117 | // headers included by quoted include directives. |
| 1118 | // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx |
| 1119 | if (LangOpts.MSVCCompat && !isAngled) { |
| 1120 | for (IncludeStackInfo &ISEntry : llvm::reverse(C&: IncludeMacroStack)) { |
| 1121 | if (IsFileLexer(I: ISEntry)) |
| 1122 | if ((FileEnt = ISEntry.ThePPLexer->getFileEntry())) |
| 1123 | Includers.push_back(Elt: std::make_pair(x&: *FileEnt, y: FileEnt->getDir())); |
| 1124 | } |
| 1125 | } |
| 1126 | } |
| 1127 | |
| 1128 | CurDir = CurDirLookup; |
| 1129 | |
| 1130 | if (FromFile) { |
| 1131 | // We're supposed to start looking from after a particular file. Search |
| 1132 | // the include path until we find that file or run out of files. |
| 1133 | ConstSearchDirIterator TmpCurDir = CurDir; |
| 1134 | ConstSearchDirIterator TmpFromDir = nullptr; |
| 1135 | while (OptionalFileEntryRef FE = HeaderInfo.LookupFile( |
| 1136 | Filename, IncludeLoc: FilenameLoc, isAngled, FromDir: TmpFromDir, CurDir: &TmpCurDir, |
| 1137 | Includers, SearchPath, RelativePath, RequestingModule, |
| 1138 | SuggestedModule, /*IsMapped=*/nullptr, |
| 1139 | /*IsFrameworkFound=*/nullptr, SkipCache)) { |
| 1140 | // Keep looking as if this file did a #include_next. |
| 1141 | TmpFromDir = TmpCurDir; |
| 1142 | ++TmpFromDir; |
| 1143 | if (&FE->getFileEntry() == FromFile) { |
| 1144 | // Found it. |
| 1145 | FromDir = TmpFromDir; |
| 1146 | CurDir = TmpCurDir; |
| 1147 | break; |
| 1148 | } |
| 1149 | } |
| 1150 | } |
| 1151 | |
| 1152 | // Do a standard file entry lookup. |
| 1153 | OptionalFileEntryRef FE = HeaderInfo.LookupFile( |
| 1154 | Filename, IncludeLoc: FilenameLoc, isAngled, FromDir, CurDir: &CurDir, Includers, SearchPath, |
| 1155 | RelativePath, RequestingModule, SuggestedModule, IsMapped, |
| 1156 | IsFrameworkFound, SkipCache, BuildSystemModule, OpenFile, CacheFailures); |
| 1157 | if (FE) |
| 1158 | return FE; |
| 1159 | |
| 1160 | OptionalFileEntryRef CurFileEnt; |
| 1161 | // Otherwise, see if this is a subframework header. If so, this is relative |
| 1162 | // to one of the headers on the #include stack. Walk the list of the current |
| 1163 | // headers on the #include stack and pass them to HeaderInfo. |
| 1164 | if (IsFileLexer()) { |
| 1165 | if ((CurFileEnt = CurPPLexer->getFileEntry())) { |
| 1166 | if (OptionalFileEntryRef FE = HeaderInfo.LookupSubframeworkHeader( |
| 1167 | Filename, ContextFileEnt: *CurFileEnt, SearchPath, RelativePath, RequestingModule, |
| 1168 | SuggestedModule)) { |
| 1169 | return FE; |
| 1170 | } |
| 1171 | } |
| 1172 | } |
| 1173 | |
| 1174 | for (IncludeStackInfo &ISEntry : llvm::reverse(C&: IncludeMacroStack)) { |
| 1175 | if (IsFileLexer(I: ISEntry)) { |
| 1176 | if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) { |
| 1177 | if (OptionalFileEntryRef FE = HeaderInfo.LookupSubframeworkHeader( |
| 1178 | Filename, ContextFileEnt: *CurFileEnt, SearchPath, RelativePath, |
| 1179 | RequestingModule, SuggestedModule)) { |
| 1180 | return FE; |
| 1181 | } |
| 1182 | } |
| 1183 | } |
| 1184 | } |
| 1185 | |
| 1186 | // Otherwise, we really couldn't find the file. |
| 1187 | return std::nullopt; |
| 1188 | } |
| 1189 | |
| 1190 | OptionalFileEntryRef Preprocessor::LookupEmbedFile(StringRef Filename, |
| 1191 | bool isAngled, |
| 1192 | bool OpenFile) { |
| 1193 | FileManager &FM = this->getFileManager(); |
| 1194 | if (llvm::sys::path::is_absolute(path: Filename)) { |
| 1195 | // lookup path or immediately fail |
| 1196 | llvm::Expected<FileEntryRef> ShouldBeEntry = FM.getFileRef( |
| 1197 | Filename, OpenFile, /*CacheFailure=*/true, /*IsText=*/false); |
| 1198 | return llvm::expectedToOptional(E: std::move(ShouldBeEntry)); |
| 1199 | } |
| 1200 | |
| 1201 | auto SeparateComponents = [](SmallVectorImpl<char> &LookupPath, |
| 1202 | StringRef StartingFrom, StringRef FileName, |
| 1203 | bool RemoveInitialFileComponentFromLookupPath) { |
| 1204 | llvm::sys::path::native(path: StartingFrom, result&: LookupPath); |
| 1205 | if (RemoveInitialFileComponentFromLookupPath) |
| 1206 | llvm::sys::path::remove_filename(path&: LookupPath); |
| 1207 | if (!LookupPath.empty() && |
| 1208 | !llvm::sys::path::is_separator(value: LookupPath.back())) { |
| 1209 | LookupPath.push_back(Elt: llvm::sys::path::get_separator().front()); |
| 1210 | } |
| 1211 | LookupPath.append(in_start: FileName.begin(), in_end: FileName.end()); |
| 1212 | }; |
| 1213 | |
| 1214 | // Otherwise, it's search time! |
| 1215 | SmallString<512> LookupPath; |
| 1216 | // Non-angled lookup |
| 1217 | if (!isAngled) { |
| 1218 | OptionalFileEntryRef LookupFromFile = getCurrentFileLexer()->getFileEntry(); |
| 1219 | if (LookupFromFile) { |
| 1220 | // Use file-based lookup. |
| 1221 | SmallString<1024> TmpDir; |
| 1222 | TmpDir = LookupFromFile->getDir().getName(); |
| 1223 | llvm::sys::path::append(path&: TmpDir, a: Filename); |
| 1224 | if (!TmpDir.empty()) { |
| 1225 | llvm::Expected<FileEntryRef> ShouldBeEntry = FM.getFileRef( |
| 1226 | Filename: TmpDir, OpenFile, /*CacheFailure=*/true, /*IsText=*/false); |
| 1227 | if (ShouldBeEntry) |
| 1228 | return llvm::expectedToOptional(E: std::move(ShouldBeEntry)); |
| 1229 | llvm::consumeError(Err: ShouldBeEntry.takeError()); |
| 1230 | } |
| 1231 | } |
| 1232 | |
| 1233 | // Otherwise, do working directory lookup. |
| 1234 | LookupPath.clear(); |
| 1235 | auto MaybeWorkingDirEntry = FM.getDirectoryRef(DirName: "." ); |
| 1236 | if (MaybeWorkingDirEntry) { |
| 1237 | DirectoryEntryRef WorkingDirEntry = *MaybeWorkingDirEntry; |
| 1238 | StringRef WorkingDir = WorkingDirEntry.getName(); |
| 1239 | if (!WorkingDir.empty()) { |
| 1240 | SeparateComponents(LookupPath, WorkingDir, Filename, false); |
| 1241 | llvm::Expected<FileEntryRef> ShouldBeEntry = FM.getFileRef( |
| 1242 | Filename: LookupPath, OpenFile, /*CacheFailure=*/true, /*IsText=*/false); |
| 1243 | if (ShouldBeEntry) |
| 1244 | return llvm::expectedToOptional(E: std::move(ShouldBeEntry)); |
| 1245 | llvm::consumeError(Err: ShouldBeEntry.takeError()); |
| 1246 | } |
| 1247 | } |
| 1248 | } |
| 1249 | |
| 1250 | for (const auto &Entry : PPOpts.EmbedEntries) { |
| 1251 | LookupPath.clear(); |
| 1252 | SeparateComponents(LookupPath, Entry, Filename, false); |
| 1253 | llvm::Expected<FileEntryRef> ShouldBeEntry = FM.getFileRef( |
| 1254 | Filename: LookupPath, OpenFile, /*CacheFailure=*/true, /*IsText=*/false); |
| 1255 | if (ShouldBeEntry) |
| 1256 | return llvm::expectedToOptional(E: std::move(ShouldBeEntry)); |
| 1257 | llvm::consumeError(Err: ShouldBeEntry.takeError()); |
| 1258 | } |
| 1259 | return std::nullopt; |
| 1260 | } |
| 1261 | |
| 1262 | //===----------------------------------------------------------------------===// |
| 1263 | // Preprocessor Directive Handling. |
| 1264 | //===----------------------------------------------------------------------===// |
| 1265 | |
| 1266 | class Preprocessor::ResetMacroExpansionHelper { |
| 1267 | public: |
| 1268 | ResetMacroExpansionHelper(Preprocessor *pp) |
| 1269 | : PP(pp), save(pp->DisableMacroExpansion) { |
| 1270 | if (pp->MacroExpansionInDirectivesOverride) |
| 1271 | pp->DisableMacroExpansion = false; |
| 1272 | } |
| 1273 | |
| 1274 | ~ResetMacroExpansionHelper() { |
| 1275 | PP->DisableMacroExpansion = save; |
| 1276 | } |
| 1277 | |
| 1278 | private: |
| 1279 | Preprocessor *PP; |
| 1280 | bool save; |
| 1281 | }; |
| 1282 | |
| 1283 | /// Process a directive while looking for the through header or a #pragma |
| 1284 | /// hdrstop. The following directives are handled: |
| 1285 | /// #include (to check if it is the through header) |
| 1286 | /// #define (to warn about macros that don't match the PCH) |
| 1287 | /// #pragma (to check for pragma hdrstop). |
| 1288 | /// All other directives are completely discarded. |
| 1289 | void Preprocessor::HandleSkippedDirectiveWhileUsingPCH(Token &Result, |
| 1290 | SourceLocation HashLoc) { |
| 1291 | if (const IdentifierInfo *II = Result.getIdentifierInfo()) { |
| 1292 | if (II->getPPKeywordID() == tok::pp_define) { |
| 1293 | return HandleDefineDirective(Tok&: Result, |
| 1294 | /*ImmediatelyAfterHeaderGuard=*/false); |
| 1295 | } |
| 1296 | if (SkippingUntilPCHThroughHeader && |
| 1297 | II->getPPKeywordID() == tok::pp_include) { |
| 1298 | return HandleIncludeDirective(HashLoc, Tok&: Result); |
| 1299 | } |
| 1300 | if (SkippingUntilPragmaHdrStop && II->getPPKeywordID() == tok::pp_pragma) { |
| 1301 | Lex(Result); |
| 1302 | auto *II = Result.getIdentifierInfo(); |
| 1303 | if (II && II->getName() == "hdrstop" ) |
| 1304 | return HandlePragmaHdrstop(Tok&: Result); |
| 1305 | } |
| 1306 | } |
| 1307 | DiscardUntilEndOfDirective(); |
| 1308 | } |
| 1309 | |
| 1310 | /// HandleDirective - This callback is invoked when the lexer sees a # token |
| 1311 | /// at the start of a line. This consumes the directive, modifies the |
| 1312 | /// lexer/preprocessor state, and advances the lexer(s) so that the next token |
| 1313 | /// read is the correct one. |
| 1314 | void Preprocessor::HandleDirective(Token &Result) { |
| 1315 | // FIXME: Traditional: # with whitespace before it not recognized by K&R? |
| 1316 | |
| 1317 | // We just parsed a # character at the start of a line, so we're in directive |
| 1318 | // mode. Tell the lexer this so any newlines we see will be converted into an |
| 1319 | // EOD token (which terminates the directive). |
| 1320 | CurPPLexer->ParsingPreprocessorDirective = true; |
| 1321 | if (CurLexer) CurLexer->SetKeepWhitespaceMode(false); |
| 1322 | |
| 1323 | bool ImmediatelyAfterTopLevelIfndef = |
| 1324 | CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef(); |
| 1325 | CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef(); |
| 1326 | |
| 1327 | ++NumDirectives; |
| 1328 | |
| 1329 | // We are about to read a token. For the multiple-include optimization FA to |
| 1330 | // work, we have to remember if we had read any tokens *before* this |
| 1331 | // pp-directive. |
| 1332 | bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal(); |
| 1333 | |
| 1334 | // Save the directive-introducing token('#' and import/module in C++20) in |
| 1335 | // case we need to return it later. |
| 1336 | Token Introducer = Result; |
| 1337 | |
| 1338 | // Read the next token, the directive flavor. This isn't expanded due to |
| 1339 | // C99 6.10.3p8. |
| 1340 | if (Introducer.is(K: tok::hash)) |
| 1341 | LexUnexpandedToken(Result); |
| 1342 | |
| 1343 | // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.: |
| 1344 | // #define A(x) #x |
| 1345 | // A(abc |
| 1346 | // #warning blah |
| 1347 | // def) |
| 1348 | // If so, the user is relying on undefined behavior, emit a diagnostic. Do |
| 1349 | // not support this for #include-like directives, since that can result in |
| 1350 | // terrible diagnostics, and does not work in GCC. |
| 1351 | if (InMacroArgs) { |
| 1352 | if (IdentifierInfo *II = Result.getIdentifierInfo()) { |
| 1353 | switch (II->getPPKeywordID()) { |
| 1354 | case tok::pp_include: |
| 1355 | case tok::pp_import: |
| 1356 | case tok::pp_include_next: |
| 1357 | case tok::pp___include_macros: |
| 1358 | case tok::pp_pragma: |
| 1359 | case tok::pp_embed: |
| 1360 | case tok::pp_module: |
| 1361 | case tok::pp___preprocessed_module: |
| 1362 | case tok::pp___preprocessed_import: |
| 1363 | Diag(Tok: Result, DiagID: diag::err_embedded_directive) |
| 1364 | << (getLangOpts().CPlusPlusModules && |
| 1365 | Introducer.isModuleContextualKeyword( |
| 1366 | /*AllowExport=*/false)) |
| 1367 | << II->getName(); |
| 1368 | Diag(Tok: *ArgMacro, DiagID: diag::note_macro_expansion_here) |
| 1369 | << ArgMacro->getIdentifierInfo(); |
| 1370 | DiscardUntilEndOfDirective(); |
| 1371 | return; |
| 1372 | default: |
| 1373 | break; |
| 1374 | } |
| 1375 | } |
| 1376 | Diag(Tok: Result, DiagID: diag::ext_embedded_directive); |
| 1377 | } |
| 1378 | |
| 1379 | // Temporarily enable macro expansion if set so |
| 1380 | // and reset to previous state when returning from this function. |
| 1381 | ResetMacroExpansionHelper helper(this); |
| 1382 | |
| 1383 | if (SkippingUntilPCHThroughHeader || SkippingUntilPragmaHdrStop) |
| 1384 | return HandleSkippedDirectiveWhileUsingPCH(Result, |
| 1385 | HashLoc: Introducer.getLocation()); |
| 1386 | |
| 1387 | switch (Result.getKind()) { |
| 1388 | case tok::eod: |
| 1389 | // Ignore the null directive with regards to the multiple-include |
| 1390 | // optimization, i.e. allow the null directive to appear outside of the |
| 1391 | // include guard and still enable the multiple-include optimization. |
| 1392 | CurPPLexer->MIOpt.SetReadToken(ReadAnyTokensBeforeDirective); |
| 1393 | return; // null directive. |
| 1394 | case tok::code_completion: |
| 1395 | setCodeCompletionReached(); |
| 1396 | if (CodeComplete) |
| 1397 | CodeComplete->CodeCompleteDirective( |
| 1398 | InConditional: CurPPLexer->getConditionalStackDepth() > 0); |
| 1399 | return; |
| 1400 | case tok::numeric_constant: // # 7 GNU line marker directive. |
| 1401 | // In a .S file "# 4" may be a comment so don't treat it as a preprocessor |
| 1402 | // directive. However do permit it in the predefines file, as we use line |
| 1403 | // markers to mark the builtin macros as being in a system header. |
| 1404 | if (getLangOpts().AsmPreprocessor && |
| 1405 | SourceMgr.getFileID(SpellingLoc: Introducer.getLocation()) != getPredefinesFileID()) |
| 1406 | break; |
| 1407 | return HandleDigitDirective(Tok&: Result); |
| 1408 | default: |
| 1409 | IdentifierInfo *II = Result.getIdentifierInfo(); |
| 1410 | if (!II) break; // Not an identifier. |
| 1411 | |
| 1412 | // Ask what the preprocessor keyword ID is. |
| 1413 | switch (II->getPPKeywordID()) { |
| 1414 | default: break; |
| 1415 | // C99 6.10.1 - Conditional Inclusion. |
| 1416 | case tok::pp_if: |
| 1417 | return HandleIfDirective(IfToken&: Result, HashToken: Introducer, |
| 1418 | ReadAnyTokensBeforeDirective); |
| 1419 | case tok::pp_ifdef: |
| 1420 | return HandleIfdefDirective(Result, HashToken: Introducer, isIfndef: false, |
| 1421 | ReadAnyTokensBeforeDirective: true /*not valid for miopt*/); |
| 1422 | case tok::pp_ifndef: |
| 1423 | return HandleIfdefDirective(Result, HashToken: Introducer, isIfndef: true, |
| 1424 | ReadAnyTokensBeforeDirective); |
| 1425 | case tok::pp_elif: |
| 1426 | case tok::pp_elifdef: |
| 1427 | case tok::pp_elifndef: |
| 1428 | return HandleElifFamilyDirective(ElifToken&: Result, HashToken: Introducer, |
| 1429 | Kind: II->getPPKeywordID()); |
| 1430 | |
| 1431 | case tok::pp_else: |
| 1432 | return HandleElseDirective(Result, HashToken: Introducer); |
| 1433 | case tok::pp_endif: |
| 1434 | return HandleEndifDirective(EndifToken&: Result); |
| 1435 | |
| 1436 | // C99 6.10.2 - Source File Inclusion. |
| 1437 | case tok::pp_include: |
| 1438 | // Handle #include. |
| 1439 | return HandleIncludeDirective(HashLoc: Introducer.getLocation(), Tok&: Result); |
| 1440 | case tok::pp___include_macros: |
| 1441 | // Handle -imacros. |
| 1442 | return HandleIncludeMacrosDirective(HashLoc: Introducer.getLocation(), Tok&: Result); |
| 1443 | |
| 1444 | // C99 6.10.3 - Macro Replacement. |
| 1445 | case tok::pp_define: |
| 1446 | return HandleDefineDirective(Tok&: Result, ImmediatelyAfterHeaderGuard: ImmediatelyAfterTopLevelIfndef); |
| 1447 | case tok::pp_undef: |
| 1448 | return HandleUndefDirective(); |
| 1449 | |
| 1450 | // C99 6.10.4 - Line Control. |
| 1451 | case tok::pp_line: |
| 1452 | return HandleLineDirective(); |
| 1453 | |
| 1454 | // C99 6.10.5 - Error Directive. |
| 1455 | case tok::pp_error: |
| 1456 | return HandleUserDiagnosticDirective(Tok&: Result, isWarning: false); |
| 1457 | |
| 1458 | // C99 6.10.6 - Pragma Directive. |
| 1459 | case tok::pp_pragma: |
| 1460 | return HandlePragmaDirective(Introducer: {.Kind: PIK_HashPragma, .Loc: Introducer.getLocation()}); |
| 1461 | case tok::pp_module: |
| 1462 | case tok::pp___preprocessed_module: |
| 1463 | return HandleCXXModuleDirective(Module: Result); |
| 1464 | case tok::pp___preprocessed_import: |
| 1465 | return HandleCXXImportDirective(Import: Result); |
| 1466 | // GNU Extensions. |
| 1467 | case tok::pp_import: |
| 1468 | if (getLangOpts().CPlusPlusModules && |
| 1469 | Introducer.isModuleContextualKeyword( |
| 1470 | /*AllowExport=*/false)) |
| 1471 | return HandleCXXImportDirective(Import: Result); |
| 1472 | return HandleImportDirective(HashLoc: Introducer.getLocation(), Tok&: Result); |
| 1473 | case tok::pp_include_next: |
| 1474 | return HandleIncludeNextDirective(HashLoc: Introducer.getLocation(), Tok&: Result); |
| 1475 | |
| 1476 | case tok::pp_warning: |
| 1477 | if (LangOpts.CPlusPlus) |
| 1478 | Diag(Tok: Result, DiagID: LangOpts.CPlusPlus23 |
| 1479 | ? diag::warn_cxx23_compat_warning_directive |
| 1480 | : diag::ext_pp_warning_directive) |
| 1481 | << /*C++23*/ 1; |
| 1482 | else |
| 1483 | Diag(Tok: Result, DiagID: LangOpts.C23 ? diag::warn_c23_compat_warning_directive |
| 1484 | : diag::ext_pp_warning_directive) |
| 1485 | << /*C23*/ 0; |
| 1486 | |
| 1487 | return HandleUserDiagnosticDirective(Tok&: Result, isWarning: true); |
| 1488 | case tok::pp_ident: |
| 1489 | return HandleIdentSCCSDirective(Tok&: Result); |
| 1490 | case tok::pp_sccs: |
| 1491 | return HandleIdentSCCSDirective(Tok&: Result); |
| 1492 | case tok::pp_embed: |
| 1493 | return HandleEmbedDirective(HashLoc: Introducer.getLocation(), Tok&: Result); |
| 1494 | case tok::pp_assert: |
| 1495 | //isExtension = true; // FIXME: implement #assert |
| 1496 | break; |
| 1497 | case tok::pp_unassert: |
| 1498 | //isExtension = true; // FIXME: implement #unassert |
| 1499 | break; |
| 1500 | |
| 1501 | case tok::pp___public_macro: |
| 1502 | if (getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) |
| 1503 | return HandleMacroPublicDirective(Tok&: Result); |
| 1504 | break; |
| 1505 | |
| 1506 | case tok::pp___private_macro: |
| 1507 | if (getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) |
| 1508 | return HandleMacroPrivateDirective(); |
| 1509 | break; |
| 1510 | } |
| 1511 | break; |
| 1512 | } |
| 1513 | |
| 1514 | // If this is a .S file, treat unknown # directives as non-preprocessor |
| 1515 | // directives. This is important because # may be a comment or introduce |
| 1516 | // various pseudo-ops. Just return the # token and push back the following |
| 1517 | // token to be lexed next time. |
| 1518 | if (getLangOpts().AsmPreprocessor) { |
| 1519 | auto Toks = std::make_unique<Token[]>(num: 2); |
| 1520 | // Return the # and the token after it. |
| 1521 | Toks[0] = Introducer; |
| 1522 | Toks[1] = Result; |
| 1523 | |
| 1524 | // If the second token is a hashhash token, then we need to translate it to |
| 1525 | // unknown so the token lexer doesn't try to perform token pasting. |
| 1526 | if (Result.is(K: tok::hashhash)) |
| 1527 | Toks[1].setKind(tok::unknown); |
| 1528 | |
| 1529 | // Enter this token stream so that we re-lex the tokens. Make sure to |
| 1530 | // enable macro expansion, in case the token after the # is an identifier |
| 1531 | // that is expanded. |
| 1532 | EnterTokenStream(Toks: std::move(Toks), NumToks: 2, DisableMacroExpansion: false, /*IsReinject*/false); |
| 1533 | return; |
| 1534 | } |
| 1535 | |
| 1536 | // If we reached here, the preprocessing token is not valid! |
| 1537 | // Start suggesting if a similar directive found. |
| 1538 | Diag(Tok: Result, DiagID: diag::err_pp_invalid_directive) << 0; |
| 1539 | |
| 1540 | // Read the rest of the PP line. |
| 1541 | DiscardUntilEndOfDirective(); |
| 1542 | |
| 1543 | // Okay, we're done parsing the directive. |
| 1544 | } |
| 1545 | |
| 1546 | /// GetLineValue - Convert a numeric token into an unsigned value, emitting |
| 1547 | /// Diagnostic DiagID if it is invalid, and returning the value in Val. |
| 1548 | static bool GetLineValue(Token &DigitTok, unsigned &Val, |
| 1549 | unsigned DiagID, Preprocessor &PP, |
| 1550 | bool IsGNULineDirective=false) { |
| 1551 | if (DigitTok.isNot(K: tok::numeric_constant)) { |
| 1552 | PP.Diag(Tok: DigitTok, DiagID); |
| 1553 | |
| 1554 | if (DigitTok.isNot(K: tok::eod)) |
| 1555 | PP.DiscardUntilEndOfDirective(); |
| 1556 | return true; |
| 1557 | } |
| 1558 | |
| 1559 | SmallString<64> IntegerBuffer; |
| 1560 | IntegerBuffer.resize(N: DigitTok.getLength()); |
| 1561 | const char *DigitTokBegin = &IntegerBuffer[0]; |
| 1562 | bool Invalid = false; |
| 1563 | unsigned ActualLength = PP.getSpelling(Tok: DigitTok, Buffer&: DigitTokBegin, Invalid: &Invalid); |
| 1564 | if (Invalid) |
| 1565 | return true; |
| 1566 | |
| 1567 | // Verify that we have a simple digit-sequence, and compute the value. This |
| 1568 | // is always a simple digit string computed in decimal, so we do this manually |
| 1569 | // here. |
| 1570 | Val = 0; |
| 1571 | for (unsigned i = 0; i != ActualLength; ++i) { |
| 1572 | // C++1y [lex.fcon]p1: |
| 1573 | // Optional separating single quotes in a digit-sequence are ignored |
| 1574 | if (DigitTokBegin[i] == '\'') |
| 1575 | continue; |
| 1576 | |
| 1577 | if (!isDigit(c: DigitTokBegin[i])) { |
| 1578 | PP.Diag(Loc: PP.AdvanceToTokenCharacter(TokStart: DigitTok.getLocation(), Char: i), |
| 1579 | DiagID: diag::err_pp_line_digit_sequence) << IsGNULineDirective; |
| 1580 | PP.DiscardUntilEndOfDirective(); |
| 1581 | return true; |
| 1582 | } |
| 1583 | |
| 1584 | unsigned NextVal = Val*10+(DigitTokBegin[i]-'0'); |
| 1585 | if (NextVal < Val) { // overflow. |
| 1586 | PP.Diag(Tok: DigitTok, DiagID); |
| 1587 | PP.DiscardUntilEndOfDirective(); |
| 1588 | return true; |
| 1589 | } |
| 1590 | Val = NextVal; |
| 1591 | } |
| 1592 | |
| 1593 | if (DigitTokBegin[0] == '0' && Val) |
| 1594 | PP.Diag(Loc: DigitTok.getLocation(), DiagID: diag::warn_pp_line_decimal) |
| 1595 | << IsGNULineDirective; |
| 1596 | |
| 1597 | return false; |
| 1598 | } |
| 1599 | |
| 1600 | /// Handle a \#line directive: C99 6.10.4. |
| 1601 | /// |
| 1602 | /// The two acceptable forms are: |
| 1603 | /// \verbatim |
| 1604 | /// # line digit-sequence |
| 1605 | /// # line digit-sequence "s-char-sequence" |
| 1606 | /// \endverbatim |
| 1607 | void Preprocessor::HandleLineDirective() { |
| 1608 | // Read the line # and string argument. Per C99 6.10.4p5, these tokens are |
| 1609 | // expanded. |
| 1610 | Token DigitTok; |
| 1611 | Lex(Result&: DigitTok); |
| 1612 | |
| 1613 | // Validate the number and convert it to an unsigned. |
| 1614 | unsigned LineNo; |
| 1615 | if (GetLineValue(DigitTok, Val&: LineNo, DiagID: diag::err_pp_line_requires_integer,PP&: *this)) |
| 1616 | return; |
| 1617 | |
| 1618 | if (LineNo == 0) |
| 1619 | Diag(Tok: DigitTok, DiagID: diag::ext_pp_line_zero); |
| 1620 | |
| 1621 | // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a |
| 1622 | // number greater than 2147483647". C90 requires that the line # be <= 32767. |
| 1623 | unsigned LineLimit = 32768U; |
| 1624 | if (LangOpts.C99 || LangOpts.CPlusPlus11) |
| 1625 | LineLimit = 2147483648U; |
| 1626 | if (LineNo >= LineLimit) |
| 1627 | Diag(Tok: DigitTok, DiagID: diag::ext_pp_line_too_big) << LineLimit; |
| 1628 | else if (LangOpts.CPlusPlus11 && LineNo >= 32768U) |
| 1629 | Diag(Tok: DigitTok, DiagID: diag::warn_cxx98_compat_pp_line_too_big); |
| 1630 | |
| 1631 | int FilenameID = -1; |
| 1632 | Token StrTok; |
| 1633 | Lex(Result&: StrTok); |
| 1634 | |
| 1635 | // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a |
| 1636 | // string followed by eod. |
| 1637 | if (StrTok.is(K: tok::eod)) |
| 1638 | ; // ok |
| 1639 | else if (StrTok.isNot(K: tok::string_literal)) { |
| 1640 | Diag(Tok: StrTok, DiagID: diag::err_pp_line_invalid_filename); |
| 1641 | DiscardUntilEndOfDirective(); |
| 1642 | return; |
| 1643 | } else if (StrTok.hasUDSuffix()) { |
| 1644 | Diag(Tok: StrTok, DiagID: diag::err_invalid_string_udl); |
| 1645 | DiscardUntilEndOfDirective(); |
| 1646 | return; |
| 1647 | } else { |
| 1648 | // Parse and validate the string, converting it into a unique ID. |
| 1649 | StringLiteralParser Literal(StrTok, *this); |
| 1650 | assert(Literal.isOrdinary() && "Didn't allow wide strings in" ); |
| 1651 | if (Literal.hadError) { |
| 1652 | DiscardUntilEndOfDirective(); |
| 1653 | return; |
| 1654 | } |
| 1655 | if (Literal.Pascal) { |
| 1656 | Diag(Tok: StrTok, DiagID: diag::err_pp_linemarker_invalid_filename); |
| 1657 | DiscardUntilEndOfDirective(); |
| 1658 | return; |
| 1659 | } |
| 1660 | FilenameID = SourceMgr.getLineTableFilenameID(Str: Literal.GetString()); |
| 1661 | |
| 1662 | // Verify that there is nothing after the string, other than EOD. Because |
| 1663 | // of C99 6.10.4p5, macros that expand to empty tokens are ok. |
| 1664 | CheckEndOfDirective(DirType: "line" , EnableMacros: true); |
| 1665 | } |
| 1666 | |
| 1667 | // Take the file kind of the file containing the #line directive. #line |
| 1668 | // directives are often used for generated sources from the same codebase, so |
| 1669 | // the new file should generally be classified the same way as the current |
| 1670 | // file. This is visible in GCC's pre-processed output, which rewrites #line |
| 1671 | // to GNU line markers. |
| 1672 | SrcMgr::CharacteristicKind FileKind = |
| 1673 | SourceMgr.getFileCharacteristic(Loc: DigitTok.getLocation()); |
| 1674 | |
| 1675 | SourceMgr.AddLineNote(Loc: DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry: false, |
| 1676 | IsFileExit: false, FileKind); |
| 1677 | |
| 1678 | if (Callbacks) |
| 1679 | Callbacks->FileChanged(Loc: CurPPLexer->getSourceLocation(), |
| 1680 | Reason: PPCallbacks::RenameFile, FileType: FileKind); |
| 1681 | } |
| 1682 | |
| 1683 | /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line |
| 1684 | /// marker directive. |
| 1685 | static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit, |
| 1686 | SrcMgr::CharacteristicKind &FileKind, |
| 1687 | Preprocessor &PP) { |
| 1688 | unsigned FlagVal; |
| 1689 | Token FlagTok; |
| 1690 | PP.Lex(Result&: FlagTok); |
| 1691 | if (FlagTok.is(K: tok::eod)) return false; |
| 1692 | if (GetLineValue(DigitTok&: FlagTok, Val&: FlagVal, DiagID: diag::err_pp_linemarker_invalid_flag, PP)) |
| 1693 | return true; |
| 1694 | |
| 1695 | if (FlagVal == 1) { |
| 1696 | IsFileEntry = true; |
| 1697 | |
| 1698 | PP.Lex(Result&: FlagTok); |
| 1699 | if (FlagTok.is(K: tok::eod)) return false; |
| 1700 | if (GetLineValue(DigitTok&: FlagTok, Val&: FlagVal, DiagID: diag::err_pp_linemarker_invalid_flag,PP)) |
| 1701 | return true; |
| 1702 | } else if (FlagVal == 2) { |
| 1703 | IsFileExit = true; |
| 1704 | |
| 1705 | SourceManager &SM = PP.getSourceManager(); |
| 1706 | // If we are leaving the current presumed file, check to make sure the |
| 1707 | // presumed include stack isn't empty! |
| 1708 | FileID CurFileID = |
| 1709 | SM.getDecomposedExpansionLoc(Loc: FlagTok.getLocation()).first; |
| 1710 | PresumedLoc PLoc = SM.getPresumedLoc(Loc: FlagTok.getLocation()); |
| 1711 | if (PLoc.isInvalid()) |
| 1712 | return true; |
| 1713 | |
| 1714 | // If there is no include loc (main file) or if the include loc is in a |
| 1715 | // different physical file, then we aren't in a "1" line marker flag region. |
| 1716 | SourceLocation IncLoc = PLoc.getIncludeLoc(); |
| 1717 | if (IncLoc.isInvalid() || |
| 1718 | SM.getDecomposedExpansionLoc(Loc: IncLoc).first != CurFileID) { |
| 1719 | PP.Diag(Tok: FlagTok, DiagID: diag::err_pp_linemarker_invalid_pop); |
| 1720 | PP.DiscardUntilEndOfDirective(); |
| 1721 | return true; |
| 1722 | } |
| 1723 | |
| 1724 | PP.Lex(Result&: FlagTok); |
| 1725 | if (FlagTok.is(K: tok::eod)) return false; |
| 1726 | if (GetLineValue(DigitTok&: FlagTok, Val&: FlagVal, DiagID: diag::err_pp_linemarker_invalid_flag,PP)) |
| 1727 | return true; |
| 1728 | } |
| 1729 | |
| 1730 | // We must have 3 if there are still flags. |
| 1731 | if (FlagVal != 3) { |
| 1732 | PP.Diag(Tok: FlagTok, DiagID: diag::err_pp_linemarker_invalid_flag); |
| 1733 | PP.DiscardUntilEndOfDirective(); |
| 1734 | return true; |
| 1735 | } |
| 1736 | |
| 1737 | FileKind = SrcMgr::C_System; |
| 1738 | |
| 1739 | PP.Lex(Result&: FlagTok); |
| 1740 | if (FlagTok.is(K: tok::eod)) return false; |
| 1741 | if (GetLineValue(DigitTok&: FlagTok, Val&: FlagVal, DiagID: diag::err_pp_linemarker_invalid_flag, PP)) |
| 1742 | return true; |
| 1743 | |
| 1744 | // We must have 4 if there is yet another flag. |
| 1745 | if (FlagVal != 4) { |
| 1746 | PP.Diag(Tok: FlagTok, DiagID: diag::err_pp_linemarker_invalid_flag); |
| 1747 | PP.DiscardUntilEndOfDirective(); |
| 1748 | return true; |
| 1749 | } |
| 1750 | |
| 1751 | FileKind = SrcMgr::C_ExternCSystem; |
| 1752 | |
| 1753 | PP.Lex(Result&: FlagTok); |
| 1754 | if (FlagTok.is(K: tok::eod)) return false; |
| 1755 | |
| 1756 | // There are no more valid flags here. |
| 1757 | PP.Diag(Tok: FlagTok, DiagID: diag::err_pp_linemarker_invalid_flag); |
| 1758 | PP.DiscardUntilEndOfDirective(); |
| 1759 | return true; |
| 1760 | } |
| 1761 | |
| 1762 | /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is |
| 1763 | /// one of the following forms: |
| 1764 | /// |
| 1765 | /// # 42 |
| 1766 | /// # 42 "file" ('1' | '2')? |
| 1767 | /// # 42 "file" ('1' | '2')? '3' '4'? |
| 1768 | /// |
| 1769 | void Preprocessor::HandleDigitDirective(Token &DigitTok) { |
| 1770 | // Validate the number and convert it to an unsigned. GNU does not have a |
| 1771 | // line # limit other than it fit in 32-bits. |
| 1772 | unsigned LineNo; |
| 1773 | if (GetLineValue(DigitTok, Val&: LineNo, DiagID: diag::err_pp_linemarker_requires_integer, |
| 1774 | PP&: *this, IsGNULineDirective: true)) |
| 1775 | return; |
| 1776 | |
| 1777 | Token StrTok; |
| 1778 | Lex(Result&: StrTok); |
| 1779 | |
| 1780 | bool IsFileEntry = false, IsFileExit = false; |
| 1781 | int FilenameID = -1; |
| 1782 | SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User; |
| 1783 | |
| 1784 | // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a |
| 1785 | // string followed by eod. |
| 1786 | if (StrTok.is(K: tok::eod)) { |
| 1787 | Diag(Tok: StrTok, DiagID: diag::ext_pp_gnu_line_directive); |
| 1788 | // Treat this like "#line NN", which doesn't change file characteristics. |
| 1789 | FileKind = SourceMgr.getFileCharacteristic(Loc: DigitTok.getLocation()); |
| 1790 | } else if (StrTok.isNot(K: tok::string_literal)) { |
| 1791 | Diag(Tok: StrTok, DiagID: diag::err_pp_linemarker_invalid_filename); |
| 1792 | DiscardUntilEndOfDirective(); |
| 1793 | return; |
| 1794 | } else if (StrTok.hasUDSuffix()) { |
| 1795 | Diag(Tok: StrTok, DiagID: diag::err_invalid_string_udl); |
| 1796 | DiscardUntilEndOfDirective(); |
| 1797 | return; |
| 1798 | } else { |
| 1799 | // Parse and validate the string, converting it into a unique ID. |
| 1800 | StringLiteralParser Literal(StrTok, *this); |
| 1801 | assert(Literal.isOrdinary() && "Didn't allow wide strings in" ); |
| 1802 | if (Literal.hadError) { |
| 1803 | DiscardUntilEndOfDirective(); |
| 1804 | return; |
| 1805 | } |
| 1806 | if (Literal.Pascal) { |
| 1807 | Diag(Tok: StrTok, DiagID: diag::err_pp_linemarker_invalid_filename); |
| 1808 | DiscardUntilEndOfDirective(); |
| 1809 | return; |
| 1810 | } |
| 1811 | |
| 1812 | // If a filename was present, read any flags that are present. |
| 1813 | if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, PP&: *this)) |
| 1814 | return; |
| 1815 | if (!SourceMgr.isInPredefinedFile(Loc: DigitTok.getLocation())) |
| 1816 | Diag(Tok: StrTok, DiagID: diag::ext_pp_gnu_line_directive); |
| 1817 | |
| 1818 | // Exiting to an empty string means pop to the including file, so leave |
| 1819 | // FilenameID as -1 in that case. |
| 1820 | if (!(IsFileExit && Literal.GetString().empty())) |
| 1821 | FilenameID = SourceMgr.getLineTableFilenameID(Str: Literal.GetString()); |
| 1822 | } |
| 1823 | |
| 1824 | // Create a line note with this information. |
| 1825 | SourceMgr.AddLineNote(Loc: DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry, |
| 1826 | IsFileExit, FileKind); |
| 1827 | |
| 1828 | // If the preprocessor has callbacks installed, notify them of the #line |
| 1829 | // change. This is used so that the line marker comes out in -E mode for |
| 1830 | // example. |
| 1831 | if (Callbacks) { |
| 1832 | PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile; |
| 1833 | if (IsFileEntry) |
| 1834 | Reason = PPCallbacks::EnterFile; |
| 1835 | else if (IsFileExit) |
| 1836 | Reason = PPCallbacks::ExitFile; |
| 1837 | |
| 1838 | Callbacks->FileChanged(Loc: CurPPLexer->getSourceLocation(), Reason, FileType: FileKind); |
| 1839 | } |
| 1840 | } |
| 1841 | |
| 1842 | /// HandleUserDiagnosticDirective - Handle a #warning or #error directive. |
| 1843 | /// |
| 1844 | void Preprocessor::HandleUserDiagnosticDirective(Token &Tok, |
| 1845 | bool isWarning) { |
| 1846 | // Read the rest of the line raw. We do this because we don't want macros |
| 1847 | // to be expanded and we don't require that the tokens be valid preprocessing |
| 1848 | // tokens. For example, this is allowed: "#warning ` 'foo". GCC does |
| 1849 | // collapse multiple consecutive white space between tokens, but this isn't |
| 1850 | // specified by the standard. |
| 1851 | SmallString<128> Message; |
| 1852 | CurLexer->ReadToEndOfLine(Result: &Message); |
| 1853 | |
| 1854 | // Find the first non-whitespace character, so that we can make the |
| 1855 | // diagnostic more succinct. |
| 1856 | StringRef Msg = Message.str().ltrim(Char: ' '); |
| 1857 | |
| 1858 | if (isWarning) |
| 1859 | Diag(Tok, DiagID: diag::pp_hash_warning) << Msg; |
| 1860 | else |
| 1861 | Diag(Tok, DiagID: diag::err_pp_hash_error) << Msg; |
| 1862 | } |
| 1863 | |
| 1864 | /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive. |
| 1865 | /// |
| 1866 | void Preprocessor::HandleIdentSCCSDirective(Token &Tok) { |
| 1867 | // Yes, this directive is an extension. |
| 1868 | Diag(Tok, DiagID: diag::ext_pp_ident_directive); |
| 1869 | |
| 1870 | // Read the string argument. |
| 1871 | Token StrTok; |
| 1872 | Lex(Result&: StrTok); |
| 1873 | |
| 1874 | // If the token kind isn't a string, it's a malformed directive. |
| 1875 | if (StrTok.isNot(K: tok::string_literal) && |
| 1876 | StrTok.isNot(K: tok::wide_string_literal)) { |
| 1877 | Diag(Tok: StrTok, DiagID: diag::err_pp_malformed_ident); |
| 1878 | if (StrTok.isNot(K: tok::eod)) |
| 1879 | DiscardUntilEndOfDirective(); |
| 1880 | return; |
| 1881 | } |
| 1882 | |
| 1883 | if (StrTok.hasUDSuffix()) { |
| 1884 | Diag(Tok: StrTok, DiagID: diag::err_invalid_string_udl); |
| 1885 | DiscardUntilEndOfDirective(); |
| 1886 | return; |
| 1887 | } |
| 1888 | |
| 1889 | // Verify that there is nothing after the string, other than EOD. |
| 1890 | CheckEndOfDirective(DirType: "ident" ); |
| 1891 | |
| 1892 | if (Callbacks) { |
| 1893 | bool Invalid = false; |
| 1894 | std::string Str = getSpelling(Tok: StrTok, Invalid: &Invalid); |
| 1895 | if (!Invalid) |
| 1896 | Callbacks->Ident(Loc: Tok.getLocation(), str: Str); |
| 1897 | } |
| 1898 | } |
| 1899 | |
| 1900 | /// Handle a #public directive. |
| 1901 | void Preprocessor::HandleMacroPublicDirective(Token &Tok) { |
| 1902 | Token MacroNameTok; |
| 1903 | ReadMacroName(MacroNameTok, isDefineUndef: MU_Undef); |
| 1904 | |
| 1905 | // Error reading macro name? If so, diagnostic already issued. |
| 1906 | if (MacroNameTok.is(K: tok::eod)) |
| 1907 | return; |
| 1908 | |
| 1909 | // Check to see if this is the last token on the #__public_macro line. |
| 1910 | CheckEndOfDirective(DirType: "__public_macro" ); |
| 1911 | |
| 1912 | IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); |
| 1913 | // Okay, we finally have a valid identifier to undef. |
| 1914 | MacroDirective *MD = getLocalMacroDirective(II); |
| 1915 | |
| 1916 | // If the macro is not defined, this is an error. |
| 1917 | if (!MD) { |
| 1918 | Diag(Tok: MacroNameTok, DiagID: diag::err_pp_visibility_non_macro) << II; |
| 1919 | return; |
| 1920 | } |
| 1921 | |
| 1922 | // Note that this macro has now been exported. |
| 1923 | appendMacroDirective(II, MD: AllocateVisibilityMacroDirective( |
| 1924 | Loc: MacroNameTok.getLocation(), /*isPublic=*/true)); |
| 1925 | } |
| 1926 | |
| 1927 | /// Handle a #private directive. |
| 1928 | void Preprocessor::HandleMacroPrivateDirective() { |
| 1929 | Token MacroNameTok; |
| 1930 | ReadMacroName(MacroNameTok, isDefineUndef: MU_Undef); |
| 1931 | |
| 1932 | // Error reading macro name? If so, diagnostic already issued. |
| 1933 | if (MacroNameTok.is(K: tok::eod)) |
| 1934 | return; |
| 1935 | |
| 1936 | // Check to see if this is the last token on the #__private_macro line. |
| 1937 | CheckEndOfDirective(DirType: "__private_macro" ); |
| 1938 | |
| 1939 | IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); |
| 1940 | // Okay, we finally have a valid identifier to undef. |
| 1941 | MacroDirective *MD = getLocalMacroDirective(II); |
| 1942 | |
| 1943 | // If the macro is not defined, this is an error. |
| 1944 | if (!MD) { |
| 1945 | Diag(Tok: MacroNameTok, DiagID: diag::err_pp_visibility_non_macro) << II; |
| 1946 | return; |
| 1947 | } |
| 1948 | |
| 1949 | // Note that this macro has now been marked private. |
| 1950 | appendMacroDirective(II, MD: AllocateVisibilityMacroDirective( |
| 1951 | Loc: MacroNameTok.getLocation(), /*isPublic=*/false)); |
| 1952 | } |
| 1953 | |
| 1954 | //===----------------------------------------------------------------------===// |
| 1955 | // Preprocessor Include Directive Handling. |
| 1956 | //===----------------------------------------------------------------------===// |
| 1957 | |
| 1958 | /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully |
| 1959 | /// checked and spelled filename, e.g. as an operand of \#include. This returns |
| 1960 | /// true if the input filename was in <>'s or false if it were in ""'s. The |
| 1961 | /// caller is expected to provide a buffer that is large enough to hold the |
| 1962 | /// spelling of the filename, but is also expected to handle the case when |
| 1963 | /// this method decides to use a different buffer. |
| 1964 | bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc, |
| 1965 | StringRef &Buffer) { |
| 1966 | // Get the text form of the filename. |
| 1967 | assert(!Buffer.empty() && "Can't have tokens with empty spellings!" ); |
| 1968 | |
| 1969 | // FIXME: Consider warning on some of the cases described in C11 6.4.7/3 and |
| 1970 | // C++20 [lex.header]/2: |
| 1971 | // |
| 1972 | // If `"`, `'`, `\`, `/*`, or `//` appears in a header-name, then |
| 1973 | // in C: behavior is undefined |
| 1974 | // in C++: program is conditionally-supported with implementation-defined |
| 1975 | // semantics |
| 1976 | |
| 1977 | // Make sure the filename is <x> or "x". |
| 1978 | bool isAngled; |
| 1979 | if (Buffer[0] == '<') { |
| 1980 | if (Buffer.back() != '>') { |
| 1981 | Diag(Loc, DiagID: diag::err_pp_expects_filename); |
| 1982 | Buffer = StringRef(); |
| 1983 | return true; |
| 1984 | } |
| 1985 | isAngled = true; |
| 1986 | } else if (Buffer[0] == '"') { |
| 1987 | if (Buffer.back() != '"') { |
| 1988 | Diag(Loc, DiagID: diag::err_pp_expects_filename); |
| 1989 | Buffer = StringRef(); |
| 1990 | return true; |
| 1991 | } |
| 1992 | isAngled = false; |
| 1993 | } else { |
| 1994 | Diag(Loc, DiagID: diag::err_pp_expects_filename); |
| 1995 | Buffer = StringRef(); |
| 1996 | return true; |
| 1997 | } |
| 1998 | |
| 1999 | // Diagnose #include "" as invalid. |
| 2000 | if (Buffer.size() <= 2) { |
| 2001 | Diag(Loc, DiagID: diag::err_pp_empty_filename); |
| 2002 | Buffer = StringRef(); |
| 2003 | return true; |
| 2004 | } |
| 2005 | |
| 2006 | // Skip the brackets. |
| 2007 | Buffer = Buffer.substr(Start: 1, N: Buffer.size()-2); |
| 2008 | return isAngled; |
| 2009 | } |
| 2010 | |
| 2011 | /// Push a token onto the token stream containing an annotation. |
| 2012 | void Preprocessor::EnterAnnotationToken(SourceRange Range, |
| 2013 | tok::TokenKind Kind, |
| 2014 | void *AnnotationVal) { |
| 2015 | // FIXME: Produce this as the current token directly, rather than |
| 2016 | // allocating a new token for it. |
| 2017 | auto Tok = std::make_unique<Token[]>(num: 1); |
| 2018 | Tok[0].startToken(); |
| 2019 | Tok[0].setKind(Kind); |
| 2020 | Tok[0].setLocation(Range.getBegin()); |
| 2021 | Tok[0].setAnnotationEndLoc(Range.getEnd()); |
| 2022 | Tok[0].setAnnotationValue(AnnotationVal); |
| 2023 | EnterTokenStream(Toks: std::move(Tok), NumToks: 1, DisableMacroExpansion: true, /*IsReinject*/ false); |
| 2024 | } |
| 2025 | |
| 2026 | /// Produce a diagnostic informing the user that a #include or similar |
| 2027 | /// was implicitly treated as a module import. |
| 2028 | static void diagnoseAutoModuleImport(Preprocessor &PP, SourceLocation HashLoc, |
| 2029 | Token &IncludeTok, |
| 2030 | ArrayRef<IdentifierLoc> Path, |
| 2031 | SourceLocation PathEnd) { |
| 2032 | SmallString<128> PathString; |
| 2033 | for (size_t I = 0, N = Path.size(); I != N; ++I) { |
| 2034 | if (I) |
| 2035 | PathString += '.'; |
| 2036 | PathString += Path[I].getIdentifierInfo()->getName(); |
| 2037 | } |
| 2038 | |
| 2039 | int IncludeKind = 0; |
| 2040 | switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) { |
| 2041 | case tok::pp_include: |
| 2042 | IncludeKind = 0; |
| 2043 | break; |
| 2044 | |
| 2045 | case tok::pp_import: |
| 2046 | IncludeKind = 1; |
| 2047 | break; |
| 2048 | |
| 2049 | case tok::pp_include_next: |
| 2050 | IncludeKind = 2; |
| 2051 | break; |
| 2052 | |
| 2053 | case tok::pp___include_macros: |
| 2054 | IncludeKind = 3; |
| 2055 | break; |
| 2056 | |
| 2057 | default: |
| 2058 | llvm_unreachable("unknown include directive kind" ); |
| 2059 | } |
| 2060 | |
| 2061 | PP.Diag(Loc: HashLoc, DiagID: diag::remark_pp_include_directive_modular_translation) |
| 2062 | << IncludeKind << PathString; |
| 2063 | } |
| 2064 | |
| 2065 | // Given a vector of path components and a string containing the real |
| 2066 | // path to the file, build a properly-cased replacement in the vector, |
| 2067 | // and return true if the replacement should be suggested. |
| 2068 | static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components, |
| 2069 | StringRef RealPathName, |
| 2070 | llvm::sys::path::Style Separator) { |
| 2071 | auto RealPathComponentIter = llvm::sys::path::rbegin(path: RealPathName); |
| 2072 | auto RealPathComponentEnd = llvm::sys::path::rend(path: RealPathName); |
| 2073 | int Cnt = 0; |
| 2074 | bool SuggestReplacement = false; |
| 2075 | |
| 2076 | auto IsSep = [Separator](StringRef Component) { |
| 2077 | return Component.size() == 1 && |
| 2078 | llvm::sys::path::is_separator(value: Component[0], style: Separator); |
| 2079 | }; |
| 2080 | |
| 2081 | // Below is a best-effort to handle ".." in paths. It is admittedly |
| 2082 | // not 100% correct in the presence of symlinks. |
| 2083 | for (auto &Component : llvm::reverse(C&: Components)) { |
| 2084 | if ("." == Component) { |
| 2085 | } else if (".." == Component) { |
| 2086 | ++Cnt; |
| 2087 | } else if (Cnt) { |
| 2088 | --Cnt; |
| 2089 | } else if (RealPathComponentIter != RealPathComponentEnd) { |
| 2090 | if (!IsSep(Component) && !IsSep(*RealPathComponentIter) && |
| 2091 | Component != *RealPathComponentIter) { |
| 2092 | // If these non-separator path components differ by more than just case, |
| 2093 | // then we may be looking at symlinked paths. Bail on this diagnostic to |
| 2094 | // avoid noisy false positives. |
| 2095 | SuggestReplacement = |
| 2096 | RealPathComponentIter->equals_insensitive(RHS: Component); |
| 2097 | if (!SuggestReplacement) |
| 2098 | break; |
| 2099 | Component = *RealPathComponentIter; |
| 2100 | } |
| 2101 | ++RealPathComponentIter; |
| 2102 | } |
| 2103 | } |
| 2104 | return SuggestReplacement; |
| 2105 | } |
| 2106 | |
| 2107 | bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts, |
| 2108 | const TargetInfo &TargetInfo, |
| 2109 | const Module &M, |
| 2110 | DiagnosticsEngine &Diags) { |
| 2111 | Module::Requirement Requirement; |
| 2112 | Module::UnresolvedHeaderDirective ; |
| 2113 | Module *ShadowingModule = nullptr; |
| 2114 | if (M.isAvailable(LangOpts, Target: TargetInfo, Req&: Requirement, MissingHeader, |
| 2115 | ShadowingModule)) |
| 2116 | return false; |
| 2117 | |
| 2118 | if (MissingHeader.FileNameLoc.isValid()) { |
| 2119 | Diags.Report(Loc: MissingHeader.FileNameLoc, DiagID: diag::err_module_header_missing) |
| 2120 | << MissingHeader.IsUmbrella << MissingHeader.FileName; |
| 2121 | } else if (ShadowingModule) { |
| 2122 | Diags.Report(Loc: M.DefinitionLoc, DiagID: diag::err_module_shadowed) << M.Name; |
| 2123 | Diags.Report(Loc: ShadowingModule->DefinitionLoc, |
| 2124 | DiagID: diag::note_previous_definition); |
| 2125 | } else { |
| 2126 | // FIXME: Track the location at which the requirement was specified, and |
| 2127 | // use it here. |
| 2128 | Diags.Report(Loc: M.DefinitionLoc, DiagID: diag::err_module_unavailable) |
| 2129 | << M.getFullModuleName() << Requirement.RequiredState |
| 2130 | << Requirement.FeatureName; |
| 2131 | } |
| 2132 | return true; |
| 2133 | } |
| 2134 | |
| 2135 | std::pair<ConstSearchDirIterator, const FileEntry *> |
| 2136 | Preprocessor::getIncludeNextStart(const Token &IncludeNextTok) const { |
| 2137 | // #include_next is like #include, except that we start searching after |
| 2138 | // the current found directory. If we can't do this, issue a |
| 2139 | // diagnostic. |
| 2140 | ConstSearchDirIterator Lookup = CurDirLookup; |
| 2141 | const FileEntry *LookupFromFile = nullptr; |
| 2142 | |
| 2143 | if (isInPrimaryFile() && LangOpts.IsHeaderFile) { |
| 2144 | // If the main file is a header, then it's either for PCH/AST generation, |
| 2145 | // or libclang opened it. Either way, handle it as a normal include below |
| 2146 | // and do not complain about include_next. |
| 2147 | } else if (isInPrimaryFile()) { |
| 2148 | Lookup = nullptr; |
| 2149 | Diag(Tok: IncludeNextTok, DiagID: diag::pp_include_next_in_primary); |
| 2150 | } else if (CurLexerSubmodule) { |
| 2151 | // Start looking up in the directory *after* the one in which the current |
| 2152 | // file would be found, if any. |
| 2153 | assert(CurPPLexer && "#include_next directive in macro?" ); |
| 2154 | if (auto FE = CurPPLexer->getFileEntry()) |
| 2155 | LookupFromFile = *FE; |
| 2156 | Lookup = nullptr; |
| 2157 | } else if (!Lookup) { |
| 2158 | // The current file was not found by walking the include path. Either it |
| 2159 | // is the primary file (handled above), or it was found by absolute path, |
| 2160 | // or it was found relative to such a file. |
| 2161 | // FIXME: Track enough information so we know which case we're in. |
| 2162 | Diag(Tok: IncludeNextTok, DiagID: diag::pp_include_next_absolute_path); |
| 2163 | } else { |
| 2164 | // Start looking up in the next directory. |
| 2165 | ++Lookup; |
| 2166 | } |
| 2167 | |
| 2168 | return {Lookup, LookupFromFile}; |
| 2169 | } |
| 2170 | |
| 2171 | /// HandleIncludeDirective - The "\#include" tokens have just been read, read |
| 2172 | /// the file to be included from the lexer, then include it! This is a common |
| 2173 | /// routine with functionality shared between \#include, \#include_next and |
| 2174 | /// \#import. LookupFrom is set when this is a \#include_next directive, it |
| 2175 | /// specifies the file to start searching from. |
| 2176 | void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc, |
| 2177 | Token &IncludeTok, |
| 2178 | ConstSearchDirIterator LookupFrom, |
| 2179 | const FileEntry *LookupFromFile) { |
| 2180 | Token FilenameTok; |
| 2181 | if (LexHeaderName(Result&: FilenameTok)) |
| 2182 | return; |
| 2183 | |
| 2184 | if (FilenameTok.isNot(K: tok::header_name)) { |
| 2185 | if (FilenameTok.is(K: tok::identifier) && |
| 2186 | (PPOpts.SingleFileParseMode || PPOpts.SingleModuleParseMode)) { |
| 2187 | // If we saw #include IDENTIFIER and lexing didn't turn in into a header |
| 2188 | // name, it was undefined. In 'single-{file,module}-parse' mode, just skip |
| 2189 | // the directive without emitting diagnostics - the identifier might be |
| 2190 | // normally defined in previously-skipped include directive. |
| 2191 | DiscardUntilEndOfDirective(); |
| 2192 | return; |
| 2193 | } |
| 2194 | |
| 2195 | Diag(Loc: FilenameTok.getLocation(), DiagID: diag::err_pp_expects_filename); |
| 2196 | if (FilenameTok.isNot(K: tok::eod)) |
| 2197 | DiscardUntilEndOfDirective(); |
| 2198 | return; |
| 2199 | } |
| 2200 | |
| 2201 | // Verify that there is nothing after the filename, other than EOD. Note |
| 2202 | // that we allow macros that expand to nothing after the filename, because |
| 2203 | // this falls into the category of "#include pp-tokens new-line" specified |
| 2204 | // in C99 6.10.2p4. |
| 2205 | SourceLocation EndLoc = |
| 2206 | CheckEndOfDirective(DirType: IncludeTok.getIdentifierInfo()->getNameStart(), EnableMacros: true); |
| 2207 | |
| 2208 | auto Action = HandleHeaderIncludeOrImport(HashLoc, IncludeTok, FilenameTok, |
| 2209 | EndLoc, LookupFrom, LookupFromFile); |
| 2210 | switch (Action.Kind) { |
| 2211 | case ImportAction::None: |
| 2212 | case ImportAction::SkippedModuleImport: |
| 2213 | break; |
| 2214 | case ImportAction::ModuleBegin: |
| 2215 | EnterAnnotationToken(Range: SourceRange(HashLoc, EndLoc), |
| 2216 | Kind: tok::annot_module_begin, AnnotationVal: Action.ModuleForHeader); |
| 2217 | break; |
| 2218 | case ImportAction::HeaderUnitImport: |
| 2219 | EnterAnnotationToken(Range: SourceRange(HashLoc, EndLoc), Kind: tok::annot_header_unit, |
| 2220 | AnnotationVal: Action.ModuleForHeader); |
| 2221 | break; |
| 2222 | case ImportAction::ModuleImport: |
| 2223 | EnterAnnotationToken(Range: SourceRange(HashLoc, EndLoc), |
| 2224 | Kind: tok::annot_module_include, AnnotationVal: Action.ModuleForHeader); |
| 2225 | break; |
| 2226 | case ImportAction::Failure: |
| 2227 | assert(TheModuleLoader.HadFatalFailure && |
| 2228 | "This should be an early exit only to a fatal error" ); |
| 2229 | TheModuleLoader.HadFatalFailure = true; |
| 2230 | IncludeTok.setKind(tok::eof); |
| 2231 | CurLexer->cutOffLexing(); |
| 2232 | return; |
| 2233 | } |
| 2234 | } |
| 2235 | |
| 2236 | OptionalFileEntryRef Preprocessor::( |
| 2237 | ConstSearchDirIterator *CurDir, StringRef &Filename, |
| 2238 | SourceLocation FilenameLoc, CharSourceRange FilenameRange, |
| 2239 | const Token &FilenameTok, bool &IsFrameworkFound, bool IsImportDecl, |
| 2240 | bool &IsMapped, ConstSearchDirIterator LookupFrom, |
| 2241 | const FileEntry *LookupFromFile, StringRef &LookupFilename, |
| 2242 | SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath, |
| 2243 | ModuleMap::KnownHeader &SuggestedModule, bool isAngled) { |
| 2244 | auto = [&](FileEntryRef FE) { |
| 2245 | if (LangOpts.AsmPreprocessor) |
| 2246 | return; |
| 2247 | |
| 2248 | Module *RequestingModule = getModuleForLocation( |
| 2249 | Loc: FilenameLoc, AllowTextual: LangOpts.ModulesValidateTextualHeaderIncludes); |
| 2250 | bool RequestingModuleIsModuleInterface = |
| 2251 | !SourceMgr.isInMainFile(Loc: FilenameLoc); |
| 2252 | |
| 2253 | HeaderInfo.getModuleMap().diagnoseHeaderInclusion( |
| 2254 | RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc, |
| 2255 | Filename, File: FE); |
| 2256 | }; |
| 2257 | |
| 2258 | OptionalFileEntryRef File = LookupFile( |
| 2259 | FilenameLoc, Filename: LookupFilename, isAngled, FromDir: LookupFrom, FromFile: LookupFromFile, CurDirArg: CurDir, |
| 2260 | SearchPath: Callbacks ? &SearchPath : nullptr, RelativePath: Callbacks ? &RelativePath : nullptr, |
| 2261 | SuggestedModule: &SuggestedModule, IsMapped: &IsMapped, IsFrameworkFound: &IsFrameworkFound); |
| 2262 | if (File) { |
| 2263 | DiagnoseHeaderInclusion(*File); |
| 2264 | return File; |
| 2265 | } |
| 2266 | |
| 2267 | // Give the clients a chance to silently skip this include. |
| 2268 | if (Callbacks && Callbacks->FileNotFound(FileName: Filename)) |
| 2269 | return std::nullopt; |
| 2270 | |
| 2271 | if (SuppressIncludeNotFoundError) |
| 2272 | return std::nullopt; |
| 2273 | |
| 2274 | // If the file could not be located and it was included via angle |
| 2275 | // brackets, we can attempt a lookup as though it were a quoted path to |
| 2276 | // provide the user with a possible fixit. |
| 2277 | if (isAngled) { |
| 2278 | OptionalFileEntryRef File = LookupFile( |
| 2279 | FilenameLoc, Filename: LookupFilename, isAngled: false, FromDir: LookupFrom, FromFile: LookupFromFile, CurDirArg: CurDir, |
| 2280 | SearchPath: Callbacks ? &SearchPath : nullptr, RelativePath: Callbacks ? &RelativePath : nullptr, |
| 2281 | SuggestedModule: &SuggestedModule, IsMapped: &IsMapped, |
| 2282 | /*IsFrameworkFound=*/nullptr); |
| 2283 | if (File) { |
| 2284 | DiagnoseHeaderInclusion(*File); |
| 2285 | Diag(Tok: FilenameTok, DiagID: diag::err_pp_file_not_found_angled_include_not_fatal) |
| 2286 | << Filename << IsImportDecl |
| 2287 | << FixItHint::CreateReplacement(RemoveRange: FilenameRange, |
| 2288 | Code: "\"" + Filename.str() + "\"" ); |
| 2289 | return File; |
| 2290 | } |
| 2291 | } |
| 2292 | |
| 2293 | // Check for likely typos due to leading or trailing non-isAlphanumeric |
| 2294 | // characters |
| 2295 | StringRef OriginalFilename = Filename; |
| 2296 | if (LangOpts.SpellChecking) { |
| 2297 | // A heuristic to correct a typo file name by removing leading and |
| 2298 | // trailing non-isAlphanumeric characters. |
| 2299 | auto CorrectTypoFilename = [](llvm::StringRef Filename) { |
| 2300 | Filename = Filename.drop_until(F: isAlphanumeric); |
| 2301 | while (!Filename.empty() && !isAlphanumeric(c: Filename.back())) { |
| 2302 | Filename = Filename.drop_back(); |
| 2303 | } |
| 2304 | return Filename; |
| 2305 | }; |
| 2306 | StringRef TypoCorrectionName = CorrectTypoFilename(Filename); |
| 2307 | StringRef TypoCorrectionLookupName = CorrectTypoFilename(LookupFilename); |
| 2308 | |
| 2309 | OptionalFileEntryRef File = LookupFile( |
| 2310 | FilenameLoc, Filename: TypoCorrectionLookupName, isAngled, FromDir: LookupFrom, |
| 2311 | FromFile: LookupFromFile, CurDirArg: CurDir, SearchPath: Callbacks ? &SearchPath : nullptr, |
| 2312 | RelativePath: Callbacks ? &RelativePath : nullptr, SuggestedModule: &SuggestedModule, IsMapped: &IsMapped, |
| 2313 | /*IsFrameworkFound=*/nullptr); |
| 2314 | if (File) { |
| 2315 | DiagnoseHeaderInclusion(*File); |
| 2316 | auto Hint = |
| 2317 | isAngled ? FixItHint::CreateReplacement( |
| 2318 | RemoveRange: FilenameRange, Code: "<" + TypoCorrectionName.str() + ">" ) |
| 2319 | : FixItHint::CreateReplacement( |
| 2320 | RemoveRange: FilenameRange, Code: "\"" + TypoCorrectionName.str() + "\"" ); |
| 2321 | Diag(Tok: FilenameTok, DiagID: diag::err_pp_file_not_found_typo_not_fatal) |
| 2322 | << OriginalFilename << TypoCorrectionName << Hint; |
| 2323 | // We found the file, so set the Filename to the name after typo |
| 2324 | // correction. |
| 2325 | Filename = TypoCorrectionName; |
| 2326 | LookupFilename = TypoCorrectionLookupName; |
| 2327 | return File; |
| 2328 | } |
| 2329 | } |
| 2330 | |
| 2331 | // If the file is still not found, just go with the vanilla diagnostic |
| 2332 | assert(!File && "expected missing file" ); |
| 2333 | Diag(Tok: FilenameTok, DiagID: diag::err_pp_file_not_found) |
| 2334 | << OriginalFilename << FilenameRange; |
| 2335 | if (IsFrameworkFound) { |
| 2336 | size_t SlashPos = OriginalFilename.find(C: '/'); |
| 2337 | assert(SlashPos != StringRef::npos && |
| 2338 | "Include with framework name should have '/' in the filename" ); |
| 2339 | StringRef FrameworkName = OriginalFilename.substr(Start: 0, N: SlashPos); |
| 2340 | FrameworkCacheEntry &CacheEntry = |
| 2341 | HeaderInfo.LookupFrameworkCache(FWName: FrameworkName); |
| 2342 | assert(CacheEntry.Directory && "Found framework should be in cache" ); |
| 2343 | Diag(Tok: FilenameTok, DiagID: diag::note_pp_framework_without_header) |
| 2344 | << OriginalFilename.substr(Start: SlashPos + 1) << FrameworkName |
| 2345 | << CacheEntry.Directory->getName(); |
| 2346 | } |
| 2347 | |
| 2348 | return std::nullopt; |
| 2349 | } |
| 2350 | |
| 2351 | /// Handle either a #include-like directive or an import declaration that names |
| 2352 | /// a header file. |
| 2353 | /// |
| 2354 | /// \param HashLoc The location of the '#' token for an include, or |
| 2355 | /// SourceLocation() for an import declaration. |
| 2356 | /// \param IncludeTok The include / include_next / import token. |
| 2357 | /// \param FilenameTok The header-name token. |
| 2358 | /// \param EndLoc The location at which any imported macros become visible. |
| 2359 | /// \param LookupFrom For #include_next, the starting directory for the |
| 2360 | /// directory lookup. |
| 2361 | /// \param LookupFromFile For #include_next, the starting file for the directory |
| 2362 | /// lookup. |
| 2363 | Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport( |
| 2364 | SourceLocation HashLoc, Token &IncludeTok, Token &FilenameTok, |
| 2365 | SourceLocation EndLoc, ConstSearchDirIterator LookupFrom, |
| 2366 | const FileEntry *LookupFromFile) { |
| 2367 | SmallString<128> FilenameBuffer; |
| 2368 | StringRef Filename = getSpelling(Tok: FilenameTok, Buffer&: FilenameBuffer); |
| 2369 | SourceLocation CharEnd = FilenameTok.getEndLoc(); |
| 2370 | |
| 2371 | CharSourceRange FilenameRange |
| 2372 | = CharSourceRange::getCharRange(B: FilenameTok.getLocation(), E: CharEnd); |
| 2373 | StringRef OriginalFilename = Filename; |
| 2374 | bool isAngled = |
| 2375 | GetIncludeFilenameSpelling(Loc: FilenameTok.getLocation(), Buffer&: Filename); |
| 2376 | |
| 2377 | // If GetIncludeFilenameSpelling set the start ptr to null, there was an |
| 2378 | // error. |
| 2379 | if (Filename.empty()) |
| 2380 | return {ImportAction::None}; |
| 2381 | |
| 2382 | bool IsImportDecl = HashLoc.isInvalid(); |
| 2383 | SourceLocation StartLoc = IsImportDecl ? IncludeTok.getLocation() : HashLoc; |
| 2384 | |
| 2385 | // Complain about attempts to #include files in an audit pragma. |
| 2386 | if (PragmaARCCFCodeAuditedInfo.getLoc().isValid()) { |
| 2387 | Diag(Loc: StartLoc, DiagID: diag::err_pp_include_in_arc_cf_code_audited) << IsImportDecl; |
| 2388 | Diag(Loc: PragmaARCCFCodeAuditedInfo.getLoc(), DiagID: diag::note_pragma_entered_here); |
| 2389 | |
| 2390 | // Immediately leave the pragma. |
| 2391 | PragmaARCCFCodeAuditedInfo = IdentifierLoc(); |
| 2392 | } |
| 2393 | |
| 2394 | // Complain about attempts to #include files in an assume-nonnull pragma. |
| 2395 | if (PragmaAssumeNonNullLoc.isValid()) { |
| 2396 | Diag(Loc: StartLoc, DiagID: diag::err_pp_include_in_assume_nonnull) << IsImportDecl; |
| 2397 | Diag(Loc: PragmaAssumeNonNullLoc, DiagID: diag::note_pragma_entered_here); |
| 2398 | |
| 2399 | // Immediately leave the pragma. |
| 2400 | PragmaAssumeNonNullLoc = SourceLocation(); |
| 2401 | } |
| 2402 | |
| 2403 | if (HeaderInfo.HasIncludeAliasMap()) { |
| 2404 | // Map the filename with the brackets still attached. If the name doesn't |
| 2405 | // map to anything, fall back on the filename we've already gotten the |
| 2406 | // spelling for. |
| 2407 | StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(Source: OriginalFilename); |
| 2408 | if (!NewName.empty()) |
| 2409 | Filename = NewName; |
| 2410 | } |
| 2411 | |
| 2412 | // Search include directories. |
| 2413 | bool IsMapped = false; |
| 2414 | bool IsFrameworkFound = false; |
| 2415 | ConstSearchDirIterator CurDir = nullptr; |
| 2416 | SmallString<1024> SearchPath; |
| 2417 | SmallString<1024> RelativePath; |
| 2418 | // We get the raw path only if we have 'Callbacks' to which we later pass |
| 2419 | // the path. |
| 2420 | ModuleMap::KnownHeader SuggestedModule; |
| 2421 | SourceLocation FilenameLoc = FilenameTok.getLocation(); |
| 2422 | StringRef LookupFilename = Filename; |
| 2423 | |
| 2424 | // Normalize slashes when compiling with -fms-extensions on non-Windows. This |
| 2425 | // is unnecessary on Windows since the filesystem there handles backslashes. |
| 2426 | SmallString<128> NormalizedPath; |
| 2427 | llvm::sys::path::Style BackslashStyle = llvm::sys::path::Style::native; |
| 2428 | if (is_style_posix(S: BackslashStyle) && LangOpts.MicrosoftExt) { |
| 2429 | NormalizedPath = Filename.str(); |
| 2430 | llvm::sys::path::native(path&: NormalizedPath); |
| 2431 | LookupFilename = NormalizedPath; |
| 2432 | BackslashStyle = llvm::sys::path::Style::windows; |
| 2433 | } |
| 2434 | |
| 2435 | OptionalFileEntryRef File = LookupHeaderIncludeOrImport( |
| 2436 | CurDir: &CurDir, Filename, FilenameLoc, FilenameRange, FilenameTok, |
| 2437 | IsFrameworkFound, IsImportDecl, IsMapped, LookupFrom, LookupFromFile, |
| 2438 | LookupFilename, RelativePath, SearchPath, SuggestedModule, isAngled); |
| 2439 | |
| 2440 | if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) { |
| 2441 | if (File && isPCHThroughHeader(FE: &File->getFileEntry())) |
| 2442 | SkippingUntilPCHThroughHeader = false; |
| 2443 | return {ImportAction::None}; |
| 2444 | } |
| 2445 | |
| 2446 | // Should we enter the source file? Set to Skip if either the source file is |
| 2447 | // known to have no effect beyond its effect on module visibility -- that is, |
| 2448 | // if it's got an include guard that is already defined, set to Import if it |
| 2449 | // is a modular header we've already built and should import. |
| 2450 | |
| 2451 | // For C++20 Modules |
| 2452 | // [cpp.include]/7 If the header identified by the header-name denotes an |
| 2453 | // importable header, it is implementation-defined whether the #include |
| 2454 | // preprocessing directive is instead replaced by an import directive. |
| 2455 | // For this implementation, the translation is permitted when we are parsing |
| 2456 | // the Global Module Fragment, and not otherwise (the cases where it would be |
| 2457 | // valid to replace an include with an import are highly constrained once in |
| 2458 | // named module purview; this choice avoids considerable complexity in |
| 2459 | // determining valid cases). |
| 2460 | |
| 2461 | enum { Enter, Import, Skip, IncludeLimitReached } Action = Enter; |
| 2462 | |
| 2463 | if (PPOpts.SingleFileParseMode) |
| 2464 | Action = IncludeLimitReached; |
| 2465 | |
| 2466 | // If we've reached the max allowed include depth, it is usually due to an |
| 2467 | // include cycle. Don't enter already processed files again as it can lead to |
| 2468 | // reaching the max allowed include depth again. |
| 2469 | if (Action == Enter && HasReachedMaxIncludeDepth && File && |
| 2470 | alreadyIncluded(File: *File)) |
| 2471 | Action = IncludeLimitReached; |
| 2472 | |
| 2473 | // FIXME: We do not have a good way to disambiguate C++ clang modules from |
| 2474 | // C++ standard modules (other than use/non-use of Header Units). |
| 2475 | |
| 2476 | Module *ModuleToImport = SuggestedModule.getModule(); |
| 2477 | |
| 2478 | bool MaybeTranslateInclude = Action == Enter && File && ModuleToImport && |
| 2479 | !ModuleToImport->isForBuilding(LangOpts: getLangOpts()); |
| 2480 | |
| 2481 | // Maybe a usable Header Unit |
| 2482 | bool = false; |
| 2483 | if (getLangOpts().CPlusPlusModules && ModuleToImport && |
| 2484 | ModuleToImport->isHeaderUnit()) { |
| 2485 | if (TrackGMFState.inGMF() || IsImportDecl) |
| 2486 | UsableHeaderUnit = true; |
| 2487 | else if (!IsImportDecl) { |
| 2488 | // This is a Header Unit that we do not include-translate |
| 2489 | ModuleToImport = nullptr; |
| 2490 | } |
| 2491 | } |
| 2492 | // Maybe a usable clang header module. |
| 2493 | bool = |
| 2494 | (getLangOpts().CPlusPlusModules || getLangOpts().Modules) && |
| 2495 | ModuleToImport && !ModuleToImport->isHeaderUnit(); |
| 2496 | |
| 2497 | if (MaybeTranslateInclude && (UsableHeaderUnit || UsableClangHeaderModule) && |
| 2498 | PPOpts.SingleModuleParseMode) { |
| 2499 | Action = IncludeLimitReached; |
| 2500 | } |
| 2501 | // Determine whether we should try to import the module for this #include, if |
| 2502 | // there is one. Don't do so if precompiled module support is disabled or we |
| 2503 | // are processing this module textually (because we're building the module). |
| 2504 | else if (MaybeTranslateInclude && |
| 2505 | (UsableHeaderUnit || UsableClangHeaderModule)) { |
| 2506 | // If this include corresponds to a module but that module is |
| 2507 | // unavailable, diagnose the situation and bail out. |
| 2508 | // FIXME: Remove this; loadModule does the same check (but produces |
| 2509 | // slightly worse diagnostics). |
| 2510 | if (checkModuleIsAvailable(LangOpts: getLangOpts(), TargetInfo: getTargetInfo(), M: *ModuleToImport, |
| 2511 | Diags&: getDiagnostics())) { |
| 2512 | Diag(Loc: FilenameTok.getLocation(), |
| 2513 | DiagID: diag::note_implicit_top_level_module_import_here) |
| 2514 | << ModuleToImport->getTopLevelModuleName(); |
| 2515 | return {ImportAction::None}; |
| 2516 | } |
| 2517 | |
| 2518 | // Compute the module access path corresponding to this module. |
| 2519 | // FIXME: Should we have a second loadModule() overload to avoid this |
| 2520 | // extra lookup step? |
| 2521 | SmallVector<IdentifierLoc, 2> Path; |
| 2522 | for (Module *Mod = ModuleToImport; Mod; Mod = Mod->Parent) |
| 2523 | Path.emplace_back(Args: FilenameTok.getLocation(), |
| 2524 | Args: getIdentifierInfo(Name: Mod->Name)); |
| 2525 | std::reverse(first: Path.begin(), last: Path.end()); |
| 2526 | |
| 2527 | // Warn that we're replacing the include/import with a module import. |
| 2528 | if (!IsImportDecl) |
| 2529 | diagnoseAutoModuleImport(PP&: *this, HashLoc: StartLoc, IncludeTok, Path, PathEnd: CharEnd); |
| 2530 | |
| 2531 | // Load the module to import its macros. We'll make the declarations |
| 2532 | // visible when the parser gets here. |
| 2533 | // FIXME: Pass ModuleToImport in here rather than converting it to a path |
| 2534 | // and making the module loader convert it back again. |
| 2535 | ModuleLoadResult Imported = TheModuleLoader.loadModule( |
| 2536 | ImportLoc: IncludeTok.getLocation(), Path, Visibility: Module::Hidden, |
| 2537 | /*IsInclusionDirective=*/true); |
| 2538 | assert((Imported == nullptr || Imported == ModuleToImport) && |
| 2539 | "the imported module is different than the suggested one" ); |
| 2540 | |
| 2541 | if (Imported) { |
| 2542 | Action = Import; |
| 2543 | } else if (Imported.isMissingExpected()) { |
| 2544 | markClangModuleAsAffecting( |
| 2545 | M: static_cast<Module *>(Imported)->getTopLevelModule()); |
| 2546 | // We failed to find a submodule that we assumed would exist (because it |
| 2547 | // was in the directory of an umbrella header, for instance), but no |
| 2548 | // actual module containing it exists (because the umbrella header is |
| 2549 | // incomplete). Treat this as a textual inclusion. |
| 2550 | ModuleToImport = nullptr; |
| 2551 | } else if (Imported.isConfigMismatch()) { |
| 2552 | // On a configuration mismatch, enter the header textually. We still know |
| 2553 | // that it's part of the corresponding module. |
| 2554 | } else { |
| 2555 | // We hit an error processing the import. Bail out. |
| 2556 | if (hadModuleLoaderFatalFailure()) { |
| 2557 | // With a fatal failure in the module loader, we abort parsing. |
| 2558 | Token &Result = IncludeTok; |
| 2559 | assert(CurLexer && "#include but no current lexer set!" ); |
| 2560 | Result.startToken(); |
| 2561 | CurLexer->FormTokenWithChars(Result, TokEnd: CurLexer->BufferEnd, Kind: tok::eof); |
| 2562 | CurLexer->cutOffLexing(); |
| 2563 | } |
| 2564 | return {ImportAction::None}; |
| 2565 | } |
| 2566 | } |
| 2567 | |
| 2568 | // The #included file will be considered to be a system header if either it is |
| 2569 | // in a system include directory, or if the #includer is a system include |
| 2570 | // header. |
| 2571 | SrcMgr::CharacteristicKind FileCharacter = |
| 2572 | SourceMgr.getFileCharacteristic(Loc: FilenameTok.getLocation()); |
| 2573 | if (File) |
| 2574 | FileCharacter = std::max(a: HeaderInfo.getFileDirFlavor(File: *File), b: FileCharacter); |
| 2575 | |
| 2576 | // If this is a '#import' or an import-declaration, don't re-enter the file. |
| 2577 | // |
| 2578 | // FIXME: If we have a suggested module for a '#include', and we've already |
| 2579 | // visited this file, don't bother entering it again. We know it has no |
| 2580 | // further effect. |
| 2581 | bool EnterOnce = |
| 2582 | IsImportDecl || |
| 2583 | IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import; |
| 2584 | |
| 2585 | bool IsFirstIncludeOfFile = false; |
| 2586 | |
| 2587 | // Ask HeaderInfo if we should enter this #include file. If not, #including |
| 2588 | // this file will have no effect. |
| 2589 | if (Action == Enter && File && |
| 2590 | !HeaderInfo.ShouldEnterIncludeFile(PP&: *this, File: *File, isImport: EnterOnce, |
| 2591 | ModulesEnabled: getLangOpts().Modules, M: ModuleToImport, |
| 2592 | IsFirstIncludeOfFile)) { |
| 2593 | // C++ standard modules: |
| 2594 | // If we are not in the GMF, then we textually include only |
| 2595 | // clang modules: |
| 2596 | // Even if we've already preprocessed this header once and know that we |
| 2597 | // don't need to see its contents again, we still need to import it if it's |
| 2598 | // modular because we might not have imported it from this submodule before. |
| 2599 | // |
| 2600 | // FIXME: We don't do this when compiling a PCH because the AST |
| 2601 | // serialization layer can't cope with it. This means we get local |
| 2602 | // submodule visibility semantics wrong in that case. |
| 2603 | if (UsableHeaderUnit && !getLangOpts().CompilingPCH) |
| 2604 | Action = TrackGMFState.inGMF() ? Import : Skip; |
| 2605 | else |
| 2606 | Action = (ModuleToImport && !getLangOpts().CompilingPCH) ? Import : Skip; |
| 2607 | } |
| 2608 | |
| 2609 | // Check for circular inclusion of the main file. |
| 2610 | // We can't generate a consistent preamble with regard to the conditional |
| 2611 | // stack if the main file is included again as due to the preamble bounds |
| 2612 | // some directives (e.g. #endif of a header guard) will never be seen. |
| 2613 | // Since this will lead to confusing errors, avoid the inclusion. |
| 2614 | if (Action == Enter && File && PreambleConditionalStack.isRecording() && |
| 2615 | SourceMgr.isMainFile(SourceFile: File->getFileEntry())) { |
| 2616 | Diag(Loc: FilenameTok.getLocation(), |
| 2617 | DiagID: diag::err_pp_including_mainfile_in_preamble); |
| 2618 | return {ImportAction::None}; |
| 2619 | } |
| 2620 | |
| 2621 | if (Callbacks && !IsImportDecl) { |
| 2622 | // Notify the callback object that we've seen an inclusion directive. |
| 2623 | // FIXME: Use a different callback for a pp-import? |
| 2624 | Callbacks->InclusionDirective(HashLoc, IncludeTok, FileName: LookupFilename, IsAngled: isAngled, |
| 2625 | FilenameRange, File, SearchPath, RelativePath, |
| 2626 | SuggestedModule: SuggestedModule.getModule(), ModuleImported: Action == Import, |
| 2627 | FileType: FileCharacter); |
| 2628 | if (Action == Skip && File) |
| 2629 | Callbacks->FileSkipped(SkippedFile: *File, FilenameTok, FileType: FileCharacter); |
| 2630 | } |
| 2631 | |
| 2632 | if (!File) |
| 2633 | return {ImportAction::None}; |
| 2634 | |
| 2635 | // If this is a C++20 pp-import declaration, diagnose if we didn't find any |
| 2636 | // module corresponding to the named header. |
| 2637 | if (IsImportDecl && !ModuleToImport) { |
| 2638 | Diag(Tok: FilenameTok, DiagID: diag::err_header_import_not_header_unit) |
| 2639 | << OriginalFilename << File->getName(); |
| 2640 | return {ImportAction::None}; |
| 2641 | } |
| 2642 | |
| 2643 | // Issue a diagnostic if the name of the file on disk has a different case |
| 2644 | // than the one we're about to open. |
| 2645 | const bool CheckIncludePathPortability = |
| 2646 | !IsMapped && !File->getFileEntry().tryGetRealPathName().empty(); |
| 2647 | |
| 2648 | if (CheckIncludePathPortability) { |
| 2649 | StringRef Name = LookupFilename; |
| 2650 | StringRef NameWithoriginalSlashes = Filename; |
| 2651 | #if defined(_WIN32) |
| 2652 | // Skip UNC prefix if present. (tryGetRealPathName() always |
| 2653 | // returns a path with the prefix skipped.) |
| 2654 | bool NameWasUNC = Name.consume_front("\\\\?\\" ); |
| 2655 | NameWithoriginalSlashes.consume_front("\\\\?\\" ); |
| 2656 | #endif |
| 2657 | StringRef RealPathName = File->getFileEntry().tryGetRealPathName(); |
| 2658 | SmallVector<StringRef, 16> Components(llvm::sys::path::begin(path: Name), |
| 2659 | llvm::sys::path::end(path: Name)); |
| 2660 | #if defined(_WIN32) |
| 2661 | // -Wnonportable-include-path is designed to diagnose includes using |
| 2662 | // case even on systems with a case-insensitive file system. |
| 2663 | // On Windows, RealPathName always starts with an upper-case drive |
| 2664 | // letter for absolute paths, but Name might start with either |
| 2665 | // case depending on if `cd c:\foo` or `cd C:\foo` was used in the shell. |
| 2666 | // ("foo" will always have on-disk case, no matter which case was |
| 2667 | // used in the cd command). To not emit this warning solely for |
| 2668 | // the drive letter, whose case is dependent on if `cd` is used |
| 2669 | // with upper- or lower-case drive letters, always consider the |
| 2670 | // given drive letter case as correct for the purpose of this warning. |
| 2671 | SmallString<128> FixedDriveRealPath; |
| 2672 | if (llvm::sys::path::is_absolute(Name) && |
| 2673 | llvm::sys::path::is_absolute(RealPathName) && |
| 2674 | toLowercase(Name[0]) == toLowercase(RealPathName[0]) && |
| 2675 | isLowercase(Name[0]) != isLowercase(RealPathName[0])) { |
| 2676 | assert(Components.size() >= 3 && "should have drive, backslash, name" ); |
| 2677 | assert(Components[0].size() == 2 && "should start with drive" ); |
| 2678 | assert(Components[0][1] == ':' && "should have colon" ); |
| 2679 | FixedDriveRealPath = (Name.substr(0, 1) + RealPathName.substr(1)).str(); |
| 2680 | RealPathName = FixedDriveRealPath; |
| 2681 | } |
| 2682 | #endif |
| 2683 | |
| 2684 | if (trySimplifyPath(Components, RealPathName, Separator: BackslashStyle)) { |
| 2685 | SmallString<128> Path; |
| 2686 | Path.reserve(N: Name.size()+2); |
| 2687 | Path.push_back(Elt: isAngled ? '<' : '"'); |
| 2688 | |
| 2689 | const auto IsSep = [BackslashStyle](char c) { |
| 2690 | return llvm::sys::path::is_separator(value: c, style: BackslashStyle); |
| 2691 | }; |
| 2692 | |
| 2693 | for (auto Component : Components) { |
| 2694 | // On POSIX, Components will contain a single '/' as first element |
| 2695 | // exactly if Name is an absolute path. |
| 2696 | // On Windows, it will contain "C:" followed by '\' for absolute paths. |
| 2697 | // The drive letter is optional for absolute paths on Windows, but |
| 2698 | // clang currently cannot process absolute paths in #include lines that |
| 2699 | // don't have a drive. |
| 2700 | // If the first entry in Components is a directory separator, |
| 2701 | // then the code at the bottom of this loop that keeps the original |
| 2702 | // directory separator style copies it. If the second entry is |
| 2703 | // a directory separator (the C:\ case), then that separator already |
| 2704 | // got copied when the C: was processed and we want to skip that entry. |
| 2705 | if (!(Component.size() == 1 && IsSep(Component[0]))) |
| 2706 | Path.append(RHS: Component); |
| 2707 | else if (Path.size() != 1) |
| 2708 | continue; |
| 2709 | |
| 2710 | // Append the separator(s) the user used, or the close quote |
| 2711 | if (Path.size() > NameWithoriginalSlashes.size()) { |
| 2712 | Path.push_back(Elt: isAngled ? '>' : '"'); |
| 2713 | continue; |
| 2714 | } |
| 2715 | assert(IsSep(NameWithoriginalSlashes[Path.size()-1])); |
| 2716 | do |
| 2717 | Path.push_back(Elt: NameWithoriginalSlashes[Path.size()-1]); |
| 2718 | while (Path.size() <= NameWithoriginalSlashes.size() && |
| 2719 | IsSep(NameWithoriginalSlashes[Path.size()-1])); |
| 2720 | } |
| 2721 | |
| 2722 | #if defined(_WIN32) |
| 2723 | // Restore UNC prefix if it was there. |
| 2724 | if (NameWasUNC) |
| 2725 | Path = (Path.substr(0, 1) + "\\\\?\\" + Path.substr(1)).str(); |
| 2726 | #endif |
| 2727 | |
| 2728 | // For user files and known standard headers, issue a diagnostic. |
| 2729 | // For other system headers, don't. They can be controlled separately. |
| 2730 | auto DiagId = |
| 2731 | (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Include: Name)) |
| 2732 | ? diag::pp_nonportable_path |
| 2733 | : diag::pp_nonportable_system_path; |
| 2734 | Diag(Tok: FilenameTok, DiagID: DiagId) << Path << |
| 2735 | FixItHint::CreateReplacement(RemoveRange: FilenameRange, Code: Path); |
| 2736 | } |
| 2737 | } |
| 2738 | |
| 2739 | switch (Action) { |
| 2740 | case Skip: |
| 2741 | // If we don't need to enter the file, stop now. |
| 2742 | if (ModuleToImport) |
| 2743 | return {ImportAction::SkippedModuleImport, ModuleToImport}; |
| 2744 | return {ImportAction::None}; |
| 2745 | |
| 2746 | case IncludeLimitReached: |
| 2747 | // If we reached our include limit and don't want to enter any more files, |
| 2748 | // don't go any further. |
| 2749 | return {ImportAction::None}; |
| 2750 | |
| 2751 | case Import: { |
| 2752 | // If this is a module import, make it visible if needed. |
| 2753 | assert(ModuleToImport && "no module to import" ); |
| 2754 | |
| 2755 | makeModuleVisible(M: ModuleToImport, Loc: EndLoc); |
| 2756 | |
| 2757 | if (IncludeTok.getIdentifierInfo()->getPPKeywordID() == |
| 2758 | tok::pp___include_macros) |
| 2759 | return {ImportAction::None}; |
| 2760 | |
| 2761 | return {ImportAction::ModuleImport, ModuleToImport}; |
| 2762 | } |
| 2763 | |
| 2764 | case Enter: |
| 2765 | break; |
| 2766 | } |
| 2767 | |
| 2768 | // Check that we don't have infinite #include recursion. |
| 2769 | if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) { |
| 2770 | Diag(Tok: FilenameTok, DiagID: diag::err_pp_include_too_deep); |
| 2771 | HasReachedMaxIncludeDepth = true; |
| 2772 | return {ImportAction::None}; |
| 2773 | } |
| 2774 | |
| 2775 | if (isAngled && isInNamedModule()) |
| 2776 | Diag(Tok: FilenameTok, DiagID: diag::warn_pp_include_angled_in_module_purview) |
| 2777 | << getNamedModuleName(); |
| 2778 | |
| 2779 | // Look up the file, create a File ID for it. |
| 2780 | SourceLocation IncludePos = FilenameTok.getLocation(); |
| 2781 | // If the filename string was the result of macro expansions, set the include |
| 2782 | // position on the file where it will be included and after the expansions. |
| 2783 | if (IncludePos.isMacroID()) |
| 2784 | IncludePos = SourceMgr.getExpansionRange(Loc: IncludePos).getEnd(); |
| 2785 | FileID FID = SourceMgr.createFileID(SourceFile: *File, IncludePos, FileCharacter); |
| 2786 | if (!FID.isValid()) { |
| 2787 | TheModuleLoader.HadFatalFailure = true; |
| 2788 | return ImportAction::Failure; |
| 2789 | } |
| 2790 | |
| 2791 | // If all is good, enter the new file! |
| 2792 | if (EnterSourceFile(FID, Dir: CurDir, Loc: FilenameTok.getLocation(), |
| 2793 | IsFirstIncludeOfFile)) |
| 2794 | return {ImportAction::None}; |
| 2795 | |
| 2796 | // Determine if we're switching to building a new submodule, and which one. |
| 2797 | // This does not apply for C++20 modules header units. |
| 2798 | if (ModuleToImport && !ModuleToImport->isHeaderUnit()) { |
| 2799 | if (ModuleToImport->getTopLevelModule()->ShadowingModule) { |
| 2800 | // We are building a submodule that belongs to a shadowed module. This |
| 2801 | // means we find header files in the shadowed module. |
| 2802 | Diag(Loc: ModuleToImport->DefinitionLoc, |
| 2803 | DiagID: diag::err_module_build_shadowed_submodule) |
| 2804 | << ModuleToImport->getFullModuleName(); |
| 2805 | Diag(Loc: ModuleToImport->getTopLevelModule()->ShadowingModule->DefinitionLoc, |
| 2806 | DiagID: diag::note_previous_definition); |
| 2807 | return {ImportAction::None}; |
| 2808 | } |
| 2809 | // When building a pch, -fmodule-name tells the compiler to textually |
| 2810 | // include headers in the specified module. We are not building the |
| 2811 | // specified module. |
| 2812 | // |
| 2813 | // FIXME: This is the wrong way to handle this. We should produce a PCH |
| 2814 | // that behaves the same as the header would behave in a compilation using |
| 2815 | // that PCH, which means we should enter the submodule. We need to teach |
| 2816 | // the AST serialization layer to deal with the resulting AST. |
| 2817 | if (getLangOpts().CompilingPCH && |
| 2818 | ModuleToImport->isForBuilding(LangOpts: getLangOpts())) |
| 2819 | return {ImportAction::None}; |
| 2820 | |
| 2821 | assert(!CurLexerSubmodule && "should not have marked this as a module yet" ); |
| 2822 | CurLexerSubmodule = ModuleToImport; |
| 2823 | |
| 2824 | // Let the macro handling code know that any future macros are within |
| 2825 | // the new submodule. |
| 2826 | EnterSubmodule(M: ModuleToImport, ImportLoc: EndLoc, /*ForPragma*/ false); |
| 2827 | |
| 2828 | // Let the parser know that any future declarations are within the new |
| 2829 | // submodule. |
| 2830 | // FIXME: There's no point doing this if we're handling a #__include_macros |
| 2831 | // directive. |
| 2832 | return {ImportAction::ModuleBegin, ModuleToImport}; |
| 2833 | } |
| 2834 | |
| 2835 | assert(!IsImportDecl && "failed to diagnose missing module for import decl" ); |
| 2836 | return {ImportAction::None}; |
| 2837 | } |
| 2838 | |
| 2839 | /// HandleIncludeNextDirective - Implements \#include_next. |
| 2840 | /// |
| 2841 | void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc, |
| 2842 | Token &IncludeNextTok) { |
| 2843 | Diag(Tok: IncludeNextTok, DiagID: diag::ext_pp_include_next_directive); |
| 2844 | |
| 2845 | ConstSearchDirIterator Lookup = nullptr; |
| 2846 | const FileEntry *LookupFromFile; |
| 2847 | std::tie(args&: Lookup, args&: LookupFromFile) = getIncludeNextStart(IncludeNextTok); |
| 2848 | |
| 2849 | return HandleIncludeDirective(HashLoc, IncludeTok&: IncludeNextTok, LookupFrom: Lookup, |
| 2850 | LookupFromFile); |
| 2851 | } |
| 2852 | |
| 2853 | /// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode |
| 2854 | void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) { |
| 2855 | // The Microsoft #import directive takes a type library and generates header |
| 2856 | // files from it, and includes those. This is beyond the scope of what clang |
| 2857 | // does, so we ignore it and error out. However, #import can optionally have |
| 2858 | // trailing attributes that span multiple lines. We're going to eat those |
| 2859 | // so we can continue processing from there. |
| 2860 | Diag(Tok, DiagID: diag::err_pp_import_directive_ms ); |
| 2861 | |
| 2862 | // Read tokens until we get to the end of the directive. Note that the |
| 2863 | // directive can be split over multiple lines using the backslash character. |
| 2864 | DiscardUntilEndOfDirective(); |
| 2865 | } |
| 2866 | |
| 2867 | /// HandleImportDirective - Implements \#import. |
| 2868 | /// |
| 2869 | void Preprocessor::HandleImportDirective(SourceLocation HashLoc, |
| 2870 | Token &ImportTok) { |
| 2871 | if (!LangOpts.ObjC) { // #import is standard for ObjC. |
| 2872 | if (LangOpts.MSVCCompat) |
| 2873 | return HandleMicrosoftImportDirective(Tok&: ImportTok); |
| 2874 | Diag(Tok: ImportTok, DiagID: diag::ext_pp_import_directive); |
| 2875 | } |
| 2876 | return HandleIncludeDirective(HashLoc, IncludeTok&: ImportTok); |
| 2877 | } |
| 2878 | |
| 2879 | /// HandleIncludeMacrosDirective - The -imacros command line option turns into a |
| 2880 | /// pseudo directive in the predefines buffer. This handles it by sucking all |
| 2881 | /// tokens through the preprocessor and discarding them (only keeping the side |
| 2882 | /// effects on the preprocessor). |
| 2883 | void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc, |
| 2884 | Token &IncludeMacrosTok) { |
| 2885 | // This directive should only occur in the predefines buffer. If not, emit an |
| 2886 | // error and reject it. |
| 2887 | SourceLocation Loc = IncludeMacrosTok.getLocation(); |
| 2888 | if (SourceMgr.getBufferName(Loc) != "<built-in>" ) { |
| 2889 | Diag(Loc: IncludeMacrosTok.getLocation(), |
| 2890 | DiagID: diag::pp_include_macros_out_of_predefines); |
| 2891 | DiscardUntilEndOfDirective(); |
| 2892 | return; |
| 2893 | } |
| 2894 | |
| 2895 | // Treat this as a normal #include for checking purposes. If this is |
| 2896 | // successful, it will push a new lexer onto the include stack. |
| 2897 | HandleIncludeDirective(HashLoc, IncludeTok&: IncludeMacrosTok); |
| 2898 | |
| 2899 | Token TmpTok; |
| 2900 | do { |
| 2901 | Lex(Result&: TmpTok); |
| 2902 | assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!" ); |
| 2903 | } while (TmpTok.isNot(K: tok::hashhash)); |
| 2904 | } |
| 2905 | |
| 2906 | //===----------------------------------------------------------------------===// |
| 2907 | // Preprocessor Macro Directive Handling. |
| 2908 | //===----------------------------------------------------------------------===// |
| 2909 | |
| 2910 | /// ReadMacroParameterList - The ( starting a parameter list of a macro |
| 2911 | /// definition has just been read. Lex the rest of the parameters and the |
| 2912 | /// closing ), updating MI with what we learn. Return true if an error occurs |
| 2913 | /// parsing the param list. |
| 2914 | bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) { |
| 2915 | SmallVector<IdentifierInfo*, 32> Parameters; |
| 2916 | |
| 2917 | while (true) { |
| 2918 | LexUnexpandedNonComment(Result&: Tok); |
| 2919 | switch (Tok.getKind()) { |
| 2920 | case tok::r_paren: |
| 2921 | // Found the end of the parameter list. |
| 2922 | if (Parameters.empty()) // #define FOO() |
| 2923 | return false; |
| 2924 | // Otherwise we have #define FOO(A,) |
| 2925 | Diag(Tok, DiagID: diag::err_pp_expected_ident_in_arg_list); |
| 2926 | return true; |
| 2927 | case tok::ellipsis: // #define X(... -> C99 varargs |
| 2928 | if (!LangOpts.C99) |
| 2929 | Diag(Tok, DiagID: LangOpts.CPlusPlus11 ? |
| 2930 | diag::warn_cxx98_compat_variadic_macro : |
| 2931 | diag::ext_variadic_macro); |
| 2932 | |
| 2933 | // OpenCL v1.2 s6.9.e: variadic macros are not supported. |
| 2934 | if (LangOpts.OpenCL && !LangOpts.OpenCLCPlusPlus) { |
| 2935 | Diag(Tok, DiagID: diag::ext_pp_opencl_variadic_macros); |
| 2936 | } |
| 2937 | |
| 2938 | // Lex the token after the identifier. |
| 2939 | LexUnexpandedNonComment(Result&: Tok); |
| 2940 | if (Tok.isNot(K: tok::r_paren)) { |
| 2941 | Diag(Tok, DiagID: diag::err_pp_missing_rparen_in_macro_def); |
| 2942 | return true; |
| 2943 | } |
| 2944 | // Add the __VA_ARGS__ identifier as a parameter. |
| 2945 | Parameters.push_back(Elt: Ident__VA_ARGS__); |
| 2946 | MI->setIsC99Varargs(); |
| 2947 | MI->setParameterList(List: Parameters, PPAllocator&: BP); |
| 2948 | return false; |
| 2949 | case tok::eod: // #define X( |
| 2950 | Diag(Tok, DiagID: diag::err_pp_missing_rparen_in_macro_def); |
| 2951 | return true; |
| 2952 | default: |
| 2953 | // Handle keywords and identifiers here to accept things like |
| 2954 | // #define Foo(for) for. |
| 2955 | IdentifierInfo *II = Tok.getIdentifierInfo(); |
| 2956 | if (!II) { |
| 2957 | // #define X(1 |
| 2958 | Diag(Tok, DiagID: diag::err_pp_invalid_tok_in_arg_list); |
| 2959 | return true; |
| 2960 | } |
| 2961 | |
| 2962 | // If this is already used as a parameter, it is used multiple times (e.g. |
| 2963 | // #define X(A,A. |
| 2964 | if (llvm::is_contained(Range&: Parameters, Element: II)) { // C99 6.10.3p6 |
| 2965 | Diag(Tok, DiagID: diag::err_pp_duplicate_name_in_arg_list) << II; |
| 2966 | return true; |
| 2967 | } |
| 2968 | |
| 2969 | // Add the parameter to the macro info. |
| 2970 | Parameters.push_back(Elt: II); |
| 2971 | |
| 2972 | // Lex the token after the identifier. |
| 2973 | LexUnexpandedNonComment(Result&: Tok); |
| 2974 | |
| 2975 | switch (Tok.getKind()) { |
| 2976 | default: // #define X(A B |
| 2977 | Diag(Tok, DiagID: diag::err_pp_expected_comma_in_arg_list); |
| 2978 | return true; |
| 2979 | case tok::r_paren: // #define X(A) |
| 2980 | MI->setParameterList(List: Parameters, PPAllocator&: BP); |
| 2981 | return false; |
| 2982 | case tok::comma: // #define X(A, |
| 2983 | break; |
| 2984 | case tok::ellipsis: // #define X(A... -> GCC extension |
| 2985 | // Diagnose extension. |
| 2986 | Diag(Tok, DiagID: diag::ext_named_variadic_macro); |
| 2987 | |
| 2988 | // Lex the token after the identifier. |
| 2989 | LexUnexpandedNonComment(Result&: Tok); |
| 2990 | if (Tok.isNot(K: tok::r_paren)) { |
| 2991 | Diag(Tok, DiagID: diag::err_pp_missing_rparen_in_macro_def); |
| 2992 | return true; |
| 2993 | } |
| 2994 | |
| 2995 | MI->setIsGNUVarargs(); |
| 2996 | MI->setParameterList(List: Parameters, PPAllocator&: BP); |
| 2997 | return false; |
| 2998 | } |
| 2999 | } |
| 3000 | } |
| 3001 | } |
| 3002 | |
| 3003 | static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI, |
| 3004 | const LangOptions &LOptions) { |
| 3005 | if (MI->getNumTokens() == 1) { |
| 3006 | const Token &Value = MI->getReplacementToken(Tok: 0); |
| 3007 | |
| 3008 | // Macro that is identity, like '#define inline inline' is a valid pattern. |
| 3009 | if (MacroName.getKind() == Value.getKind()) |
| 3010 | return true; |
| 3011 | |
| 3012 | // Macro that maps a keyword to the same keyword decorated with leading/ |
| 3013 | // trailing underscores is a valid pattern: |
| 3014 | // #define inline __inline |
| 3015 | // #define inline __inline__ |
| 3016 | // #define inline _inline (in MS compatibility mode) |
| 3017 | StringRef MacroText = MacroName.getIdentifierInfo()->getName(); |
| 3018 | if (IdentifierInfo *II = Value.getIdentifierInfo()) { |
| 3019 | if (!II->isKeyword(LangOpts: LOptions)) |
| 3020 | return false; |
| 3021 | StringRef ValueText = II->getName(); |
| 3022 | StringRef TrimmedValue = ValueText; |
| 3023 | if (!ValueText.starts_with(Prefix: "__" )) { |
| 3024 | if (ValueText.starts_with(Prefix: "_" )) |
| 3025 | TrimmedValue = TrimmedValue.drop_front(N: 1); |
| 3026 | else |
| 3027 | return false; |
| 3028 | } else { |
| 3029 | TrimmedValue = TrimmedValue.drop_front(N: 2); |
| 3030 | if (TrimmedValue.ends_with(Suffix: "__" )) |
| 3031 | TrimmedValue = TrimmedValue.drop_back(N: 2); |
| 3032 | } |
| 3033 | return TrimmedValue == MacroText; |
| 3034 | } else { |
| 3035 | return false; |
| 3036 | } |
| 3037 | } |
| 3038 | |
| 3039 | // #define inline |
| 3040 | return MacroName.isOneOf(Ks: tok::kw_extern, Ks: tok::kw_inline, Ks: tok::kw_static, |
| 3041 | Ks: tok::kw_const) && |
| 3042 | MI->getNumTokens() == 0; |
| 3043 | } |
| 3044 | |
| 3045 | // ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the |
| 3046 | // entire line) of the macro's tokens and adds them to MacroInfo, and while |
| 3047 | // doing so performs certain validity checks including (but not limited to): |
| 3048 | // - # (stringization) is followed by a macro parameter |
| 3049 | // |
| 3050 | // Returns a nullptr if an invalid sequence of tokens is encountered or returns |
| 3051 | // a pointer to a MacroInfo object. |
| 3052 | |
| 3053 | MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody( |
| 3054 | const Token &MacroNameTok, const bool ) { |
| 3055 | |
| 3056 | Token LastTok = MacroNameTok; |
| 3057 | // Create the new macro. |
| 3058 | MacroInfo *const MI = AllocateMacroInfo(L: MacroNameTok.getLocation()); |
| 3059 | |
| 3060 | Token Tok; |
| 3061 | LexUnexpandedToken(Result&: Tok); |
| 3062 | |
| 3063 | // Ensure we consume the rest of the macro body if errors occur. |
| 3064 | llvm::scope_exit _([&]() { |
| 3065 | // The flag indicates if we are still waiting for 'eod'. |
| 3066 | if (CurLexer->ParsingPreprocessorDirective) |
| 3067 | DiscardUntilEndOfDirective(); |
| 3068 | }); |
| 3069 | |
| 3070 | // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk |
| 3071 | // within their appropriate context. |
| 3072 | VariadicMacroScopeGuard VariadicMacroScopeGuard(*this); |
| 3073 | |
| 3074 | // If this is a function-like macro definition, parse the argument list, |
| 3075 | // marking each of the identifiers as being used as macro arguments. Also, |
| 3076 | // check other constraints on the first token of the macro body. |
| 3077 | if (Tok.is(K: tok::eod)) { |
| 3078 | if (ImmediatelyAfterHeaderGuard) { |
| 3079 | // Save this macro information since it may part of a header guard. |
| 3080 | CurPPLexer->MIOpt.SetDefinedMacro(M: MacroNameTok.getIdentifierInfo(), |
| 3081 | Loc: MacroNameTok.getLocation()); |
| 3082 | } |
| 3083 | // If there is no body to this macro, we have no special handling here. |
| 3084 | } else if (Tok.hasLeadingSpace()) { |
| 3085 | // This is a normal token with leading space. Clear the leading space |
| 3086 | // marker on the first token to get proper expansion. |
| 3087 | Tok.clearFlag(Flag: Token::LeadingSpace); |
| 3088 | } else if (Tok.is(K: tok::l_paren)) { |
| 3089 | // This is a function-like macro definition. Read the argument list. |
| 3090 | MI->setIsFunctionLike(); |
| 3091 | if (ReadMacroParameterList(MI, Tok&: LastTok)) |
| 3092 | return nullptr; |
| 3093 | |
| 3094 | // If this is a definition of an ISO C/C++ variadic function-like macro (not |
| 3095 | // using the GNU named varargs extension) inform our variadic scope guard |
| 3096 | // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__) |
| 3097 | // allowed only within the definition of a variadic macro. |
| 3098 | |
| 3099 | if (MI->isC99Varargs()) { |
| 3100 | VariadicMacroScopeGuard.enterScope(); |
| 3101 | } |
| 3102 | |
| 3103 | // Read the first token after the arg list for down below. |
| 3104 | LexUnexpandedToken(Result&: Tok); |
| 3105 | } else if (LangOpts.C99 || LangOpts.CPlusPlus11) { |
| 3106 | // C99 requires whitespace between the macro definition and the body. Emit |
| 3107 | // a diagnostic for something like "#define X+". |
| 3108 | Diag(Tok, DiagID: diag::ext_c99_whitespace_required_after_macro_name); |
| 3109 | } else { |
| 3110 | // C90 6.8 TC1 says: "In the definition of an object-like macro, if the |
| 3111 | // first character of a replacement list is not a character required by |
| 3112 | // subclause 5.2.1, then there shall be white-space separation between the |
| 3113 | // identifier and the replacement list.". 5.2.1 lists this set: |
| 3114 | // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which |
| 3115 | // is irrelevant here. |
| 3116 | bool isInvalid = false; |
| 3117 | if (Tok.is(K: tok::at)) // @ is not in the list above. |
| 3118 | isInvalid = true; |
| 3119 | else if (Tok.is(K: tok::unknown)) { |
| 3120 | // If we have an unknown token, it is something strange like "`". Since |
| 3121 | // all of valid characters would have lexed into a single character |
| 3122 | // token of some sort, we know this is not a valid case. |
| 3123 | isInvalid = true; |
| 3124 | } |
| 3125 | if (isInvalid) |
| 3126 | Diag(Tok, DiagID: diag::ext_missing_whitespace_after_macro_name); |
| 3127 | else |
| 3128 | Diag(Tok, DiagID: diag::warn_missing_whitespace_after_macro_name); |
| 3129 | } |
| 3130 | |
| 3131 | if (!Tok.is(K: tok::eod)) |
| 3132 | LastTok = Tok; |
| 3133 | |
| 3134 | SmallVector<Token, 16> Tokens; |
| 3135 | |
| 3136 | // Read the rest of the macro body. |
| 3137 | if (MI->isObjectLike()) { |
| 3138 | // Object-like macros are very simple, just read their body. |
| 3139 | while (Tok.isNot(K: tok::eod)) { |
| 3140 | LastTok = Tok; |
| 3141 | Tokens.push_back(Elt: Tok); |
| 3142 | // Get the next token of the macro. |
| 3143 | LexUnexpandedToken(Result&: Tok); |
| 3144 | } |
| 3145 | } else { |
| 3146 | // Otherwise, read the body of a function-like macro. While we are at it, |
| 3147 | // check C99 6.10.3.2p1: ensure that # operators are followed by macro |
| 3148 | // parameters in function-like macro expansions. |
| 3149 | |
| 3150 | VAOptDefinitionContext VAOCtx(*this); |
| 3151 | |
| 3152 | while (Tok.isNot(K: tok::eod)) { |
| 3153 | LastTok = Tok; |
| 3154 | |
| 3155 | if (!Tok.isOneOf(Ks: tok::hash, Ks: tok::hashat, Ks: tok::hashhash)) { |
| 3156 | Tokens.push_back(Elt: Tok); |
| 3157 | |
| 3158 | if (VAOCtx.isVAOptToken(T: Tok)) { |
| 3159 | // If we're already within a VAOPT, emit an error. |
| 3160 | if (VAOCtx.isInVAOpt()) { |
| 3161 | Diag(Tok, DiagID: diag::err_pp_vaopt_nested_use); |
| 3162 | return nullptr; |
| 3163 | } |
| 3164 | // Ensure VAOPT is followed by a '(' . |
| 3165 | LexUnexpandedToken(Result&: Tok); |
| 3166 | if (Tok.isNot(K: tok::l_paren)) { |
| 3167 | Diag(Tok, DiagID: diag::err_pp_missing_lparen_in_vaopt_use); |
| 3168 | return nullptr; |
| 3169 | } |
| 3170 | Tokens.push_back(Elt: Tok); |
| 3171 | VAOCtx.sawVAOptFollowedByOpeningParens(LParenLoc: Tok.getLocation()); |
| 3172 | LexUnexpandedToken(Result&: Tok); |
| 3173 | if (Tok.is(K: tok::hashhash)) { |
| 3174 | Diag(Tok, DiagID: diag::err_vaopt_paste_at_start); |
| 3175 | return nullptr; |
| 3176 | } |
| 3177 | continue; |
| 3178 | } else if (VAOCtx.isInVAOpt()) { |
| 3179 | if (Tok.is(K: tok::r_paren)) { |
| 3180 | if (VAOCtx.sawClosingParen()) { |
| 3181 | assert(Tokens.size() >= 3 && |
| 3182 | "Must have seen at least __VA_OPT__( " |
| 3183 | "and a subsequent tok::r_paren" ); |
| 3184 | if (Tokens[Tokens.size() - 2].is(K: tok::hashhash)) { |
| 3185 | Diag(Tok, DiagID: diag::err_vaopt_paste_at_end); |
| 3186 | return nullptr; |
| 3187 | } |
| 3188 | } |
| 3189 | } else if (Tok.is(K: tok::l_paren)) { |
| 3190 | VAOCtx.sawOpeningParen(LParenLoc: Tok.getLocation()); |
| 3191 | } |
| 3192 | } |
| 3193 | // Get the next token of the macro. |
| 3194 | LexUnexpandedToken(Result&: Tok); |
| 3195 | continue; |
| 3196 | } |
| 3197 | |
| 3198 | // If we're in -traditional mode, then we should ignore stringification |
| 3199 | // and token pasting. Mark the tokens as unknown so as not to confuse |
| 3200 | // things. |
| 3201 | if (getLangOpts().TraditionalCPP) { |
| 3202 | Tok.setKind(tok::unknown); |
| 3203 | Tokens.push_back(Elt: Tok); |
| 3204 | |
| 3205 | // Get the next token of the macro. |
| 3206 | LexUnexpandedToken(Result&: Tok); |
| 3207 | continue; |
| 3208 | } |
| 3209 | |
| 3210 | if (Tok.is(K: tok::hashhash)) { |
| 3211 | // If we see token pasting, check if it looks like the gcc comma |
| 3212 | // pasting extension. We'll use this information to suppress |
| 3213 | // diagnostics later on. |
| 3214 | |
| 3215 | // Get the next token of the macro. |
| 3216 | LexUnexpandedToken(Result&: Tok); |
| 3217 | |
| 3218 | if (Tok.is(K: tok::eod)) { |
| 3219 | Tokens.push_back(Elt: LastTok); |
| 3220 | break; |
| 3221 | } |
| 3222 | |
| 3223 | if (!Tokens.empty() && Tok.getIdentifierInfo() == Ident__VA_ARGS__ && |
| 3224 | Tokens[Tokens.size() - 1].is(K: tok::comma)) |
| 3225 | MI->setHasCommaPasting(); |
| 3226 | |
| 3227 | // Things look ok, add the '##' token to the macro. |
| 3228 | Tokens.push_back(Elt: LastTok); |
| 3229 | continue; |
| 3230 | } |
| 3231 | |
| 3232 | // Our Token is a stringization operator. |
| 3233 | // Get the next token of the macro. |
| 3234 | LexUnexpandedToken(Result&: Tok); |
| 3235 | |
| 3236 | // Check for a valid macro arg identifier or __VA_OPT__. |
| 3237 | if (!VAOCtx.isVAOptToken(T: Tok) && |
| 3238 | (Tok.getIdentifierInfo() == nullptr || |
| 3239 | MI->getParameterNum(Arg: Tok.getIdentifierInfo()) == -1)) { |
| 3240 | |
| 3241 | // If this is assembler-with-cpp mode, we accept random gibberish after |
| 3242 | // the '#' because '#' is often a comment character. However, change |
| 3243 | // the kind of the token to tok::unknown so that the preprocessor isn't |
| 3244 | // confused. |
| 3245 | if (getLangOpts().AsmPreprocessor && Tok.isNot(K: tok::eod)) { |
| 3246 | LastTok.setKind(tok::unknown); |
| 3247 | Tokens.push_back(Elt: LastTok); |
| 3248 | continue; |
| 3249 | } else { |
| 3250 | Diag(Tok, DiagID: diag::err_pp_stringize_not_parameter) |
| 3251 | << LastTok.is(K: tok::hashat); |
| 3252 | return nullptr; |
| 3253 | } |
| 3254 | } |
| 3255 | |
| 3256 | // Things look ok, add the '#' and param name tokens to the macro. |
| 3257 | Tokens.push_back(Elt: LastTok); |
| 3258 | |
| 3259 | // If the token following '#' is VAOPT, let the next iteration handle it |
| 3260 | // and check it for correctness, otherwise add the token and prime the |
| 3261 | // loop with the next one. |
| 3262 | if (!VAOCtx.isVAOptToken(T: Tok)) { |
| 3263 | Tokens.push_back(Elt: Tok); |
| 3264 | LastTok = Tok; |
| 3265 | |
| 3266 | // Get the next token of the macro. |
| 3267 | LexUnexpandedToken(Result&: Tok); |
| 3268 | } |
| 3269 | } |
| 3270 | if (VAOCtx.isInVAOpt()) { |
| 3271 | assert(Tok.is(tok::eod) && "Must be at End Of preprocessing Directive" ); |
| 3272 | Diag(Tok, DiagID: diag::err_pp_expected_after) |
| 3273 | << LastTok.getKind() << tok::r_paren; |
| 3274 | Diag(Loc: VAOCtx.getUnmatchedOpeningParenLoc(), DiagID: diag::note_matching) << tok::l_paren; |
| 3275 | return nullptr; |
| 3276 | } |
| 3277 | } |
| 3278 | MI->setDefinitionEndLoc(LastTok.getLocation()); |
| 3279 | |
| 3280 | MI->setTokens(Tokens, PPAllocator&: BP); |
| 3281 | return MI; |
| 3282 | } |
| 3283 | |
| 3284 | static bool isObjCProtectedMacro(const IdentifierInfo *II) { |
| 3285 | return II->isStr(Str: "__strong" ) || II->isStr(Str: "__weak" ) || |
| 3286 | II->isStr(Str: "__unsafe_unretained" ) || II->isStr(Str: "__autoreleasing" ); |
| 3287 | } |
| 3288 | |
| 3289 | /// HandleDefineDirective - Implements \#define. This consumes the entire macro |
| 3290 | /// line then lets the caller lex the next real token. |
| 3291 | void Preprocessor::HandleDefineDirective( |
| 3292 | Token &DefineTok, const bool ) { |
| 3293 | ++NumDefined; |
| 3294 | |
| 3295 | Token MacroNameTok; |
| 3296 | bool MacroShadowsKeyword; |
| 3297 | ReadMacroName(MacroNameTok, isDefineUndef: MU_Define, ShadowFlag: &MacroShadowsKeyword); |
| 3298 | |
| 3299 | // Error reading macro name? If so, diagnostic already issued. |
| 3300 | if (MacroNameTok.is(K: tok::eod)) |
| 3301 | return; |
| 3302 | |
| 3303 | IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); |
| 3304 | // Issue a final pragma warning if we're defining a macro that was has been |
| 3305 | // undefined and is being redefined. |
| 3306 | if (!II->hasMacroDefinition() && II->hadMacroDefinition() && II->isFinal()) |
| 3307 | emitFinalMacroWarning(Identifier: MacroNameTok, /*IsUndef=*/false); |
| 3308 | |
| 3309 | // If we are supposed to keep comments in #defines, reenable comment saving |
| 3310 | // mode. |
| 3311 | if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments); |
| 3312 | |
| 3313 | MacroInfo *const MI = ReadOptionalMacroParameterListAndBody( |
| 3314 | MacroNameTok, ImmediatelyAfterHeaderGuard); |
| 3315 | |
| 3316 | if (!MI) return; |
| 3317 | |
| 3318 | if (MacroShadowsKeyword && |
| 3319 | !isConfigurationPattern(MacroName&: MacroNameTok, MI, LOptions: getLangOpts())) { |
| 3320 | Diag(Tok: MacroNameTok, DiagID: diag::warn_pp_macro_hides_keyword); |
| 3321 | } |
| 3322 | // Check that there is no paste (##) operator at the beginning or end of the |
| 3323 | // replacement list. |
| 3324 | unsigned NumTokens = MI->getNumTokens(); |
| 3325 | if (NumTokens != 0) { |
| 3326 | if (MI->getReplacementToken(Tok: 0).is(K: tok::hashhash)) { |
| 3327 | Diag(Tok: MI->getReplacementToken(Tok: 0), DiagID: diag::err_paste_at_start); |
| 3328 | return; |
| 3329 | } |
| 3330 | if (MI->getReplacementToken(Tok: NumTokens-1).is(K: tok::hashhash)) { |
| 3331 | Diag(Tok: MI->getReplacementToken(Tok: NumTokens-1), DiagID: diag::err_paste_at_end); |
| 3332 | return; |
| 3333 | } |
| 3334 | } |
| 3335 | |
| 3336 | // When skipping just warn about macros that do not match. |
| 3337 | if (SkippingUntilPCHThroughHeader) { |
| 3338 | const MacroInfo *OtherMI = getMacroInfo(II: MacroNameTok.getIdentifierInfo()); |
| 3339 | if (!OtherMI || !MI->isIdenticalTo(Other: *OtherMI, PP&: *this, |
| 3340 | /*Syntactic=*/Syntactically: LangOpts.MicrosoftExt)) |
| 3341 | Diag(Loc: MI->getDefinitionLoc(), DiagID: diag::warn_pp_macro_def_mismatch_with_pch) |
| 3342 | << MacroNameTok.getIdentifierInfo(); |
| 3343 | // Issue the diagnostic but allow the change if msvc extensions are enabled |
| 3344 | if (!LangOpts.MicrosoftExt) |
| 3345 | return; |
| 3346 | } |
| 3347 | |
| 3348 | // Finally, if this identifier already had a macro defined for it, verify that |
| 3349 | // the macro bodies are identical, and issue diagnostics if they are not. |
| 3350 | if (const MacroInfo *OtherMI=getMacroInfo(II: MacroNameTok.getIdentifierInfo())) { |
| 3351 | // Final macros are hard-mode: they always warn. Even if the bodies are |
| 3352 | // identical. Even if they are in system headers. Even if they are things we |
| 3353 | // would silently allow in the past. |
| 3354 | if (MacroNameTok.getIdentifierInfo()->isFinal()) |
| 3355 | emitFinalMacroWarning(Identifier: MacroNameTok, /*IsUndef=*/false); |
| 3356 | |
| 3357 | // In Objective-C, ignore attempts to directly redefine the builtin |
| 3358 | // definitions of the ownership qualifiers. It's still possible to |
| 3359 | // #undef them. |
| 3360 | if (getLangOpts().ObjC && |
| 3361 | SourceMgr.getFileID(SpellingLoc: OtherMI->getDefinitionLoc()) == |
| 3362 | getPredefinesFileID() && |
| 3363 | isObjCProtectedMacro(II: MacroNameTok.getIdentifierInfo())) { |
| 3364 | // Warn if it changes the tokens. |
| 3365 | if ((!getDiagnostics().getSuppressSystemWarnings() || |
| 3366 | !SourceMgr.isInSystemHeader(Loc: DefineTok.getLocation())) && |
| 3367 | !MI->isIdenticalTo(Other: *OtherMI, PP&: *this, |
| 3368 | /*Syntactic=*/Syntactically: LangOpts.MicrosoftExt)) { |
| 3369 | Diag(Loc: MI->getDefinitionLoc(), DiagID: diag::warn_pp_objc_macro_redef_ignored); |
| 3370 | } |
| 3371 | assert(!OtherMI->isWarnIfUnused()); |
| 3372 | return; |
| 3373 | } |
| 3374 | |
| 3375 | // It is very common for system headers to have tons of macro redefinitions |
| 3376 | // and for warnings to be disabled in system headers. If this is the case, |
| 3377 | // then don't bother calling MacroInfo::isIdenticalTo. |
| 3378 | if (!getDiagnostics().getSuppressSystemWarnings() || |
| 3379 | !SourceMgr.isInSystemHeader(Loc: DefineTok.getLocation())) { |
| 3380 | |
| 3381 | if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused()) |
| 3382 | Diag(Loc: OtherMI->getDefinitionLoc(), DiagID: diag::pp_macro_not_used); |
| 3383 | |
| 3384 | // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and |
| 3385 | // C++ [cpp.predefined]p4, but allow it as an extension. |
| 3386 | if (isLanguageDefinedBuiltin(SourceMgr, MI: OtherMI, MacroName: II->getName())) |
| 3387 | Diag(Tok: MacroNameTok, DiagID: diag::ext_pp_redef_builtin_macro); |
| 3388 | // Macros must be identical. This means all tokens and whitespace |
| 3389 | // separation must be the same. C99 6.10.3p2. |
| 3390 | else if (!OtherMI->isAllowRedefinitionsWithoutWarning() && |
| 3391 | !MI->isIdenticalTo(Other: *OtherMI, PP&: *this, /*Syntactic=*/Syntactically: LangOpts.MicrosoftExt)) { |
| 3392 | Diag(Loc: MI->getDefinitionLoc(), DiagID: diag::ext_pp_macro_redef) |
| 3393 | << MacroNameTok.getIdentifierInfo(); |
| 3394 | Diag(Loc: OtherMI->getDefinitionLoc(), DiagID: diag::note_previous_definition); |
| 3395 | } |
| 3396 | } |
| 3397 | if (OtherMI->isWarnIfUnused()) |
| 3398 | WarnUnusedMacroLocs.erase(V: OtherMI->getDefinitionLoc()); |
| 3399 | } |
| 3400 | |
| 3401 | DefMacroDirective *MD = |
| 3402 | appendDefMacroDirective(II: MacroNameTok.getIdentifierInfo(), MI); |
| 3403 | |
| 3404 | assert(!MI->isUsed()); |
| 3405 | // If we need warning for not using the macro, add its location in the |
| 3406 | // warn-because-unused-macro set. If it gets used it will be removed from set. |
| 3407 | if (getSourceManager().isInMainFile(Loc: MI->getDefinitionLoc()) && |
| 3408 | !Diags->isIgnored(DiagID: diag::pp_macro_not_used, Loc: MI->getDefinitionLoc()) && |
| 3409 | !MacroExpansionInDirectivesOverride && |
| 3410 | getSourceManager().getFileID(SpellingLoc: MI->getDefinitionLoc()) != |
| 3411 | getPredefinesFileID()) { |
| 3412 | MI->setIsWarnIfUnused(true); |
| 3413 | WarnUnusedMacroLocs.insert(V: MI->getDefinitionLoc()); |
| 3414 | } |
| 3415 | |
| 3416 | // If the callbacks want to know, tell them about the macro definition. |
| 3417 | if (Callbacks) |
| 3418 | Callbacks->MacroDefined(MacroNameTok, MD); |
| 3419 | } |
| 3420 | |
| 3421 | /// HandleUndefDirective - Implements \#undef. |
| 3422 | /// |
| 3423 | void Preprocessor::HandleUndefDirective() { |
| 3424 | ++NumUndefined; |
| 3425 | |
| 3426 | Token MacroNameTok; |
| 3427 | ReadMacroName(MacroNameTok, isDefineUndef: MU_Undef); |
| 3428 | |
| 3429 | // Error reading macro name? If so, diagnostic already issued. |
| 3430 | if (MacroNameTok.is(K: tok::eod)) |
| 3431 | return; |
| 3432 | |
| 3433 | // Check to see if this is the last token on the #undef line. |
| 3434 | CheckEndOfDirective(DirType: "undef" ); |
| 3435 | |
| 3436 | // Okay, we have a valid identifier to undef. |
| 3437 | auto *II = MacroNameTok.getIdentifierInfo(); |
| 3438 | auto MD = getMacroDefinition(II); |
| 3439 | UndefMacroDirective *Undef = nullptr; |
| 3440 | |
| 3441 | if (II->isFinal()) |
| 3442 | emitFinalMacroWarning(Identifier: MacroNameTok, /*IsUndef=*/true); |
| 3443 | |
| 3444 | // If the macro is not defined, this is a noop undef. |
| 3445 | if (const MacroInfo *MI = MD.getMacroInfo()) { |
| 3446 | if (!MI->isUsed() && MI->isWarnIfUnused()) |
| 3447 | Diag(Loc: MI->getDefinitionLoc(), DiagID: diag::pp_macro_not_used); |
| 3448 | |
| 3449 | // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4 and |
| 3450 | // C++ [cpp.predefined]p4, but allow it as an extension. |
| 3451 | if (isLanguageDefinedBuiltin(SourceMgr, MI, MacroName: II->getName())) |
| 3452 | Diag(Tok: MacroNameTok, DiagID: diag::ext_pp_undef_builtin_macro); |
| 3453 | |
| 3454 | if (MI->isWarnIfUnused()) |
| 3455 | WarnUnusedMacroLocs.erase(V: MI->getDefinitionLoc()); |
| 3456 | |
| 3457 | Undef = AllocateUndefMacroDirective(UndefLoc: MacroNameTok.getLocation()); |
| 3458 | } |
| 3459 | |
| 3460 | // If the callbacks want to know, tell them about the macro #undef. |
| 3461 | // Note: no matter if the macro was defined or not. |
| 3462 | if (Callbacks) |
| 3463 | Callbacks->MacroUndefined(MacroNameTok, MD, Undef); |
| 3464 | |
| 3465 | if (Undef) |
| 3466 | appendMacroDirective(II, MD: Undef); |
| 3467 | } |
| 3468 | |
| 3469 | //===----------------------------------------------------------------------===// |
| 3470 | // Preprocessor Conditional Directive Handling. |
| 3471 | //===----------------------------------------------------------------------===// |
| 3472 | |
| 3473 | /// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef |
| 3474 | /// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is |
| 3475 | /// true if any tokens have been returned or pp-directives activated before this |
| 3476 | /// \#ifndef has been lexed. |
| 3477 | /// |
| 3478 | void Preprocessor::HandleIfdefDirective(Token &Result, |
| 3479 | const Token &HashToken, |
| 3480 | bool isIfndef, |
| 3481 | bool ReadAnyTokensBeforeDirective) { |
| 3482 | ++NumIf; |
| 3483 | Token DirectiveTok = Result; |
| 3484 | |
| 3485 | Token MacroNameTok; |
| 3486 | ReadMacroName(MacroNameTok); |
| 3487 | |
| 3488 | // Error reading macro name? If so, diagnostic already issued. |
| 3489 | if (MacroNameTok.is(K: tok::eod)) { |
| 3490 | // Skip code until we get to #endif. This helps with recovery by not |
| 3491 | // emitting an error when the #endif is reached. |
| 3492 | SkipExcludedConditionalBlock(HashTokenLoc: HashToken.getLocation(), |
| 3493 | IfTokenLoc: DirectiveTok.getLocation(), |
| 3494 | /*Foundnonskip*/ FoundNonSkipPortion: false, /*FoundElse*/ false); |
| 3495 | return; |
| 3496 | } |
| 3497 | |
| 3498 | emitMacroExpansionWarnings(Identifier: MacroNameTok, /*IsIfnDef=*/true); |
| 3499 | |
| 3500 | // Check to see if this is the last token on the #if[n]def line. |
| 3501 | CheckEndOfDirective(DirType: isIfndef ? "ifndef" : "ifdef" ); |
| 3502 | |
| 3503 | IdentifierInfo *MII = MacroNameTok.getIdentifierInfo(); |
| 3504 | auto MD = getMacroDefinition(II: MII); |
| 3505 | MacroInfo *MI = MD.getMacroInfo(); |
| 3506 | |
| 3507 | if (CurPPLexer->getConditionalStackDepth() == 0) { |
| 3508 | // If the start of a top-level #ifdef and if the macro is not defined, |
| 3509 | // inform MIOpt that this might be the start of a proper include guard. |
| 3510 | // Otherwise it is some other form of unknown conditional which we can't |
| 3511 | // handle. |
| 3512 | if (!ReadAnyTokensBeforeDirective && !MI) { |
| 3513 | assert(isIfndef && "#ifdef shouldn't reach here" ); |
| 3514 | CurPPLexer->MIOpt.EnterTopLevelIfndef(M: MII, Loc: MacroNameTok.getLocation()); |
| 3515 | } else |
| 3516 | CurPPLexer->MIOpt.EnterTopLevelConditional(); |
| 3517 | } |
| 3518 | |
| 3519 | // If there is a macro, process it. |
| 3520 | if (MI) // Mark it used. |
| 3521 | markMacroAsUsed(MI); |
| 3522 | |
| 3523 | if (Callbacks) { |
| 3524 | if (isIfndef) |
| 3525 | Callbacks->Ifndef(Loc: DirectiveTok.getLocation(), MacroNameTok, MD); |
| 3526 | else |
| 3527 | Callbacks->Ifdef(Loc: DirectiveTok.getLocation(), MacroNameTok, MD); |
| 3528 | } |
| 3529 | |
| 3530 | bool RetainExcludedCB = PPOpts.RetainExcludedConditionalBlocks && |
| 3531 | getSourceManager().isInMainFile(Loc: DirectiveTok.getLocation()); |
| 3532 | |
| 3533 | // Should we include the stuff contained by this directive? |
| 3534 | if (PPOpts.SingleFileParseMode && !MI) { |
| 3535 | // In 'single-file-parse mode' undefined identifiers trigger parsing of all |
| 3536 | // the directive blocks. |
| 3537 | CurPPLexer->pushConditionalLevel(DirectiveStart: DirectiveTok.getLocation(), |
| 3538 | /*wasskip*/WasSkipping: false, /*foundnonskip*/FoundNonSkip: false, |
| 3539 | /*foundelse*/FoundElse: false); |
| 3540 | } else if (PPOpts.SingleModuleParseMode && !MI) { |
| 3541 | // In 'single-module-parse mode' undefined identifiers trigger skipping of |
| 3542 | // all the directive blocks. We lie here and set FoundNonSkipPortion so that |
| 3543 | // even any \#else blocks get skipped. |
| 3544 | SkipExcludedConditionalBlock( |
| 3545 | HashTokenLoc: HashToken.getLocation(), IfTokenLoc: DirectiveTok.getLocation(), |
| 3546 | /*FoundNonSkipPortion=*/true, /*FoundElse=*/false); |
| 3547 | } else if (!MI == isIfndef || RetainExcludedCB) { |
| 3548 | // Yes, remember that we are inside a conditional, then lex the next token. |
| 3549 | CurPPLexer->pushConditionalLevel(DirectiveStart: DirectiveTok.getLocation(), |
| 3550 | /*wasskip*/WasSkipping: false, /*foundnonskip*/FoundNonSkip: true, |
| 3551 | /*foundelse*/FoundElse: false); |
| 3552 | } else { |
| 3553 | // No, skip the contents of this block. |
| 3554 | SkipExcludedConditionalBlock(HashTokenLoc: HashToken.getLocation(), |
| 3555 | IfTokenLoc: DirectiveTok.getLocation(), |
| 3556 | /*Foundnonskip*/ FoundNonSkipPortion: false, |
| 3557 | /*FoundElse*/ false); |
| 3558 | } |
| 3559 | } |
| 3560 | |
| 3561 | /// HandleIfDirective - Implements the \#if directive. |
| 3562 | /// |
| 3563 | void Preprocessor::HandleIfDirective(Token &IfToken, |
| 3564 | const Token &HashToken, |
| 3565 | bool ReadAnyTokensBeforeDirective) { |
| 3566 | ++NumIf; |
| 3567 | |
| 3568 | // Parse and evaluate the conditional expression. |
| 3569 | IdentifierInfo *IfNDefMacro = nullptr; |
| 3570 | const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro); |
| 3571 | const bool ConditionalTrue = DER.Conditional; |
| 3572 | // Lexer might become invalid if we hit code completion point while evaluating |
| 3573 | // expression. |
| 3574 | if (!CurPPLexer) |
| 3575 | return; |
| 3576 | |
| 3577 | // If this condition is equivalent to #ifndef X, and if this is the first |
| 3578 | // directive seen, handle it for the multiple-include optimization. |
| 3579 | if (CurPPLexer->getConditionalStackDepth() == 0) { |
| 3580 | if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue) |
| 3581 | // FIXME: Pass in the location of the macro name, not the 'if' token. |
| 3582 | CurPPLexer->MIOpt.EnterTopLevelIfndef(M: IfNDefMacro, Loc: IfToken.getLocation()); |
| 3583 | else |
| 3584 | CurPPLexer->MIOpt.EnterTopLevelConditional(); |
| 3585 | } |
| 3586 | |
| 3587 | if (Callbacks) |
| 3588 | Callbacks->If( |
| 3589 | Loc: IfToken.getLocation(), ConditionRange: DER.ExprRange, |
| 3590 | ConditionValue: (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False)); |
| 3591 | |
| 3592 | bool RetainExcludedCB = PPOpts.RetainExcludedConditionalBlocks && |
| 3593 | getSourceManager().isInMainFile(Loc: IfToken.getLocation()); |
| 3594 | |
| 3595 | // Should we include the stuff contained by this directive? |
| 3596 | if (PPOpts.SingleFileParseMode && DER.IncludedUndefinedIds) { |
| 3597 | // In 'single-file-parse mode' undefined identifiers trigger parsing of all |
| 3598 | // the directive blocks. |
| 3599 | CurPPLexer->pushConditionalLevel(DirectiveStart: IfToken.getLocation(), /*wasskip*/WasSkipping: false, |
| 3600 | /*foundnonskip*/FoundNonSkip: false, /*foundelse*/FoundElse: false); |
| 3601 | } else if (PPOpts.SingleModuleParseMode && DER.IncludedUndefinedIds) { |
| 3602 | // In 'single-module-parse mode' undefined identifiers trigger skipping of |
| 3603 | // all the directive blocks. We lie here and set FoundNonSkipPortion so that |
| 3604 | // even any \#else blocks get skipped. |
| 3605 | SkipExcludedConditionalBlock(HashTokenLoc: HashToken.getLocation(), IfTokenLoc: IfToken.getLocation(), |
| 3606 | /*FoundNonSkipPortion=*/true, |
| 3607 | /*FoundElse=*/false); |
| 3608 | } else if (ConditionalTrue || RetainExcludedCB) { |
| 3609 | // Yes, remember that we are inside a conditional, then lex the next token. |
| 3610 | CurPPLexer->pushConditionalLevel(DirectiveStart: IfToken.getLocation(), /*wasskip*/WasSkipping: false, |
| 3611 | /*foundnonskip*/FoundNonSkip: true, /*foundelse*/FoundElse: false); |
| 3612 | } else { |
| 3613 | // No, skip the contents of this block. |
| 3614 | SkipExcludedConditionalBlock(HashTokenLoc: HashToken.getLocation(), IfTokenLoc: IfToken.getLocation(), |
| 3615 | /*Foundnonskip*/ FoundNonSkipPortion: false, |
| 3616 | /*FoundElse*/ false); |
| 3617 | } |
| 3618 | } |
| 3619 | |
| 3620 | /// HandleEndifDirective - Implements the \#endif directive. |
| 3621 | /// |
| 3622 | void Preprocessor::HandleEndifDirective(Token &EndifToken) { |
| 3623 | ++NumEndif; |
| 3624 | |
| 3625 | // Check that this is the whole directive. |
| 3626 | CheckEndOfDirective(DirType: "endif" ); |
| 3627 | |
| 3628 | PPConditionalInfo CondInfo; |
| 3629 | if (CurPPLexer->popConditionalLevel(CI&: CondInfo)) { |
| 3630 | // No conditionals on the stack: this is an #endif without an #if. |
| 3631 | Diag(Tok: EndifToken, DiagID: diag::err_pp_endif_without_if); |
| 3632 | return; |
| 3633 | } |
| 3634 | |
| 3635 | // If this the end of a top-level #endif, inform MIOpt. |
| 3636 | if (CurPPLexer->getConditionalStackDepth() == 0) |
| 3637 | CurPPLexer->MIOpt.ExitTopLevelConditional(); |
| 3638 | |
| 3639 | assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode && |
| 3640 | "This code should only be reachable in the non-skipping case!" ); |
| 3641 | |
| 3642 | if (Callbacks) |
| 3643 | Callbacks->Endif(Loc: EndifToken.getLocation(), IfLoc: CondInfo.IfLoc); |
| 3644 | } |
| 3645 | |
| 3646 | /// HandleElseDirective - Implements the \#else directive. |
| 3647 | /// |
| 3648 | void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) { |
| 3649 | ++NumElse; |
| 3650 | |
| 3651 | // #else directive in a non-skipping conditional... start skipping. |
| 3652 | CheckEndOfDirective(DirType: "else" ); |
| 3653 | |
| 3654 | PPConditionalInfo CI; |
| 3655 | if (CurPPLexer->popConditionalLevel(CI)) { |
| 3656 | Diag(Tok: Result, DiagID: diag::pp_err_else_without_if); |
| 3657 | return; |
| 3658 | } |
| 3659 | |
| 3660 | // If this is a top-level #else, inform the MIOpt. |
| 3661 | if (CurPPLexer->getConditionalStackDepth() == 0) |
| 3662 | CurPPLexer->MIOpt.EnterTopLevelConditional(); |
| 3663 | |
| 3664 | // If this is a #else with a #else before it, report the error. |
| 3665 | if (CI.FoundElse) Diag(Tok: Result, DiagID: diag::pp_err_else_after_else); |
| 3666 | |
| 3667 | if (Callbacks) |
| 3668 | Callbacks->Else(Loc: Result.getLocation(), IfLoc: CI.IfLoc); |
| 3669 | |
| 3670 | bool RetainExcludedCB = PPOpts.RetainExcludedConditionalBlocks && |
| 3671 | getSourceManager().isInMainFile(Loc: Result.getLocation()); |
| 3672 | |
| 3673 | if ((PPOpts.SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) { |
| 3674 | // In 'single-file-parse mode' undefined identifiers trigger parsing of all |
| 3675 | // the directive blocks. |
| 3676 | CurPPLexer->pushConditionalLevel(DirectiveStart: CI.IfLoc, /*wasskip*/WasSkipping: false, |
| 3677 | /*foundnonskip*/FoundNonSkip: false, /*foundelse*/FoundElse: true); |
| 3678 | return; |
| 3679 | } |
| 3680 | |
| 3681 | // Finally, skip the rest of the contents of this block. |
| 3682 | SkipExcludedConditionalBlock(HashTokenLoc: HashToken.getLocation(), IfTokenLoc: CI.IfLoc, |
| 3683 | /*Foundnonskip*/ FoundNonSkipPortion: true, |
| 3684 | /*FoundElse*/ true, ElseLoc: Result.getLocation()); |
| 3685 | } |
| 3686 | |
| 3687 | /// Implements the \#elif, \#elifdef, and \#elifndef directives. |
| 3688 | void Preprocessor::HandleElifFamilyDirective(Token &ElifToken, |
| 3689 | const Token &HashToken, |
| 3690 | tok::PPKeywordKind Kind) { |
| 3691 | PPElifDiag DirKind = Kind == tok::pp_elif ? PED_Elif |
| 3692 | : Kind == tok::pp_elifdef ? PED_Elifdef |
| 3693 | : PED_Elifndef; |
| 3694 | ++NumElse; |
| 3695 | |
| 3696 | // Warn if using `#elifdef` & `#elifndef` in not C23 & C++23 mode. |
| 3697 | switch (DirKind) { |
| 3698 | case PED_Elifdef: |
| 3699 | case PED_Elifndef: |
| 3700 | unsigned DiagID; |
| 3701 | if (LangOpts.CPlusPlus) |
| 3702 | DiagID = LangOpts.CPlusPlus23 ? diag::warn_cxx23_compat_pp_directive |
| 3703 | : diag::ext_cxx23_pp_directive; |
| 3704 | else |
| 3705 | DiagID = LangOpts.C23 ? diag::warn_c23_compat_pp_directive |
| 3706 | : diag::ext_c23_pp_directive; |
| 3707 | Diag(Tok: ElifToken, DiagID) << DirKind; |
| 3708 | break; |
| 3709 | default: |
| 3710 | break; |
| 3711 | } |
| 3712 | |
| 3713 | // #elif directive in a non-skipping conditional... start skipping. |
| 3714 | // We don't care what the condition is, because we will always skip it (since |
| 3715 | // the block immediately before it was included). |
| 3716 | SourceRange ConditionRange = DiscardUntilEndOfDirective(); |
| 3717 | |
| 3718 | PPConditionalInfo CI; |
| 3719 | if (CurPPLexer->popConditionalLevel(CI)) { |
| 3720 | Diag(Tok: ElifToken, DiagID: diag::pp_err_elif_without_if) << DirKind; |
| 3721 | return; |
| 3722 | } |
| 3723 | |
| 3724 | // If this is a top-level #elif, inform the MIOpt. |
| 3725 | if (CurPPLexer->getConditionalStackDepth() == 0) |
| 3726 | CurPPLexer->MIOpt.EnterTopLevelConditional(); |
| 3727 | |
| 3728 | // If this is a #elif with a #else before it, report the error. |
| 3729 | if (CI.FoundElse) |
| 3730 | Diag(Tok: ElifToken, DiagID: diag::pp_err_elif_after_else) << DirKind; |
| 3731 | |
| 3732 | if (Callbacks) { |
| 3733 | switch (Kind) { |
| 3734 | case tok::pp_elif: |
| 3735 | Callbacks->Elif(Loc: ElifToken.getLocation(), ConditionRange, |
| 3736 | ConditionValue: PPCallbacks::CVK_NotEvaluated, IfLoc: CI.IfLoc); |
| 3737 | break; |
| 3738 | case tok::pp_elifdef: |
| 3739 | Callbacks->Elifdef(Loc: ElifToken.getLocation(), ConditionRange, IfLoc: CI.IfLoc); |
| 3740 | break; |
| 3741 | case tok::pp_elifndef: |
| 3742 | Callbacks->Elifndef(Loc: ElifToken.getLocation(), ConditionRange, IfLoc: CI.IfLoc); |
| 3743 | break; |
| 3744 | default: |
| 3745 | assert(false && "unexpected directive kind" ); |
| 3746 | break; |
| 3747 | } |
| 3748 | } |
| 3749 | |
| 3750 | bool RetainExcludedCB = PPOpts.RetainExcludedConditionalBlocks && |
| 3751 | getSourceManager().isInMainFile(Loc: ElifToken.getLocation()); |
| 3752 | |
| 3753 | if ((PPOpts.SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) { |
| 3754 | // In 'single-file-parse mode' undefined identifiers trigger parsing of all |
| 3755 | // the directive blocks. |
| 3756 | CurPPLexer->pushConditionalLevel(DirectiveStart: ElifToken.getLocation(), /*wasskip*/WasSkipping: false, |
| 3757 | /*foundnonskip*/FoundNonSkip: false, /*foundelse*/FoundElse: false); |
| 3758 | return; |
| 3759 | } |
| 3760 | |
| 3761 | // Finally, skip the rest of the contents of this block. |
| 3762 | SkipExcludedConditionalBlock( |
| 3763 | HashTokenLoc: HashToken.getLocation(), IfTokenLoc: CI.IfLoc, /*Foundnonskip*/ FoundNonSkipPortion: true, |
| 3764 | /*FoundElse*/ CI.FoundElse, ElseLoc: ElifToken.getLocation()); |
| 3765 | } |
| 3766 | |
| 3767 | std::optional<LexEmbedParametersResult> |
| 3768 | Preprocessor::LexEmbedParameters(Token &CurTok, bool ForHasEmbed) { |
| 3769 | LexEmbedParametersResult Result{}; |
| 3770 | tok::TokenKind EndTokenKind = ForHasEmbed ? tok::r_paren : tok::eod; |
| 3771 | |
| 3772 | auto DiagMismatchedBracesAndSkipToEOD = |
| 3773 | [&](tok::TokenKind Expected, |
| 3774 | std::pair<tok::TokenKind, SourceLocation> Matches) { |
| 3775 | Diag(Tok: CurTok, DiagID: diag::err_expected) << Expected; |
| 3776 | Diag(Loc: Matches.second, DiagID: diag::note_matching) << Matches.first; |
| 3777 | if (CurTok.isNot(K: tok::eod)) |
| 3778 | DiscardUntilEndOfDirective(Tmp&: CurTok); |
| 3779 | }; |
| 3780 | |
| 3781 | auto ExpectOrDiagAndSkipToEOD = [&](tok::TokenKind Kind) { |
| 3782 | if (CurTok.isNot(K: Kind)) { |
| 3783 | Diag(Tok: CurTok, DiagID: diag::err_expected) << Kind; |
| 3784 | if (CurTok.isNot(K: tok::eod)) |
| 3785 | DiscardUntilEndOfDirective(Tmp&: CurTok); |
| 3786 | return false; |
| 3787 | } |
| 3788 | return true; |
| 3789 | }; |
| 3790 | |
| 3791 | // C23 6.10: |
| 3792 | // pp-parameter-name: |
| 3793 | // pp-standard-parameter |
| 3794 | // pp-prefixed-parameter |
| 3795 | // |
| 3796 | // pp-standard-parameter: |
| 3797 | // identifier |
| 3798 | // |
| 3799 | // pp-prefixed-parameter: |
| 3800 | // identifier :: identifier |
| 3801 | auto LexPPParameterName = [&]() -> std::optional<std::string> { |
| 3802 | // We expect the current token to be an identifier; if it's not, things |
| 3803 | // have gone wrong. |
| 3804 | if (!ExpectOrDiagAndSkipToEOD(tok::identifier)) |
| 3805 | return std::nullopt; |
| 3806 | |
| 3807 | const IdentifierInfo *Prefix = CurTok.getIdentifierInfo(); |
| 3808 | |
| 3809 | // Lex another token; it is either a :: or we're done with the parameter |
| 3810 | // name. |
| 3811 | LexNonComment(Result&: CurTok); |
| 3812 | if (CurTok.is(K: tok::coloncolon)) { |
| 3813 | // We found a ::, so lex another identifier token. |
| 3814 | LexNonComment(Result&: CurTok); |
| 3815 | if (!ExpectOrDiagAndSkipToEOD(tok::identifier)) |
| 3816 | return std::nullopt; |
| 3817 | |
| 3818 | const IdentifierInfo *Suffix = CurTok.getIdentifierInfo(); |
| 3819 | |
| 3820 | // Lex another token so we're past the name. |
| 3821 | LexNonComment(Result&: CurTok); |
| 3822 | return (llvm::Twine(Prefix->getName()) + "::" + Suffix->getName()).str(); |
| 3823 | } |
| 3824 | return Prefix->getName().str(); |
| 3825 | }; |
| 3826 | |
| 3827 | // C23 6.10p5: In all aspects, a preprocessor standard parameter specified by |
| 3828 | // this document as an identifier pp_param and an identifier of the form |
| 3829 | // __pp_param__ shall behave the same when used as a preprocessor parameter, |
| 3830 | // except for the spelling. |
| 3831 | auto NormalizeParameterName = [](StringRef Name) { |
| 3832 | if (Name.size() > 4 && Name.starts_with(Prefix: "__" ) && Name.ends_with(Suffix: "__" )) |
| 3833 | return Name.substr(Start: 2, N: Name.size() - 4); |
| 3834 | return Name; |
| 3835 | }; |
| 3836 | |
| 3837 | auto LexParenthesizedIntegerExpr = [&]() -> std::optional<size_t> { |
| 3838 | // we have a limit parameter and its internals are processed using |
| 3839 | // evaluation rules from #if. |
| 3840 | if (!ExpectOrDiagAndSkipToEOD(tok::l_paren)) |
| 3841 | return std::nullopt; |
| 3842 | |
| 3843 | // We do not consume the ( because EvaluateDirectiveExpression will lex |
| 3844 | // the next token for us. |
| 3845 | IdentifierInfo *ParameterIfNDef = nullptr; |
| 3846 | bool EvaluatedDefined; |
| 3847 | DirectiveEvalResult LimitEvalResult = EvaluateDirectiveExpression( |
| 3848 | IfNDefMacro&: ParameterIfNDef, Tok&: CurTok, EvaluatedDefined, /*CheckForEOD=*/CheckForEoD: false); |
| 3849 | |
| 3850 | if (!LimitEvalResult.Value) { |
| 3851 | // If there was an error evaluating the directive expression, we expect |
| 3852 | // to be at the end of directive token. |
| 3853 | assert(CurTok.is(tok::eod) && "expect to be at the end of directive" ); |
| 3854 | return std::nullopt; |
| 3855 | } |
| 3856 | |
| 3857 | if (!ExpectOrDiagAndSkipToEOD(tok::r_paren)) |
| 3858 | return std::nullopt; |
| 3859 | |
| 3860 | // Eat the ). |
| 3861 | LexNonComment(Result&: CurTok); |
| 3862 | |
| 3863 | // C23 6.10.3.2p2: The token defined shall not appear within the constant |
| 3864 | // expression. |
| 3865 | if (EvaluatedDefined) { |
| 3866 | Diag(Tok: CurTok, DiagID: diag::err_defined_in_pp_embed); |
| 3867 | return std::nullopt; |
| 3868 | } |
| 3869 | |
| 3870 | if (LimitEvalResult.Value) { |
| 3871 | const llvm::APSInt &Result = *LimitEvalResult.Value; |
| 3872 | if (Result.isNegative()) { |
| 3873 | Diag(Tok: CurTok, DiagID: diag::err_requires_positive_value) |
| 3874 | << toString(I: Result, Radix: 10) << /*positive*/ 0; |
| 3875 | if (CurTok.isNot(K: EndTokenKind)) |
| 3876 | DiscardUntilEndOfDirective(Tmp&: CurTok); |
| 3877 | return std::nullopt; |
| 3878 | } |
| 3879 | return Result.getLimitedValue(); |
| 3880 | } |
| 3881 | return std::nullopt; |
| 3882 | }; |
| 3883 | |
| 3884 | auto GetMatchingCloseBracket = [](tok::TokenKind Kind) { |
| 3885 | switch (Kind) { |
| 3886 | case tok::l_paren: |
| 3887 | return tok::r_paren; |
| 3888 | case tok::l_brace: |
| 3889 | return tok::r_brace; |
| 3890 | case tok::l_square: |
| 3891 | return tok::r_square; |
| 3892 | default: |
| 3893 | llvm_unreachable("should not get here" ); |
| 3894 | } |
| 3895 | }; |
| 3896 | |
| 3897 | auto LexParenthesizedBalancedTokenSoup = |
| 3898 | [&](llvm::SmallVectorImpl<Token> &Tokens) { |
| 3899 | std::vector<std::pair<tok::TokenKind, SourceLocation>> BracketStack; |
| 3900 | |
| 3901 | // We expect the current token to be a left paren. |
| 3902 | if (!ExpectOrDiagAndSkipToEOD(tok::l_paren)) |
| 3903 | return false; |
| 3904 | LexNonComment(Result&: CurTok); // Eat the ( |
| 3905 | |
| 3906 | bool WaitingForInnerCloseParen = false; |
| 3907 | while (CurTok.isNot(K: tok::eod) && |
| 3908 | (WaitingForInnerCloseParen || CurTok.isNot(K: tok::r_paren))) { |
| 3909 | switch (CurTok.getKind()) { |
| 3910 | default: // Shutting up diagnostics about not fully-covered switch. |
| 3911 | break; |
| 3912 | case tok::l_paren: |
| 3913 | WaitingForInnerCloseParen = true; |
| 3914 | [[fallthrough]]; |
| 3915 | case tok::l_brace: |
| 3916 | case tok::l_square: |
| 3917 | BracketStack.push_back(x: {CurTok.getKind(), CurTok.getLocation()}); |
| 3918 | break; |
| 3919 | case tok::r_paren: |
| 3920 | WaitingForInnerCloseParen = false; |
| 3921 | [[fallthrough]]; |
| 3922 | case tok::r_brace: |
| 3923 | case tok::r_square: { |
| 3924 | if (BracketStack.empty()) { |
| 3925 | ExpectOrDiagAndSkipToEOD(tok::r_paren); |
| 3926 | return false; |
| 3927 | } |
| 3928 | tok::TokenKind Matching = |
| 3929 | GetMatchingCloseBracket(BracketStack.back().first); |
| 3930 | if (CurTok.getKind() != Matching) { |
| 3931 | DiagMismatchedBracesAndSkipToEOD(Matching, BracketStack.back()); |
| 3932 | return false; |
| 3933 | } |
| 3934 | BracketStack.pop_back(); |
| 3935 | } break; |
| 3936 | } |
| 3937 | Tokens.push_back(Elt: CurTok); |
| 3938 | LexNonComment(Result&: CurTok); |
| 3939 | } |
| 3940 | |
| 3941 | // When we're done, we want to eat the closing paren. |
| 3942 | if (!ExpectOrDiagAndSkipToEOD(tok::r_paren)) |
| 3943 | return false; |
| 3944 | |
| 3945 | LexNonComment(Result&: CurTok); // Eat the ) |
| 3946 | return true; |
| 3947 | }; |
| 3948 | |
| 3949 | LexNonComment(Result&: CurTok); // Prime the pump. |
| 3950 | while (!CurTok.isOneOf(Ks: EndTokenKind, Ks: tok::eod)) { |
| 3951 | SourceLocation ParamStartLoc = CurTok.getLocation(); |
| 3952 | std::optional<std::string> ParamName = LexPPParameterName(); |
| 3953 | if (!ParamName) |
| 3954 | return std::nullopt; |
| 3955 | StringRef Parameter = NormalizeParameterName(*ParamName); |
| 3956 | |
| 3957 | // Lex the parameters (dependent on the parameter type we want!). |
| 3958 | // |
| 3959 | // C23 6.10.3.Xp1: The X standard embed parameter may appear zero times or |
| 3960 | // one time in the embed parameter sequence. |
| 3961 | if (Parameter == "limit" ) { |
| 3962 | if (Result.MaybeLimitParam) |
| 3963 | Diag(Tok: CurTok, DiagID: diag::err_pp_embed_dup_params) << Parameter; |
| 3964 | |
| 3965 | std::optional<size_t> Limit = LexParenthesizedIntegerExpr(); |
| 3966 | if (!Limit) |
| 3967 | return std::nullopt; |
| 3968 | Result.MaybeLimitParam = |
| 3969 | PPEmbedParameterLimit{*Limit, {ParamStartLoc, CurTok.getLocation()}}; |
| 3970 | } else if (Parameter == "clang::offset" ) { |
| 3971 | if (Result.MaybeOffsetParam) |
| 3972 | Diag(Tok: CurTok, DiagID: diag::err_pp_embed_dup_params) << Parameter; |
| 3973 | |
| 3974 | std::optional<size_t> Offset = LexParenthesizedIntegerExpr(); |
| 3975 | if (!Offset) |
| 3976 | return std::nullopt; |
| 3977 | Result.MaybeOffsetParam = PPEmbedParameterOffset{ |
| 3978 | *Offset, {ParamStartLoc, CurTok.getLocation()}}; |
| 3979 | } else if (Parameter == "prefix" ) { |
| 3980 | if (Result.MaybePrefixParam) |
| 3981 | Diag(Tok: CurTok, DiagID: diag::err_pp_embed_dup_params) << Parameter; |
| 3982 | |
| 3983 | SmallVector<Token, 4> Soup; |
| 3984 | if (!LexParenthesizedBalancedTokenSoup(Soup)) |
| 3985 | return std::nullopt; |
| 3986 | Result.MaybePrefixParam = PPEmbedParameterPrefix{ |
| 3987 | std::move(Soup), {ParamStartLoc, CurTok.getLocation()}}; |
| 3988 | } else if (Parameter == "suffix" ) { |
| 3989 | if (Result.MaybeSuffixParam) |
| 3990 | Diag(Tok: CurTok, DiagID: diag::err_pp_embed_dup_params) << Parameter; |
| 3991 | |
| 3992 | SmallVector<Token, 4> Soup; |
| 3993 | if (!LexParenthesizedBalancedTokenSoup(Soup)) |
| 3994 | return std::nullopt; |
| 3995 | Result.MaybeSuffixParam = PPEmbedParameterSuffix{ |
| 3996 | std::move(Soup), {ParamStartLoc, CurTok.getLocation()}}; |
| 3997 | } else if (Parameter == "if_empty" ) { |
| 3998 | if (Result.MaybeIfEmptyParam) |
| 3999 | Diag(Tok: CurTok, DiagID: diag::err_pp_embed_dup_params) << Parameter; |
| 4000 | |
| 4001 | SmallVector<Token, 4> Soup; |
| 4002 | if (!LexParenthesizedBalancedTokenSoup(Soup)) |
| 4003 | return std::nullopt; |
| 4004 | Result.MaybeIfEmptyParam = PPEmbedParameterIfEmpty{ |
| 4005 | std::move(Soup), {ParamStartLoc, CurTok.getLocation()}}; |
| 4006 | } else { |
| 4007 | ++Result.UnrecognizedParams; |
| 4008 | |
| 4009 | // If there's a left paren, we need to parse a balanced token sequence |
| 4010 | // and just eat those tokens. |
| 4011 | if (CurTok.is(K: tok::l_paren)) { |
| 4012 | SmallVector<Token, 4> Soup; |
| 4013 | if (!LexParenthesizedBalancedTokenSoup(Soup)) |
| 4014 | return std::nullopt; |
| 4015 | } |
| 4016 | if (!ForHasEmbed) { |
| 4017 | Diag(Loc: ParamStartLoc, DiagID: diag::err_pp_unknown_parameter) << 1 << Parameter; |
| 4018 | if (CurTok.isNot(K: EndTokenKind)) |
| 4019 | DiscardUntilEndOfDirective(Tmp&: CurTok); |
| 4020 | return std::nullopt; |
| 4021 | } |
| 4022 | } |
| 4023 | } |
| 4024 | return Result; |
| 4025 | } |
| 4026 | |
| 4027 | void Preprocessor::HandleEmbedDirectiveImpl( |
| 4028 | SourceLocation HashLoc, const LexEmbedParametersResult &Params, |
| 4029 | StringRef BinaryContents, StringRef FileName) { |
| 4030 | if (BinaryContents.empty()) { |
| 4031 | // If we have no binary contents, the only thing we need to emit are the |
| 4032 | // if_empty tokens, if any. |
| 4033 | // FIXME: this loses AST fidelity; nothing in the compiler will see that |
| 4034 | // these tokens came from #embed. We have to hack around this when printing |
| 4035 | // preprocessed output. The same is true for prefix and suffix tokens. |
| 4036 | if (Params.MaybeIfEmptyParam) { |
| 4037 | ArrayRef<Token> Toks = Params.MaybeIfEmptyParam->Tokens; |
| 4038 | size_t TokCount = Toks.size(); |
| 4039 | auto NewToks = std::make_unique<Token[]>(num: TokCount); |
| 4040 | llvm::copy(Range&: Toks, Out: NewToks.get()); |
| 4041 | EnterTokenStream(Toks: std::move(NewToks), NumToks: TokCount, DisableMacroExpansion: true, IsReinject: true); |
| 4042 | } |
| 4043 | return; |
| 4044 | } |
| 4045 | |
| 4046 | size_t NumPrefixToks = Params.PrefixTokenCount(), |
| 4047 | NumSuffixToks = Params.SuffixTokenCount(); |
| 4048 | size_t TotalNumToks = 1 + NumPrefixToks + NumSuffixToks; |
| 4049 | size_t CurIdx = 0; |
| 4050 | auto Toks = std::make_unique<Token[]>(num: TotalNumToks); |
| 4051 | |
| 4052 | // Add the prefix tokens, if any. |
| 4053 | if (Params.MaybePrefixParam) { |
| 4054 | llvm::copy(Range: Params.MaybePrefixParam->Tokens, Out: &Toks[CurIdx]); |
| 4055 | CurIdx += NumPrefixToks; |
| 4056 | } |
| 4057 | |
| 4058 | EmbedAnnotationData *Data = new (BP) EmbedAnnotationData; |
| 4059 | Data->BinaryData = BinaryContents; |
| 4060 | Data->FileName = FileName; |
| 4061 | |
| 4062 | Toks[CurIdx].startToken(); |
| 4063 | Toks[CurIdx].setKind(tok::annot_embed); |
| 4064 | Toks[CurIdx].setAnnotationRange(HashLoc); |
| 4065 | Toks[CurIdx++].setAnnotationValue(Data); |
| 4066 | |
| 4067 | // Now add the suffix tokens, if any. |
| 4068 | if (Params.MaybeSuffixParam) { |
| 4069 | llvm::copy(Range: Params.MaybeSuffixParam->Tokens, Out: &Toks[CurIdx]); |
| 4070 | CurIdx += NumSuffixToks; |
| 4071 | } |
| 4072 | |
| 4073 | assert(CurIdx == TotalNumToks && "Calculated the incorrect number of tokens" ); |
| 4074 | EnterTokenStream(Toks: std::move(Toks), NumToks: TotalNumToks, DisableMacroExpansion: true, IsReinject: true); |
| 4075 | } |
| 4076 | |
| 4077 | void Preprocessor::HandleEmbedDirective(SourceLocation HashLoc, |
| 4078 | Token &EmbedTok) { |
| 4079 | // Give the usual extension/compatibility warnings. |
| 4080 | if (LangOpts.C23) |
| 4081 | Diag(Tok: EmbedTok, DiagID: diag::warn_compat_pp_embed_directive); |
| 4082 | else |
| 4083 | Diag(Tok: EmbedTok, DiagID: diag::ext_pp_embed_directive) |
| 4084 | << (LangOpts.CPlusPlus ? /*Clang*/ 1 : /*C23*/ 0); |
| 4085 | |
| 4086 | // Parse the filename header |
| 4087 | Token FilenameTok; |
| 4088 | if (LexHeaderName(Result&: FilenameTok)) |
| 4089 | return; |
| 4090 | |
| 4091 | if (FilenameTok.isNot(K: tok::header_name)) { |
| 4092 | Diag(Loc: FilenameTok.getLocation(), DiagID: diag::err_pp_expects_filename); |
| 4093 | if (FilenameTok.isNot(K: tok::eod)) |
| 4094 | DiscardUntilEndOfDirective(); |
| 4095 | return; |
| 4096 | } |
| 4097 | |
| 4098 | // Parse the optional sequence of |
| 4099 | // directive-parameters: |
| 4100 | // identifier parameter-name-list[opt] directive-argument-list[opt] |
| 4101 | // directive-argument-list: |
| 4102 | // '(' balanced-token-sequence ')' |
| 4103 | // parameter-name-list: |
| 4104 | // '::' identifier parameter-name-list[opt] |
| 4105 | Token CurTok; |
| 4106 | std::optional<LexEmbedParametersResult> Params = |
| 4107 | LexEmbedParameters(CurTok, /*ForHasEmbed=*/false); |
| 4108 | |
| 4109 | assert((Params || CurTok.is(tok::eod)) && |
| 4110 | "expected success or to be at the end of the directive" ); |
| 4111 | if (!Params) |
| 4112 | return; |
| 4113 | |
| 4114 | // Now, splat the data out! |
| 4115 | SmallString<128> FilenameBuffer; |
| 4116 | StringRef Filename = getSpelling(Tok: FilenameTok, Buffer&: FilenameBuffer); |
| 4117 | StringRef OriginalFilename = Filename; |
| 4118 | bool isAngled = |
| 4119 | GetIncludeFilenameSpelling(Loc: FilenameTok.getLocation(), Buffer&: Filename); |
| 4120 | |
| 4121 | // If GetIncludeFilenameSpelling set the start ptr to null, there was an |
| 4122 | // error. |
| 4123 | if (Filename.empty()) |
| 4124 | return; |
| 4125 | |
| 4126 | OptionalFileEntryRef MaybeFileRef = |
| 4127 | this->LookupEmbedFile(Filename, isAngled, /*OpenFile=*/true); |
| 4128 | if (!MaybeFileRef) { |
| 4129 | // could not find file |
| 4130 | if (Callbacks && Callbacks->EmbedFileNotFound(FileName: Filename)) { |
| 4131 | return; |
| 4132 | } |
| 4133 | Diag(Tok: FilenameTok, DiagID: diag::err_pp_file_not_found) << Filename; |
| 4134 | return; |
| 4135 | } |
| 4136 | |
| 4137 | if (MaybeFileRef->isDeviceFile()) { |
| 4138 | Diag(Tok: FilenameTok, DiagID: diag::err_pp_embed_device_file) << Filename; |
| 4139 | return; |
| 4140 | } |
| 4141 | |
| 4142 | std::optional<llvm::MemoryBufferRef> MaybeFile = |
| 4143 | getSourceManager().getMemoryBufferForFileOrNone(File: *MaybeFileRef); |
| 4144 | if (!MaybeFile) { |
| 4145 | // could not find file |
| 4146 | Diag(Tok: FilenameTok, DiagID: diag::err_cannot_open_file) |
| 4147 | << Filename << "a buffer to the contents could not be created" ; |
| 4148 | return; |
| 4149 | } |
| 4150 | StringRef BinaryContents = MaybeFile->getBuffer(); |
| 4151 | |
| 4152 | // The order is important between 'offset' and 'limit'; we want to offset |
| 4153 | // first and then limit second; otherwise we may reduce the notional resource |
| 4154 | // size to something too small to offset into. |
| 4155 | if (Params->MaybeOffsetParam) { |
| 4156 | // FIXME: just like with the limit() and if_empty() parameters, this loses |
| 4157 | // source fidelity in the AST; it has no idea that there was an offset |
| 4158 | // involved. |
| 4159 | // offsets all the way to the end of the file make for an empty file. |
| 4160 | BinaryContents = BinaryContents.substr(Start: Params->MaybeOffsetParam->Offset); |
| 4161 | } |
| 4162 | |
| 4163 | if (Params->MaybeLimitParam) { |
| 4164 | // FIXME: just like with the clang::offset() and if_empty() parameters, |
| 4165 | // this loses source fidelity in the AST; it has no idea there was a limit |
| 4166 | // involved. |
| 4167 | BinaryContents = BinaryContents.substr(Start: 0, N: Params->MaybeLimitParam->Limit); |
| 4168 | } |
| 4169 | |
| 4170 | if (Callbacks) |
| 4171 | Callbacks->EmbedDirective(HashLoc, FileName: Filename, IsAngled: isAngled, File: MaybeFileRef, |
| 4172 | Params: *Params); |
| 4173 | // getSpelling() may return a buffer from the token itself or it may use the |
| 4174 | // SmallString buffer we provided. getSpelling() may also return a string that |
| 4175 | // is actually longer than FilenameTok.getLength(), so we first pass a |
| 4176 | // locally created buffer to getSpelling() to get the string of real length |
| 4177 | // and then we allocate a long living buffer because the buffer we used |
| 4178 | // previously will only live till the end of this function and we need |
| 4179 | // filename info to live longer. |
| 4180 | void *Mem = BP.Allocate(Size: OriginalFilename.size(), Alignment: alignof(char *)); |
| 4181 | memcpy(dest: Mem, src: OriginalFilename.data(), n: OriginalFilename.size()); |
| 4182 | StringRef FilenameToGo = |
| 4183 | StringRef(static_cast<char *>(Mem), OriginalFilename.size()); |
| 4184 | HandleEmbedDirectiveImpl(HashLoc, Params: *Params, BinaryContents, FileName: FilenameToGo); |
| 4185 | } |
| 4186 | |
| 4187 | /// HandleCXXImportDirective - Handle the C++ modules import directives |
| 4188 | /// |
| 4189 | /// pp-import: |
| 4190 | /// export[opt] import header-name pp-tokens[opt] ; new-line |
| 4191 | /// export[opt] import header-name-tokens pp-tokens[opt] ; new-line |
| 4192 | /// export[opt] import pp-tokens ; new-line |
| 4193 | /// |
| 4194 | /// The header importing are replaced by annot_header_unit token, and the |
| 4195 | /// lexed module name are replaced by annot_module_name token. |
| 4196 | void Preprocessor::HandleCXXImportDirective(Token ImportTok) { |
| 4197 | assert(getLangOpts().CPlusPlusModules && ImportTok.is(tok::kw_import)); |
| 4198 | llvm::SaveAndRestore<bool> SaveImportingCXXModules( |
| 4199 | this->ImportingCXXNamedModules, true); |
| 4200 | |
| 4201 | if (LastTokenWasExportKeyword.isValid()) |
| 4202 | LastTokenWasExportKeyword.reset(); |
| 4203 | |
| 4204 | Token Tok; |
| 4205 | if (LexHeaderName(Result&: Tok)) { |
| 4206 | if (Tok.isNot(K: tok::eod)) |
| 4207 | CheckEndOfDirective(DirType: ImportTok.getIdentifierInfo()->getName()); |
| 4208 | return; |
| 4209 | } |
| 4210 | |
| 4211 | SourceLocation UseLoc = ImportTok.getLocation(); |
| 4212 | SmallVector<Token, 4> DirToks{ImportTok}; |
| 4213 | SmallVector<IdentifierLoc, 2> Path; |
| 4214 | bool = false; |
| 4215 | bool IsPartition = false; |
| 4216 | std::string FlatName; |
| 4217 | switch (Tok.getKind()) { |
| 4218 | case tok::header_name: |
| 4219 | ImportingHeader = true; |
| 4220 | DirToks.push_back(Elt: Tok); |
| 4221 | Lex(Result&: DirToks.emplace_back()); |
| 4222 | break; |
| 4223 | case tok::colon: |
| 4224 | IsPartition = true; |
| 4225 | DirToks.push_back(Elt: Tok); |
| 4226 | UseLoc = Tok.getLocation(); |
| 4227 | Lex(Result&: Tok); |
| 4228 | [[fallthrough]]; |
| 4229 | case tok::identifier: { |
| 4230 | bool LeadingSpace = Tok.hasLeadingSpace(); |
| 4231 | unsigned NumToksInDirective = DirToks.size(); |
| 4232 | if (LexModuleNameContinue(Tok, UseLoc, Suffix&: DirToks, Path)) { |
| 4233 | if (Tok.isNot(K: tok::eod)) |
| 4234 | CheckEndOfDirective(DirType: ImportTok.getIdentifierInfo()->getName(), |
| 4235 | /*EnableMacros=*/false, ExtraToks: &DirToks); |
| 4236 | EnterModuleSuffixTokenStream(Toks: DirToks); |
| 4237 | return; |
| 4238 | } |
| 4239 | |
| 4240 | // Clean the module-name tokens and replace these tokens with |
| 4241 | // annot_module_name. |
| 4242 | DirToks.resize(N: NumToksInDirective); |
| 4243 | ModuleNameLoc *NameLoc = ModuleNameLoc::Create(PP&: *this, Path); |
| 4244 | DirToks.emplace_back(); |
| 4245 | DirToks.back().setKind(tok::annot_module_name); |
| 4246 | DirToks.back().setAnnotationRange(NameLoc->getRange()); |
| 4247 | DirToks.back().setAnnotationValue(static_cast<void *>(NameLoc)); |
| 4248 | DirToks.back().setFlagValue(Flag: Token::LeadingSpace, Val: LeadingSpace); |
| 4249 | DirToks.push_back(Elt: Tok); |
| 4250 | |
| 4251 | bool IsValid = |
| 4252 | (IsPartition && ModuleDeclState.isNamedModule()) || !IsPartition; |
| 4253 | if (Callbacks && IsValid) { |
| 4254 | if (IsPartition && ModuleDeclState.isNamedModule()) { |
| 4255 | FlatName += ModuleDeclState.getPrimaryName(); |
| 4256 | FlatName += ":" ; |
| 4257 | } |
| 4258 | |
| 4259 | FlatName += ModuleLoader::getFlatNameFromPath(Path); |
| 4260 | SourceLocation StartLoc = IsPartition ? UseLoc : Path[0].getLoc(); |
| 4261 | IdentifierLoc FlatNameLoc(StartLoc, getIdentifierInfo(Name: FlatName)); |
| 4262 | |
| 4263 | // We don't/shouldn't load the standard c++20 modules when preprocessing. |
| 4264 | // so the imported module is nullptr. |
| 4265 | Callbacks->moduleImport(ImportLoc: ImportTok.getLocation(), |
| 4266 | Path: ModuleIdPath(FlatNameLoc), |
| 4267 | /*Imported=*/nullptr); |
| 4268 | } |
| 4269 | break; |
| 4270 | } |
| 4271 | default: |
| 4272 | DirToks.push_back(Elt: Tok); |
| 4273 | break; |
| 4274 | } |
| 4275 | |
| 4276 | // Consume the pp-import-suffix and expand any macros in it now, if we're not |
| 4277 | // at the semicolon already. |
| 4278 | if (!DirToks.back().isOneOf(Ks: tok::semi, Ks: tok::eod)) |
| 4279 | CollectPPImportSuffix(Toks&: DirToks); |
| 4280 | |
| 4281 | if (DirToks.back().isNot(K: tok::eod)) |
| 4282 | CheckEndOfDirective(DirType: ImportTok.getIdentifierInfo()->getName()); |
| 4283 | else |
| 4284 | DirToks.pop_back(); |
| 4285 | |
| 4286 | // This is not a pp-import after all. |
| 4287 | if (DirToks.back().isNot(K: tok::semi)) { |
| 4288 | EnterModuleSuffixTokenStream(Toks: DirToks); |
| 4289 | return; |
| 4290 | } |
| 4291 | |
| 4292 | if (ImportingHeader) { |
| 4293 | // C++2a [cpp.module]p1: |
| 4294 | // The ';' preprocessing-token terminating a pp-import shall not have |
| 4295 | // been produced by macro replacement. |
| 4296 | SourceLocation SemiLoc = DirToks.back().getLocation(); |
| 4297 | if (SemiLoc.isMacroID()) |
| 4298 | Diag(Loc: SemiLoc, DiagID: diag::err_header_import_semi_in_macro); |
| 4299 | |
| 4300 | auto Action = HandleHeaderIncludeOrImport( |
| 4301 | /*HashLoc*/ SourceLocation(), IncludeTok&: ImportTok, FilenameTok&: Tok, EndLoc: SemiLoc); |
| 4302 | switch (Action.Kind) { |
| 4303 | case ImportAction::None: |
| 4304 | break; |
| 4305 | |
| 4306 | case ImportAction::ModuleBegin: |
| 4307 | // Let the parser know we're textually entering the module. |
| 4308 | DirToks.emplace_back(); |
| 4309 | DirToks.back().startToken(); |
| 4310 | DirToks.back().setKind(tok::annot_module_begin); |
| 4311 | DirToks.back().setLocation(SemiLoc); |
| 4312 | DirToks.back().setAnnotationEndLoc(SemiLoc); |
| 4313 | DirToks.back().setAnnotationValue(Action.ModuleForHeader); |
| 4314 | [[fallthrough]]; |
| 4315 | |
| 4316 | case ImportAction::ModuleImport: |
| 4317 | case ImportAction::HeaderUnitImport: |
| 4318 | case ImportAction::SkippedModuleImport: |
| 4319 | // We chose to import (or textually enter) the file. Convert the |
| 4320 | // header-name token into a header unit annotation token. |
| 4321 | DirToks[1].setKind(tok::annot_header_unit); |
| 4322 | DirToks[1].setAnnotationEndLoc(DirToks[0].getLocation()); |
| 4323 | DirToks[1].setAnnotationValue(Action.ModuleForHeader); |
| 4324 | // FIXME: Call the moduleImport callback? |
| 4325 | break; |
| 4326 | case ImportAction::Failure: |
| 4327 | assert(TheModuleLoader.HadFatalFailure && |
| 4328 | "This should be an early exit only to a fatal error" ); |
| 4329 | CurLexer->cutOffLexing(); |
| 4330 | return; |
| 4331 | } |
| 4332 | } |
| 4333 | |
| 4334 | EnterModuleSuffixTokenStream(Toks: DirToks); |
| 4335 | } |
| 4336 | |
| 4337 | /// HandleCXXModuleDirective - Handle C++ module declaration directives. |
| 4338 | /// |
| 4339 | /// pp-module: |
| 4340 | /// export[opt] module pp-tokens[opt] ; new-line |
| 4341 | /// |
| 4342 | /// pp-module-name: |
| 4343 | /// pp-module-name-qualifier[opt] identifier |
| 4344 | /// pp-module-partition: |
| 4345 | /// : pp-module-name-qualifier[opt] identifier |
| 4346 | /// pp-module-name-qualifier: |
| 4347 | /// identifier . |
| 4348 | /// pp-module-name-qualifier identifier . |
| 4349 | /// |
| 4350 | /// global-module-fragment: |
| 4351 | /// module-keyword ; declaration-seq[opt] |
| 4352 | /// |
| 4353 | /// private-module-fragment: |
| 4354 | /// module-keyword : private ; declaration-seq[opt] |
| 4355 | /// |
| 4356 | /// The lexed module name are replaced by annot_module_name token. |
| 4357 | void Preprocessor::HandleCXXModuleDirective(Token ModuleTok) { |
| 4358 | assert(getLangOpts().CPlusPlusModules && ModuleTok.is(tok::kw_module)); |
| 4359 | Token Introducer = ModuleTok; |
| 4360 | if (LastTokenWasExportKeyword.isValid()) { |
| 4361 | Introducer = LastTokenWasExportKeyword.getExportTok(); |
| 4362 | LastTokenWasExportKeyword.reset(); |
| 4363 | } |
| 4364 | |
| 4365 | SourceLocation StartLoc = Introducer.getLocation(); |
| 4366 | |
| 4367 | Token Tok; |
| 4368 | SourceLocation UseLoc = ModuleTok.getLocation(); |
| 4369 | SmallVector<Token, 4> DirToks{ModuleTok}; |
| 4370 | SmallVector<IdentifierLoc, 2> Path, Partition; |
| 4371 | LexUnexpandedToken(Result&: Tok); |
| 4372 | |
| 4373 | switch (Tok.getKind()) { |
| 4374 | // Global Module Fragment. |
| 4375 | case tok::semi: |
| 4376 | DirToks.push_back(Elt: Tok); |
| 4377 | break; |
| 4378 | case tok::colon: |
| 4379 | DirToks.push_back(Elt: Tok); |
| 4380 | LexUnexpandedToken(Result&: Tok); |
| 4381 | if (Tok.isNot(K: tok::kw_private)) { |
| 4382 | if (Tok.isNot(K: tok::eod)) |
| 4383 | CheckEndOfDirective(DirType: ModuleTok.getIdentifierInfo()->getName(), |
| 4384 | /*EnableMacros=*/false, ExtraToks: &DirToks); |
| 4385 | EnterModuleSuffixTokenStream(Toks: DirToks); |
| 4386 | return; |
| 4387 | } |
| 4388 | DirToks.push_back(Elt: Tok); |
| 4389 | break; |
| 4390 | case tok::identifier: { |
| 4391 | bool LeadingSpace = Tok.hasLeadingSpace(); |
| 4392 | unsigned NumToksInDirective = DirToks.size(); |
| 4393 | |
| 4394 | // C++ [cpp.module]p3: Any preprocessing tokens after the module |
| 4395 | // preprocessing token in the module directive are processed just as in |
| 4396 | // normal text. |
| 4397 | // |
| 4398 | // P3034R1 Module Declarations Shouldn’t be Macros. |
| 4399 | if (LexModuleNameContinue(Tok, UseLoc, Suffix&: DirToks, Path, |
| 4400 | /*AllowMacroExpansion=*/false)) { |
| 4401 | if (Tok.isNot(K: tok::eod)) |
| 4402 | CheckEndOfDirective(DirType: ModuleTok.getIdentifierInfo()->getName(), |
| 4403 | /*EnableMacros=*/false, ExtraToks: &DirToks); |
| 4404 | EnterModuleSuffixTokenStream(Toks: DirToks); |
| 4405 | return; |
| 4406 | } |
| 4407 | |
| 4408 | ModuleNameLoc *NameLoc = ModuleNameLoc::Create(PP&: *this, Path); |
| 4409 | DirToks.resize(N: NumToksInDirective); |
| 4410 | DirToks.emplace_back(); |
| 4411 | DirToks.back().setKind(tok::annot_module_name); |
| 4412 | DirToks.back().setAnnotationRange(NameLoc->getRange()); |
| 4413 | DirToks.back().setAnnotationValue(static_cast<void *>(NameLoc)); |
| 4414 | DirToks.back().setFlagValue(Flag: Token::LeadingSpace, Val: LeadingSpace); |
| 4415 | DirToks.push_back(Elt: Tok); |
| 4416 | |
| 4417 | // C++20 [cpp.module]p |
| 4418 | // The pp-tokens, if any, of a pp-module shall be of the form: |
| 4419 | // pp-module-name pp-module-partition[opt] pp-tokens[opt] |
| 4420 | if (Tok.is(K: tok::colon)) { |
| 4421 | NumToksInDirective = DirToks.size(); |
| 4422 | LexUnexpandedToken(Result&: Tok); |
| 4423 | LeadingSpace = Tok.hasLeadingSpace(); |
| 4424 | if (LexModuleNameContinue(Tok, UseLoc, Suffix&: DirToks, Path&: Partition, |
| 4425 | /*AllowMacroExpansion=*/false, |
| 4426 | /*IsPartition=*/true)) { |
| 4427 | if (Tok.isNot(K: tok::eod)) |
| 4428 | CheckEndOfDirective(DirType: ModuleTok.getIdentifierInfo()->getName(), |
| 4429 | /*EnableMacros=*/false, ExtraToks: &DirToks); |
| 4430 | EnterModuleSuffixTokenStream(Toks: DirToks); |
| 4431 | return; |
| 4432 | } |
| 4433 | |
| 4434 | ModuleNameLoc *PartitionLoc = ModuleNameLoc::Create(PP&: *this, Path: Partition); |
| 4435 | DirToks.resize(N: NumToksInDirective); |
| 4436 | DirToks.emplace_back(); |
| 4437 | DirToks.back().setKind(tok::annot_module_name); |
| 4438 | DirToks.back().setAnnotationRange(NameLoc->getRange()); |
| 4439 | DirToks.back().setAnnotationValue(static_cast<void *>(PartitionLoc)); |
| 4440 | DirToks.back().setFlagValue(Flag: Token::LeadingSpace, Val: LeadingSpace); |
| 4441 | DirToks.push_back(Elt: Tok); |
| 4442 | } |
| 4443 | |
| 4444 | // If the current token is a macro definition, put it back to token stream |
| 4445 | // and expand any macros in it later. |
| 4446 | // |
| 4447 | // export module M ATTR(some_attr); // -D'ATTR(x)=[[x]]' |
| 4448 | // |
| 4449 | // Current token is `ATTR`. |
| 4450 | if (Tok.is(K: tok::identifier) && |
| 4451 | getMacroDefinition(II: Tok.getIdentifierInfo())) { |
| 4452 | std::unique_ptr<Token[]> TokCopy = std::make_unique<Token[]>(num: 1); |
| 4453 | TokCopy[0] = Tok; |
| 4454 | EnterTokenStream(Toks: std::move(TokCopy), /*NumToks=*/1, |
| 4455 | /*DisableMacroExpansion=*/false, /*IsReinject=*/false); |
| 4456 | Lex(Result&: Tok); |
| 4457 | DirToks.back() = Tok; |
| 4458 | } |
| 4459 | break; |
| 4460 | } |
| 4461 | default: |
| 4462 | DirToks.push_back(Elt: Tok); |
| 4463 | break; |
| 4464 | } |
| 4465 | |
| 4466 | // Consume the pp-import-suffix and expand any macros in it now, if we're not |
| 4467 | // at the semicolon already. |
| 4468 | SourceLocation End = DirToks.back().getLocation(); |
| 4469 | std::optional<Token> NextPPTok = DirToks.back(); |
| 4470 | if (DirToks.back().is(K: tok::eod)) { |
| 4471 | NextPPTok = peekNextPPToken(); |
| 4472 | if (NextPPTok && NextPPTok->is(K: tok::raw_identifier)) |
| 4473 | LookUpIdentifierInfo(Identifier&: *NextPPTok); |
| 4474 | } |
| 4475 | |
| 4476 | // Only ';' and '[' are allowed after module name. |
| 4477 | // We also check 'private' because the previous is not a module name. |
| 4478 | if (!NextPPTok->isOneOf(Ks: tok::semi, Ks: tok::eod, Ks: tok::l_square, Ks: tok::kw_private)) |
| 4479 | Diag(Tok: *NextPPTok, DiagID: diag::err_pp_unexpected_tok_after_module_name) |
| 4480 | << getSpelling(Tok: *NextPPTok); |
| 4481 | |
| 4482 | if (!DirToks.back().isOneOf(Ks: tok::semi, Ks: tok::eod)) { |
| 4483 | // Consume the pp-import-suffix and expand any macros in it now. We'll add |
| 4484 | // it back into the token stream later. |
| 4485 | CollectPPImportSuffix(Toks&: DirToks); |
| 4486 | End = DirToks.back().getLocation(); |
| 4487 | } |
| 4488 | |
| 4489 | if (DirToks.back().isNot(K: tok::eod)) |
| 4490 | End = CheckEndOfDirective(DirType: ModuleTok.getIdentifierInfo()->getName(), |
| 4491 | /*EnableMacros=*/false, ExtraToks: &DirToks); |
| 4492 | else |
| 4493 | End = DirToks.pop_back_val().getLocation(); |
| 4494 | |
| 4495 | if (!IncludeMacroStack.empty()) { |
| 4496 | Diag(Loc: StartLoc, DiagID: diag::err_pp_module_decl_in_header) |
| 4497 | << SourceRange(StartLoc, End); |
| 4498 | } |
| 4499 | |
| 4500 | if (CurPPLexer->getConditionalStackDepth() != 0) { |
| 4501 | Diag(Loc: StartLoc, DiagID: diag::err_pp_cond_span_module_decl) |
| 4502 | << SourceRange(StartLoc, End); |
| 4503 | } |
| 4504 | EnterModuleSuffixTokenStream(Toks: DirToks); |
| 4505 | } |
| 4506 | |