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