clang 24.0.0git
Preprocessor.cpp
Go to the documentation of this file.
1//===- Preprocessor.cpp - C Language Family Preprocessor Implementation ---===//
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// This file implements the Preprocessor interface.
10//
11//===----------------------------------------------------------------------===//
12//
13// Options to support:
14// -H - Print the name of each header file used.
15// -d[DNI] - Dump various things.
16// -fworking-directory - #line's with preprocessor's working dir.
17// -fpreprocessed
18// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
19// -W*
20// -w
21//
22// Messages to emit:
23// "Multiple include guards may be useful for:\n"
24//
25//===----------------------------------------------------------------------===//
26
31#include "clang/Basic/LLVM.h"
33#include "clang/Basic/Module.h"
42#include "clang/Lex/Lexer.h"
44#include "clang/Lex/MacroArgs.h"
45#include "clang/Lex/MacroInfo.h"
48#include "clang/Lex/Pragma.h"
53#include "clang/Lex/Token.h"
56#include "llvm/ADT/APInt.h"
57#include "llvm/ADT/ArrayRef.h"
58#include "llvm/ADT/DenseMap.h"
59#include "llvm/ADT/STLExtras.h"
60#include "llvm/ADT/ScopeExit.h"
61#include "llvm/ADT/SmallVector.h"
62#include "llvm/ADT/StringRef.h"
63#include "llvm/Support/Capacity.h"
64#include "llvm/Support/ErrorHandling.h"
65#include "llvm/Support/FormatVariadic.h"
66#include "llvm/Support/MemoryBuffer.h"
67#include "llvm/Support/MemoryBufferRef.h"
68#include "llvm/Support/SaveAndRestore.h"
69#include "llvm/Support/raw_ostream.h"
70#include <algorithm>
71#include <cassert>
72#include <memory>
73#include <optional>
74#include <string>
75#include <utility>
76#include <vector>
77
78using namespace clang;
79
80/// Minimum distance between two check points, in tokens.
81static constexpr unsigned CheckPointStepSize = 1024;
82
84
86
88 DiagnosticsEngine &diags, const LangOptions &opts,
89 SourceManager &SM, HeaderSearch &Headers,
90 ModuleLoader &TheModuleLoader,
91 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
93 : PPOpts(PPOpts), Diags(&diags), LangOpts(opts),
94 FileMgr(Headers.getFileMgr()), SourceMgr(SM),
95 ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
96 TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
97 // As the language options may have not been loaded yet (when
98 // deserializing an ASTUnit), adding keywords to the identifier table is
99 // deferred to Preprocessor::Initialize().
100 Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
101 TUKind(TUKind), SkipMainFilePreamble(0, true),
102 CurSubmoduleState(&NullSubmoduleState) {
103 OwnsHeaderSearch = OwnsHeaders;
104
105 // Only record check points if we might highlight diagnostic snippets.
106 RecordCheckPoints = getDiagnostics().getShowColors();
107
108 // Default to discarding comments.
109 KeepComments = false;
110 KeepMacroComments = false;
111 SuppressIncludeNotFoundError = false;
112
113 // Macro expansion is enabled.
114 DisableMacroExpansion = false;
115 MacroExpansionInDirectivesOverride = false;
116 InMacroArgs = false;
117 ArgMacro = nullptr;
118 InMacroArgPreExpansion = false;
119 NumCachedTokenLexers = 0;
120 PragmasEnabled = true;
121 ParsingIfOrElifDirective = false;
122 PreprocessedOutput = false;
123
124 // We haven't read anything from the external source.
125 ReadMacrosFromExternalSource = false;
126
127 LastExportKeyword.startToken();
128
129 BuiltinInfo = std::make_unique<Builtin::Context>();
130
131 // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of
132 // a macro. They get unpoisoned where it is allowed.
133 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
134 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
135 (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
136 SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
137
138 // Initialize the pragma handlers.
139 RegisterBuiltinPragmas();
140
141 // Initialize builtin macros like __LINE__ and friends.
142 RegisterBuiltinMacros();
143
144 if(LangOpts.Borland) {
145 Ident__exception_info = getIdentifierInfo("_exception_info");
146 Ident___exception_info = getIdentifierInfo("__exception_info");
147 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
148 Ident__exception_code = getIdentifierInfo("_exception_code");
149 Ident___exception_code = getIdentifierInfo("__exception_code");
150 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
151 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
152 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
153 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
154 } else {
155 Ident__exception_info = Ident__exception_code = nullptr;
156 Ident__abnormal_termination = Ident___exception_info = nullptr;
157 Ident___exception_code = Ident___abnormal_termination = nullptr;
158 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
159 Ident_AbnormalTermination = nullptr;
160 }
161
162 Ident__GLIBCXX__ = getIdentifierInfo("__GLIBCXX__");
163
164 // Default incremental processing to -fincremental-extensions, clients can
165 // override with `enableIncrementalProcessing` if desired.
166 IncrementalProcessing = LangOpts.IncrementalExtensions;
167
168 // If using a PCH where a #pragma hdrstop is expected, start skipping tokens.
170 SkippingUntilPragmaHdrStop = true;
171
172 // If using a PCH with a through header, start skipping tokens.
173 if (!this->PPOpts.PCHThroughHeader.empty() &&
174 !this->PPOpts.ImplicitPCHInclude.empty())
175 SkippingUntilPCHThroughHeader = true;
176
177 if (this->PPOpts.GeneratePreamble)
178 PreambleConditionalStack.startRecording();
179
180 MaxTokens = LangOpts.MaxTokens;
181}
182
184 assert(!isBacktrackEnabled() && "EnableBacktrack/Backtrack imbalance!");
185
186 IncludeMacroStack.clear();
187
188 // Free any cached macro expanders.
189 // This populates MacroArgCache, so all TokenLexers need to be destroyed
190 // before the code below that frees up the MacroArgCache list.
191 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
192 CurTokenLexer.reset();
193
194 // Free any cached MacroArgs.
195 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
196 ArgList = ArgList->deallocate();
197
198 // Delete the header search info, if we own it.
199 if (OwnsHeaderSearch)
200 delete &HeaderInfo;
201}
202
204 const TargetInfo *AuxTarget) {
205 assert((!this->Target || this->Target == &Target) &&
206 "Invalid override of target information");
207 this->Target = &Target;
208
209 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
210 "Invalid override of aux target information.");
211 this->AuxTarget = AuxTarget;
212
213 // Initialize information about built-ins.
214 BuiltinInfo->InitializeTarget(Target, AuxTarget);
215 HeaderInfo.setTarget(Target);
216
217 // Populate the identifier table with info about keywords for the current language.
218 Identifiers.AddKeywords(LangOpts);
219
220 // Initialize the __FTL_EVAL_METHOD__ macro to the TargetInfo.
221 setTUFPEvalMethod(getTargetInfo().getFPEvalMethod());
222
223 if (getLangOpts().getFPEvalMethod() == LangOptions::FEM_UnsetOnCommandLine)
224 // Use setting from TargetInfo.
225 setCurrentFPEvalMethod(SourceLocation(), Target.getFPEvalMethod());
226 else
227 // Set initial value of __FLT_EVAL_METHOD__ from the command line.
228 setCurrentFPEvalMethod(SourceLocation(), getLangOpts().getFPEvalMethod());
229}
230
232 NumEnteredSourceFiles = 0;
233
234 // Reset pragmas
235 PragmaHandlersBackup = std::move(PragmaHandlers);
236 PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef());
237 RegisterBuiltinPragmas();
238
239 // Reset PredefinesFileID
240 PredefinesFileID = FileID();
241}
242
244 NumEnteredSourceFiles = 1;
245
246 PragmaHandlers = std::move(PragmaHandlersBackup);
247}
248
249void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
250 std::string TokenStr;
251 llvm::raw_string_ostream OS(TokenStr);
252
253 // The alignment of 16 is chosen to comfortably fit most identifiers.
254 OS << llvm::formatv("{0,-16} ", tok::getTokenName(Tok.getKind()));
255
256 // Annotation tokens are just markers that don't have a spelling -- they
257 // indicate where something expanded.
258 if (!Tok.isAnnotation()) {
259 OS << "'";
260 // Escape string to prevent token spelling from spanning multiple lines.
261 OS.write_escaped(getSpelling(Tok));
262 OS << "'";
263 }
264
265 // The alignment of 48 (32 characters for the spelling + the 16 for
266 // the identifier name) fits most variable names, keywords and annotations.
267 llvm::errs() << llvm::formatv("{0,-48} ", OS.str());
268
269 if (!DumpFlags) return;
270
271 auto Loc = Tok.getLocation();
272 llvm::errs() << "Loc=<";
273 DumpLocation(Loc);
274 llvm::errs() << ">";
275
276 // If the token points directly to a file location (i.e. not a macro
277 // expansion), then add additional padding so that trailing markers
278 // align, provided the line/column numbers are reasonably sized.
279 //
280 // Otherwise, if it's a macro expansion, don't bother with alignment,
281 // as the line will include multiple locations and be very long.
282 //
283 // NOTE: To keep this stateless, it doesn't account for filename
284 // length, so when a header starts markers will be temporarily misaligned.
285 if (Loc.isFileID()) {
286 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
287
288 if (!PLoc.isInvalid()) {
289 int LineWidth = llvm::utostr(PLoc.getLine()).size();
290 int ColumnWidth = llvm::utostr(PLoc.getColumn()).size();
291
292 // Reserve space for lines up to 9999 and columns up to 99,
293 // which is 4 + 2 = 6 characters in total.
294 const int ReservedSpace = 6;
295
296 int LeftSpace = ReservedSpace - LineWidth - ColumnWidth;
297 int Padding = std::max<int>(0, LeftSpace);
298
299 llvm::errs().indent(Padding);
300 }
301 }
302
303 if (Tok.isAtStartOfLine())
304 llvm::errs() << " [StartOfLine]";
305 if (Tok.hasLeadingSpace())
306 llvm::errs() << " [LeadingSpace]";
307 if (Tok.isExpandDisabled())
308 llvm::errs() << " [ExpandDisabled]";
309 if (Tok.needsCleaning()) {
310 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
311 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength()) << "']";
312 }
313}
314
316 Loc.print(llvm::errs(), SourceMgr);
317}
318
319void Preprocessor::DumpMacro(const MacroInfo &MI) const {
320 llvm::errs() << "MACRO: ";
321 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
323 llvm::errs() << " ";
324 }
325 llvm::errs() << "\n";
326}
327
329 llvm::errs() << "\n*** Preprocessor Stats:\n";
330 llvm::errs() << NumDirectives << " directives found:\n";
331 llvm::errs() << " " << NumDefined << " #define.\n";
332 llvm::errs() << " " << NumUndefined << " #undef.\n";
333 llvm::errs() << " #include/#include_next/#import:\n";
334 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
335 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
336 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
337 llvm::errs() << " " << NumElse << " #else/#elif/#elifdef/#elifndef.\n";
338 llvm::errs() << " " << NumEndif << " #endif.\n";
339 llvm::errs() << " " << NumPragma << " #pragma.\n";
340 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
341
342 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
343 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
344 << NumFastMacroExpanded << " on the fast path.\n";
345 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
346 << " token paste (##) operations performed, "
347 << NumFastTokenPaste << " on the fast path.\n";
348
349 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
350
351 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
352 llvm::errs() << "\n Macro Expanded Tokens: "
353 << llvm::capacity_in_bytes(MacroExpandedTokens);
354 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
355 // FIXME: List information for all submodules.
356 llvm::errs() << "\n Macros: "
357 << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
358 llvm::errs() << "\n #pragma push_macro Info: "
359 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
360 llvm::errs() << "\n Poison Reasons: "
361 << llvm::capacity_in_bytes(PoisonReasons);
362 llvm::errs() << "\n Comment Handlers: "
363 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
364}
365
366llvm::iterator_range<Preprocessor::macro_iterator>
367Preprocessor::macros(bool IncludeExternalMacros) const {
368 if (IncludeExternalMacros && ExternalSource &&
369 !ReadMacrosFromExternalSource) {
370 ReadMacrosFromExternalSource = true;
371 ExternalSource->ReadDefinedMacros();
372 }
373 // Make sure we cover all macros in visible modules.
374 for (const ModuleMacro &Macro : ModuleMacros)
375 CurSubmoduleState->Macros.try_emplace(Macro.II);
376
377 return CurSubmoduleState->Macros;
378}
379
381 return BP.getTotalMemory()
382 + llvm::capacity_in_bytes(MacroExpandedTokens)
383 + Predefines.capacity() /* Predefines buffer. */
384 // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
385 // and ModuleMacros.
386 + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
387 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
388 + llvm::capacity_in_bytes(PoisonReasons)
389 + llvm::capacity_in_bytes(CommentHandlers);
390}
391
392/// Compares macro tokens with a specified token value sequence.
393static bool MacroDefinitionEquals(const MacroInfo *MI,
394 ArrayRef<TokenValue> Tokens) {
395 return Tokens.size() == MI->getNumTokens() &&
396 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
397}
398
400 SourceLocation Loc,
401 ArrayRef<TokenValue> Tokens) const {
402 SourceLocation BestLocation;
403 StringRef BestSpelling;
404 for (const auto &M : macros()) {
405 const MacroDirective::DefInfo Def =
406 M.second.findDirectiveAtLoc(Loc, SourceMgr);
407 if (!Def || !Def.getMacroInfo())
408 continue;
409 if (!Def.getMacroInfo()->isObjectLike())
410 continue;
411 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
412 continue;
413 SourceLocation Location = Def.getLocation();
414 // Choose the macro defined latest.
415 if (BestLocation.isInvalid() ||
416 (Location.isValid() &&
417 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
418 BestLocation = Location;
419 BestSpelling = M.first->getName();
420 }
421 }
422 return BestSpelling;
423}
424
426 if (InCachingLexMode())
427 CurLexerCallback = CLK_CachingLexer;
428 else if (CurLexer)
429 CurLexerCallback = CurLexer->isDependencyDirectivesLexer()
430 ? CLK_DependencyDirectivesLexer
431 : CLK_Lexer;
432 else if (CurTokenLexer)
433 CurLexerCallback = CLK_TokenLexer;
434 else
435 CurLexerCallback = CLK_Lexer;
436}
437
439 unsigned CompleteLine,
440 unsigned CompleteColumn) {
441 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
442 assert(!CodeCompletionFile && "Already set");
443
444 // Load the actual file's contents.
445 std::optional<llvm::MemoryBufferRef> Buffer =
446 SourceMgr.getMemoryBufferForFileOrNone(File);
447 if (!Buffer)
448 return true;
449
450 // Find the byte position of the truncation point.
451 const char *Position = Buffer->getBufferStart();
452 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
453 for (; *Position; ++Position) {
454 if (*Position != '\r' && *Position != '\n')
455 continue;
456
457 // Eat \r\n or \n\r as a single line.
458 if ((Position[1] == '\r' || Position[1] == '\n') &&
459 Position[0] != Position[1])
460 ++Position;
461 ++Position;
462 break;
463 }
464 }
465
466 Position += CompleteColumn - 1;
467
468 // If pointing inside the preamble, adjust the position at the beginning of
469 // the file after the preamble.
470 if (SkipMainFilePreamble.first &&
471 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
472 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
473 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
474 }
475
476 if (Position > Buffer->getBufferEnd())
477 Position = Buffer->getBufferEnd();
478
479 CodeCompletionFile = File;
480 CodeCompletionOffset = Position - Buffer->getBufferStart();
481
482 auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
483 Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
484 char *NewBuf = NewBuffer->getBufferStart();
485 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
486 *NewPos = '\0';
487 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
488 SourceMgr.overrideFileContents(File, std::move(NewBuffer));
489
490 return false;
491}
492
494 bool IsAngled) {
496 if (CodeComplete)
497 CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);
498}
499
502 if (CodeComplete)
503 CodeComplete->CodeCompleteNaturalLanguage();
504}
505
506/// getSpelling - This method is used to get the spelling of a token into a
507/// SmallVector. Note that the returned StringRef may not point to the
508/// supplied buffer if a copy can be avoided.
510 SmallVectorImpl<char> &Buffer,
511 bool *Invalid) const {
512 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
513 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
514 // Try the fast path.
515 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
516 return II->getName();
517 }
518
519 // Resize the buffer if we need to copy into it.
520 if (Tok.needsCleaning())
521 Buffer.resize(Tok.getLength());
522
523 const char *Ptr = Buffer.data();
524 unsigned Len = getSpelling(Tok, Ptr, Invalid);
525 return StringRef(Ptr, Len);
526}
527
528/// CreateString - Plop the specified string into a scratch buffer and return a
529/// location for it. If specified, the source location provides a source
530/// location for the token.
532 SourceLocation ExpansionLocStart,
533 SourceLocation ExpansionLocEnd) {
534 Tok.setLength(Str.size());
535
536 const char *DestPtr;
537 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
538
539 if (ExpansionLocStart.isValid())
540 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
541 ExpansionLocEnd, Str.size());
542 Tok.setLocation(Loc);
543
544 // If this is a raw identifier or a literal token, set the pointer data.
545 if (Tok.is(tok::raw_identifier))
546 Tok.setRawIdentifierData(DestPtr);
547 else if (Tok.isLiteral())
548 Tok.setLiteralData(DestPtr);
549}
550
552 auto &SM = getSourceManager();
553 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
554 FileIDAndOffset LocInfo = SM.getDecomposedLoc(SpellingLoc);
555 bool Invalid = false;
556 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
557 if (Invalid)
558 return SourceLocation();
559
560 // FIXME: We could consider re-using spelling for tokens we see repeatedly.
561 const char *DestPtr;
562 SourceLocation Spelling =
563 ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
564 return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
565}
566
568 if (!getLangOpts().isCompilingModule())
569 return nullptr;
570
571 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
572}
573
575 if (!getLangOpts().isCompilingModuleImplementation())
576 return nullptr;
577
578 return getHeaderSearchInfo().lookupModule(getLangOpts().ModuleName);
579}
580
581//===----------------------------------------------------------------------===//
582// Preprocessor Initialization Methods
583//===----------------------------------------------------------------------===//
584
585/// EnterMainSourceFile - Enter the specified FileID as the main source file,
586/// which implicitly adds the builtin defines etc.
588 // We do not allow the preprocessor to reenter the main file. Doing so will
589 // cause FileID's to accumulate information from both runs (e.g. #line
590 // information) and predefined macros aren't guaranteed to be set properly.
591 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
592 FileID MainFileID = SourceMgr.getMainFileID();
593
594 // If MainFileID is loaded it means we loaded an AST file, no need to enter
595 // a main file.
596 if (!SourceMgr.isLoadedFileID(MainFileID)) {
597 // Enter the main file source buffer.
598 EnterSourceFile(MainFileID, nullptr, SourceLocation());
599
600 // If we've been asked to skip bytes in the main file (e.g., as part of a
601 // precompiled preamble), do so now.
602 if (SkipMainFilePreamble.first > 0)
603 CurLexer->SetByteOffset(SkipMainFilePreamble.first,
604 SkipMainFilePreamble.second);
605
606 // Tell the header info that the main file was entered. If the file is later
607 // #imported, it won't be re-entered.
608 if (OptionalFileEntryRef FE = SourceMgr.getFileEntryRefForID(MainFileID))
609 markIncluded(*FE);
610
611 // Record the first PP token in the main file. This is used to generate
612 // better diagnostics for C++ modules.
613 //
614 // // This is a comment.
615 // #define FOO int // note: add 'module;' to the start of the file
616 // ^ FirstPPToken // to introduce a global module fragment.
617 //
618 // export module M; // error: module declaration must occur
619 // // at the start of the translation unit.
620 if (getLangOpts().CPlusPlusModules) {
621 std::optional<StringRef> Input =
623 if (!isPreprocessedModuleFile() && Input)
624 MainFileIsPreprocessedModuleFile =
626 auto Tracer = std::make_unique<NoTrivialPPDirectiveTracer>(*this);
627 DirTracer = Tracer.get();
628 addPPCallbacks(std::move(Tracer));
629 std::optional<Token> FirstPPTok = CurLexer->peekNextPPToken();
630 if (FirstPPTok)
631 FirstPPTokenLoc = FirstPPTok->getLocation();
632 }
633 }
634
635 // Preprocess Predefines to populate the initial preprocessor state.
636 std::unique_ptr<llvm::MemoryBuffer> SB =
637 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
638 assert(SB && "Cannot create predefined source buffer");
639 FileID FID = SourceMgr.createFileID(std::move(SB));
640 assert(FID.isValid() && "Could not create FileID for predefines?");
641 setPredefinesFileID(FID);
642
643 // Start parsing the predefines.
644 EnterSourceFile(FID, nullptr, SourceLocation());
645
646 if (!PPOpts.PCHThroughHeader.empty()) {
647 // Lookup and save the FileID for the through header. If it isn't found
648 // in the search path, it's a fatal error.
650 SourceLocation(), PPOpts.PCHThroughHeader,
651 /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr,
652 /*CurDir=*/nullptr, /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
653 /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,
654 /*IsFrameworkFound=*/nullptr);
655 if (!File) {
656 Diag(SourceLocation(), diag::err_pp_through_header_not_found)
657 << PPOpts.PCHThroughHeader;
658 return;
659 }
660 setPCHThroughHeaderFileID(
661 SourceMgr.createFileID(*File, SourceLocation(), SrcMgr::C_User));
662 }
663
664 // Skip tokens from the Predefines and if needed the main file.
665 if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||
666 (usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))
668}
669
670void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
671 assert(PCHThroughHeaderFileID.isInvalid() &&
672 "PCHThroughHeaderFileID already set!");
673 PCHThroughHeaderFileID = FID;
674}
675
677 assert(PCHThroughHeaderFileID.isValid() &&
678 "Invalid PCH through header FileID");
679 return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
680}
681
683 return TUKind == TU_Prefix && !PPOpts.PCHThroughHeader.empty() &&
684 PCHThroughHeaderFileID.isValid();
685}
686
688 return TUKind != TU_Prefix && !PPOpts.PCHThroughHeader.empty() &&
689 PCHThroughHeaderFileID.isValid();
690}
691
693 return TUKind == TU_Prefix && PPOpts.PCHWithHdrStop;
694}
695
697 return TUKind != TU_Prefix && PPOpts.PCHWithHdrStop;
698}
699
700/// Skip tokens until after the #include of the through header or
701/// until after a #pragma hdrstop is seen. Tokens in the predefines file
702/// and the main file may be skipped. If the end of the predefines file
703/// is reached, skipping continues into the main file. If the end of the
704/// main file is reached, it's a fatal error.
706 bool ReachedMainFileEOF = false;
707 bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
708 bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
709 Token Tok;
710 while (true) {
711 bool InPredefines =
712 (CurLexer && CurLexer->getFileID() == getPredefinesFileID());
713 CurLexerCallback(*this, Tok);
714 if (Tok.is(tok::eof) && !InPredefines) {
715 ReachedMainFileEOF = true;
716 break;
717 }
718 if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
719 break;
720 if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
721 break;
722 }
723 if (ReachedMainFileEOF) {
724 if (UsingPCHThroughHeader)
725 Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
726 << PPOpts.PCHThroughHeader << 1;
727 else if (!PPOpts.PCHWithHdrStopCreate)
728 Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);
729 }
730}
731
732void Preprocessor::replayPreambleConditionalStack() {
733 // Restore the conditional stack from the preamble, if there is one.
734 if (PreambleConditionalStack.isReplaying()) {
735 assert(CurPPLexer &&
736 "CurPPLexer is null when calling replayPreambleConditionalStack.");
737 CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
738 PreambleConditionalStack.doneReplaying();
739 if (PreambleConditionalStack.reachedEOFWhileSkipping())
740 SkipExcludedConditionalBlock(
741 PreambleConditionalStack.SkipInfo->HashTokenLoc,
742 PreambleConditionalStack.SkipInfo->IfTokenLoc,
743 PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
744 PreambleConditionalStack.SkipInfo->FoundElse,
745 PreambleConditionalStack.SkipInfo->ElseLoc);
746 }
747}
748
750 // Notify the client that we reached the end of the source file.
751 if (Callbacks)
752 Callbacks->EndOfMainFile();
753}
754
755//===----------------------------------------------------------------------===//
756// Lexer Event Handling.
757//===----------------------------------------------------------------------===//
758
759/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
760/// identifier information for the token and install it into the token,
761/// updating the token kind accordingly.
763 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
764
765 // Look up this token, see if it is a macro, or if it is a language keyword.
766 IdentifierInfo *II;
767 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
768 // No cleaning needed, just use the characters from the lexed buffer.
769 II = getIdentifierInfo(Identifier.getRawIdentifier());
770 } else {
771 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
772 SmallString<64> IdentifierBuffer;
773 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
774
775 if (Identifier.hasUCN()) {
776 SmallString<64> UCNIdentifierBuffer;
777 expandUCNs(UCNIdentifierBuffer, CleanedStr);
778 II = getIdentifierInfo(UCNIdentifierBuffer);
779 } else {
780 II = getIdentifierInfo(CleanedStr);
781 }
782 }
783
784 // Update the token info (identifier info and appropriate token kind).
785 // FIXME: the raw_identifier may contain leading whitespace which is removed
786 // from the cleaned identifier token. The SourceLocation should be updated to
787 // refer to the non-whitespace character. For instance, the text "\\\nB" (a
788 // line continuation before 'B') is parsed as a single tok::raw_identifier and
789 // is cleaned to tok::identifier "B". After cleaning the token's length is
790 // still 3 and the SourceLocation refers to the location of the backslash.
791 Identifier.setIdentifierInfo(II);
792 Identifier.setKind(II->getTokenID());
793
794 return II;
795}
796
798 PoisonReasons[II] = DiagID;
799}
800
802 assert(Ident__exception_code && Ident__exception_info);
803 assert(Ident___exception_code && Ident___exception_info);
804 Ident__exception_code->setIsPoisoned(Poison);
805 Ident___exception_code->setIsPoisoned(Poison);
806 Ident_GetExceptionCode->setIsPoisoned(Poison);
807 Ident__exception_info->setIsPoisoned(Poison);
808 Ident___exception_info->setIsPoisoned(Poison);
809 Ident_GetExceptionInfo->setIsPoisoned(Poison);
810 Ident__abnormal_termination->setIsPoisoned(Poison);
811 Ident___abnormal_termination->setIsPoisoned(Poison);
812 Ident_AbnormalTermination->setIsPoisoned(Poison);
813}
814
816 assert(Identifier.getIdentifierInfo() &&
817 "Can't handle identifiers without identifier info!");
818 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
819 PoisonReasons.find(Identifier.getIdentifierInfo());
820 if(it == PoisonReasons.end())
821 Diag(Identifier, diag::err_pp_used_poisoned_id);
822 else
823 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
824}
825
826void Preprocessor::updateOutOfDateIdentifier(const IdentifierInfo &II) const {
827 assert(II.isOutOfDate() && "not out of date");
828 assert(getExternalSource() &&
829 "getExternalSource() should not return nullptr");
831}
832
833/// HandleIdentifier - This callback is invoked when the lexer reads an
834/// identifier. This callback looks up the identifier in the map and/or
835/// potentially macro expands it or turns it into a named token (like 'for').
836///
837/// Note that callers of this method are guarded by checking the
838/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
839/// IdentifierInfo methods that compute these properties will need to change to
840/// match.
842 assert(Identifier.getIdentifierInfo() &&
843 "Can't handle identifiers without identifier info!");
844
845 IdentifierInfo &II = *Identifier.getIdentifierInfo();
846
847 // If the information about this identifier is out of date, update it from
848 // the external source.
849 // We have to treat __VA_ARGS__ in a special way, since it gets
850 // serialized with isPoisoned = true, but our preprocessor may have
851 // unpoisoned it if we're defining a C99 macro.
852 if (II.isOutOfDate()) {
853 bool CurrentIsPoisoned = false;
854 const bool IsSpecialVariadicMacro =
855 &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
856 if (IsSpecialVariadicMacro)
857 CurrentIsPoisoned = II.isPoisoned();
858
859 updateOutOfDateIdentifier(II);
860 Identifier.setKind(II.getTokenID());
861
862 if (IsSpecialVariadicMacro)
863 II.setIsPoisoned(CurrentIsPoisoned);
864 }
865
866 // If this identifier was poisoned, and if it was not produced from a macro
867 // expansion, emit an error.
868 if (II.isPoisoned() && CurPPLexer) {
869 HandlePoisonedIdentifier(Identifier);
870 }
871
872 // If this is a macro to be expanded, do it.
873 if (const MacroDefinition MD = getMacroDefinition(&II)) {
874 const auto *MI = MD.getMacroInfo();
875 assert(MI && "macro definition with no macro info?");
876 if (!DisableMacroExpansion) {
877 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
878 // C99 6.10.3p10: If the preprocessing token immediately after the
879 // macro name isn't a '(', this macro should not be expanded.
880 if (!MI->isFunctionLike() || isNextPPTokenOneOf(tok::l_paren))
881 return HandleMacroExpandedIdentifier(Identifier, MD);
882 } else {
883 // C99 6.10.3.4p2 says that a disabled macro may never again be
884 // expanded, even if it's in a context where it could be expanded in the
885 // future.
886 Identifier.setFlag(Token::DisableExpand);
887 if (MI->isObjectLike() || isNextPPTokenOneOf(tok::l_paren))
888 Diag(Identifier, diag::pp_disabled_macro_expansion);
889 }
890 }
891 }
892
893 // If this identifier is a keyword in a newer Standard or proposed Standard,
894 // produce a warning. Don't warn if we're not considering macro expansion,
895 // since this identifier might be the name of a macro.
896 // FIXME: This warning is disabled in cases where it shouldn't be, like
897 // "#define constexpr constexpr", "int constexpr;"
898 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
899 Diag(Identifier, getIdentifierTable().getFutureCompatDiagKind(II, getLangOpts()))
900 << II.getName();
901 // Don't diagnose this keyword again in this translation unit.
902 II.setIsFutureCompatKeyword(false);
903 }
904
905 // If this identifier would be a keyword in C++, diagnose as a compatibility
906 // issue.
907 if (II.IsKeywordInCPlusPlus() && !DisableMacroExpansion)
908 Diag(Identifier, diag::warn_pp_identifier_is_cpp_keyword) << &II;
909
910 // If this is an extension token, diagnose its use.
911 // We avoid diagnosing tokens that originate from macro definitions.
912 // FIXME: This warning is disabled in cases where it shouldn't be,
913 // like "#define TY typeof", "TY(1) x".
914 if (II.isExtensionToken() && !DisableMacroExpansion)
915 Diag(Identifier, diag::ext_token_used);
916
917 // Handle module contextual keywords.
918 if (getLangOpts().CPlusPlusModules && CurLexer &&
919 !CurLexer->isLexingRawMode() && !CurLexer->isPragmaLexer() &&
920 !CurLexer->ParsingPreprocessorDirective &&
921 Identifier.isModuleContextualKeyword() &&
922 HandleModuleContextualKeyword(Identifier)) {
923 HandleDirective(Identifier);
924 // With a fatal failure in the module loader, we abort parsing.
926 }
927
928 return true;
929}
930
932 ++LexLevel;
933
934 // We loop here until a lex function returns a token; this avoids recursion.
935 while (!CurLexerCallback(*this, Result))
936 ;
937
938 if (Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure)
939 return;
940
941 if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
942 // Remember the identifier before code completion token.
943 setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
944 setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
945 // Set IdenfitierInfo to null to avoid confusing code that handles both
946 // identifiers and completion tokens.
947 Result.setIdentifierInfo(nullptr);
948 }
949
950 // Update StdCXXImportSeqState to track our position within a C++20 import-seq
951 // if this token is being produced as a result of phase 4 of translation.
952 // Update TrackGMFState to decide if we are currently in a Global Module
953 // Fragment. GMF state updates should precede StdCXXImportSeq ones, since GMF state
954 // depends on the prevailing StdCXXImportSeq state in two cases.
955 if (getLangOpts().CPlusPlusModules && LexLevel == 1 &&
956 !Result.getFlag(Token::IsReinjected)) {
957 switch (Result.getKind()) {
958 case tok::l_paren: case tok::l_square: case tok::l_brace:
959 StdCXXImportSeqState.handleOpenBracket();
960 break;
961 case tok::r_paren: case tok::r_square:
962 StdCXXImportSeqState.handleCloseBracket();
963 break;
964 case tok::r_brace:
965 StdCXXImportSeqState.handleCloseBrace();
966 break;
967#define PRAGMA_ANNOTATION(X) case tok::annot_##X:
968// For `#pragma ...` mimic ';'.
969#include "clang/Basic/TokenKinds.def"
970#undef PRAGMA_ANNOTATION
971 // This token is injected to represent the translation of '#include "a.h"'
972 // into "import a.h;". Mimic the notional ';'.
973 case tok::annot_module_include:
974 case tok::annot_repl_input_end:
975 case tok::semi:
976 TrackGMFState.handleSemi();
977 StdCXXImportSeqState.handleSemi();
978 ModuleDeclState.handleSemi();
979 break;
980 case tok::header_name:
981 case tok::annot_header_unit:
982 StdCXXImportSeqState.handleHeaderName();
983 break;
984 case tok::kw_export:
987 TrackGMFState.handleExport();
988 StdCXXImportSeqState.handleExport();
989 ModuleDeclState.handleExport();
990 break;
991 case tok::colon:
992 ModuleDeclState.handleColon();
993 break;
994 case tok::kw_import:
995 if (StdCXXImportSeqState.atTopLevel()) {
996 TrackGMFState.handleImport(StdCXXImportSeqState.afterTopLevelSeq());
997 StdCXXImportSeqState.handleImport();
998 }
999 break;
1000 case tok::kw_module:
1001 if (StdCXXImportSeqState.atTopLevel()) {
1004 TrackGMFState.handleModule(StdCXXImportSeqState.afterTopLevelSeq());
1005 ModuleDeclState.handleModule();
1006 }
1007 break;
1008 case tok::annot_module_name:
1009 ModuleDeclState.handleModuleName(
1010 static_cast<ModuleNameLoc *>(Result.getAnnotationValue()));
1011 if (ModuleDeclState.isModuleCandidate())
1012 break;
1013 [[fallthrough]];
1014 default:
1015 TrackGMFState.handleMisc();
1016 StdCXXImportSeqState.handleMisc();
1017 ModuleDeclState.handleMisc();
1018 break;
1019 }
1020 }
1021
1022 if (RecordCheckPoints && CurLexer &&
1023 ++CheckPointCounter == CheckPointStepSize) {
1024 CheckPoints[CurLexer->getFileID()].push_back(CurLexer->BufferPtr);
1025 CheckPointCounter = 0;
1026 }
1027
1028 if (Result.isNot(tok::kw_export))
1029 LastExportKeyword.startToken();
1030
1031 --LexLevel;
1032
1033 // Destroy any lexers that were deferred while we were in nested Lex calls.
1034 // This must happen after decrementing LexLevel but before any other
1035 // processing that might re-enter Lex.
1036 if (LexLevel == 0 && !PendingDestroyLexers.empty())
1037 PendingDestroyLexers.clear();
1038
1039 if ((LexLevel == 0 || PreprocessToken) &&
1040 !Result.getFlag(Token::IsReinjected)) {
1041 if (LexLevel == 0)
1042 ++TokenCount;
1043 if (OnToken)
1044 OnToken(Result);
1045 }
1046}
1047
1048void Preprocessor::LexTokensUntilEOF(std::vector<Token> *Tokens) {
1049 while (1) {
1050 Token Tok;
1051 Lex(Tok);
1052 if (Tok.isOneOf(tok::unknown, tok::eof, tok::eod,
1053 tok::annot_repl_input_end))
1054 break;
1055 if (Tokens != nullptr)
1056 Tokens->push_back(Tok);
1057 }
1058}
1059
1060/// Lex a header-name token (including one formed from header-name-tokens if
1061/// \p AllowMacroExpansion is \c true).
1062///
1063/// \param FilenameTok Filled in with the next token. On success, this will
1064/// be either a header_name token. On failure, it will be whatever other
1065/// token was found instead.
1066/// \param AllowMacroExpansion If \c true, allow the header name to be formed
1067/// by macro expansion (concatenating tokens as necessary if the first
1068/// token is a '<').
1069/// \return \c true if we reached EOD or EOF while looking for a > token in
1070/// a concatenated header name and diagnosed it. \c false otherwise.
1071bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) {
1072 // Lex using header-name tokenization rules if tokens are being lexed from
1073 // a file. Just grab a token normally if we're in a macro expansion.
1074 if (CurPPLexer) {
1075 // Avoid nested header-name lexing when macro expansion recurses
1076 // __has_include(__has_include))
1077 if (CurPPLexer->ParsingFilename)
1078 LexUnexpandedToken(FilenameTok);
1079 else
1080 CurPPLexer->LexIncludeFilename(FilenameTok);
1081 } else {
1082 Lex(FilenameTok);
1083 }
1084
1085 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1086 // case, glue the tokens together into an angle_string_literal token.
1087 SmallString<128> FilenameBuffer;
1088 if (FilenameTok.is(tok::less) && AllowMacroExpansion) {
1089 bool StartOfLine = FilenameTok.isAtStartOfLine();
1090 bool LeadingSpace = FilenameTok.hasLeadingSpace();
1091 bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro();
1092
1093 SourceLocation Start = FilenameTok.getLocation();
1094 SourceLocation End;
1095 FilenameBuffer.push_back('<');
1096
1097 // Consume tokens until we find a '>'.
1098 // FIXME: A header-name could be formed starting or ending with an
1099 // alternative token. It's not clear whether that's ill-formed in all
1100 // cases.
1101 while (FilenameTok.isNot(tok::greater)) {
1102 Lex(FilenameTok);
1103 if (FilenameTok.isOneOf(tok::eod, tok::eof)) {
1104 Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater;
1105 Diag(Start, diag::note_matching) << tok::less;
1106 return true;
1107 }
1108
1109 End = FilenameTok.getLocation();
1110
1111 // FIXME: Provide code completion for #includes.
1112 if (FilenameTok.is(tok::code_completion)) {
1114 Lex(FilenameTok);
1115 continue;
1116 }
1117
1118 // Append the spelling of this token to the buffer. If there was a space
1119 // before it, add it now.
1120 if (FilenameTok.hasLeadingSpace())
1121 FilenameBuffer.push_back(' ');
1122
1123 // Get the spelling of the token, directly into FilenameBuffer if
1124 // possible.
1125 size_t PreAppendSize = FilenameBuffer.size();
1126 FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength());
1127
1128 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1129 unsigned ActualLen = getSpelling(FilenameTok, BufPtr);
1130
1131 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1132 if (BufPtr != &FilenameBuffer[PreAppendSize])
1133 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1134
1135 // Resize FilenameBuffer to the correct size.
1136 if (FilenameTok.getLength() != ActualLen)
1137 FilenameBuffer.resize(PreAppendSize + ActualLen);
1138 }
1139
1140 FilenameTok.startToken();
1141 FilenameTok.setKind(tok::header_name);
1142 FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine);
1143 FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace);
1144 FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro);
1145 CreateString(FilenameBuffer, FilenameTok, Start, End);
1146 } else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) {
1147 // Convert a string-literal token of the form " h-char-sequence "
1148 // (produced by macro expansion) into a header-name token.
1149 //
1150 // The rules for header-names don't quite match the rules for
1151 // string-literals, but all the places where they differ result in
1152 // undefined behavior, so we can and do treat them the same.
1153 //
1154 // A string-literal with a prefix or suffix is not translated into a
1155 // header-name. This could theoretically be observable via the C++20
1156 // context-sensitive header-name formation rules.
1157 StringRef Str = getSpelling(FilenameTok, FilenameBuffer);
1158 if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"')
1159 FilenameTok.setKind(tok::header_name);
1160 }
1161
1162 return false;
1163}
1164
1165std::optional<Token> Preprocessor::peekNextPPToken() const {
1166 // Do some quick tests for rejection cases.
1167 std::optional<Token> Val;
1168 if (CurLexer)
1169 Val = CurLexer->peekNextPPToken();
1170 else
1171 Val = CurTokenLexer->peekNextPPToken();
1172
1173 if (!Val) {
1174 // We have run off the end. If it's a source file we don't
1175 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
1176 // macro stack.
1177 if (CurPPLexer)
1178 return std::nullopt;
1179 for (const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) {
1180 if (Entry.TheLexer)
1181 Val = Entry.TheLexer->peekNextPPToken();
1182 else
1183 Val = Entry.TheTokenLexer->peekNextPPToken();
1184
1185 if (Val)
1186 break;
1187
1188 // Ran off the end of a source file?
1189 if (Entry.ThePPLexer)
1190 return std::nullopt;
1191 }
1192 }
1193
1194 // Okay, we found the token and return. Otherwise we found the end of the
1195 // translation unit.
1196 return Val;
1197}
1198
1199// We represent the primary and partition names as 'Paths' which are sections
1200// of the hierarchical access path for a clang module. However for C++20
1201// the periods in a name are just another character, and we will need to
1202// flatten them into a string.
1204 std::string Name;
1205 if (Path.empty())
1206 return Name;
1207
1208 for (auto &Piece : Path) {
1209 assert(Piece.getIdentifierInfo() && Piece.getLoc().isValid());
1210 if (!Name.empty())
1211 Name += ".";
1212 Name += Piece.getIdentifierInfo()->getName();
1213 }
1214 return Name;
1215}
1216
1218 assert(!Path.empty() && "expect at least one identifier in a module name");
1219 void *Mem = PP.getPreprocessorAllocator().Allocate(
1220 totalSizeToAlloc<IdentifierLoc>(Path.size()), alignof(ModuleNameLoc));
1221 return new (Mem) ModuleNameLoc(Path);
1222}
1223
1225 SmallVectorImpl<Token> &Suffix,
1227 bool AllowMacroExpansion,
1228 bool IsPartition) {
1229 auto ConsumeToken = [&]() {
1230 if (AllowMacroExpansion)
1231 Lex(Tok);
1232 else
1234 Suffix.push_back(Tok);
1235 };
1236
1237 while (true) {
1238 if (Tok.isNot(tok::identifier)) {
1239 if (Tok.is(tok::code_completion)) {
1240 CurLexer->cutOffLexing();
1241 CodeComplete->CodeCompleteModuleImport(UseLoc, Path);
1242 return true;
1243 }
1244
1245 Diag(Tok, diag::err_pp_module_expected_ident) << Path.empty();
1246 return true;
1247 }
1248
1249 // [cpp.pre]/p2:
1250 // No identifier in the pp-module-name or pp-module-partition shall
1251 // currently be defined as an object-like macro.
1252 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo());
1253 MI && MI->isObjectLike() && getLangOpts().CPlusPlus20 &&
1254 !AllowMacroExpansion) {
1255 Diag(Tok, diag::err_pp_module_name_is_macro)
1256 << IsPartition << Tok.getIdentifierInfo();
1257 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
1258 << Tok.getIdentifierInfo();
1259 }
1260
1261 // Record this part of the module path.
1262 Path.emplace_back(Tok.getLocation(), Tok.getIdentifierInfo());
1263 ConsumeToken();
1264
1265 if (Tok.isNot(tok::period))
1266 return false;
1267
1268 ConsumeToken();
1269 }
1270}
1271
1272bool Preprocessor::HandleModuleName(StringRef DirType, SourceLocation UseLoc,
1273 Token &Tok,
1275 SmallVectorImpl<Token> &DirToks,
1276 bool AllowMacroExpansion,
1277 bool IsPartition) {
1278 bool LeadingSpace = Tok.hasLeadingSpace();
1279 unsigned NumToksInDirective = DirToks.size();
1280 if (LexModuleNameContinue(Tok, UseLoc, DirToks, Path, AllowMacroExpansion,
1281 IsPartition)) {
1282 if (Tok.isNot(tok::eod))
1283 CheckEndOfDirective(DirType,
1284 /*EnableMacros=*/false, &DirToks);
1286 return true;
1287 }
1288
1289 // Clean the module-name tokens and replace these tokens with
1290 // annot_module_name.
1291 DirToks.resize(NumToksInDirective);
1292 ModuleNameLoc *NameLoc = ModuleNameLoc::Create(*this, Path);
1293 DirToks.emplace_back();
1294 DirToks.back().setKind(tok::annot_module_name);
1295 DirToks.back().setAnnotationRange(NameLoc->getRange());
1296 DirToks.back().setAnnotationValue(static_cast<void *>(NameLoc));
1297 DirToks.back().setFlagValue(Token::LeadingSpace, LeadingSpace);
1298 DirToks.push_back(Tok);
1299 return false;
1300}
1301
1302/// [cpp.pre]/p2:
1303/// A preprocessing directive consists of a sequence of preprocessing tokens
1304/// that satisfies the following constraints: At the start of translation phase
1305/// 4, the first preprocessing token in the sequence, referred to as a
1306/// directive-introducing token, begins with the first character in the source
1307/// file (optionally after whitespace containing no new-line characters) or
1308/// follows whitespace containing at least one new-line character, and is:
1309/// - a # preprocessing token, or
1310/// - an import preprocessing token immediately followed on the same logical
1311/// source line by a header-name, <, identifier, or : preprocessing token, or
1312/// - a module preprocessing token immediately followed on the same logical
1313/// source line by an identifier, :, or ; preprocessing token, or
1314/// - an export preprocessing token immediately followed on the same logical
1315/// source line by one of the two preceding forms.
1316///
1317///
1318/// At the start of phase 4 an import or module token is treated as starting a
1319/// directive and are converted to their respective keywords iff:
1320/// - After skipping horizontal whitespace are
1321/// - at the start of a logical line, or
1322/// - preceded by an 'export' at the start of the logical line.
1323/// - Are followed by an identifier pp token (before macro expansion), or
1324/// - <, ", or : (but not ::) pp tokens for 'import', or
1325/// - ; for 'module'
1326/// Otherwise the token is treated as an identifier.
1328 if (!getLangOpts().CPlusPlusModules || !Result.isModuleContextualKeyword())
1329 return false;
1330
1331 if (Result.is(tok::kw_export)) {
1332 LastExportKeyword = Result;
1333 return false;
1334 }
1335
1336 /// Trait 'module' and 'import' as a identifier when the main file is a
1337 /// preprocessed module file. We only allow '__preprocessed_module' and
1338 /// '__preprocessed_import' in this context.
1339 IdentifierInfo *II = Result.getIdentifierInfo();
1341 (II->isStr(tok::getKeywordSpelling(tok::kw_import)) ||
1342 II->isStr(tok::getKeywordSpelling(tok::kw_module))))
1343 return false;
1344
1345 if (LastExportKeyword.is(tok::kw_export)) {
1346 // The export keyword was not at the start of line, it's not a
1347 // directive-introducing token.
1348 if (!LastExportKeyword.isAtPhysicalStartOfLine())
1349 return false;
1350 // [cpp.pre]/1.4
1351 // export // not a preprocessing directive
1352 // import foo; // preprocessing directive (ill-formed at phase7)
1353 if (Result.isAtPhysicalStartOfLine())
1354 return false;
1355 } else if (!Result.isAtPhysicalStartOfLine())
1356 return false;
1357
1358 assert(CurPPLexer && "CurPPLexer must not be null");
1359
1360 llvm::SaveAndRestore<bool> SavedParsingPreprocessorDirective(
1361 CurPPLexer->ParsingPreprocessorDirective, true);
1362
1363 if (II->isModuleKeyword()) {
1364 if (auto NextTok = peekNextPPToken()) {
1365 if (NextTok->is(tok::raw_identifier))
1366 LookUpIdentifierInfo(*NextTok);
1367 if (NextTok->isOneOf(tok::identifier, tok::colon, tok::semi)) {
1368 Result.setKind(tok::kw_module);
1369 ModuleDeclLoc = Result.getLocation();
1370 return true;
1371 }
1372 }
1373 return false;
1374 }
1375
1376 if (II->isImportKeyword()) {
1377 llvm::SaveAndRestore<bool> SavedParsingFilename(CurPPLexer->ParsingFilename,
1378 true);
1379 if (auto NextTok = peekNextPPToken()) {
1380 if (NextTok->is(tok::raw_identifier))
1381 LookUpIdentifierInfo(*NextTok);
1382 if (NextTok->isOneOf(tok::header_name, tok::identifier, tok::colon,
1383 tok::less)) {
1384 Result.setKind(tok::kw_import);
1385 ModuleImportLoc = Result.getLocation();
1386 return true;
1387 }
1388 }
1389 return false;
1390 }
1391
1392 // Ok, it's an identifier.
1393 return false;
1394}
1395
1397 SmallVectorImpl<Token> &Toks, bool StopUntilEOD) {
1400 return false;
1401}
1402
1403/// Collect the tokens of a C++20 pp-import-suffix.
1405 bool StopUntilEOD) {
1406 while (true) {
1407 Toks.emplace_back();
1408 Lex(Toks.back());
1409
1410 switch (Toks.back().getKind()) {
1411 case tok::semi:
1412 if (!StopUntilEOD)
1413 return;
1414 [[fallthrough]];
1415 case tok::eod:
1416 case tok::eof:
1417 return;
1418 default:
1419 break;
1420 }
1421 }
1422}
1423
1424// Allocate a holding buffer for a sequence of tokens and introduce it into
1425// the token stream.
1427 if (Toks.empty())
1428 return;
1429 auto ToksCopy = std::make_unique<Token[]>(Toks.size());
1430 std::copy(Toks.begin(), Toks.end(), ToksCopy.get());
1431 EnterTokenStream(std::move(ToksCopy), Toks.size(),
1432 /*DisableMacroExpansion*/ false, /*IsReinject*/ false);
1433 assert(CurTokenLexer && "Must have a TokenLexer");
1434 CurTokenLexer->setLexingCXXModuleDirective();
1435}
1436
1438 bool IncludeExports) {
1439 CurSubmoduleState->VisibleModules.setVisible(
1440 M, Loc, IncludeExports, [](Module *) {},
1441 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
1442 // FIXME: Include the path in the diagnostic.
1443 // FIXME: Include the import location for the conflicting module.
1444 Diag(ModuleImportLoc, diag::warn_module_conflict)
1445 << Path[0]->getFullModuleName()
1446 << Conflict->getFullModuleName()
1447 << Message;
1448 });
1449
1450 // Add this module to the imports list of the currently-built submodule.
1451 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
1452 BuildingSubmoduleStack.back().M->Imports.push_back(M);
1453}
1454
1456 const char *DiagnosticTag,
1457 bool AllowMacroExpansion) {
1458 // We need at least one string literal.
1459 if (Result.isNot(tok::string_literal)) {
1460 Diag(Result, diag::err_expected_string_literal)
1461 << /*Source='in...'*/0 << DiagnosticTag;
1462 return false;
1463 }
1464
1465 // Lex string literal tokens, optionally with macro expansion.
1466 SmallVector<Token, 4> StrToks;
1467 do {
1468 StrToks.push_back(Result);
1469
1470 if (Result.hasUDSuffix())
1471 Diag(Result, diag::err_invalid_string_udl);
1472
1473 if (AllowMacroExpansion)
1474 Lex(Result);
1475 else
1477 } while (Result.is(tok::string_literal));
1478
1479 // Concatenate and parse the strings.
1480 StringLiteralParser Literal(StrToks, *this);
1481 assert(Literal.isOrdinary() && "Didn't allow wide strings in");
1482
1483 if (Literal.hadError)
1484 return false;
1485
1486 if (Literal.Pascal) {
1487 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
1488 << /*Source='in...'*/0 << DiagnosticTag;
1489 return false;
1490 }
1491
1492 String = std::string(Literal.GetString());
1493 return true;
1494}
1495
1497 assert(Tok.is(tok::numeric_constant));
1498 SmallString<8> IntegerBuffer;
1499 bool NumberInvalid = false;
1500 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
1501 if (NumberInvalid)
1502 return false;
1503 NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(),
1505 getDiagnostics());
1506 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
1507 return false;
1508 llvm::APInt APVal(64, 0);
1509 if (Literal.GetIntegerValue(APVal))
1510 return false;
1511 Lex(Tok);
1512 Value = APVal.getLimitedValue();
1513 return true;
1514}
1515
1517 assert(Handler && "NULL comment handler");
1518 assert(!llvm::is_contained(CommentHandlers, Handler) &&
1519 "Comment handler already registered");
1520 CommentHandlers.push_back(Handler);
1521}
1522
1524 std::vector<CommentHandler *>::iterator Pos =
1525 llvm::find(CommentHandlers, Handler);
1526 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
1527 CommentHandlers.erase(Pos);
1528}
1529
1531 bool AnyPendingTokens = false;
1532 for (CommentHandler *H : CommentHandlers) {
1533 if (H->HandleComment(*this, Comment))
1534 AnyPendingTokens = true;
1535 }
1536 if (!AnyPendingTokens || getCommentRetentionState())
1537 return false;
1538 Lex(result);
1539 return true;
1540}
1541
1542void Preprocessor::emitMacroDeprecationWarning(const Token &Identifier) const {
1543 const MacroAnnotations &A =
1545 assert(A.DeprecationInfo &&
1546 "Macro deprecation warning without recorded annotation!");
1547 const MacroAnnotationInfo &Info = *A.DeprecationInfo;
1548 if (Info.Message.empty())
1549 Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1550 << Identifier.getIdentifierInfo() << 0;
1551 else
1552 Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1553 << Identifier.getIdentifierInfo() << 1 << Info.Message;
1554 Diag(Info.Location, diag::note_pp_macro_annotation) << 0;
1555}
1556
1557void Preprocessor::emitRestrictExpansionWarning(const Token &Identifier) const {
1558 const MacroAnnotations &A =
1560 assert(A.RestrictExpansionInfo &&
1561 "Macro restricted expansion warning without recorded annotation!");
1562 const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo;
1563 if (Info.Message.empty())
1564 Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1565 << Identifier.getIdentifierInfo() << 0;
1566 else
1567 Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1568 << Identifier.getIdentifierInfo() << 1 << Info.Message;
1569 Diag(Info.Location, diag::note_pp_macro_annotation) << 1;
1570}
1571
1572void Preprocessor::emitRestrictInfNaNWarning(const Token &Identifier,
1573 unsigned DiagSelection) const {
1574 Diag(Identifier, diag::warn_fp_nan_inf_when_disabled) << DiagSelection << 1;
1575}
1576
1577void Preprocessor::emitFinalMacroWarning(const Token &Identifier,
1578 bool IsUndef) const {
1579 const MacroAnnotations &A =
1581 assert(A.FinalAnnotationLoc &&
1582 "Final macro warning without recorded annotation!");
1583
1584 Diag(Identifier, diag::warn_pragma_final_macro)
1585 << Identifier.getIdentifierInfo() << (IsUndef ? 0 : 1);
1586 Diag(*A.FinalAnnotationLoc, diag::note_pp_macro_annotation) << 2;
1587}
1588
1590 const SourceLocation &Loc) const {
1591 // The lambda that tests if a `Loc` is in an opt-out region given one opt-out
1592 // region map:
1593 auto TestInMap = [&SourceMgr](const SafeBufferOptOutRegionsTy &Map,
1594 const SourceLocation &Loc) -> bool {
1595 // Try to find a region in `SafeBufferOptOutMap` where `Loc` is in:
1596 auto FirstRegionEndingAfterLoc = llvm::partition_point(
1597 Map, [&SourceMgr,
1598 &Loc](const std::pair<SourceLocation, SourceLocation> &Region) {
1599 return SourceMgr.isBeforeInTranslationUnit(Region.second, Loc);
1600 });
1601
1602 if (FirstRegionEndingAfterLoc != Map.end()) {
1603 // To test if the start location of the found region precedes `Loc`:
1604 return SourceMgr.isBeforeInTranslationUnit(
1605 FirstRegionEndingAfterLoc->first, Loc);
1606 }
1607 // If we do not find a region whose end location passes `Loc`, we want to
1608 // check if the current region is still open:
1609 if (!Map.empty() && Map.back().first == Map.back().second)
1610 return SourceMgr.isBeforeInTranslationUnit(Map.back().first, Loc);
1611 return false;
1612 };
1613
1614 // What the following does:
1615 //
1616 // If `Loc` belongs to the local TU, we just look up `SafeBufferOptOutMap`.
1617 // Otherwise, `Loc` is from a loaded AST. We look up the
1618 // `LoadedSafeBufferOptOutMap` first to get the opt-out region map of the
1619 // loaded AST where `Loc` is at. Then we find if `Loc` is in an opt-out
1620 // region w.r.t. the region map. If the region map is absent, it means there
1621 // is no opt-out pragma in that loaded AST.
1622 //
1623 // Opt-out pragmas in the local TU or a loaded AST is not visible to another
1624 // one of them. That means if you put the pragmas around a `#include
1625 // "module.h"`, where module.h is a module, it is not actually suppressing
1626 // warnings in module.h. This is fine because warnings in module.h will be
1627 // reported when module.h is compiled in isolation and nothing in module.h
1628 // will be analyzed ever again. So you will not see warnings from the file
1629 // that imports module.h anyway. And you can't even do the same thing for PCHs
1630 // because they can only be included from the command line.
1631
1632 if (SourceMgr.isLocalSourceLocation(Loc))
1633 return TestInMap(SafeBufferOptOutMap, Loc);
1634
1635 const SafeBufferOptOutRegionsTy *LoadedRegions =
1636 LoadedSafeBufferOptOutMap.lookupLoadedOptOutMap(Loc, SourceMgr);
1637
1638 if (LoadedRegions)
1639 return TestInMap(*LoadedRegions, Loc);
1640 return false;
1641}
1642
1644 bool isEnter, const SourceLocation &Loc) {
1645 if (isEnter) {
1647 return true; // invalid enter action
1648 InSafeBufferOptOutRegion = true;
1649 CurrentSafeBufferOptOutStart = Loc;
1650
1651 // To set the start location of a new region:
1652
1653 if (!SafeBufferOptOutMap.empty()) {
1654 [[maybe_unused]] auto *PrevRegion = &SafeBufferOptOutMap.back();
1655 assert(PrevRegion->first != PrevRegion->second &&
1656 "Shall not begin a safe buffer opt-out region before closing the "
1657 "previous one.");
1658 }
1659 // If the start location equals to the end location, we call the region a
1660 // open region or a unclosed region (i.e., end location has not been set
1661 // yet).
1662 SafeBufferOptOutMap.emplace_back(Loc, Loc);
1663 } else {
1665 return true; // invalid enter action
1666 InSafeBufferOptOutRegion = false;
1667
1668 // To set the end location of the current open region:
1669
1670 assert(!SafeBufferOptOutMap.empty() &&
1671 "Misordered safe buffer opt-out regions");
1672 auto *CurrRegion = &SafeBufferOptOutMap.back();
1673 assert(CurrRegion->first == CurrRegion->second &&
1674 "Set end location to a closed safe buffer opt-out region");
1675 CurrRegion->second = Loc;
1676 }
1677 return false;
1678}
1679
1681 return InSafeBufferOptOutRegion;
1682}
1684 StartLoc = CurrentSafeBufferOptOutStart;
1685 return InSafeBufferOptOutRegion;
1686}
1687
1690 assert(!InSafeBufferOptOutRegion &&
1691 "Attempt to serialize safe buffer opt-out regions before file being "
1692 "completely preprocessed");
1693
1695
1696 for (const auto &[begin, end] : SafeBufferOptOutMap) {
1697 SrcSeq.push_back(begin);
1698 SrcSeq.push_back(end);
1699 }
1700 // Only `SafeBufferOptOutMap` gets serialized. No need to serialize
1701 // `LoadedSafeBufferOptOutMap` because if this TU loads a pch/module, every
1702 // pch/module in the pch-chain/module-DAG will be loaded one by one in order.
1703 // It means that for each loading pch/module m, it just needs to load m's own
1704 // `SafeBufferOptOutMap`.
1705 return SrcSeq;
1706}
1707
1709 const SmallVectorImpl<SourceLocation> &SourceLocations) {
1710 if (SourceLocations.size() == 0)
1711 return false;
1712
1713 assert(SourceLocations.size() % 2 == 0 &&
1714 "ill-formed SourceLocation sequence");
1715
1716 auto It = SourceLocations.begin();
1717 SafeBufferOptOutRegionsTy &Regions =
1718 LoadedSafeBufferOptOutMap.findAndConsLoadedOptOutMap(*It, SourceMgr);
1719
1720 do {
1721 SourceLocation Begin = *It++;
1722 SourceLocation End = *It++;
1723
1724 Regions.emplace_back(Begin, End);
1725 } while (It != SourceLocations.end());
1726 return true;
1727}
1728
1729ModuleLoader::~ModuleLoader() = default;
1730
1732
1734
1736
1738 if (Record)
1739 return;
1740
1741 Record = new PreprocessingRecord(getSourceManager());
1742 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
1743}
1744
1746 auto IsPreserved = [&](PPCallbacks *C) {
1747 return C == Record || C == DirTracer;
1748 };
1750 PPCallbacks::releaseIfPreserved(Callbacks, IsPreserved, Released);
1751 Callbacks.reset();
1752 for (auto *P : Released)
1753 addPPCallbacks(std::unique_ptr<PPCallbacks>(P));
1754}
1755
1756const char *Preprocessor::getCheckPoint(FileID FID, const char *Start) const {
1757 if (auto It = CheckPoints.find(FID); It != CheckPoints.end()) {
1758 const SmallVector<const char *> &FileCheckPoints = It->second;
1759 auto P = llvm::upper_bound(FileCheckPoints, Start);
1760 if (P == FileCheckPoints.begin())
1761 return nullptr;
1762 return *std::prev(P);
1763 }
1764 return nullptr;
1765}
1766
1768 return DirTracer && DirTracer->hasSeenNoTrivialPPDirective();
1769}
1770
1772 return SeenNoTrivialPPDirective;
1773}
1774
1775void NoTrivialPPDirectiveTracer::setSeenNoTrivialPPDirective() {
1776 if (InMainFile && !SeenNoTrivialPPDirective)
1777 SeenNoTrivialPPDirective = true;
1778}
1779
1781 FileID FID, LexedFileChangeReason Reason,
1782 SrcMgr::CharacteristicKind FileType, FileID PrevFID, SourceLocation Loc) {
1783 InMainFile = (FID == PP.getSourceManager().getMainFileID());
1784}
1785
1787 const MacroDefinition &MD,
1788 SourceRange Range,
1789 const MacroArgs *Args) {
1790 // FIXME: Does only enable builtin macro expansion make sense?
1791 if (!MD.getMacroInfo()->isBuiltinMacro())
1792 setSeenNoTrivialPPDirective();
1793}
Defines enum values for all the target-independent builtin functions.
This is the interface for scanning header and source files to get the minimum necessary preprocessor ...
LLVM_INSTANTIATE_REGISTRY_EX(CLANG_ABI_EXPORT, clang::tooling::ToolExecutorPluginRegistry) namespace clang
Definition Execution.cpp:14
Defines the clang::FileManager interface and associated types.
unsigned ColumnWidth
The width of the non-whitespace parts of the token (or its first line for multi-line tokens) in colum...
Token Tok
The Token.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
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 PreprocessorLexer interface.
static bool MacroDefinitionEquals(const MacroInfo *MI, ArrayRef< TokenValue > Tokens)
Compares macro tokens with a specified token value sequence.
static constexpr unsigned CheckPointStepSize
Minimum distance between two check points, in tokens.
Defines the clang::Preprocessor interface.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
Abstract base class that describes a handler that will receive source ranges for each of the comments...
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
virtual void updateOutOfDateIdentifier(const IdentifierInfo &II)=0
Update an out-of-date identifier.
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
Cached information about one file (either on disk or in the virtual file system).
Definition FileEntry.h:273
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
bool isInvalid() const
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
Provides lookups to, and iteration over, IdentiferInfo objects.
One of these records is kept for each identifier that is lexed.
bool IsKeywordInCPlusPlus() const
Return true if this identifier would be a keyword in C++ mode.
bool isModuleKeyword() const
Determine whether this is the contextual keyword module.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
void setIsPoisoned(bool Value=true)
setIsPoisoned - Mark this identifier as poisoned.
bool isPoisoned() const
Return true if this token has been poisoned.
bool isImportKeyword() const
Determine whether this is the contextual keyword import.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
void setIsFutureCompatKeyword(bool Val)
StringRef getName() const
Return the actual identifier string.
bool isFutureCompatKeyword() const
is/setIsFutureCompatKeyword - Initialize information about whether or not this language token is a ke...
bool isExtensionToken() const
get/setExtension - Initialize information about whether or not this language token is an extension.
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
MacroArgs - An instance of this class captures information about the formal arguments specified to a ...
Definition MacroArgs.h:30
A description of the current definition of a macro.
Definition MacroInfo.h:596
MacroInfo * getMacroInfo() const
Get the MacroInfo that should be used for this definition.
Definition MacroInfo.h:612
SourceLocation getLocation() const
Definition MacroInfo.h:489
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:40
const_tokens_iterator tokens_begin() const
Definition MacroInfo.h:245
unsigned getNumTokens() const
Return the number of tokens that this macro expands to.
Definition MacroInfo.h:236
const Token & getReplacementToken(unsigned Tok) const
Definition MacroInfo.h:238
bool isBuiltinMacro() const
Return true if this macro requires processing before expansion.
Definition MacroInfo.h:218
bool isObjectLike() const
Definition MacroInfo.h:203
Abstract interface for a module loader.
virtual ~ModuleLoader()
static std::string getFlatNameFromPath(ModuleIdPath Path)
Represents a macro directive exported by a module.
Definition MacroInfo.h:515
static ModuleNameLoc * Create(Preprocessor &PP, ModuleIdPath Path)
SourceRange getRange() const
Describes a module or submodule.
Definition Module.h:340
void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD, SourceRange Range, const MacroArgs *Args) override
Called by Preprocessor::HandleMacroExpandedIdentifier when a macro invocation is found.
void LexedFileChanged(FileID FID, LexedFileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID, SourceLocation Loc) override
Callback invoked whenever the Lexer moves to a different file for lexing.
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber,...
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition PPCallbacks.h:37
static void releaseIfPreserved(std::unique_ptr< PPCallbacks > &CB, llvm::function_ref< bool(PPCallbacks *)> Pred, SmallVectorImpl< PPCallbacks * > &Released)
Walk the subtree rooted at CB (recursing into descendants first), then check CB itself.
PragmaNamespace - This PragmaHandler subdivides the namespace of pragmas, allowing hierarchical pragm...
Definition Pragma.h:96
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
void setConditionalLevels(ArrayRef< PPConditionalInfo > CL)
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::string PCHThroughHeader
If non-empty, the filename used in an include directive in the primary source file (or command-line p...
bool GeneratePreamble
True indicates that a preamble is being generated.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
bool markIncluded(FileEntryRef File)
Mark the file as included.
void FinalizeForModelFile()
Cleanup after model file parsing.
bool FinishLexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion)
Complete the lexing of a string literal where the first token has already been lexed (see LexStringLi...
bool creatingPCHWithThroughHeader()
True if creating a PCH with a through header.
void DumpToken(const Token &Tok, bool DumpFlags=false) const
Print the token to stderr, used for debugging.
void EnterModuleSuffixTokenStream(ArrayRef< Token > Toks)
void InitializeForModelFile()
Initialize the preprocessor to parse a model file.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
void setCodeCompletionTokenRange(const SourceLocation Start, const SourceLocation End)
Set the code completion token range for detecting replacement range later on.
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
bool isSafeBufferOptOut(const SourceManager &SourceMgr, const SourceLocation &Loc) const
const char * getCheckPoint(FileID FID, const char *Start) const
Returns a pointer into the given file's buffer that's guaranteed to be between tokens.
IdentifierInfo * LookUpIdentifierInfo(Token &Identifier) const
Given a tok::raw_identifier token, look up the identifier information for the token and install it in...
friend class MacroArgs
void DumpMacro(const MacroInfo &MI) const
llvm::iterator_range< macro_iterator > macros(bool IncludeExternalMacros=true) const
void setCodeCompletionReached()
Note that we hit the code-completion point.
bool SetCodeCompletionPoint(FileEntryRef File, unsigned Line, unsigned Column)
Specify the point at which code-completion will be performed.
void Lex(Token &Result)
Lex the next token for this preprocessor.
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
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 addCommentHandler(CommentHandler *Handler)
Add the specified comment handler to the preprocessor.
void removeCommentHandler(CommentHandler *Handler)
Remove the specified comment handler.
void HandlePoisonedIdentifier(Token &Identifier)
Display reason for poisoned identifier.
bool HandleIdentifier(Token &Identifier)
Callback invoked when the lexer reads an identifier and has filled in the tokens IdentifierInfo membe...
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
bool enterOrExitSafeBufferOptOutRegion(bool isEnter, const SourceLocation &Loc)
Alter the state of whether this PP currently is in a "-Wunsafe-buffer-usage" opt-out region.
void EnterMainSourceFile()
Enter the specified FileID as the main source file, which implicitly adds the builtin defines etc.
const MacroAnnotations & getMacroAnnotations(const IdentifierInfo *II) const
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceManager & getSourceManager() const
bool isBacktrackEnabled() const
True if EnableBacktrackAtThisPos() was called and caching of tokens is on.
MacroDefinition getMacroDefinition(const IdentifierInfo *II)
bool isPreprocessedModuleFile() const
Whether the main file is preprocessed module file.
void SetPoisonReason(IdentifierInfo *II, unsigned DiagID)
Specifies the reason for poisoning an identifier.
SourceLocation CheckEndOfDirective(StringRef DirType, bool EnableMacros=false, SmallVectorImpl< Token > *ExtraToks=nullptr)
Ensure that the next token is a tok::eod token.
bool getCommentRetentionState() const
Module * getCurrentModuleImplementation()
Retrieves the module whose implementation we're current compiling, if any.
void createPreprocessingRecord()
Create a new preprocessing record, which will keep track of all macro expansions, macro definitions,...
SourceLocation SplitToken(SourceLocation TokLoc, unsigned Length)
Split the first Length characters out of the token starting at TokLoc and return a location pointing ...
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
void makeModuleVisible(Module *M, SourceLocation Loc, bool IncludeExports=true)
bool hadModuleLoaderFatalFailure() const
void setCurrentFPEvalMethod(SourceLocation PragmaLoc, LangOptions::FPEvalMethodKind Val)
bool HandleModuleContextualKeyword(Token &Result)
Callback invoked when the lexer sees one of export, import or module token at the start of a line.
const TargetInfo & getTargetInfo() const
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.
void DumpLocation(SourceLocation Loc) const
bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value)
Parses a simple integer literal to get its numeric value.
void LexUnexpandedToken(Token &Result)
Just like Lex, but disables macro expansion of identifier tokens.
bool creatingPCHWithPragmaHdrStop()
True if creating a PCH with a pragma hdrstop.
void Initialize(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize the preprocessor using information about the target.
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
llvm::BumpPtrAllocator & getPreprocessorAllocator()
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 HandleComment(Token &result, SourceRange Comment)
HeaderSearch & getHeaderSearchInfo() const
bool setDeserializedSafeBufferOptOutMap(const SmallVectorImpl< SourceLocation > &SrcLocSeqs)
ExternalPreprocessorSource * getExternalSource() const
void HandleDirective(Token &Result)
Callback invoked when the lexer sees a # token at the start of a line.
SmallVector< SourceLocation, 64 > serializeSafeBufferOptOutMap() const
void recomputeCurLexerKind()
Recompute the current lexer kind based on the CurLexer/ CurTokenLexer pointers.
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.
IdentifierTable & getIdentifierTable()
bool LexModuleNameContinue(Token &Tok, SourceLocation UseLoc, SmallVectorImpl< Token > &Suffix, SmallVectorImpl< IdentifierLoc > &Path, bool AllowMacroExpansion, bool IsPartition)
const LangOptions & getLangOpts() const
void setTUFPEvalMethod(LangOptions::FPEvalMethodKind Val)
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled)
Hook used by the lexer to invoke the "included file" code completion point.
llvm::DenseMap< FileID, SafeBufferOptOutRegionsTy > LoadedRegions
void PoisonSEHIdentifiers(bool Poison=true)
size_t getTotalMemory() const
void LexTokensUntilEOF(std::vector< Token > *Tokens=nullptr)
Lex all tokens for this preprocessor until (and excluding) end of file.
bool isNextPPTokenOneOf(Ts... Ks) const
isNextPPTokenOneOf - Check whether the next pp-token is one of the specificed token kind.
bool usingPCHWithPragmaHdrStop()
True if using a PCH with a pragma hdrstop.
void CodeCompleteNaturalLanguage()
Hook used by the lexer to invoke the "natural language" code completion point.
void EndSourceFile()
Inform the preprocessor callbacks that processing is complete.
void CollectPPImportSuffix(SmallVectorImpl< Token > &Toks, bool StopUntilEOD=false)
Collect the tokens of a C++20 pp-import-suffix.
DiagnosticsEngine & getDiagnostics() const
bool hasSeenNoTrivialPPDirective() const
Whether we've seen pp-directives which may have changed the preprocessing state.
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
void setCodeCompletionIdentifierInfo(IdentifierInfo *Filter)
Set the code completion token for filtering purposes.
bool HandleModuleName(StringRef DirType, SourceLocation UseLoc, Token &Tok, SmallVectorImpl< IdentifierLoc > &Path, SmallVectorImpl< Token > &DirToks, bool AllowMacroExpansion, bool IsPartition)
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
void SkipTokensWhileUsingPCH()
Skip tokens until after the include of the through header or until after a pragma hdrstop.
bool usingPCHWithThroughHeader()
True if using a PCH with a through header.
bool CollectPPImportSuffixAndEnterStream(SmallVectorImpl< Token > &Toks, bool StopUntilEOD=false)
Preprocessor(const PreprocessorOptions &PPOpts, DiagnosticsEngine &diags, const LangOptions &LangOpts, SourceManager &SM, HeaderSearch &Headers, ModuleLoader &TheModuleLoader, IdentifierInfoLookup *IILookup=nullptr, bool OwnsHeaderSearch=false, TranslationUnitKind TUKind=TU_Complete)
Represents an unpacked "presumed" location which can be presented to the user.
unsigned getColumn() const
Return the presumed column number of this location.
unsigned getLine() const
Return the presumed line number of this location.
bool isInvalid() const
Return true if this object is invalid or uninitialized.
ScratchBuffer - This class exposes a simple interface for the dynamic construction of tokens.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
void print(raw_ostream &OS, const SourceManager &SM) const
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.
std::optional< StringRef > getBufferDataOrNone(FileID FID) const
Return a StringRef to the source buffer data for the specified FileID, returning std::nullopt if inva...
A trivial tuple used to represent a source range.
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
Exposes information about the current target.
Definition TargetInfo.h:227
Token - This structure provides full information about a lexed token.
Definition Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition Token.h:197
bool hasUCN() const
Returns true if this token contains a universal character name.
Definition Token.h:324
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:142
unsigned getLength() const
Definition Token.h:145
bool isExpandDisabled() const
Return true if this identifier token should never be expanded in the future, due to C99 6....
Definition Token.h:298
void setKind(tok::TokenKind K)
Definition Token.h:100
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:104
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition Token.h:286
bool isOneOf(Ts... Ks) const
Definition Token.h:105
@ DisableExpand
Definition Token.h:79
@ HasSeenNoTrivialPPDirective
Definition Token.h:92
@ IsReinjected
Definition Token.h:89
@ LeadingEmptyMacro
Definition Token.h:81
@ LeadingSpace
Definition Token.h:77
@ StartOfLine
Definition Token.h:75
bool isModuleContextualKeyword(bool AllowExport=true) const
Return true if we have a C++20 modules contextual keyword(export, importor module).
Definition Lexer.cpp:77
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
Definition Token.h:294
bool hasLeadingEmptyMacro() const
Return true if this token has an empty macro before it.
Definition Token.h:317
bool isNot(tok::TokenKind K) const
Definition Token.h:111
void startToken()
Reset all flags to cleared.
Definition Token.h:187
bool needsCleaning() const
Return true if this token has trigraphs or escaped newlines in it.
Definition Token.h:313
void setIdentifierInfo(IdentifierInfo *II)
Definition Token.h:206
void setFlagValue(TokenFlags Flag, bool Val)
Set a flag to either true or false.
Definition Token.h:277
StringRef getRawIdentifier() const
getRawIdentifier - For a raw identifier token (i.e., an identifier lexed in raw mode),...
Definition Token.h:223
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition Token.h:254
Defines the clang::TargetInfo interface.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
const char * getTokenName(TokenKind Kind) LLVM_READNONE
Determines the name of a token as used within the front end.
const char * getKeywordSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple keyword and contextual keyword tokens like 'int' and 'dynamic_cast'...
The JSON file list parser is used to communicate input to InstallAPI.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:196
@ CPlusPlus20
llvm::Registry< PragmaHandler > PragmaHandlerRegistry
Registry of pragma handlers added by plugins.
void expandUCNs(SmallVectorImpl< char > &Buf, StringRef Input)
Copy characters from Input to Buf, expanding any UCNs.
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
std::pair< FileID, unsigned > FileIDAndOffset
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isPreprocessedModuleFile(StringRef Source)
Scan an input source buffer, and check whether the input source is a preprocessed output.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
TranslationUnitKind
Describes the kind of translation unit being processed.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
#define true
Definition stdbool.h:25