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