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