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