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 LexHeaderName(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::header_name)) {
1642 Diag(StrTok, diag::err_pp_line_invalid_filename);
1644 return;
1645 } else {
1646 SmallString<128> FilenameBuffer;
1647 StringRef Filename = getSpelling(StrTok, FilenameBuffer);
1649 FilenameID = SourceMgr.getLineTableFilenameID(Filename);
1650
1651 // Verify that there is nothing after the string, other than EOD. Because
1652 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1653 CheckEndOfDirective("line", true);
1654 }
1655
1656 // Take the file kind of the file containing the #line directive. #line
1657 // directives are often used for generated sources from the same codebase, so
1658 // the new file should generally be classified the same way as the current
1659 // file. This is visible in GCC's pre-processed output, which rewrites #line
1660 // to GNU line markers.
1662 SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1663
1664 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false,
1665 false, FileKind);
1666
1667 if (Callbacks)
1668 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
1669 PPCallbacks::RenameFile, FileKind);
1670}
1671
1672/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1673/// marker directive.
1674static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
1676 Preprocessor &PP) {
1677 unsigned FlagVal;
1678 Token FlagTok;
1679 PP.Lex(FlagTok);
1680 if (FlagTok.is(tok::eod)) return false;
1681 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1682 return true;
1683
1684 if (FlagVal == 1) {
1685 IsFileEntry = true;
1686
1687 PP.Lex(FlagTok);
1688 if (FlagTok.is(tok::eod)) return false;
1689 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1690 return true;
1691 } else if (FlagVal == 2) {
1692 IsFileExit = true;
1693
1695 // If we are leaving the current presumed file, check to make sure the
1696 // presumed include stack isn't empty!
1697 FileID CurFileID =
1698 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
1699 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
1700 if (PLoc.isInvalid())
1701 return true;
1702
1703 // If there is no include loc (main file) or if the include loc is in a
1704 // different physical file, then we aren't in a "1" line marker flag region.
1705 SourceLocation IncLoc = PLoc.getIncludeLoc();
1706 if (IncLoc.isInvalid() ||
1707 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
1708 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1710 return true;
1711 }
1712
1713 PP.Lex(FlagTok);
1714 if (FlagTok.is(tok::eod)) return false;
1715 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1716 return true;
1717 }
1718
1719 // We must have 3 if there are still flags.
1720 if (FlagVal != 3) {
1721 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1723 return true;
1724 }
1725
1726 FileKind = SrcMgr::C_System;
1727
1728 PP.Lex(FlagTok);
1729 if (FlagTok.is(tok::eod)) return false;
1730 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1731 return true;
1732
1733 // We must have 4 if there is yet another flag.
1734 if (FlagVal != 4) {
1735 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1737 return true;
1738 }
1739
1740 FileKind = SrcMgr::C_ExternCSystem;
1741
1742 PP.Lex(FlagTok);
1743 if (FlagTok.is(tok::eod)) return false;
1744
1745 // There are no more valid flags here.
1746 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1748 return true;
1749}
1750
1751/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1752/// one of the following forms:
1753///
1754/// # 42
1755/// # 42 "file" ('1' | '2')?
1756/// # 42 "file" ('1' | '2')? '3' '4'?
1757///
1758void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1759 // Validate the number and convert it to an unsigned. GNU does not have a
1760 // line # limit other than it fit in 32-bits.
1761 unsigned LineNo;
1762 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
1763 *this, true))
1764 return;
1765
1766 Token StrTok;
1767 LexHeaderName(StrTok);
1768
1769 bool IsFileEntry = false, IsFileExit = false;
1770 int FilenameID = -1;
1772
1773 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1774 // string followed by eod.
1775 if (StrTok.is(tok::eod)) {
1776 Diag(StrTok, diag::ext_pp_gnu_line_directive);
1777 // Treat this like "#line NN", which doesn't change file characteristics.
1778 FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1779 } else if (StrTok.isNot(tok::header_name)) {
1780 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1782 return;
1783 } else {
1784 SmallString<128> FilenameBuffer;
1785 StringRef Filename = getSpelling(StrTok, FilenameBuffer);
1787 // If a filename was present, read any flags that are present.
1788 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
1789 return;
1790 if (!SourceMgr.isInPredefinedFile(DigitTok.getLocation()))
1791 Diag(StrTok, diag::ext_pp_gnu_line_directive);
1792
1793 // Exiting to an empty string means pop to the including file, so leave
1794 // FilenameID as -1 in that case.
1795 if (!(IsFileExit && Filename.empty()))
1796 FilenameID = SourceMgr.getLineTableFilenameID(Filename);
1797 }
1798
1799 // Create a line note with this information.
1800 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry,
1801 IsFileExit, FileKind);
1802
1803 // If the preprocessor has callbacks installed, notify them of the #line
1804 // change. This is used so that the line marker comes out in -E mode for
1805 // example.
1806 if (Callbacks) {
1808 if (IsFileEntry)
1809 Reason = PPCallbacks::EnterFile;
1810 else if (IsFileExit)
1811 Reason = PPCallbacks::ExitFile;
1812
1813 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
1814 }
1815}
1816
1817/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1818///
1819void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
1820 bool isWarning) {
1821 // Read the rest of the line raw. We do this because we don't want macros
1822 // to be expanded and we don't require that the tokens be valid preprocessing
1823 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1824 // collapse multiple consecutive white space between tokens, but this isn't
1825 // specified by the standard.
1826 SmallString<128> Message;
1827 CurLexer->ReadToEndOfLine(&Message);
1828
1829 // Find the first non-whitespace character, so that we can make the
1830 // diagnostic more succinct.
1831 StringRef Msg = Message.str().ltrim(' ');
1832
1833 if (isWarning)
1834 Diag(Tok, diag::pp_hash_warning) << Msg;
1835 else
1836 Diag(Tok, diag::err_pp_hash_error) << Msg;
1837}
1838
1839/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1840///
1841void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1842 // Yes, this directive is an extension.
1843 Diag(Tok, diag::ext_pp_ident_directive);
1844
1845 // Read the string argument.
1846 Token StrTok;
1847 Lex(StrTok);
1848
1849 // If the token kind isn't a string, it's a malformed directive.
1850 if (StrTok.isNot(tok::string_literal) &&
1851 StrTok.isNot(tok::wide_string_literal)) {
1852 Diag(StrTok, diag::err_pp_malformed_ident);
1853 if (StrTok.isNot(tok::eod))
1855 return;
1856 }
1857
1858 if (StrTok.hasUDSuffix()) {
1859 Diag(StrTok, diag::err_invalid_string_udl);
1861 return;
1862 }
1863
1864 // Verify that there is nothing after the string, other than EOD.
1865 CheckEndOfDirective("ident");
1866
1867 if (Callbacks) {
1868 bool Invalid = false;
1869 std::string Str = getSpelling(StrTok, &Invalid);
1870 if (!Invalid)
1871 Callbacks->Ident(Tok.getLocation(), Str);
1872 }
1873}
1874
1875/// Handle a #public directive.
1876void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
1877 Token MacroNameTok;
1878 ReadMacroName(MacroNameTok, MU_Undef);
1879
1880 // Error reading macro name? If so, diagnostic already issued.
1881 if (MacroNameTok.is(tok::eod))
1882 return;
1883
1884 // Check to see if this is the last token on the #__public_macro line.
1885 CheckEndOfDirective("__public_macro");
1886
1887 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1888 // Okay, we finally have a valid identifier to undef.
1889 MacroDirective *MD = getLocalMacroDirective(II);
1890
1891 // If the macro is not defined, this is an error.
1892 if (!MD) {
1893 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
1894 return;
1895 }
1896
1897 // Note that this macro has now been exported.
1898 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1899 MacroNameTok.getLocation(), /*isPublic=*/true));
1900}
1901
1902/// Handle a #private directive.
1903void Preprocessor::HandleMacroPrivateDirective() {
1904 Token MacroNameTok;
1905 ReadMacroName(MacroNameTok, MU_Undef);
1906
1907 // Error reading macro name? If so, diagnostic already issued.
1908 if (MacroNameTok.is(tok::eod))
1909 return;
1910
1911 // Check to see if this is the last token on the #__private_macro line.
1912 CheckEndOfDirective("__private_macro");
1913
1914 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1915 // Okay, we finally have a valid identifier to undef.
1916 MacroDirective *MD = getLocalMacroDirective(II);
1917
1918 // If the macro is not defined, this is an error.
1919 if (!MD) {
1920 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
1921 return;
1922 }
1923
1924 // Note that this macro has now been marked private.
1925 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1926 MacroNameTok.getLocation(), /*isPublic=*/false));
1927}
1928
1929//===----------------------------------------------------------------------===//
1930// Preprocessor Include Directive Handling.
1931//===----------------------------------------------------------------------===//
1932
1933/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1934/// checked and spelled filename, e.g. as an operand of \#include. This returns
1935/// true if the input filename was in <>'s or false if it were in ""'s. The
1936/// caller is expected to provide a buffer that is large enough to hold the
1937/// spelling of the filename, but is also expected to handle the case when
1938/// this method decides to use a different buffer.
1940 StringRef &Buffer) {
1941 // Get the text form of the filename.
1942 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
1943
1944 // FIXME: Consider warning on some of the cases described in C11 6.4.7/3 and
1945 // C++20 [lex.header]/2:
1946 //
1947 // If `"`, `'`, `\`, `/*`, or `//` appears in a header-name, then
1948 // in C: behavior is undefined
1949 // in C++: program is conditionally-supported with implementation-defined
1950 // semantics
1951
1952 // Make sure the filename is <x> or "x".
1953 bool isAngled;
1954 if (Buffer[0] == '<') {
1955 if (Buffer.back() != '>') {
1956 Diag(Loc, diag::err_pp_expects_filename);
1957 Buffer = StringRef();
1958 return true;
1959 }
1960 isAngled = true;
1961 } else if (Buffer[0] == '"') {
1962 if (Buffer.back() != '"') {
1963 Diag(Loc, diag::err_pp_expects_filename);
1964 Buffer = StringRef();
1965 return true;
1966 }
1967 isAngled = false;
1968 } else {
1969 Diag(Loc, diag::err_pp_expects_filename);
1970 Buffer = StringRef();
1971 return true;
1972 }
1973
1974 // Diagnose #include "" as invalid.
1975 if (Buffer.size() <= 2) {
1976 Diag(Loc, diag::err_pp_empty_filename);
1977 Buffer = StringRef();
1978 return true;
1979 }
1980
1981 // Skip the brackets.
1982 Buffer = Buffer.substr(1, Buffer.size()-2);
1983 return isAngled;
1984}
1985
1987 StringRef &Buffer) {
1988 // Get the text form of the filename.
1989 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
1990 if (Buffer.size() < 2 || Buffer.front() != '"' || Buffer.back() != '"') {
1991 Diag(Loc, diag::err_pp_line_invalid_filename);
1992 Buffer = StringRef();
1993 return;
1994 }
1995 Buffer = Buffer.substr(1, Buffer.size() - 2);
1996}
1997
1998/// Push a token onto the token stream containing an annotation.
2000 tok::TokenKind Kind,
2001 void *AnnotationVal) {
2002 // FIXME: Produce this as the current token directly, rather than
2003 // allocating a new token for it.
2004 auto Tok = std::make_unique<Token[]>(1);
2005 Tok[0].startToken();
2006 Tok[0].setKind(Kind);
2007 Tok[0].setLocation(Range.getBegin());
2008 Tok[0].setAnnotationEndLoc(Range.getEnd());
2009 Tok[0].setAnnotationValue(AnnotationVal);
2010 EnterTokenStream(std::move(Tok), 1, true, /*IsReinject*/ false);
2011}
2012
2013/// Produce a diagnostic informing the user that a #include or similar
2014/// was implicitly treated as a module import.
2016 Token &IncludeTok,
2018 SourceLocation PathEnd) {
2019 SmallString<128> PathString;
2020 for (size_t I = 0, N = Path.size(); I != N; ++I) {
2021 if (I)
2022 PathString += '.';
2023 PathString += Path[I].getIdentifierInfo()->getName();
2024 }
2025
2026 int IncludeKind = 0;
2027 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
2028 case tok::pp_include:
2029 IncludeKind = 0;
2030 break;
2031
2032 case tok::pp_import:
2033 IncludeKind = 1;
2034 break;
2035
2036 case tok::pp_include_next:
2037 IncludeKind = 2;
2038 break;
2039
2040 case tok::pp___include_macros:
2041 IncludeKind = 3;
2042 break;
2043
2044 default:
2045 llvm_unreachable("unknown include directive kind");
2046 }
2047
2048 PP.Diag(HashLoc, diag::remark_pp_include_directive_modular_translation)
2049 << IncludeKind << PathString;
2050}
2051
2052// Given a vector of path components and a string containing the real
2053// path to the file, build a properly-cased replacement in the vector,
2054// and return true if the replacement should be suggested.
2056 StringRef RealPathName,
2057 llvm::sys::path::Style Separator) {
2058 auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
2059 auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
2060 int Cnt = 0;
2061 bool SuggestReplacement = false;
2062
2063 auto IsSep = [Separator](StringRef Component) {
2064 return Component.size() == 1 &&
2065 llvm::sys::path::is_separator(Component[0], Separator);
2066 };
2067
2068 // Below is a best-effort to handle ".." in paths. It is admittedly
2069 // not 100% correct in the presence of symlinks.
2070 for (auto &Component : llvm::reverse(Components)) {
2071 if ("." == Component) {
2072 } else if (".." == Component) {
2073 ++Cnt;
2074 } else if (Cnt) {
2075 --Cnt;
2076 } else if (RealPathComponentIter != RealPathComponentEnd) {
2077 if (!IsSep(Component) && !IsSep(*RealPathComponentIter) &&
2078 Component != *RealPathComponentIter) {
2079 // If these non-separator path components differ by more than just case,
2080 // then we may be looking at symlinked paths. Bail on this diagnostic to
2081 // avoid noisy false positives.
2082 SuggestReplacement =
2083 RealPathComponentIter->equals_insensitive(Component);
2084 if (!SuggestReplacement)
2085 break;
2086 Component = *RealPathComponentIter;
2087 }
2088 ++RealPathComponentIter;
2089 }
2090 }
2091 return SuggestReplacement;
2092}
2093
2095 const TargetInfo &TargetInfo,
2096 const Module &M,
2097 DiagnosticsEngine &Diags) {
2098 Module::Requirement Requirement;
2100 Module *ShadowingModule = nullptr;
2101 if (M.isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader,
2102 ShadowingModule))
2103 return false;
2104
2105 if (MissingHeader.FileNameLoc.isValid()) {
2106 Diags.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
2107 << MissingHeader.IsUmbrella << MissingHeader.FileName;
2108 } else if (ShadowingModule) {
2109 Diags.Report(M.DefinitionLoc, diag::err_module_shadowed) << M.Name;
2110 Diags.Report(ShadowingModule->DefinitionLoc,
2111 diag::note_previous_definition);
2112 } else {
2113 // FIXME: Track the location at which the requirement was specified, and
2114 // use it here.
2115 Diags.Report(M.DefinitionLoc, diag::err_module_unavailable)
2116 << M.getFullModuleName() << Requirement.RequiredState
2117 << Requirement.FeatureName;
2118 }
2119 return true;
2120}
2121
2122std::pair<ConstSearchDirIterator, const FileEntry *>
2123Preprocessor::getIncludeNextStart(const Token &IncludeNextTok) const {
2124 // #include_next is like #include, except that we start searching after
2125 // the current found directory. If we can't do this, issue a
2126 // diagnostic.
2127 ConstSearchDirIterator Lookup = CurDirLookup;
2128 const FileEntry *LookupFromFile = nullptr;
2129
2130 if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
2131 // If the main file is a header, then it's either for PCH/AST generation,
2132 // or libclang opened it. Either way, handle it as a normal include below
2133 // and do not complain about include_next.
2134 } else if (isInPrimaryFile()) {
2135 Lookup = nullptr;
2136 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
2137 } else if (CurLexerSubmodule) {
2138 // Start looking up in the directory *after* the one in which the current
2139 // file would be found, if any.
2140 assert(CurPPLexer && "#include_next directive in macro?");
2141 if (auto FE = CurPPLexer->getFileEntry())
2142 LookupFromFile = *FE;
2143 Lookup = nullptr;
2144 } else if (!Lookup) {
2145 // The current file was not found by walking the include path. Either it
2146 // is the primary file (handled above), or it was found by absolute path,
2147 // or it was found relative to such a file.
2148 // FIXME: Track enough information so we know which case we're in.
2149 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
2150 } else {
2151 // Start looking up in the next directory.
2152 ++Lookup;
2153 }
2154
2155 return {Lookup, LookupFromFile};
2156}
2157
2158/// HandleIncludeDirective - The "\#include" tokens have just been read, read
2159/// the file to be included from the lexer, then include it! This is a common
2160/// routine with functionality shared between \#include, \#include_next and
2161/// \#import. LookupFrom is set when this is a \#include_next directive, it
2162/// specifies the file to start searching from.
2163void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
2164 Token &IncludeTok,
2165 ConstSearchDirIterator LookupFrom,
2166 const FileEntry *LookupFromFile) {
2167 Token FilenameTok;
2168 if (LexHeaderName(FilenameTok))
2169 return;
2170
2171 if (FilenameTok.isNot(tok::header_name)) {
2172 if (FilenameTok.is(tok::identifier) &&
2173 (PPOpts.SingleFileParseMode || PPOpts.SingleModuleParseMode)) {
2174 // If we saw #include IDENTIFIER and lexing didn't turn in into a header
2175 // name, it was undefined. In 'single-{file,module}-parse' mode, just skip
2176 // the directive without emitting diagnostics - the identifier might be
2177 // normally defined in previously-skipped include directive.
2179 return;
2180 }
2181
2182 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
2183 if (FilenameTok.isNot(tok::eod))
2185 return;
2186 }
2187
2188 // Verify that there is nothing after the filename, other than EOD. Note
2189 // that we allow macros that expand to nothing after the filename, because
2190 // this falls into the category of "#include pp-tokens new-line" specified
2191 // in C99 6.10.2p4.
2192 SourceLocation EndLoc =
2193 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
2194
2195 auto Action = HandleHeaderIncludeOrImport(HashLoc, IncludeTok, FilenameTok,
2196 EndLoc, LookupFrom, LookupFromFile);
2197 switch (Action.Kind) {
2198 case ImportAction::None:
2199 case ImportAction::SkippedModuleImport:
2200 break;
2201 case ImportAction::ModuleBegin:
2202 EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
2203 tok::annot_module_begin, Action.ModuleForHeader);
2204 break;
2205 case ImportAction::HeaderUnitImport:
2206 EnterAnnotationToken(SourceRange(HashLoc, EndLoc), tok::annot_header_unit,
2207 Action.ModuleForHeader);
2208 break;
2209 case ImportAction::ModuleImport:
2210 EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
2211 tok::annot_module_include, Action.ModuleForHeader);
2212 break;
2213 case ImportAction::Failure:
2214 assert(TheModuleLoader.HadFatalFailure &&
2215 "This should be an early exit only to a fatal error");
2216 TheModuleLoader.HadFatalFailure = true;
2217 IncludeTok.setKind(tok::eof);
2218 CurLexer->cutOffLexing();
2219 return;
2220 }
2221}
2222
2223OptionalFileEntryRef Preprocessor::LookupHeaderIncludeOrImport(
2224 ConstSearchDirIterator *CurDir, StringRef &Filename,
2225 SourceLocation FilenameLoc, CharSourceRange FilenameRange,
2226 const Token &FilenameTok, bool &IsFrameworkFound, bool IsImportDecl,
2227 bool &IsMapped, ConstSearchDirIterator LookupFrom,
2228 const FileEntry *LookupFromFile, StringRef &LookupFilename,
2229 SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath,
2230 ModuleMap::KnownHeader &SuggestedModule, bool isAngled) {
2231 auto DiagnoseHeaderInclusion = [&](FileEntryRef FE) {
2232 if (LangOpts.AsmPreprocessor)
2233 return;
2234
2235 Module *RequestingModule = getModuleForLocation(
2236 FilenameLoc, LangOpts.ModulesValidateTextualHeaderIncludes);
2237 bool RequestingModuleIsModuleInterface =
2238 !SourceMgr.isInMainFile(FilenameLoc);
2239
2240 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
2241 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
2242 Filename, FE);
2243 };
2244
2246 FilenameLoc, LookupFilename, isAngled, LookupFrom, LookupFromFile, CurDir,
2247 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
2248 &SuggestedModule, &IsMapped, &IsFrameworkFound);
2249 if (File) {
2250 DiagnoseHeaderInclusion(*File);
2251 return File;
2252 }
2253
2254 // Give the clients a chance to silently skip this include.
2255 if (Callbacks && Callbacks->FileNotFound(Filename))
2256 return std::nullopt;
2257
2258 if (SuppressIncludeNotFoundError)
2259 return std::nullopt;
2260
2261 // If the file could not be located and it was included via angle
2262 // brackets, we can attempt a lookup as though it were a quoted path to
2263 // provide the user with a possible fixit.
2264 if (isAngled) {
2266 FilenameLoc, LookupFilename, false, LookupFrom, LookupFromFile, CurDir,
2267 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
2268 &SuggestedModule, &IsMapped,
2269 /*IsFrameworkFound=*/nullptr);
2270 if (File) {
2271 DiagnoseHeaderInclusion(*File);
2272 Diag(FilenameTok, diag::err_pp_file_not_found_angled_include_not_fatal)
2273 << Filename << IsImportDecl
2274 << FixItHint::CreateReplacement(FilenameRange,
2275 "\"" + Filename.str() + "\"");
2276 return File;
2277 }
2278 }
2279
2280 // Check for likely typos due to leading or trailing non-isAlphanumeric
2281 // characters
2282 StringRef OriginalFilename = Filename;
2283 if (LangOpts.SpellChecking) {
2284 // A heuristic to correct a typo file name by removing leading and
2285 // trailing non-isAlphanumeric characters.
2286 auto CorrectTypoFilename = [](llvm::StringRef Filename) {
2287 Filename = Filename.drop_until(isAlphanumeric);
2288 while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
2289 Filename = Filename.drop_back();
2290 }
2291 return Filename;
2292 };
2293 StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
2294 StringRef TypoCorrectionLookupName = CorrectTypoFilename(LookupFilename);
2295
2297 FilenameLoc, TypoCorrectionLookupName, isAngled, LookupFrom,
2298 LookupFromFile, CurDir, Callbacks ? &SearchPath : nullptr,
2299 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped,
2300 /*IsFrameworkFound=*/nullptr);
2301 if (File) {
2302 DiagnoseHeaderInclusion(*File);
2303 auto Hint =
2305 FilenameRange, "<" + TypoCorrectionName.str() + ">")
2306 : FixItHint::CreateReplacement(
2307 FilenameRange, "\"" + TypoCorrectionName.str() + "\"");
2308 Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
2309 << OriginalFilename << TypoCorrectionName << Hint;
2310 // We found the file, so set the Filename to the name after typo
2311 // correction.
2312 Filename = TypoCorrectionName;
2313 LookupFilename = TypoCorrectionLookupName;
2314 return File;
2315 }
2316 }
2317
2318 // If the file is still not found, just go with the vanilla diagnostic
2319 assert(!File && "expected missing file");
2320 Diag(FilenameTok, diag::err_pp_file_not_found)
2321 << OriginalFilename << FilenameRange;
2322 if (IsFrameworkFound) {
2323 size_t SlashPos = OriginalFilename.find('/');
2324 assert(SlashPos != StringRef::npos &&
2325 "Include with framework name should have '/' in the filename");
2326 StringRef FrameworkName = OriginalFilename.substr(0, SlashPos);
2327 FrameworkCacheEntry &CacheEntry =
2328 HeaderInfo.LookupFrameworkCache(FrameworkName);
2329 assert(CacheEntry.Directory && "Found framework should be in cache");
2330 Diag(FilenameTok, diag::note_pp_framework_without_header)
2331 << OriginalFilename.substr(SlashPos + 1) << FrameworkName
2332 << CacheEntry.Directory->getName();
2333 }
2334
2335 return std::nullopt;
2336}
2337
2338/// Handle either a #include-like directive or an import declaration that names
2339/// a header file.
2340///
2341/// \param HashLoc The location of the '#' token for an include, or
2342/// SourceLocation() for an import declaration.
2343/// \param IncludeTok The include / include_next / import token.
2344/// \param FilenameTok The header-name token.
2345/// \param EndLoc The location at which any imported macros become visible.
2346/// \param LookupFrom For #include_next, the starting directory for the
2347/// directory lookup.
2348/// \param LookupFromFile For #include_next, the starting file for the directory
2349/// lookup.
2350Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport(
2351 SourceLocation HashLoc, Token &IncludeTok, Token &FilenameTok,
2352 SourceLocation EndLoc, ConstSearchDirIterator LookupFrom,
2353 const FileEntry *LookupFromFile) {
2354 SmallString<128> FilenameBuffer;
2355 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer);
2356 SourceLocation CharEnd = FilenameTok.getEndLoc();
2357
2358 CharSourceRange FilenameRange
2359 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
2360 StringRef OriginalFilename = Filename;
2361 bool isAngled =
2362 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
2363
2364 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
2365 // error.
2366 if (Filename.empty())
2367 return {ImportAction::None};
2368 if (Filename.ends_with(' ') || Filename.ends_with('.')) {
2369 unsigned Selection = Filename.ends_with('.') ? 1 : 0;
2370 Diag(FilenameTok, diag::pp_nonportable_path_trailing)
2371 << Filename << Selection;
2372 }
2373
2374 bool IsImportDecl = HashLoc.isInvalid();
2375 SourceLocation StartLoc = IsImportDecl ? IncludeTok.getLocation() : HashLoc;
2376
2377 // Complain about attempts to #include files in an audit pragma.
2378 if (PragmaARCCFCodeAuditedInfo.getLoc().isValid()) {
2379 Diag(StartLoc, diag::err_pp_include_in_arc_cf_code_audited) << IsImportDecl;
2380 Diag(PragmaARCCFCodeAuditedInfo.getLoc(), diag::note_pragma_entered_here);
2381
2382 // Immediately leave the pragma.
2383 PragmaARCCFCodeAuditedInfo = IdentifierLoc();
2384 }
2385
2386 // Complain about attempts to #include files in an assume-nonnull pragma.
2387 if (PragmaAssumeNonNullLoc.isValid()) {
2388 Diag(StartLoc, diag::err_pp_include_in_assume_nonnull) << IsImportDecl;
2389 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
2390
2391 // Immediately leave the pragma.
2392 PragmaAssumeNonNullLoc = SourceLocation();
2393 }
2394
2395 if (HeaderInfo.HasIncludeAliasMap()) {
2396 // Map the filename with the brackets still attached. If the name doesn't
2397 // map to anything, fall back on the filename we've already gotten the
2398 // spelling for.
2399 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
2400 if (!NewName.empty())
2401 Filename = NewName;
2402 }
2403
2404 // Search include directories.
2405 bool IsMapped = false;
2406 bool IsFrameworkFound = false;
2407 ConstSearchDirIterator CurDir = nullptr;
2408 SmallString<1024> SearchPath;
2409 SmallString<1024> RelativePath;
2410 // We get the raw path only if we have 'Callbacks' to which we later pass
2411 // the path.
2412 ModuleMap::KnownHeader SuggestedModule;
2413 SourceLocation FilenameLoc = FilenameTok.getLocation();
2414 StringRef LookupFilename = Filename;
2415
2416 // Normalize slashes when compiling with -fms-extensions on non-Windows. This
2417 // is unnecessary on Windows since the filesystem there handles backslashes.
2418 SmallString<128> NormalizedPath;
2419 llvm::sys::path::Style BackslashStyle = llvm::sys::path::Style::native;
2420 if (is_style_posix(BackslashStyle) && LangOpts.MicrosoftExt) {
2421 NormalizedPath = Filename.str();
2422 llvm::sys::path::native(NormalizedPath);
2423 LookupFilename = NormalizedPath;
2424 BackslashStyle = llvm::sys::path::Style::windows;
2425 }
2426
2427 OptionalFileEntryRef File = LookupHeaderIncludeOrImport(
2428 &CurDir, Filename, FilenameLoc, FilenameRange, FilenameTok,
2429 IsFrameworkFound, IsImportDecl, IsMapped, LookupFrom, LookupFromFile,
2430 LookupFilename, RelativePath, SearchPath, SuggestedModule, isAngled);
2431
2432 if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) {
2433 if (File && isPCHThroughHeader(&File->getFileEntry()))
2434 SkippingUntilPCHThroughHeader = false;
2435 return {ImportAction::None};
2436 }
2437
2438 // Should we enter the source file? Set to Skip if either the source file is
2439 // known to have no effect beyond its effect on module visibility -- that is,
2440 // if it's got an include guard that is already defined, set to Import if it
2441 // is a modular header we've already built and should import.
2442
2443 // For C++20 Modules
2444 // [cpp.include]/7 If the header identified by the header-name denotes an
2445 // importable header, it is implementation-defined whether the #include
2446 // preprocessing directive is instead replaced by an import directive.
2447 // For this implementation, the translation is permitted when we are parsing
2448 // the Global Module Fragment, and not otherwise (the cases where it would be
2449 // valid to replace an include with an import are highly constrained once in
2450 // named module purview; this choice avoids considerable complexity in
2451 // determining valid cases).
2452
2453 enum { Enter, Import, Skip, IncludeLimitReached } Action = Enter;
2454
2455 if (PPOpts.SingleFileParseMode)
2456 Action = IncludeLimitReached;
2457
2458 // If we've reached the max allowed include depth, it is usually due to an
2459 // include cycle. Don't enter already processed files again as it can lead to
2460 // reaching the max allowed include depth again.
2461 if (Action == Enter && HasReachedMaxIncludeDepth && File &&
2463 Action = IncludeLimitReached;
2464
2465 // FIXME: We do not have a good way to disambiguate C++ clang modules from
2466 // C++ standard modules (other than use/non-use of Header Units).
2467
2468 Module *ModuleToImport = SuggestedModule.getModule();
2469
2470 bool MaybeTranslateInclude = Action == Enter && File && ModuleToImport &&
2471 !ModuleToImport->isForBuilding(getLangOpts());
2472
2473 // Maybe a usable Header Unit
2474 bool UsableHeaderUnit = false;
2475 if (getLangOpts().CPlusPlusModules && ModuleToImport &&
2476 ModuleToImport->isHeaderUnit()) {
2477 if (TrackGMFState.inGMF() || IsImportDecl)
2478 UsableHeaderUnit = true;
2479 else if (!IsImportDecl) {
2480 // This is a Header Unit that we do not include-translate
2481 ModuleToImport = nullptr;
2482 }
2483 }
2484 // Maybe a usable clang header module.
2485 bool UsableClangHeaderModule =
2486 (getLangOpts().CPlusPlusModules || getLangOpts().Modules) &&
2487 ModuleToImport && !ModuleToImport->isHeaderUnit();
2488
2489 // Determine whether we should try to import the module for this #include, if
2490 // there is one. Don't do so if precompiled module support is disabled or we
2491 // are processing this module textually (because we're building the module).
2492 if (MaybeTranslateInclude && (UsableHeaderUnit || UsableClangHeaderModule)) {
2493 // If this include corresponds to a module but that module is
2494 // unavailable, diagnose the situation and bail out.
2495 // FIXME: Remove this; loadModule does the same check (but produces
2496 // slightly worse diagnostics).
2497 if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), *ModuleToImport,
2498 getDiagnostics())) {
2499 Diag(FilenameTok.getLocation(),
2500 diag::note_implicit_top_level_module_import_here)
2501 << ModuleToImport->getTopLevelModuleName();
2502 return {ImportAction::None};
2503 }
2504
2505 // Compute the module access path corresponding to this module.
2506 // FIXME: Should we have a second loadModule() overload to avoid this
2507 // extra lookup step?
2508 SmallVector<IdentifierLoc, 2> Path;
2509 for (Module *Mod = ModuleToImport; Mod; Mod = Mod->Parent)
2510 Path.emplace_back(FilenameTok.getLocation(),
2511 getIdentifierInfo(Mod->Name));
2512 std::reverse(Path.begin(), Path.end());
2513
2514 // Warn that we're replacing the include/import with a module import.
2515 if (!IsImportDecl)
2516 diagnoseAutoModuleImport(*this, StartLoc, IncludeTok, Path, CharEnd);
2517
2518 // Load the module to import its macros. We'll make the declarations
2519 // visible when the parser gets here.
2520 // FIXME: Pass ModuleToImport in here rather than converting it to a path
2521 // and making the module loader convert it back again.
2522 ModuleLoadResult Imported = TheModuleLoader.loadModule(
2523 IncludeTok.getLocation(), Path, Module::Hidden,
2524 /*IsInclusionDirective=*/true);
2525 assert((Imported == nullptr || Imported == ModuleToImport) &&
2526 "the imported module is different than the suggested one");
2527
2528 if (Imported) {
2529 Action = Import;
2530 } else if (Imported.isMissingExpected()) {
2532 static_cast<Module *>(Imported)->getTopLevelModule());
2533 // We failed to find a submodule that we assumed would exist (because it
2534 // was in the directory of an umbrella header, for instance), but no
2535 // actual module containing it exists (because the umbrella header is
2536 // incomplete). Treat this as a textual inclusion.
2537 ModuleToImport = nullptr;
2538 } else if (Imported.isConfigMismatch()) {
2539 // On a configuration mismatch, enter the header textually. We still know
2540 // that it's part of the corresponding module.
2541 } else {
2542 // We hit an error processing the import. Bail out.
2544 // With a fatal failure in the module loader, we abort parsing.
2545 Token &Result = IncludeTok;
2546 assert(CurLexer && "#include but no current lexer set!");
2547 Result.startToken();
2548 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
2549 CurLexer->cutOffLexing();
2550 }
2551 return {ImportAction::None};
2552 }
2553 }
2554
2555 // The #included file will be considered to be a system header if either it is
2556 // in a system include directory, or if the #includer is a system include
2557 // header.
2558 SrcMgr::CharacteristicKind FileCharacter =
2559 SourceMgr.getFileCharacteristic(FilenameTok.getLocation());
2560 if (File)
2561 FileCharacter = std::max(HeaderInfo.getFileDirFlavor(*File), FileCharacter);
2562
2563 // If this is a '#import' or an import-declaration, don't re-enter the file.
2564 //
2565 // FIXME: If we have a suggested module for a '#include', and we've already
2566 // visited this file, don't bother entering it again. We know it has no
2567 // further effect.
2568 bool EnterOnce =
2569 IsImportDecl ||
2570 IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import;
2571
2572 bool IsFirstIncludeOfFile = false;
2573
2574 // Ask HeaderInfo if we should enter this #include file. If not, #including
2575 // this file will have no effect.
2576 if (Action == Enter && File &&
2577 !HeaderInfo.ShouldEnterIncludeFile(*this, *File, EnterOnce,
2578 getLangOpts().Modules, ModuleToImport,
2579 IsFirstIncludeOfFile)) {
2580 // C++ standard modules:
2581 // If we are not in the GMF, then we textually include only
2582 // clang modules:
2583 // Even if we've already preprocessed this header once and know that we
2584 // don't need to see its contents again, we still need to import it if it's
2585 // modular because we might not have imported it from this submodule before.
2586 //
2587 // FIXME: We don't do this when compiling a PCH because the AST
2588 // serialization layer can't cope with it. This means we get local
2589 // submodule visibility semantics wrong in that case.
2590 if (UsableHeaderUnit && !getLangOpts().CompilingPCH)
2591 Action = TrackGMFState.inGMF() ? Import : Skip;
2592 else
2593 Action = (ModuleToImport && !getLangOpts().CompilingPCH) ? Import : Skip;
2594 }
2595
2596 // Check for circular inclusion of the main file.
2597 // We can't generate a consistent preamble with regard to the conditional
2598 // stack if the main file is included again as due to the preamble bounds
2599 // some directives (e.g. #endif of a header guard) will never be seen.
2600 // Since this will lead to confusing errors, avoid the inclusion.
2601 if (Action == Enter && File && PreambleConditionalStack.isRecording() &&
2602 SourceMgr.isMainFile(File->getFileEntry())) {
2603 Diag(FilenameTok.getLocation(),
2604 diag::err_pp_including_mainfile_in_preamble);
2605 return {ImportAction::None};
2606 }
2607
2608 if (Callbacks && !IsImportDecl) {
2609 // Notify the callback object that we've seen an inclusion directive.
2610 // FIXME: Use a different callback for a pp-import?
2611 Callbacks->InclusionDirective(HashLoc, IncludeTok, LookupFilename, isAngled,
2612 FilenameRange, File, SearchPath, RelativePath,
2613 SuggestedModule.getModule(), Action == Import,
2614 FileCharacter);
2615 if (Action == Skip && File)
2616 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
2617 }
2618
2619 if (!File)
2620 return {ImportAction::None};
2621
2622 // If this is a C++20 pp-import declaration, diagnose if we didn't find any
2623 // module corresponding to the named header.
2624 if (IsImportDecl && !ModuleToImport) {
2625 Diag(FilenameTok, diag::err_header_import_not_header_unit)
2626 << OriginalFilename << File->getName();
2627 return {ImportAction::None};
2628 }
2629
2630 // Issue a diagnostic if the name of the file on disk has a different case
2631 // than the one we're about to open.
2632 const bool CheckIncludePathPortability =
2633 !IsMapped && !File->getFileEntry().tryGetRealPathName().empty();
2634
2635 if (CheckIncludePathPortability) {
2636 StringRef Name = LookupFilename;
2637 StringRef NameWithoriginalSlashes = Filename;
2638#if defined(_WIN32)
2639 // Skip UNC prefix if present. (tryGetRealPathName() always
2640 // returns a path with the prefix skipped.)
2641 bool NameWasUNC = Name.consume_front("\\\\?\\");
2642 NameWithoriginalSlashes.consume_front("\\\\?\\");
2643#endif
2644 StringRef RealPathName = File->getFileEntry().tryGetRealPathName();
2645 SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
2646 llvm::sys::path::end(Name));
2647#if defined(_WIN32)
2648 // -Wnonportable-include-path is designed to diagnose includes using
2649 // case even on systems with a case-insensitive file system.
2650 // On Windows, RealPathName always starts with an upper-case drive
2651 // letter for absolute paths, but Name might start with either
2652 // case depending on if `cd c:\foo` or `cd C:\foo` was used in the shell.
2653 // ("foo" will always have on-disk case, no matter which case was
2654 // used in the cd command). To not emit this warning solely for
2655 // the drive letter, whose case is dependent on if `cd` is used
2656 // with upper- or lower-case drive letters, always consider the
2657 // given drive letter case as correct for the purpose of this warning.
2658 SmallString<128> FixedDriveRealPath;
2659 if (llvm::sys::path::is_absolute(Name) &&
2660 llvm::sys::path::is_absolute(RealPathName) &&
2661 toLowercase(Name[0]) == toLowercase(RealPathName[0]) &&
2662 isLowercase(Name[0]) != isLowercase(RealPathName[0])) {
2663 assert(Components.size() >= 3 && "should have drive, backslash, name");
2664 assert(Components[0].size() == 2 && "should start with drive");
2665 assert(Components[0][1] == ':' && "should have colon");
2666 FixedDriveRealPath = (Name.substr(0, 1) + RealPathName.substr(1)).str();
2667 RealPathName = FixedDriveRealPath;
2668 }
2669#endif
2670
2671 if (trySimplifyPath(Components, RealPathName, BackslashStyle)) {
2672 SmallString<128> Path;
2673 Path.reserve(Name.size()+2);
2674 Path.push_back(isAngled ? '<' : '"');
2675
2676 const auto IsSep = [BackslashStyle](char c) {
2677 return llvm::sys::path::is_separator(c, BackslashStyle);
2678 };
2679
2680 for (auto Component : Components) {
2681 // On POSIX, Components will contain a single '/' as first element
2682 // exactly if Name is an absolute path.
2683 // On Windows, it will contain "C:" followed by '\' for absolute paths.
2684 // The drive letter is optional for absolute paths on Windows, but
2685 // clang currently cannot process absolute paths in #include lines that
2686 // don't have a drive.
2687 // If the first entry in Components is a directory separator,
2688 // then the code at the bottom of this loop that keeps the original
2689 // directory separator style copies it. If the second entry is
2690 // a directory separator (the C:\ case), then that separator already
2691 // got copied when the C: was processed and we want to skip that entry.
2692 if (!(Component.size() == 1 && IsSep(Component[0])))
2693 Path.append(Component);
2694 else if (Path.size() != 1)
2695 continue;
2696
2697 // Append the separator(s) the user used, or the close quote
2698 if (Path.size() > NameWithoriginalSlashes.size()) {
2699 Path.push_back(isAngled ? '>' : '"');
2700 continue;
2701 }
2702 assert(IsSep(NameWithoriginalSlashes[Path.size()-1]));
2703 do
2704 Path.push_back(NameWithoriginalSlashes[Path.size()-1]);
2705 while (Path.size() <= NameWithoriginalSlashes.size() &&
2706 IsSep(NameWithoriginalSlashes[Path.size()-1]));
2707 }
2708
2709#if defined(_WIN32)
2710 // Restore UNC prefix if it was there.
2711 if (NameWasUNC)
2712 Path = (Path.substr(0, 1) + "\\\\?\\" + Path.substr(1)).str();
2713#endif
2714
2715 // For user files and known standard headers, issue a diagnostic.
2716 // For other system headers, don't. They can be controlled separately.
2717 auto DiagId =
2718 (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name))
2719 ? diag::pp_nonportable_path
2720 : diag::pp_nonportable_system_path;
2721 Diag(FilenameTok, DiagId) << Path <<
2722 FixItHint::CreateReplacement(FilenameRange, Path);
2723 }
2724
2725 bool SuppressBackslashDiag =
2726 // The diagnostic logic is expensive, so only run it if it's enabled...
2727 Diags->isIgnored(diag::pp_nonportable_path_separator, FilenameLoc) ||
2728 // ...and try to only trigger on paths that appear in source.
2729 FilenameLoc.isMacroID() ||
2730 SourceMgr.isWrittenInBuiltinFile(FilenameLoc) ||
2731 SourceMgr.isWrittenInModuleIncludes(FilenameLoc);
2732 if (!SuppressBackslashDiag && OriginalFilename.contains('\\')) {
2733 std::string SuggestedPath = OriginalFilename.str();
2734 llvm::replace(SuggestedPath, '\\', '/');
2735 Diag(FilenameTok, diag::pp_nonportable_path_separator)
2736 << Name << FixItHint::CreateReplacement(FilenameRange, SuggestedPath);
2737 }
2738 }
2739
2740 switch (Action) {
2741 case Skip:
2742 // If we don't need to enter the file, stop now.
2743 if (ModuleToImport)
2744 return {ImportAction::SkippedModuleImport, ModuleToImport};
2745 return {ImportAction::None};
2746
2747 case IncludeLimitReached:
2748 // If we reached our include limit and don't want to enter any more files,
2749 // don't go any further.
2750 return {ImportAction::None};
2751
2752 case Import: {
2753 // If this is a module import, make it visible if needed.
2754 assert(ModuleToImport && "no module to import");
2755
2756 makeModuleVisible(ModuleToImport, EndLoc);
2757
2758 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() ==
2759 tok::pp___include_macros)
2760 return {ImportAction::None};
2761
2762 return {ImportAction::ModuleImport, ModuleToImport};
2763 }
2764
2765 case Enter:
2766 break;
2767 }
2768
2769 // Check that we don't have infinite #include recursion.
2770 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
2771 Diag(FilenameTok, diag::err_pp_include_too_deep);
2772 HasReachedMaxIncludeDepth = true;
2773 return {ImportAction::None};
2774 }
2775
2776 if (isAngled && isInNamedModule())
2777 Diag(FilenameTok, diag::warn_pp_include_angled_in_module_purview)
2778 << getNamedModuleName();
2779
2780 // Look up the file, create a File ID for it.
2781 SourceLocation IncludePos = FilenameTok.getLocation();
2782 // If the filename string was the result of macro expansions, set the include
2783 // position on the file where it will be included and after the expansions.
2784 if (IncludePos.isMacroID())
2785 IncludePos = SourceMgr.getExpansionRange(IncludePos).getEnd();
2786 FileID FID = SourceMgr.createFileID(*File, IncludePos, FileCharacter);
2787 if (!FID.isValid()) {
2788 TheModuleLoader.HadFatalFailure = true;
2789 return ImportAction::Failure;
2790 }
2791
2792 // If all is good, enter the new file!
2793 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation(),
2794 IsFirstIncludeOfFile))
2795 return {ImportAction::None};
2796
2797 // Determine if we're switching to building a new submodule, and which one.
2798 // This does not apply for C++20 modules header units.
2799 if (ModuleToImport && !ModuleToImport->isHeaderUnit()) {
2800 if (ModuleToImport->getTopLevelModule()->ShadowingModule) {
2801 // We are building a submodule that belongs to a shadowed module. This
2802 // means we find header files in the shadowed module.
2803 Diag(ModuleToImport->DefinitionLoc,
2804 diag::err_module_build_shadowed_submodule)
2805 << ModuleToImport->getFullModuleName();
2807 diag::note_previous_definition);
2808 return {ImportAction::None};
2809 }
2810 // When building a pch, -fmodule-name tells the compiler to textually
2811 // include headers in the specified module. We are not building the
2812 // specified module.
2813 //
2814 // FIXME: This is the wrong way to handle this. We should produce a PCH
2815 // that behaves the same as the header would behave in a compilation using
2816 // that PCH, which means we should enter the submodule. We need to teach
2817 // the AST serialization layer to deal with the resulting AST.
2818 if (getLangOpts().CompilingPCH &&
2819 ModuleToImport->isForBuilding(getLangOpts()))
2820 return {ImportAction::None};
2821
2822 assert(!CurLexerSubmodule && "should not have marked this as a module yet");
2823 CurLexerSubmodule = ModuleToImport;
2824
2825 // Let the macro handling code know that any future macros are within
2826 // the new submodule.
2827 EnterSubmodule(ModuleToImport, EndLoc, /*ForPragma*/ false);
2828
2829 // Let the parser know that any future declarations are within the new
2830 // submodule.
2831 // FIXME: There's no point doing this if we're handling a #__include_macros
2832 // directive.
2833 return {ImportAction::ModuleBegin, ModuleToImport};
2834 }
2835
2836 assert(!IsImportDecl && "failed to diagnose missing module for import decl");
2837 return {ImportAction::None};
2838}
2839
2840/// HandleIncludeNextDirective - Implements \#include_next.
2841///
2842void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2843 Token &IncludeNextTok) {
2844 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
2845
2846 ConstSearchDirIterator Lookup = nullptr;
2847 const FileEntry *LookupFromFile;
2848 std::tie(Lookup, LookupFromFile) = getIncludeNextStart(IncludeNextTok);
2849
2850 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2851 LookupFromFile);
2852}
2853
2854/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
2855void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2856 // The Microsoft #import directive takes a type library and generates header
2857 // files from it, and includes those. This is beyond the scope of what clang
2858 // does, so we ignore it and error out. However, #import can optionally have
2859 // trailing attributes that span multiple lines. We're going to eat those
2860 // so we can continue processing from there.
2861 Diag(Tok, diag::err_pp_import_directive_ms );
2862
2863 // Read tokens until we get to the end of the directive. Note that the
2864 // directive can be split over multiple lines using the backslash character.
2866}
2867
2868/// HandleImportDirective - Implements \#import.
2869///
2870void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2871 Token &ImportTok) {
2872 if (!LangOpts.ObjC) { // #import is standard for ObjC.
2873 if (LangOpts.MSVCCompat)
2874 return HandleMicrosoftImportDirective(ImportTok);
2875 Diag(ImportTok, diag::ext_pp_import_directive);
2876 }
2877 return HandleIncludeDirective(HashLoc, ImportTok);
2878}
2879
2880/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2881/// pseudo directive in the predefines buffer. This handles it by sucking all
2882/// tokens through the preprocessor and discarding them (only keeping the side
2883/// effects on the preprocessor).
2884void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2885 Token &IncludeMacrosTok) {
2886 // This directive should only occur in the predefines buffer. If not, emit an
2887 // error and reject it.
2888 SourceLocation Loc = IncludeMacrosTok.getLocation();
2889 if (SourceMgr.getBufferName(Loc) != "<built-in>") {
2890 Diag(IncludeMacrosTok.getLocation(),
2891 diag::pp_include_macros_out_of_predefines);
2893 return;
2894 }
2895
2896 // Treat this as a normal #include for checking purposes. If this is
2897 // successful, it will push a new lexer onto the include stack.
2898 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
2899
2900 Token TmpTok;
2901 do {
2902 Lex(TmpTok);
2903 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2904 } while (TmpTok.isNot(tok::hashhash));
2905}
2906
2907//===----------------------------------------------------------------------===//
2908// Preprocessor Macro Directive Handling.
2909//===----------------------------------------------------------------------===//
2910
2911/// ReadMacroParameterList - The ( starting a parameter list of a macro
2912/// definition has just been read. Lex the rest of the parameters and the
2913/// closing ), updating MI with what we learn. Return true if an error occurs
2914/// parsing the param list.
2915bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) {
2916 SmallVector<IdentifierInfo*, 32> Parameters;
2917
2918 while (true) {
2920 switch (Tok.getKind()) {
2921 case tok::r_paren:
2922 // Found the end of the parameter list.
2923 if (Parameters.empty()) // #define FOO()
2924 return false;
2925 // Otherwise we have #define FOO(A,)
2926 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2927 return true;
2928 case tok::ellipsis: // #define X(... -> C99 varargs
2929 if (!LangOpts.C99)
2930 Diag(Tok, LangOpts.CPlusPlus11 ?
2931 diag::warn_cxx98_compat_variadic_macro :
2932 diag::ext_variadic_macro);
2933
2934 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2935 if (LangOpts.OpenCL && !LangOpts.OpenCLCPlusPlus) {
2936 Diag(Tok, diag::ext_pp_opencl_variadic_macros);
2937 }
2938
2939 // Lex the token after the identifier.
2941 if (Tok.isNot(tok::r_paren)) {
2942 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2943 return true;
2944 }
2945 // Add the __VA_ARGS__ identifier as a parameter.
2946 Parameters.push_back(Ident__VA_ARGS__);
2947 MI->setIsC99Varargs();
2948 MI->setParameterList(Parameters, BP);
2949 return false;
2950 case tok::eod: // #define X(
2951 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2952 return true;
2953 default:
2954 // Handle keywords and identifiers here to accept things like
2955 // #define Foo(for) for.
2956 IdentifierInfo *II = Tok.getIdentifierInfo();
2957 if (!II) {
2958 // #define X(1
2959 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2960 return true;
2961 }
2962
2963 // If this is already used as a parameter, it is used multiple times (e.g.
2964 // #define X(A,A.
2965 if (llvm::is_contained(Parameters, II)) { // C99 6.10.3p6
2966 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
2967 return true;
2968 }
2969
2970 // Add the parameter to the macro info.
2971 Parameters.push_back(II);
2972
2973 // Lex the token after the identifier.
2975
2976 switch (Tok.getKind()) {
2977 default: // #define X(A B
2978 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2979 return true;
2980 case tok::r_paren: // #define X(A)
2981 MI->setParameterList(Parameters, BP);
2982 return false;
2983 case tok::comma: // #define X(A,
2984 break;
2985 case tok::ellipsis: // #define X(A... -> GCC extension
2986 // Diagnose extension.
2987 Diag(Tok, diag::ext_named_variadic_macro);
2988
2989 // Lex the token after the identifier.
2991 if (Tok.isNot(tok::r_paren)) {
2992 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2993 return true;
2994 }
2995
2996 MI->setIsGNUVarargs();
2997 MI->setParameterList(Parameters, BP);
2998 return false;
2999 }
3000 }
3001 }
3002}
3003
3004static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
3005 const LangOptions &LOptions) {
3006 if (MI->getNumTokens() == 1) {
3007 const Token &Value = MI->getReplacementToken(0);
3008
3009 // Macro that is identity, like '#define inline inline' is a valid pattern.
3010 if (MacroName.getKind() == Value.getKind())
3011 return true;
3012
3013 // Macro that maps a keyword to the same keyword decorated with leading/
3014 // trailing underscores is a valid pattern:
3015 // #define inline __inline
3016 // #define inline __inline__
3017 // #define inline _inline (in MS compatibility mode)
3018 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
3019 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
3020 if (!II->isKeyword(LOptions))
3021 return false;
3022 StringRef ValueText = II->getName();
3023 StringRef TrimmedValue = ValueText;
3024 if (!ValueText.starts_with("__")) {
3025 if (ValueText.starts_with("_"))
3026 TrimmedValue = TrimmedValue.drop_front(1);
3027 else
3028 return false;
3029 } else {
3030 TrimmedValue = TrimmedValue.drop_front(2);
3031 if (TrimmedValue.ends_with("__"))
3032 TrimmedValue = TrimmedValue.drop_back(2);
3033 }
3034 return TrimmedValue == MacroText;
3035 } else {
3036 return false;
3037 }
3038 }
3039
3040 // #define inline
3041 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
3042 tok::kw_const) &&
3043 MI->getNumTokens() == 0;
3044}
3045
3046// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
3047// entire line) of the macro's tokens and adds them to MacroInfo, and while
3048// doing so performs certain validity checks including (but not limited to):
3049// - # (stringization) is followed by a macro parameter
3050//
3051// Returns a nullptr if an invalid sequence of tokens is encountered or returns
3052// a pointer to a MacroInfo object.
3053
3054MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody(
3055 const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) {
3056
3057 Token LastTok = MacroNameTok;
3058 // Create the new macro.
3059 MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation());
3060
3061 Token Tok;
3063
3064 // Ensure we consume the rest of the macro body if errors occur.
3065 llvm::scope_exit _([&]() {
3066 // The flag indicates if we are still waiting for 'eod'.
3067 if (CurLexer->ParsingPreprocessorDirective)
3069 });
3070
3071 // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk
3072 // within their appropriate context.
3074
3075 // If this is a function-like macro definition, parse the argument list,
3076 // marking each of the identifiers as being used as macro arguments. Also,
3077 // check other constraints on the first token of the macro body.
3078 if (Tok.is(tok::eod)) {
3079 if (ImmediatelyAfterHeaderGuard) {
3080 // Save this macro information since it may part of a header guard.
3081 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
3082 MacroNameTok.getLocation());
3083 }
3084 // If there is no body to this macro, we have no special handling here.
3085 } else if (Tok.hasLeadingSpace()) {
3086 // This is a normal token with leading space. Clear the leading space
3087 // marker on the first token to get proper expansion.
3089 } else if (Tok.is(tok::l_paren)) {
3090 // This is a function-like macro definition. Read the argument list.
3091 MI->setIsFunctionLike();
3092 if (ReadMacroParameterList(MI, LastTok))
3093 return nullptr;
3094
3095 // If this is a definition of an ISO C/C++ variadic function-like macro (not
3096 // using the GNU named varargs extension) inform our variadic scope guard
3097 // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__)
3098 // allowed only within the definition of a variadic macro.
3099
3100 if (MI->isC99Varargs()) {
3101 VariadicMacroScopeGuard.enterScope();
3102 }
3103
3104 // Read the first token after the arg list for down below.
3106 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
3107 // C99 requires whitespace between the macro definition and the body. Emit
3108 // a diagnostic for something like "#define X+".
3109 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
3110 } else {
3111 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
3112 // first character of a replacement list is not a character required by
3113 // subclause 5.2.1, then there shall be white-space separation between the
3114 // identifier and the replacement list.". 5.2.1 lists this set:
3115 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
3116 // is irrelevant here.
3117 bool isInvalid = false;
3118 if (Tok.is(tok::at)) // @ is not in the list above.
3119 isInvalid = true;
3120 else if (Tok.is(tok::unknown)) {
3121 // If we have an unknown token, it is something strange like "`". Since
3122 // all of valid characters would have lexed into a single character
3123 // token of some sort, we know this is not a valid case.
3124 isInvalid = true;
3125 }
3126 if (isInvalid)
3127 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
3128 else
3129 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
3130 }
3131
3132 if (!Tok.is(tok::eod))
3133 LastTok = Tok;
3134
3135 SmallVector<Token, 16> Tokens;
3136
3137 // Read the rest of the macro body.
3138 if (MI->isObjectLike()) {
3139 // Object-like macros are very simple, just read their body.
3140 while (Tok.isNot(tok::eod)) {
3141 LastTok = Tok;
3142 Tokens.push_back(Tok);
3143 // Get the next token of the macro.
3145 }
3146 } else {
3147 // Otherwise, read the body of a function-like macro. While we are at it,
3148 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
3149 // parameters in function-like macro expansions.
3150
3151 VAOptDefinitionContext VAOCtx(*this);
3152
3153 while (Tok.isNot(tok::eod)) {
3154 LastTok = Tok;
3155
3156 if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
3157 Tokens.push_back(Tok);
3158
3159 if (VAOCtx.isVAOptToken(Tok)) {
3160 // If we're already within a VAOPT, emit an error.
3161 if (VAOCtx.isInVAOpt()) {
3162 Diag(Tok, diag::err_pp_vaopt_nested_use);
3163 return nullptr;
3164 }
3165 // Ensure VAOPT is followed by a '(' .
3167 if (Tok.isNot(tok::l_paren)) {
3168 Diag(Tok, diag::err_pp_missing_lparen_in_vaopt_use);
3169 return nullptr;
3170 }
3171 Tokens.push_back(Tok);
3172 VAOCtx.sawVAOptFollowedByOpeningParens(Tok.getLocation());
3174 if (Tok.is(tok::hashhash)) {
3175 Diag(Tok, diag::err_vaopt_paste_at_start);
3176 return nullptr;
3177 }
3178 continue;
3179 } else if (VAOCtx.isInVAOpt()) {
3180 if (Tok.is(tok::r_paren)) {
3181 if (VAOCtx.sawClosingParen()) {
3182 assert(Tokens.size() >= 3 &&
3183 "Must have seen at least __VA_OPT__( "
3184 "and a subsequent tok::r_paren");
3185 if (Tokens[Tokens.size() - 2].is(tok::hashhash)) {
3186 Diag(Tok, diag::err_vaopt_paste_at_end);
3187 return nullptr;
3188 }
3189 }
3190 } else if (Tok.is(tok::l_paren)) {
3191 VAOCtx.sawOpeningParen(Tok.getLocation());
3192 }
3193 }
3194 // Get the next token of the macro.
3196 continue;
3197 }
3198
3199 // If we're in -traditional mode, then we should ignore stringification
3200 // and token pasting. Mark the tokens as unknown so as not to confuse
3201 // things.
3202 if (getLangOpts().TraditionalCPP) {
3203 Tok.setKind(tok::unknown);
3204 Tokens.push_back(Tok);
3205
3206 // Get the next token of the macro.
3208 continue;
3209 }
3210
3211 if (Tok.is(tok::hashhash)) {
3212 // If we see token pasting, check if it looks like the gcc comma
3213 // pasting extension. We'll use this information to suppress
3214 // diagnostics later on.
3215
3216 // Get the next token of the macro.
3218
3219 if (Tok.is(tok::eod)) {
3220 Tokens.push_back(LastTok);
3221 break;
3222 }
3223
3224 if (!Tokens.empty() && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
3225 Tokens[Tokens.size() - 1].is(tok::comma))
3226 MI->setHasCommaPasting();
3227
3228 // Things look ok, add the '##' token to the macro.
3229 Tokens.push_back(LastTok);
3230 continue;
3231 }
3232
3233 // Our Token is a stringization operator.
3234 // Get the next token of the macro.
3236
3237 // Check for a valid macro arg identifier or __VA_OPT__.
3238 if (!VAOCtx.isVAOptToken(Tok) &&
3239 (Tok.getIdentifierInfo() == nullptr ||
3240 MI->getParameterNum(Tok.getIdentifierInfo()) == -1)) {
3241
3242 // If this is assembler-with-cpp mode, we accept random gibberish after
3243 // the '#' because '#' is often a comment character. However, change
3244 // the kind of the token to tok::unknown so that the preprocessor isn't
3245 // confused.
3246 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
3247 LastTok.setKind(tok::unknown);
3248 Tokens.push_back(LastTok);
3249 continue;
3250 } else {
3251 Diag(Tok, diag::err_pp_stringize_not_parameter)
3252 << LastTok.is(tok::hashat);
3253 return nullptr;
3254 }
3255 }
3256
3257 // Things look ok, add the '#' and param name tokens to the macro.
3258 Tokens.push_back(LastTok);
3259
3260 // If the token following '#' is VAOPT, let the next iteration handle it
3261 // and check it for correctness, otherwise add the token and prime the
3262 // loop with the next one.
3263 if (!VAOCtx.isVAOptToken(Tok)) {
3264 Tokens.push_back(Tok);
3265 LastTok = Tok;
3266
3267 // Get the next token of the macro.
3269 }
3270 }
3271 if (VAOCtx.isInVAOpt()) {
3272 assert(Tok.is(tok::eod) && "Must be at End Of preprocessing Directive");
3273 Diag(Tok, diag::err_pp_expected_after)
3274 << LastTok.getKind() << tok::r_paren;
3275 Diag(VAOCtx.getUnmatchedOpeningParenLoc(), diag::note_matching) << tok::l_paren;
3276 return nullptr;
3277 }
3278 }
3279 MI->setDefinitionEndLoc(LastTok.getLocation());
3280
3281 MI->setTokens(Tokens, BP);
3282 return MI;
3283}
3284
3285static bool isObjCProtectedMacro(const IdentifierInfo *II) {
3286 return II->isStr("__strong") || II->isStr("__weak") ||
3287 II->isStr("__unsafe_unretained") || II->isStr("__autoreleasing");
3288}
3289
3290/// HandleDefineDirective - Implements \#define. This consumes the entire macro
3291/// line then lets the caller lex the next real token.
3292void Preprocessor::HandleDefineDirective(
3293 Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) {
3294 ++NumDefined;
3295
3296 Token MacroNameTok;
3297 bool MacroShadowsKeyword;
3298 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
3299
3300 // Error reading macro name? If so, diagnostic already issued.
3301 if (MacroNameTok.is(tok::eod))
3302 return;
3303
3304 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
3305 // Issue a final pragma warning if we're defining a macro that was has been
3306 // undefined and is being redefined.
3307 if (!II->hasMacroDefinition() && II->hadMacroDefinition() && II->isFinal())
3308 emitFinalMacroWarning(MacroNameTok, /*IsUndef=*/false);
3309
3310 // If we are supposed to keep comments in #defines, reenable comment saving
3311 // mode.
3312 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
3313
3314 MacroInfo *const MI = ReadOptionalMacroParameterListAndBody(
3315 MacroNameTok, ImmediatelyAfterHeaderGuard);
3316
3317 if (!MI) return;
3318
3319 if (MacroShadowsKeyword &&
3320 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
3321 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
3322 }
3323 // Check that there is no paste (##) operator at the beginning or end of the
3324 // replacement list.
3325 unsigned NumTokens = MI->getNumTokens();
3326 if (NumTokens != 0) {
3327 if (MI->getReplacementToken(0).is(tok::hashhash)) {
3328 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
3329 return;
3330 }
3331 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
3332 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
3333 return;
3334 }
3335 }
3336
3337 // When skipping just warn about macros that do not match.
3338 if (SkippingUntilPCHThroughHeader) {
3339 const MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo());
3340 if (!OtherMI || !MI->isIdenticalTo(*OtherMI, *this,
3341 /*Syntactic=*/LangOpts.MicrosoftExt))
3342 Diag(MI->getDefinitionLoc(), diag::warn_pp_macro_def_mismatch_with_pch)
3343 << MacroNameTok.getIdentifierInfo();
3344 // Issue the diagnostic but allow the change if msvc extensions are enabled
3345 if (!LangOpts.MicrosoftExt)
3346 return;
3347 }
3348
3349 // Finally, if this identifier already had a macro defined for it, verify that
3350 // the macro bodies are identical, and issue diagnostics if they are not.
3351 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
3352 // Final macros are hard-mode: they always warn. Even if the bodies are
3353 // identical. Even if they are in system headers. Even if they are things we
3354 // would silently allow in the past.
3355 if (MacroNameTok.getIdentifierInfo()->isFinal())
3356 emitFinalMacroWarning(MacroNameTok, /*IsUndef=*/false);
3357
3358 // In Objective-C, ignore attempts to directly redefine the builtin
3359 // definitions of the ownership qualifiers. It's still possible to
3360 // #undef them.
3361 if (getLangOpts().ObjC &&
3362 SourceMgr.getFileID(OtherMI->getDefinitionLoc()) ==
3364 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
3365 // Warn if it changes the tokens.
3366 if ((!getDiagnostics().getSuppressSystemWarnings() ||
3367 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
3368 !MI->isIdenticalTo(*OtherMI, *this,
3369 /*Syntactic=*/LangOpts.MicrosoftExt)) {
3370 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
3371 }
3372 assert(!OtherMI->isWarnIfUnused());
3373 return;
3374 }
3375
3376 // It is very common for system headers to have tons of macro redefinitions
3377 // and for warnings to be disabled in system headers. If this is the case,
3378 // then don't bother calling MacroInfo::isIdenticalTo.
3379 if (!getDiagnostics().getSuppressSystemWarnings() ||
3380 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
3381
3382 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
3383 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
3384
3385 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
3386 // C++ [cpp.predefined]p4, but allow it as an extension.
3387 if (isLanguageDefinedBuiltin(SourceMgr, OtherMI, II->getName()))
3388 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
3389 // Macros must be identical. This means all tokens and whitespace
3390 // separation must be the same. C99 6.10.3p2.
3391 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
3392 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
3393 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
3394 << MacroNameTok.getIdentifierInfo();
3395 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
3396 }
3397 }
3398 if (OtherMI->isWarnIfUnused())
3399 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
3400 }
3401
3402 DefMacroDirective *MD =
3403 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
3404
3405 assert(!MI->isUsed());
3406 // If we need warning for not using the macro, add its location in the
3407 // warn-because-unused-macro set. If it gets used it will be removed from set.
3409 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc()) &&
3410 !MacroExpansionInDirectivesOverride &&
3411 getSourceManager().getFileID(MI->getDefinitionLoc()) !=
3413 MI->setIsWarnIfUnused(true);
3414 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
3415 }
3416
3417 // If the callbacks want to know, tell them about the macro definition.
3418 if (Callbacks)
3419 Callbacks->MacroDefined(MacroNameTok, MD);
3420}
3421
3422/// HandleUndefDirective - Implements \#undef.
3423///
3424void Preprocessor::HandleUndefDirective() {
3425 ++NumUndefined;
3426
3427 Token MacroNameTok;
3428 ReadMacroName(MacroNameTok, MU_Undef);
3429
3430 // Error reading macro name? If so, diagnostic already issued.
3431 if (MacroNameTok.is(tok::eod))
3432 return;
3433
3434 // Check to see if this is the last token on the #undef line.
3435 CheckEndOfDirective("undef");
3436
3437 // Okay, we have a valid identifier to undef.
3438 auto *II = MacroNameTok.getIdentifierInfo();
3439 auto MD = getMacroDefinition(II);
3440 UndefMacroDirective *Undef = nullptr;
3441
3442 if (II->isFinal())
3443 emitFinalMacroWarning(MacroNameTok, /*IsUndef=*/true);
3444
3445 // If the macro is not defined, this is a noop undef.
3446 if (const MacroInfo *MI = MD.getMacroInfo()) {
3447 if (!MI->isUsed() && MI->isWarnIfUnused())
3448 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
3449
3450 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4 and
3451 // C++ [cpp.predefined]p4, but allow it as an extension.
3452 if (isLanguageDefinedBuiltin(SourceMgr, MI, II->getName()))
3453 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
3454
3455 if (MI->isWarnIfUnused())
3456 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
3457
3458 Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
3459 }
3460
3461 // If the callbacks want to know, tell them about the macro #undef.
3462 // Note: no matter if the macro was defined or not.
3463 if (Callbacks)
3464 Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
3465
3466 if (Undef)
3467 appendMacroDirective(II, Undef);
3468}
3469
3470//===----------------------------------------------------------------------===//
3471// Preprocessor Conditional Directive Handling.
3472//===----------------------------------------------------------------------===//
3473
3474/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
3475/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
3476/// true if any tokens have been returned or pp-directives activated before this
3477/// \#ifndef has been lexed.
3478///
3479void Preprocessor::HandleIfdefDirective(Token &Result,
3480 const Token &HashToken,
3481 bool isIfndef,
3482 bool ReadAnyTokensBeforeDirective) {
3483 ++NumIf;
3484 Token DirectiveTok = Result;
3485
3486 Token MacroNameTok;
3487 ReadMacroName(MacroNameTok);
3488
3489 // Error reading macro name? If so, diagnostic already issued.
3490 if (MacroNameTok.is(tok::eod)) {
3491 // Skip code until we get to #endif. This helps with recovery by not
3492 // emitting an error when the #endif is reached.
3493 SkipExcludedConditionalBlock(HashToken.getLocation(),
3494 DirectiveTok.getLocation(),
3495 /*Foundnonskip*/ false, /*FoundElse*/ false);
3496 return;
3497 }
3498
3499 emitMacroExpansionWarnings(MacroNameTok, /*IsIfnDef=*/true);
3500
3501 // Check to see if this is the last token on the #if[n]def line.
3502 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
3503
3504 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
3505 auto MD = getMacroDefinition(MII);
3506 MacroInfo *MI = MD.getMacroInfo();
3507
3508 if (CurPPLexer->getConditionalStackDepth() == 0) {
3509 // If the start of a top-level #ifdef and if the macro is not defined,
3510 // inform MIOpt that this might be the start of a proper include guard.
3511 // Otherwise it is some other form of unknown conditional which we can't
3512 // handle.
3513 if (!ReadAnyTokensBeforeDirective && !MI) {
3514 assert(isIfndef && "#ifdef shouldn't reach here");
3515 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
3516 } else
3517 CurPPLexer->MIOpt.EnterTopLevelConditional();
3518 }
3519
3520 // If there is a macro, process it.
3521 if (MI) // Mark it used.
3522 markMacroAsUsed(MI);
3523
3524 if (Callbacks) {
3525 if (isIfndef)
3526 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
3527 else
3528 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
3529 }
3530
3531 bool RetainExcludedCB = PPOpts.RetainExcludedConditionalBlocks &&
3532 getSourceManager().isInMainFile(DirectiveTok.getLocation());
3533
3534 // Should we include the stuff contained by this directive?
3535 if (PPOpts.SingleFileParseMode && !MI) {
3536 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3537 // the directive blocks.
3538 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
3539 /*wasskip*/false, /*foundnonskip*/false,
3540 /*foundelse*/false);
3541 } else if (PPOpts.SingleModuleParseMode && !MI) {
3542 // In 'single-module-parse mode' undefined identifiers trigger skipping of
3543 // all the directive blocks. We lie here and set FoundNonSkipPortion so that
3544 // even any \#else blocks get skipped.
3545 SkipExcludedConditionalBlock(
3546 HashToken.getLocation(), DirectiveTok.getLocation(),
3547 /*FoundNonSkipPortion=*/true, /*FoundElse=*/false);
3548 } else if (!MI == isIfndef || RetainExcludedCB) {
3549 // Yes, remember that we are inside a conditional, then lex the next token.
3550 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
3551 /*wasskip*/false, /*foundnonskip*/true,
3552 /*foundelse*/false);
3553 } else {
3554 // No, skip the contents of this block.
3555 SkipExcludedConditionalBlock(HashToken.getLocation(),
3556 DirectiveTok.getLocation(),
3557 /*Foundnonskip*/ false,
3558 /*FoundElse*/ false);
3559 }
3560}
3561
3562/// HandleIfDirective - Implements the \#if directive.
3563///
3564void Preprocessor::HandleIfDirective(Token &IfToken,
3565 const Token &HashToken,
3566 bool ReadAnyTokensBeforeDirective) {
3567 ++NumIf;
3568
3569 // Parse and evaluate the conditional expression.
3570 IdentifierInfo *IfNDefMacro = nullptr;
3571 const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
3572 const bool ConditionalTrue = DER.Conditional;
3573 // Lexer might become invalid if we hit code completion point while evaluating
3574 // expression.
3575 if (!CurPPLexer)
3576 return;
3577
3578 // If this condition is equivalent to #ifndef X, and if this is the first
3579 // directive seen, handle it for the multiple-include optimization.
3580 if (CurPPLexer->getConditionalStackDepth() == 0) {
3581 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
3582 // FIXME: Pass in the location of the macro name, not the 'if' token.
3583 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
3584 else
3585 CurPPLexer->MIOpt.EnterTopLevelConditional();
3586 }
3587
3588 if (Callbacks)
3589 Callbacks->If(
3590 IfToken.getLocation(), DER.ExprRange,
3591 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
3592
3593 bool RetainExcludedCB = PPOpts.RetainExcludedConditionalBlocks &&
3595
3596 // Should we include the stuff contained by this directive?
3597 if (PPOpts.SingleFileParseMode && DER.IncludedUndefinedIds) {
3598 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3599 // the directive blocks.
3600 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
3601 /*foundnonskip*/false, /*foundelse*/false);
3602 } else if (PPOpts.SingleModuleParseMode && DER.IncludedUndefinedIds) {
3603 // In 'single-module-parse mode' undefined identifiers trigger skipping of
3604 // all the directive blocks. We lie here and set FoundNonSkipPortion so that
3605 // even any \#else blocks get skipped.
3606 SkipExcludedConditionalBlock(HashToken.getLocation(), IfToken.getLocation(),
3607 /*FoundNonSkipPortion=*/true,
3608 /*FoundElse=*/false);
3609 } else if (ConditionalTrue || RetainExcludedCB) {
3610 // Yes, remember that we are inside a conditional, then lex the next token.
3611 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
3612 /*foundnonskip*/true, /*foundelse*/false);
3613 } else {
3614 // No, skip the contents of this block.
3615 SkipExcludedConditionalBlock(HashToken.getLocation(), IfToken.getLocation(),
3616 /*Foundnonskip*/ false,
3617 /*FoundElse*/ false);
3618 }
3619}
3620
3621/// HandleEndifDirective - Implements the \#endif directive.
3622///
3623void Preprocessor::HandleEndifDirective(Token &EndifToken) {
3624 ++NumEndif;
3625
3626 // Check that this is the whole directive.
3627 CheckEndOfDirective("endif");
3628
3629 PPConditionalInfo CondInfo;
3630 if (CurPPLexer->popConditionalLevel(CondInfo)) {
3631 // No conditionals on the stack: this is an #endif without an #if.
3632 Diag(EndifToken, diag::err_pp_endif_without_if);
3633 return;
3634 }
3635
3636 // If this the end of a top-level #endif, inform MIOpt.
3637 if (CurPPLexer->getConditionalStackDepth() == 0)
3638 CurPPLexer->MIOpt.ExitTopLevelConditional();
3639
3640 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
3641 "This code should only be reachable in the non-skipping case!");
3642
3643 if (Callbacks)
3644 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
3645}
3646
3647/// HandleElseDirective - Implements the \#else directive.
3648///
3649void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) {
3650 ++NumElse;
3651
3652 // #else directive in a non-skipping conditional... start skipping.
3653 CheckEndOfDirective("else");
3654
3655 PPConditionalInfo CI;
3656 if (CurPPLexer->popConditionalLevel(CI)) {
3657 Diag(Result, diag::pp_err_else_without_if);
3658 return;
3659 }
3660
3661 // If this is a top-level #else, inform the MIOpt.
3662 if (CurPPLexer->getConditionalStackDepth() == 0)
3663 CurPPLexer->MIOpt.EnterTopLevelConditional();
3664
3665 // If this is a #else with a #else before it, report the error.
3666 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
3667
3668 if (Callbacks)
3669 Callbacks->Else(Result.getLocation(), CI.IfLoc);
3670
3671 bool RetainExcludedCB = PPOpts.RetainExcludedConditionalBlocks &&
3672 getSourceManager().isInMainFile(Result.getLocation());
3673
3674 if ((PPOpts.SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
3675 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3676 // the directive blocks.
3677 CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false,
3678 /*foundnonskip*/false, /*foundelse*/true);
3679 return;
3680 }
3681
3682 // Finally, skip the rest of the contents of this block.
3683 SkipExcludedConditionalBlock(HashToken.getLocation(), CI.IfLoc,
3684 /*Foundnonskip*/ true,
3685 /*FoundElse*/ true, Result.getLocation());
3686}
3687
3688/// Implements the \#elif, \#elifdef, and \#elifndef directives.
3689void Preprocessor::HandleElifFamilyDirective(Token &ElifToken,
3690 const Token &HashToken,
3691 tok::PPKeywordKind Kind) {
3692 PPElifDiag DirKind = Kind == tok::pp_elif ? PED_Elif
3693 : Kind == tok::pp_elifdef ? PED_Elifdef
3694 : PED_Elifndef;
3695 ++NumElse;
3696
3697 // Warn if using `#elifdef` & `#elifndef` in not C23 & C++23 mode.
3698 switch (DirKind) {
3699 case PED_Elifdef:
3700 case PED_Elifndef:
3701 unsigned DiagID;
3702 if (LangOpts.CPlusPlus)
3703 DiagID = LangOpts.CPlusPlus23 ? diag::warn_cxx23_compat_pp_directive
3704 : diag::ext_cxx23_pp_directive;
3705 else
3706 DiagID = LangOpts.C23 ? diag::warn_c23_compat_pp_directive
3707 : diag::ext_c23_pp_directive;
3708 Diag(ElifToken, DiagID) << DirKind;
3709 break;
3710 default:
3711 break;
3712 }
3713
3714 // #elif directive in a non-skipping conditional... start skipping.
3715 // We don't care what the condition is, because we will always skip it (since
3716 // the block immediately before it was included).
3717 SourceRange ConditionRange = DiscardUntilEndOfDirective();
3718
3719 PPConditionalInfo CI;
3720 if (CurPPLexer->popConditionalLevel(CI)) {
3721 Diag(ElifToken, diag::pp_err_elif_without_if) << DirKind;
3722 return;
3723 }
3724
3725 // If this is a top-level #elif, inform the MIOpt.
3726 if (CurPPLexer->getConditionalStackDepth() == 0)
3727 CurPPLexer->MIOpt.EnterTopLevelConditional();
3728
3729 // If this is a #elif with a #else before it, report the error.
3730 if (CI.FoundElse)
3731 Diag(ElifToken, diag::pp_err_elif_after_else) << DirKind;
3732
3733 if (Callbacks) {
3734 switch (Kind) {
3735 case tok::pp_elif:
3736 Callbacks->Elif(ElifToken.getLocation(), ConditionRange,
3738 break;
3739 case tok::pp_elifdef:
3740 Callbacks->Elifdef(ElifToken.getLocation(), ConditionRange, CI.IfLoc);
3741 break;
3742 case tok::pp_elifndef:
3743 Callbacks->Elifndef(ElifToken.getLocation(), ConditionRange, CI.IfLoc);
3744 break;
3745 default:
3746 assert(false && "unexpected directive kind");
3747 break;
3748 }
3749 }
3750
3751 bool RetainExcludedCB = PPOpts.RetainExcludedConditionalBlocks &&
3753
3754 if ((PPOpts.SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
3755 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3756 // the directive blocks.
3757 CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false,
3758 /*foundnonskip*/false, /*foundelse*/false);
3759 return;
3760 }
3761
3762 // Finally, skip the rest of the contents of this block.
3763 SkipExcludedConditionalBlock(
3764 HashToken.getLocation(), CI.IfLoc, /*Foundnonskip*/ true,
3765 /*FoundElse*/ CI.FoundElse, ElifToken.getLocation());
3766}
3767
3768std::optional<LexEmbedParametersResult>
3769Preprocessor::LexEmbedParameters(Token &CurTok, bool ForHasEmbed) {
3771 tok::TokenKind EndTokenKind = ForHasEmbed ? tok::r_paren : tok::eod;
3772
3773 auto DiagMismatchedBracesAndSkipToEOD =
3775 std::pair<tok::TokenKind, SourceLocation> Matches) {
3776 Diag(CurTok, diag::err_expected) << Expected;
3777 Diag(Matches.second, diag::note_matching) << Matches.first;
3778 if (CurTok.isNot(tok::eod))
3780 };
3781
3782 auto ExpectOrDiagAndSkipToEOD = [&](tok::TokenKind Kind) {
3783 if (CurTok.isNot(Kind)) {
3784 Diag(CurTok, diag::err_expected) << Kind;
3785 if (CurTok.isNot(tok::eod))
3787 return false;
3788 }
3789 return true;
3790 };
3791
3792 // C23 6.10:
3793 // pp-parameter-name:
3794 // pp-standard-parameter
3795 // pp-prefixed-parameter
3796 //
3797 // pp-standard-parameter:
3798 // identifier
3799 //
3800 // pp-prefixed-parameter:
3801 // identifier :: identifier
3802 auto LexPPParameterName = [&]() -> std::optional<std::string> {
3803 // We expect the current token to be an identifier; if it's not, things
3804 // have gone wrong.
3805 if (!ExpectOrDiagAndSkipToEOD(tok::identifier))
3806 return std::nullopt;
3807
3808 const IdentifierInfo *Prefix = CurTok.getIdentifierInfo();
3809
3810 // Lex another token; it is either a :: or we're done with the parameter
3811 // name.
3812 LexNonComment(CurTok);
3813 if (CurTok.is(tok::coloncolon)) {
3814 // We found a ::, so lex another identifier token.
3815 LexNonComment(CurTok);
3816 if (!ExpectOrDiagAndSkipToEOD(tok::identifier))
3817 return std::nullopt;
3818
3819 const IdentifierInfo *Suffix = CurTok.getIdentifierInfo();
3820
3821 // Lex another token so we're past the name.
3822 LexNonComment(CurTok);
3823 return (llvm::Twine(Prefix->getName()) + "::" + Suffix->getName()).str();
3824 }
3825 return Prefix->getName().str();
3826 };
3827
3828 // C23 6.10p5: In all aspects, a preprocessor standard parameter specified by
3829 // this document as an identifier pp_param and an identifier of the form
3830 // __pp_param__ shall behave the same when used as a preprocessor parameter,
3831 // except for the spelling.
3832 auto NormalizeParameterName = [](StringRef Name) {
3833 if (Name.size() > 4 && Name.starts_with("__") && Name.ends_with("__"))
3834 return Name.substr(2, Name.size() - 4);
3835 return Name;
3836 };
3837
3838 auto LexParenthesizedIntegerExpr = [&]() -> std::optional<size_t> {
3839 // we have a limit parameter and its internals are processed using
3840 // evaluation rules from #if.
3841 if (!ExpectOrDiagAndSkipToEOD(tok::l_paren))
3842 return std::nullopt;
3843
3844 // We do not consume the ( because EvaluateDirectiveExpression will lex
3845 // the next token for us.
3846 IdentifierInfo *ParameterIfNDef = nullptr;
3847 bool EvaluatedDefined;
3848 DirectiveEvalResult LimitEvalResult = EvaluateDirectiveExpression(
3849 ParameterIfNDef, CurTok, EvaluatedDefined, /*CheckForEOD=*/false);
3850
3851 if (!LimitEvalResult.Value) {
3852 // If there was an error evaluating the directive expression, we expect
3853 // to be at the end of directive token.
3854 assert(CurTok.is(tok::eod) && "expect to be at the end of directive");
3855 return std::nullopt;
3856 }
3857
3858 if (!ExpectOrDiagAndSkipToEOD(tok::r_paren))
3859 return std::nullopt;
3860
3861 // Eat the ).
3862 LexNonComment(CurTok);
3863
3864 // C23 6.10.3.2p2: The token defined shall not appear within the constant
3865 // expression.
3866 if (EvaluatedDefined) {
3867 Diag(CurTok, diag::err_defined_in_pp_embed);
3868 return std::nullopt;
3869 }
3870
3871 if (LimitEvalResult.Value) {
3872 const llvm::APSInt &Result = *LimitEvalResult.Value;
3873 if (Result.isNegative()) {
3874 Diag(CurTok, diag::err_requires_positive_value)
3875 << toString(Result, 10) << /*positive*/ 0;
3876 if (CurTok.isNot(EndTokenKind))
3878 return std::nullopt;
3879 }
3880 return Result.getLimitedValue();
3881 }
3882 return std::nullopt;
3883 };
3884
3885 auto GetMatchingCloseBracket = [](tok::TokenKind Kind) {
3886 switch (Kind) {
3887 case tok::l_paren:
3888 return tok::r_paren;
3889 case tok::l_brace:
3890 return tok::r_brace;
3891 case tok::l_square:
3892 return tok::r_square;
3893 default:
3894 llvm_unreachable("should not get here");
3895 }
3896 };
3897
3898 auto LexParenthesizedBalancedTokenSoup =
3899 [&](llvm::SmallVectorImpl<Token> &Tokens) {
3900 std::vector<std::pair<tok::TokenKind, SourceLocation>> BracketStack;
3901
3902 // We expect the current token to be a left paren.
3903 if (!ExpectOrDiagAndSkipToEOD(tok::l_paren))
3904 return false;
3905 LexNonComment(CurTok); // Eat the (
3906
3907 bool WaitingForInnerCloseParen = false;
3908 while (CurTok.isNot(tok::eod) &&
3909 (WaitingForInnerCloseParen || CurTok.isNot(tok::r_paren))) {
3910 switch (CurTok.getKind()) {
3911 default: // Shutting up diagnostics about not fully-covered switch.
3912 break;
3913 case tok::l_paren:
3914 WaitingForInnerCloseParen = true;
3915 [[fallthrough]];
3916 case tok::l_brace:
3917 case tok::l_square:
3918 BracketStack.push_back({CurTok.getKind(), CurTok.getLocation()});
3919 break;
3920 case tok::r_paren:
3921 WaitingForInnerCloseParen = false;
3922 [[fallthrough]];
3923 case tok::r_brace:
3924 case tok::r_square: {
3925 if (BracketStack.empty()) {
3926 ExpectOrDiagAndSkipToEOD(tok::r_paren);
3927 return false;
3928 }
3929 tok::TokenKind Matching =
3930 GetMatchingCloseBracket(BracketStack.back().first);
3931 if (CurTok.getKind() != Matching) {
3932 DiagMismatchedBracesAndSkipToEOD(Matching, BracketStack.back());
3933 return false;
3934 }
3935 BracketStack.pop_back();
3936 } break;
3937 }
3938 Tokens.push_back(CurTok);
3939 LexNonComment(CurTok);
3940 }
3941
3942 // When we're done, we want to eat the closing paren.
3943 if (!ExpectOrDiagAndSkipToEOD(tok::r_paren))
3944 return false;
3945
3946 LexNonComment(CurTok); // Eat the )
3947 return true;
3948 };
3949
3950 LexNonComment(CurTok); // Prime the pump.
3951 while (!CurTok.isOneOf(EndTokenKind, tok::eod)) {
3952 SourceLocation ParamStartLoc = CurTok.getLocation();
3953 std::optional<std::string> ParamName = LexPPParameterName();
3954 if (!ParamName)
3955 return std::nullopt;
3956 StringRef Parameter = NormalizeParameterName(*ParamName);
3957
3958 // Lex the parameters (dependent on the parameter type we want!).
3959 //
3960 // C23 6.10.3.Xp1: The X standard embed parameter may appear zero times or
3961 // one time in the embed parameter sequence.
3962 if (Parameter == "limit") {
3963 if (Result.MaybeLimitParam)
3964 Diag(CurTok, diag::err_pp_embed_dup_params) << Parameter;
3965
3966 std::optional<size_t> Limit = LexParenthesizedIntegerExpr();
3967 if (!Limit)
3968 return std::nullopt;
3969 Result.MaybeLimitParam =
3970 PPEmbedParameterLimit{*Limit, {ParamStartLoc, CurTok.getLocation()}};
3971 } else if (Parameter == "clang::offset") {
3972 if (Result.MaybeOffsetParam)
3973 Diag(CurTok, diag::err_pp_embed_dup_params) << Parameter;
3974
3975 std::optional<size_t> Offset = LexParenthesizedIntegerExpr();
3976 if (!Offset)
3977 return std::nullopt;
3978 Result.MaybeOffsetParam = PPEmbedParameterOffset{
3979 *Offset, {ParamStartLoc, CurTok.getLocation()}};
3980 } else if (Parameter == "prefix") {
3981 if (Result.MaybePrefixParam)
3982 Diag(CurTok, diag::err_pp_embed_dup_params) << Parameter;
3983
3985 if (!LexParenthesizedBalancedTokenSoup(Soup))
3986 return std::nullopt;
3987 Result.MaybePrefixParam = PPEmbedParameterPrefix{
3988 std::move(Soup), {ParamStartLoc, CurTok.getLocation()}};
3989 } else if (Parameter == "suffix") {
3990 if (Result.MaybeSuffixParam)
3991 Diag(CurTok, diag::err_pp_embed_dup_params) << Parameter;
3992
3994 if (!LexParenthesizedBalancedTokenSoup(Soup))
3995 return std::nullopt;
3996 Result.MaybeSuffixParam = PPEmbedParameterSuffix{
3997 std::move(Soup), {ParamStartLoc, CurTok.getLocation()}};
3998 } else if (Parameter == "if_empty") {
3999 if (Result.MaybeIfEmptyParam)
4000 Diag(CurTok, diag::err_pp_embed_dup_params) << Parameter;
4001
4003 if (!LexParenthesizedBalancedTokenSoup(Soup))
4004 return std::nullopt;
4005 Result.MaybeIfEmptyParam = PPEmbedParameterIfEmpty{
4006 std::move(Soup), {ParamStartLoc, CurTok.getLocation()}};
4007 } else {
4008 ++Result.UnrecognizedParams;
4009
4010 // If there's a left paren, we need to parse a balanced token sequence
4011 // and just eat those tokens.
4012 if (CurTok.is(tok::l_paren)) {
4014 if (!LexParenthesizedBalancedTokenSoup(Soup))
4015 return std::nullopt;
4016 }
4017 if (!ForHasEmbed) {
4018 Diag(ParamStartLoc, diag::err_pp_unknown_parameter) << 1 << Parameter;
4019 if (CurTok.isNot(EndTokenKind))
4021 return std::nullopt;
4022 }
4023 }
4024 }
4025 return Result;
4026}
4027
4028void Preprocessor::HandleEmbedDirectiveImpl(
4029 SourceLocation HashLoc, const LexEmbedParametersResult &Params,
4030 StringRef BinaryContents, StringRef FileName) {
4031 if (BinaryContents.empty()) {
4032 // If we have no binary contents, the only thing we need to emit are the
4033 // if_empty tokens, if any.
4034 // FIXME: this loses AST fidelity; nothing in the compiler will see that
4035 // these tokens came from #embed. We have to hack around this when printing
4036 // preprocessed output. The same is true for prefix and suffix tokens.
4037 if (Params.MaybeIfEmptyParam) {
4038 ArrayRef<Token> Toks = Params.MaybeIfEmptyParam->Tokens;
4039 size_t TokCount = Toks.size();
4040 auto NewToks = std::make_unique<Token[]>(TokCount);
4041 llvm::copy(Toks, NewToks.get());
4042 EnterTokenStream(std::move(NewToks), TokCount, true, true);
4043 }
4044 return;
4045 }
4046
4047 size_t NumPrefixToks = Params.PrefixTokenCount(),
4048 NumSuffixToks = Params.SuffixTokenCount();
4049 size_t TotalNumToks = 1 + NumPrefixToks + NumSuffixToks;
4050 size_t CurIdx = 0;
4051 auto Toks = std::make_unique<Token[]>(TotalNumToks);
4052
4053 // Add the prefix tokens, if any.
4054 if (Params.MaybePrefixParam) {
4055 llvm::copy(Params.MaybePrefixParam->Tokens, &Toks[CurIdx]);
4056 CurIdx += NumPrefixToks;
4057 }
4058
4059 EmbedAnnotationData *Data = new (BP) EmbedAnnotationData;
4060 Data->BinaryData = BinaryContents;
4061 Data->FileName = FileName;
4062
4063 Toks[CurIdx].startToken();
4064 Toks[CurIdx].setKind(tok::annot_embed);
4065 Toks[CurIdx].setAnnotationRange(HashLoc);
4066 Toks[CurIdx++].setAnnotationValue(Data);
4067
4068 // Now add the suffix tokens, if any.
4069 if (Params.MaybeSuffixParam) {
4070 llvm::copy(Params.MaybeSuffixParam->Tokens, &Toks[CurIdx]);
4071 CurIdx += NumSuffixToks;
4072 }
4073
4074 assert(CurIdx == TotalNumToks && "Calculated the incorrect number of tokens");
4075 EnterTokenStream(std::move(Toks), TotalNumToks, true, true);
4076}
4077
4078void Preprocessor::HandleEmbedDirective(SourceLocation HashLoc,
4079 Token &EmbedTok) {
4080 // Give the usual extension/compatibility warnings.
4081 if (LangOpts.C23)
4082 Diag(EmbedTok, diag::warn_compat_pp_embed_directive);
4083 else
4084 Diag(EmbedTok, diag::ext_pp_embed_directive)
4085 << (LangOpts.CPlusPlus ? /*Clang*/ 1 : /*C23*/ 0);
4086
4087 // Parse the filename header
4088 Token FilenameTok;
4089 if (LexHeaderName(FilenameTok))
4090 return;
4091
4092 if (FilenameTok.isNot(tok::header_name)) {
4093 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
4094 if (FilenameTok.isNot(tok::eod))
4096 return;
4097 }
4098
4099 // Parse the optional sequence of
4100 // directive-parameters:
4101 // identifier parameter-name-list[opt] directive-argument-list[opt]
4102 // directive-argument-list:
4103 // '(' balanced-token-sequence ')'
4104 // parameter-name-list:
4105 // '::' identifier parameter-name-list[opt]
4106 Token CurTok;
4107 std::optional<LexEmbedParametersResult> Params =
4108 LexEmbedParameters(CurTok, /*ForHasEmbed=*/false);
4109
4110 assert((Params || CurTok.is(tok::eod)) &&
4111 "expected success or to be at the end of the directive");
4112 if (!Params)
4113 return;
4114
4115 // Now, splat the data out!
4116 SmallString<128> FilenameBuffer;
4117 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer);
4118 StringRef OriginalFilename = Filename;
4119 bool isAngled =
4120 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
4121
4122 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
4123 // error.
4124 if (Filename.empty())
4125 return;
4126
4127 OptionalFileEntryRef MaybeFileRef =
4128 this->LookupEmbedFile(Filename, isAngled, /*OpenFile=*/true);
4129 if (!MaybeFileRef) {
4130 // could not find file
4131 if (Callbacks && Callbacks->EmbedFileNotFound(Filename)) {
4132 return;
4133 }
4134 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
4135 return;
4136 }
4137
4138 if (MaybeFileRef->isDeviceFile()) {
4139 Diag(FilenameTok, diag::err_pp_embed_device_file) << Filename;
4140 return;
4141 }
4142
4143 std::optional<llvm::MemoryBufferRef> MaybeFile =
4145 if (!MaybeFile) {
4146 // could not find file
4147 Diag(FilenameTok, diag::err_cannot_open_file)
4148 << Filename << "a buffer to the contents could not be created";
4149 return;
4150 }
4151 StringRef BinaryContents = MaybeFile->getBuffer();
4152
4153 // The order is important between 'offset' and 'limit'; we want to offset
4154 // first and then limit second; otherwise we may reduce the notional resource
4155 // size to something too small to offset into.
4156 if (Params->MaybeOffsetParam) {
4157 // FIXME: just like with the limit() and if_empty() parameters, this loses
4158 // source fidelity in the AST; it has no idea that there was an offset
4159 // involved.
4160 // offsets all the way to the end of the file make for an empty file.
4161 BinaryContents = BinaryContents.substr(Params->MaybeOffsetParam->Offset);
4162 }
4163
4164 if (Params->MaybeLimitParam) {
4165 // FIXME: just like with the clang::offset() and if_empty() parameters,
4166 // this loses source fidelity in the AST; it has no idea there was a limit
4167 // involved.
4168 BinaryContents = BinaryContents.substr(0, Params->MaybeLimitParam->Limit);
4169 }
4170
4171 if (Callbacks)
4172 Callbacks->EmbedDirective(HashLoc, Filename, isAngled, MaybeFileRef,
4173 *Params);
4174 // getSpelling() may return a buffer from the token itself or it may use the
4175 // SmallString buffer we provided. getSpelling() may also return a string that
4176 // is actually longer than FilenameTok.getLength(), so we first pass a
4177 // locally created buffer to getSpelling() to get the string of real length
4178 // and then we allocate a long living buffer because the buffer we used
4179 // previously will only live till the end of this function and we need
4180 // filename info to live longer.
4181 void *Mem = BP.Allocate(OriginalFilename.size(), alignof(char *));
4182 memcpy(Mem, OriginalFilename.data(), OriginalFilename.size());
4183 StringRef FilenameToGo =
4184 StringRef(static_cast<char *>(Mem), OriginalFilename.size());
4185 HandleEmbedDirectiveImpl(HashLoc, *Params, BinaryContents, FilenameToGo);
4186}
4187
4188/// HandleCXXImportDirective - Handle the C++ modules import directives
4189///
4190/// pp-import:
4191/// export[opt] import header-name pp-tokens[opt] ; new-line
4192/// export[opt] import header-name-tokens pp-tokens[opt] ; new-line
4193/// export[opt] import pp-tokens ; new-line
4194///
4195/// The header importing are replaced by annot_header_unit token, and the
4196/// lexed module name are replaced by annot_module_name token.
4198 assert(getLangOpts().CPlusPlusModules && ImportTok.is(tok::kw_import));
4199 llvm::SaveAndRestore<bool> SaveImportingCXXModules(
4200 this->ImportingCXXNamedModules, true);
4201
4202 Token Tok;
4203 if (LexHeaderName(Tok)) {
4204 if (Tok.isNot(tok::eod))
4206 return;
4207 }
4208
4209 SourceLocation UseLoc = ImportTok.getLocation();
4210 SmallVector<Token, 4> DirToks{ImportTok};
4212 bool ImportingHeader = false;
4213 bool IsPartition = false;
4214
4215 switch (Tok.getKind()) {
4216 case tok::header_name:
4217 ImportingHeader = true;
4218 DirToks.push_back(Tok);
4219 Lex(DirToks.emplace_back());
4220 break;
4221 case tok::colon:
4222 IsPartition = true;
4223 DirToks.push_back(Tok);
4224 UseLoc = Tok.getLocation();
4225 Lex(Tok);
4226 [[fallthrough]];
4227 case tok::identifier: {
4228 if (HandleModuleName(ImportTok.getIdentifierInfo()->getName(), UseLoc, Tok,
4229 Path, DirToks, /*AllowMacroExpansion=*/true,
4230 IsPartition))
4231 return;
4232
4233 std::string FlatName;
4234 bool IsValid =
4235 (IsPartition && ModuleDeclState.isNamedModule()) || !IsPartition;
4236 if (Callbacks && IsValid) {
4237 if (IsPartition && ModuleDeclState.isNamedModule()) {
4238 FlatName += ModuleDeclState.getPrimaryName();
4239 FlatName += ":";
4240 }
4241
4242 FlatName += ModuleLoader::getFlatNameFromPath(Path);
4243 SourceLocation StartLoc = IsPartition ? UseLoc : Path[0].getLoc();
4244 IdentifierLoc FlatNameLoc(StartLoc, getIdentifierInfo(FlatName));
4245
4246 // We don't/shouldn't load the standard c++20 modules when preprocessing.
4247 // so the imported module is nullptr.
4248 Callbacks->moduleImport(ImportTok.getLocation(),
4249 ModuleIdPath(FlatNameLoc),
4250 /*Imported=*/nullptr);
4251 }
4252 break;
4253 }
4254 default:
4255 DirToks.push_back(Tok);
4256 break;
4257 }
4258
4259 // Consume the pp-import-suffix and expand any macros in it now, if we're not
4260 // at the semicolon already.
4261 if (!DirToks.back().isOneOf(tok::semi, tok::eod))
4262 CollectPPImportSuffix(DirToks);
4263
4264 if (DirToks.back().isNot(tok::eod))
4266 else
4267 DirToks.pop_back();
4268
4269 // This is not a pp-import after all.
4270 if (DirToks.back().isNot(tok::semi)) {
4272 return;
4273 }
4274
4275 if (ImportingHeader) {
4276 // C++2a [cpp.module]p1:
4277 // The ';' preprocessing-token terminating a pp-import shall not have
4278 // been produced by macro replacement.
4279 SourceLocation SemiLoc = DirToks.back().getLocation();
4280 if (SemiLoc.isMacroID())
4281 Diag(SemiLoc, diag::err_header_import_semi_in_macro);
4282
4283 auto Action = HandleHeaderIncludeOrImport(
4284 /*HashLoc*/ SourceLocation(), ImportTok, Tok, SemiLoc);
4285 switch (Action.Kind) {
4286 case ImportAction::None:
4287 break;
4288
4289 case ImportAction::ModuleBegin:
4290 // Let the parser know we're textually entering the module.
4291 DirToks.emplace_back();
4292 DirToks.back().startToken();
4293 DirToks.back().setKind(tok::annot_module_begin);
4294 DirToks.back().setLocation(SemiLoc);
4295 DirToks.back().setAnnotationEndLoc(SemiLoc);
4296 DirToks.back().setAnnotationValue(Action.ModuleForHeader);
4297 [[fallthrough]];
4298
4299 case ImportAction::ModuleImport:
4300 case ImportAction::HeaderUnitImport:
4301 case ImportAction::SkippedModuleImport:
4302 // We chose to import (or textually enter) the file. Convert the
4303 // header-name token into a header unit annotation token.
4304 DirToks[1].setKind(tok::annot_header_unit);
4305 DirToks[1].setAnnotationEndLoc(DirToks[0].getLocation());
4306 DirToks[1].setAnnotationValue(Action.ModuleForHeader);
4307 // FIXME: Call the moduleImport callback?
4308 break;
4309 case ImportAction::Failure:
4310 assert(TheModuleLoader.HadFatalFailure &&
4311 "This should be an early exit only to a fatal error");
4312 CurLexer->cutOffLexing();
4313 return;
4314 }
4315 }
4316
4318}
4319
4320/// HandleCXXModuleDirective - Handle C++ module declaration directives.
4321///
4322/// pp-module:
4323/// export[opt] module pp-tokens[opt] ; new-line
4324///
4325/// pp-module-name:
4326/// pp-module-name-qualifier[opt] identifier
4327/// pp-module-partition:
4328/// : pp-module-name-qualifier[opt] identifier
4329/// pp-module-name-qualifier:
4330/// identifier .
4331/// pp-module-name-qualifier identifier .
4332///
4333/// global-module-fragment:
4334/// module-keyword ; declaration-seq[opt]
4335///
4336/// private-module-fragment:
4337/// module-keyword : private ; declaration-seq[opt]
4338///
4339/// The lexed module name are replaced by annot_module_name token.
4341 assert(getLangOpts().CPlusPlusModules && ModuleTok.is(tok::kw_module));
4342 SourceLocation StartLoc = ModuleTok.getLocation();
4343
4344 Token Tok;
4345 SourceLocation UseLoc = ModuleTok.getLocation();
4346 SmallVector<Token, 4> DirToks{ModuleTok};
4347 SmallVector<IdentifierLoc, 2> Path, Partition;
4349
4350 switch (Tok.getKind()) {
4351 // Global Module Fragment.
4352 case tok::semi:
4353 DirToks.push_back(Tok);
4354 break;
4355 case tok::colon:
4356 DirToks.push_back(Tok);
4358 if (Tok.isNot(tok::kw_private)) {
4359 if (Tok.isNot(tok::eod))
4361 /*EnableMacros=*/false, &DirToks);
4363 return;
4364 }
4365 DirToks.push_back(Tok);
4366 break;
4367 case tok::identifier: {
4368 if (HandleModuleName(ModuleTok.getIdentifierInfo()->getName(), UseLoc, Tok,
4369 Path, DirToks, /*AllowMacroExpansion=*/false,
4370 /*IsPartition=*/false))
4371 return;
4372
4373 // C++20 [cpp.module]p
4374 // The pp-tokens, if any, of a pp-module shall be of the form:
4375 // pp-module-name pp-module-partition[opt] pp-tokens[opt]
4376 if (Tok.is(tok::colon)) {
4378 if (HandleModuleName(ModuleTok.getIdentifierInfo()->getName(), UseLoc,
4379 Tok, Partition, DirToks,
4380 /*AllowMacroExpansion=*/false, /*IsPartition=*/true))
4381 return;
4382 }
4383
4384 // If the current token is a macro definition, put it back to token stream
4385 // and expand any macros in it later.
4386 //
4387 // export module M ATTR(some_attr); // -D'ATTR(x)=[[x]]'
4388 //
4389 // Current token is `ATTR`.
4390 if (Tok.is(tok::identifier) &&
4391 getMacroDefinition(Tok.getIdentifierInfo())) {
4392 std::unique_ptr<Token[]> TokCopy = std::make_unique<Token[]>(1);
4393 TokCopy[0] = Tok;
4394 EnterTokenStream(std::move(TokCopy), /*NumToks=*/1,
4395 /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
4396 Lex(Tok);
4397 DirToks.back() = Tok;
4398 }
4399 break;
4400 }
4401 default:
4402 DirToks.push_back(Tok);
4403 break;
4404 }
4405
4406 // Consume the pp-import-suffix and expand any macros in it now, if we're not
4407 // at the semicolon already.
4408 std::optional<Token> NextPPTok =
4409 DirToks.back().is(tok::eod) ? peekNextPPToken() : DirToks.back();
4410
4411 // Only ';' and '[' are allowed after module name.
4412 // We also check 'private' because the previous is not a module name.
4413 if (NextPPTok) {
4414 if (NextPPTok->is(tok::raw_identifier))
4415 LookUpIdentifierInfo(*NextPPTok);
4416 if (!NextPPTok->isOneOf(tok::semi, tok::eod, tok::l_square,
4417 tok::kw_private))
4418 Diag(*NextPPTok, diag::err_pp_unexpected_tok_after_module_name)
4419 << getSpelling(*NextPPTok);
4420 }
4421
4422 if (!DirToks.back().isOneOf(tok::semi, tok::eod)) {
4423 // Consume the pp-import-suffix and expand any macros in it now. We'll add
4424 // it back into the token stream later.
4425 CollectPPImportSuffix(DirToks);
4426 }
4427
4428 SourceLocation End =
4429 DirToks.back().isNot(tok::eod)
4431 /*EnableMacros=*/false, &DirToks)
4432
4433 : DirToks.pop_back_val().getLocation();
4434
4435 if (!IncludeMacroStack.empty()) {
4436 Diag(StartLoc, diag::err_pp_module_decl_in_header)
4437 << SourceRange(StartLoc, End);
4438 }
4439
4440 if (CurPPLexer->getConditionalStackDepth() != 0) {
4441 Diag(StartLoc, diag::err_pp_cond_span_module_decl)
4442 << SourceRange(StartLoc, End);
4443 }
4445}
4446
4447/// Lex a token following the 'import' contextual keyword.
4448///
4449/// pp-import:
4450/// [ObjC] @ import module-name ;
4451///
4452/// module-name:
4453/// module-name-qualifier[opt] identifier
4454///
4455/// module-name-qualifier
4456/// module-name-qualifier[opt] identifier .
4457///
4458/// We respond to a pp-import by importing macros from the named module.
4459void Preprocessor::HandleObjCImportDirective(Token &AtTok, Token &ImportTok) {
4460 assert(getLangOpts().ObjC && AtTok.is(tok::at) &&
4461 ImportTok.isObjCAtKeyword(tok::objc_import));
4462 ImportTok.setKind(tok::kw_import);
4463 SmallVector<Token, 32> DirToks{AtTok, ImportTok};
4465 SourceLocation UseLoc = ImportTok.getLocation();
4466 ModuleImportLoc = ImportTok.getLocation();
4467 Token Tok;
4468 Lex(Tok);
4469 if (HandleModuleName(ImportTok.getIdentifierInfo()->getName(), UseLoc, Tok,
4470 Path, DirToks,
4471 /*AllowMacroExpansion=*/true,
4472 /*IsPartition=*/false))
4473 return;
4474
4475 // Consume the pp-import-suffix and expand any macros in it now, if we're not
4476 // at the semicolon already.
4477 if (!DirToks.back().isOneOf(tok::semi, tok::eod))
4478 CollectPPImportSuffix(DirToks);
4479
4480 SourceLocation End =
4481 DirToks.back().isNot(tok::eod)
4483 /*EnableMacros=*/false, &DirToks)
4484
4485 : DirToks.pop_back_val().getLocation();
4486
4487 Module *Imported = nullptr;
4488 if (getLangOpts().Modules) {
4489 Imported = TheModuleLoader.loadModule(ModuleImportLoc, Path, Module::Hidden,
4490 /*IsInclusionDirective=*/false);
4491 if (Imported)
4492 makeModuleVisible(Imported, End);
4493 }
4494
4495 if (Callbacks)
4496 Callbacks->moduleImport(ModuleImportLoc, Path, Imported);
4497
4499}
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 GetLineDirectiveFilenameSpelling(SourceLocation Loc, StringRef &Buffer)
Turn the specified lexer token into a fully checked and spelled filename, e.g.
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:77
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:61
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...
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:33
PPKeywordKind
Provides a namespace for preprocessor keywords which start with a '#' at the beginning of the line.
Definition TokenKinds.h:41
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:909
@ Result
The result type of a method or function.
Definition TypeBase.h:906
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