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