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