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