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