llvm-project
1656 строк · 61.3 Кб
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
27#include "clang/Lex/Preprocessor.h"
28#include "clang/Basic/Builtins.h"
29#include "clang/Basic/FileManager.h"
30#include "clang/Basic/FileSystemStatCache.h"
31#include "clang/Basic/IdentifierTable.h"
32#include "clang/Basic/LLVM.h"
33#include "clang/Basic/LangOptions.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/SourceLocation.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/Lex/CodeCompletionHandler.h"
39#include "clang/Lex/ExternalPreprocessorSource.h"
40#include "clang/Lex/HeaderSearch.h"
41#include "clang/Lex/LexDiagnostic.h"
42#include "clang/Lex/Lexer.h"
43#include "clang/Lex/LiteralSupport.h"
44#include "clang/Lex/MacroArgs.h"
45#include "clang/Lex/MacroInfo.h"
46#include "clang/Lex/ModuleLoader.h"
47#include "clang/Lex/Pragma.h"
48#include "clang/Lex/PreprocessingRecord.h"
49#include "clang/Lex/PreprocessorLexer.h"
50#include "clang/Lex/PreprocessorOptions.h"
51#include "clang/Lex/ScratchBuffer.h"
52#include "clang/Lex/Token.h"
53#include "clang/Lex/TokenLexer.h"
54#include "llvm/ADT/APInt.h"
55#include "llvm/ADT/ArrayRef.h"
56#include "llvm/ADT/DenseMap.h"
57#include "llvm/ADT/STLExtras.h"
58#include "llvm/ADT/SmallString.h"
59#include "llvm/ADT/SmallVector.h"
60#include "llvm/ADT/StringRef.h"
61#include "llvm/ADT/iterator_range.h"
62#include "llvm/Support/Capacity.h"
63#include "llvm/Support/ErrorHandling.h"
64#include "llvm/Support/MemoryBuffer.h"
65#include "llvm/Support/raw_ostream.h"
66#include <algorithm>
67#include <cassert>
68#include <memory>
69#include <optional>
70#include <string>
71#include <utility>
72#include <vector>
73
74using namespace clang;
75
76/// Minimum distance between two check points, in tokens.
77static constexpr unsigned CheckPointStepSize = 1024;
78
79LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
80
81ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;
82
83Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
84DiagnosticsEngine &diags, const LangOptions &opts,
85SourceManager &SM, HeaderSearch &Headers,
86ModuleLoader &TheModuleLoader,
87IdentifierInfoLookup *IILookup, bool OwnsHeaders,
88TranslationUnitKind TUKind)
89: PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
90FileMgr(Headers.getFileMgr()), SourceMgr(SM),
91ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
92TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
93// As the language options may have not been loaded yet (when
94// deserializing an ASTUnit), adding keywords to the identifier table is
95// deferred to Preprocessor::Initialize().
96Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
97TUKind(TUKind), SkipMainFilePreamble(0, true),
98CurSubmoduleState(&NullSubmoduleState) {
99OwnsHeaderSearch = OwnsHeaders;
100
101// Default to discarding comments.
102KeepComments = false;
103KeepMacroComments = false;
104SuppressIncludeNotFoundError = false;
105
106// Macro expansion is enabled.
107DisableMacroExpansion = false;
108MacroExpansionInDirectivesOverride = false;
109InMacroArgs = false;
110ArgMacro = nullptr;
111InMacroArgPreExpansion = false;
112NumCachedTokenLexers = 0;
113PragmasEnabled = true;
114ParsingIfOrElifDirective = false;
115PreprocessedOutput = false;
116
117// We haven't read anything from the external source.
118ReadMacrosFromExternalSource = false;
119
120BuiltinInfo = std::make_unique<Builtin::Context>();
121
122// "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of
123// a macro. They get unpoisoned where it is allowed.
124(Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
125SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
126(Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
127SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
128
129// Initialize the pragma handlers.
130RegisterBuiltinPragmas();
131
132// Initialize builtin macros like __LINE__ and friends.
133RegisterBuiltinMacros();
134
135if(LangOpts.Borland) {
136Ident__exception_info = getIdentifierInfo("_exception_info");
137Ident___exception_info = getIdentifierInfo("__exception_info");
138Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
139Ident__exception_code = getIdentifierInfo("_exception_code");
140Ident___exception_code = getIdentifierInfo("__exception_code");
141Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
142Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
143Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
144Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
145} else {
146Ident__exception_info = Ident__exception_code = nullptr;
147Ident__abnormal_termination = Ident___exception_info = nullptr;
148Ident___exception_code = Ident___abnormal_termination = nullptr;
149Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
150Ident_AbnormalTermination = nullptr;
151}
152
153// Default incremental processing to -fincremental-extensions, clients can
154// override with `enableIncrementalProcessing` if desired.
155IncrementalProcessing = LangOpts.IncrementalExtensions;
156
157// If using a PCH where a #pragma hdrstop is expected, start skipping tokens.
158if (usingPCHWithPragmaHdrStop())
159SkippingUntilPragmaHdrStop = true;
160
161// If using a PCH with a through header, start skipping tokens.
162if (!this->PPOpts->PCHThroughHeader.empty() &&
163!this->PPOpts->ImplicitPCHInclude.empty())
164SkippingUntilPCHThroughHeader = true;
165
166if (this->PPOpts->GeneratePreamble)
167PreambleConditionalStack.startRecording();
168
169MaxTokens = LangOpts.MaxTokens;
170}
171
172Preprocessor::~Preprocessor() {
173assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
174
175IncludeMacroStack.clear();
176
177// Free any cached macro expanders.
178// This populates MacroArgCache, so all TokenLexers need to be destroyed
179// before the code below that frees up the MacroArgCache list.
180std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
181CurTokenLexer.reset();
182
183// Free any cached MacroArgs.
184for (MacroArgs *ArgList = MacroArgCache; ArgList;)
185ArgList = ArgList->deallocate();
186
187// Delete the header search info, if we own it.
188if (OwnsHeaderSearch)
189delete &HeaderInfo;
190}
191
192void Preprocessor::Initialize(const TargetInfo &Target,
193const TargetInfo *AuxTarget) {
194assert((!this->Target || this->Target == &Target) &&
195"Invalid override of target information");
196this->Target = &Target;
197
198assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
199"Invalid override of aux target information.");
200this->AuxTarget = AuxTarget;
201
202// Initialize information about built-ins.
203BuiltinInfo->InitializeTarget(Target, AuxTarget);
204HeaderInfo.setTarget(Target);
205
206// Populate the identifier table with info about keywords for the current language.
207Identifiers.AddKeywords(LangOpts);
208
209// Initialize the __FTL_EVAL_METHOD__ macro to the TargetInfo.
210setTUFPEvalMethod(getTargetInfo().getFPEvalMethod());
211
212if (getLangOpts().getFPEvalMethod() == LangOptions::FEM_UnsetOnCommandLine)
213// Use setting from TargetInfo.
214setCurrentFPEvalMethod(SourceLocation(), Target.getFPEvalMethod());
215else
216// Set initial value of __FLT_EVAL_METHOD__ from the command line.
217setCurrentFPEvalMethod(SourceLocation(), getLangOpts().getFPEvalMethod());
218}
219
220void Preprocessor::InitializeForModelFile() {
221NumEnteredSourceFiles = 0;
222
223// Reset pragmas
224PragmaHandlersBackup = std::move(PragmaHandlers);
225PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef());
226RegisterBuiltinPragmas();
227
228// Reset PredefinesFileID
229PredefinesFileID = FileID();
230}
231
232void Preprocessor::FinalizeForModelFile() {
233NumEnteredSourceFiles = 1;
234
235PragmaHandlers = std::move(PragmaHandlersBackup);
236}
237
238void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
239llvm::errs() << tok::getTokenName(Tok.getKind());
240
241if (!Tok.isAnnotation())
242llvm::errs() << " '" << getSpelling(Tok) << "'";
243
244if (!DumpFlags) return;
245
246llvm::errs() << "\t";
247if (Tok.isAtStartOfLine())
248llvm::errs() << " [StartOfLine]";
249if (Tok.hasLeadingSpace())
250llvm::errs() << " [LeadingSpace]";
251if (Tok.isExpandDisabled())
252llvm::errs() << " [ExpandDisabled]";
253if (Tok.needsCleaning()) {
254const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
255llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
256<< "']";
257}
258
259llvm::errs() << "\tLoc=<";
260DumpLocation(Tok.getLocation());
261llvm::errs() << ">";
262}
263
264void Preprocessor::DumpLocation(SourceLocation Loc) const {
265Loc.print(llvm::errs(), SourceMgr);
266}
267
268void Preprocessor::DumpMacro(const MacroInfo &MI) const {
269llvm::errs() << "MACRO: ";
270for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
271DumpToken(MI.getReplacementToken(i));
272llvm::errs() << " ";
273}
274llvm::errs() << "\n";
275}
276
277void Preprocessor::PrintStats() {
278llvm::errs() << "\n*** Preprocessor Stats:\n";
279llvm::errs() << NumDirectives << " directives found:\n";
280llvm::errs() << " " << NumDefined << " #define.\n";
281llvm::errs() << " " << NumUndefined << " #undef.\n";
282llvm::errs() << " #include/#include_next/#import:\n";
283llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
284llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
285llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
286llvm::errs() << " " << NumElse << " #else/#elif/#elifdef/#elifndef.\n";
287llvm::errs() << " " << NumEndif << " #endif.\n";
288llvm::errs() << " " << NumPragma << " #pragma.\n";
289llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
290
291llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
292<< NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
293<< NumFastMacroExpanded << " on the fast path.\n";
294llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
295<< " token paste (##) operations performed, "
296<< NumFastTokenPaste << " on the fast path.\n";
297
298llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
299
300llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
301llvm::errs() << "\n Macro Expanded Tokens: "
302<< llvm::capacity_in_bytes(MacroExpandedTokens);
303llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
304// FIXME: List information for all submodules.
305llvm::errs() << "\n Macros: "
306<< llvm::capacity_in_bytes(CurSubmoduleState->Macros);
307llvm::errs() << "\n #pragma push_macro Info: "
308<< llvm::capacity_in_bytes(PragmaPushMacroInfo);
309llvm::errs() << "\n Poison Reasons: "
310<< llvm::capacity_in_bytes(PoisonReasons);
311llvm::errs() << "\n Comment Handlers: "
312<< llvm::capacity_in_bytes(CommentHandlers) << "\n";
313}
314
315Preprocessor::macro_iterator
316Preprocessor::macro_begin(bool IncludeExternalMacros) const {
317if (IncludeExternalMacros && ExternalSource &&
318!ReadMacrosFromExternalSource) {
319ReadMacrosFromExternalSource = true;
320ExternalSource->ReadDefinedMacros();
321}
322
323// Make sure we cover all macros in visible modules.
324for (const ModuleMacro &Macro : ModuleMacros)
325CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
326
327return CurSubmoduleState->Macros.begin();
328}
329
330size_t Preprocessor::getTotalMemory() const {
331return BP.getTotalMemory()
332+ llvm::capacity_in_bytes(MacroExpandedTokens)
333+ Predefines.capacity() /* Predefines buffer. */
334// FIXME: Include sizes from all submodules, and include MacroInfo sizes,
335// and ModuleMacros.
336+ llvm::capacity_in_bytes(CurSubmoduleState->Macros)
337+ llvm::capacity_in_bytes(PragmaPushMacroInfo)
338+ llvm::capacity_in_bytes(PoisonReasons)
339+ llvm::capacity_in_bytes(CommentHandlers);
340}
341
342Preprocessor::macro_iterator
343Preprocessor::macro_end(bool IncludeExternalMacros) const {
344if (IncludeExternalMacros && ExternalSource &&
345!ReadMacrosFromExternalSource) {
346ReadMacrosFromExternalSource = true;
347ExternalSource->ReadDefinedMacros();
348}
349
350return CurSubmoduleState->Macros.end();
351}
352
353/// Compares macro tokens with a specified token value sequence.
354static bool MacroDefinitionEquals(const MacroInfo *MI,
355ArrayRef<TokenValue> Tokens) {
356return Tokens.size() == MI->getNumTokens() &&
357std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
358}
359
360StringRef Preprocessor::getLastMacroWithSpelling(
361SourceLocation Loc,
362ArrayRef<TokenValue> Tokens) const {
363SourceLocation BestLocation;
364StringRef BestSpelling;
365for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
366I != E; ++I) {
367const MacroDirective::DefInfo
368Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
369if (!Def || !Def.getMacroInfo())
370continue;
371if (!Def.getMacroInfo()->isObjectLike())
372continue;
373if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
374continue;
375SourceLocation Location = Def.getLocation();
376// Choose the macro defined latest.
377if (BestLocation.isInvalid() ||
378(Location.isValid() &&
379SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
380BestLocation = Location;
381BestSpelling = I->first->getName();
382}
383}
384return BestSpelling;
385}
386
387void Preprocessor::recomputeCurLexerKind() {
388if (CurLexer)
389CurLexerCallback = CurLexer->isDependencyDirectivesLexer()
390? CLK_DependencyDirectivesLexer
391: CLK_Lexer;
392else if (CurTokenLexer)
393CurLexerCallback = CLK_TokenLexer;
394else
395CurLexerCallback = CLK_CachingLexer;
396}
397
398bool Preprocessor::SetCodeCompletionPoint(FileEntryRef File,
399unsigned CompleteLine,
400unsigned CompleteColumn) {
401assert(CompleteLine && CompleteColumn && "Starts from 1:1");
402assert(!CodeCompletionFile && "Already set");
403
404// Load the actual file's contents.
405std::optional<llvm::MemoryBufferRef> Buffer =
406SourceMgr.getMemoryBufferForFileOrNone(File);
407if (!Buffer)
408return true;
409
410// Find the byte position of the truncation point.
411const char *Position = Buffer->getBufferStart();
412for (unsigned Line = 1; Line < CompleteLine; ++Line) {
413for (; *Position; ++Position) {
414if (*Position != '\r' && *Position != '\n')
415continue;
416
417// Eat \r\n or \n\r as a single line.
418if ((Position[1] == '\r' || Position[1] == '\n') &&
419Position[0] != Position[1])
420++Position;
421++Position;
422break;
423}
424}
425
426Position += CompleteColumn - 1;
427
428// If pointing inside the preamble, adjust the position at the beginning of
429// the file after the preamble.
430if (SkipMainFilePreamble.first &&
431SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
432if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
433Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
434}
435
436if (Position > Buffer->getBufferEnd())
437Position = Buffer->getBufferEnd();
438
439CodeCompletionFile = File;
440CodeCompletionOffset = Position - Buffer->getBufferStart();
441
442auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
443Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
444char *NewBuf = NewBuffer->getBufferStart();
445char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
446*NewPos = '\0';
447std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
448SourceMgr.overrideFileContents(File, std::move(NewBuffer));
449
450return false;
451}
452
453void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir,
454bool IsAngled) {
455setCodeCompletionReached();
456if (CodeComplete)
457CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);
458}
459
460void Preprocessor::CodeCompleteNaturalLanguage() {
461setCodeCompletionReached();
462if (CodeComplete)
463CodeComplete->CodeCompleteNaturalLanguage();
464}
465
466/// getSpelling - This method is used to get the spelling of a token into a
467/// SmallVector. Note that the returned StringRef may not point to the
468/// supplied buffer if a copy can be avoided.
469StringRef Preprocessor::getSpelling(const Token &Tok,
470SmallVectorImpl<char> &Buffer,
471bool *Invalid) const {
472// NOTE: this has to be checked *before* testing for an IdentifierInfo.
473if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
474// Try the fast path.
475if (const IdentifierInfo *II = Tok.getIdentifierInfo())
476return II->getName();
477}
478
479// Resize the buffer if we need to copy into it.
480if (Tok.needsCleaning())
481Buffer.resize(Tok.getLength());
482
483const char *Ptr = Buffer.data();
484unsigned Len = getSpelling(Tok, Ptr, Invalid);
485return StringRef(Ptr, Len);
486}
487
488/// CreateString - Plop the specified string into a scratch buffer and return a
489/// location for it. If specified, the source location provides a source
490/// location for the token.
491void Preprocessor::CreateString(StringRef Str, Token &Tok,
492SourceLocation ExpansionLocStart,
493SourceLocation ExpansionLocEnd) {
494Tok.setLength(Str.size());
495
496const char *DestPtr;
497SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
498
499if (ExpansionLocStart.isValid())
500Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
501ExpansionLocEnd, Str.size());
502Tok.setLocation(Loc);
503
504// If this is a raw identifier or a literal token, set the pointer data.
505if (Tok.is(tok::raw_identifier))
506Tok.setRawIdentifierData(DestPtr);
507else if (Tok.isLiteral())
508Tok.setLiteralData(DestPtr);
509}
510
511SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {
512auto &SM = getSourceManager();
513SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
514std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
515bool Invalid = false;
516StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
517if (Invalid)
518return SourceLocation();
519
520// FIXME: We could consider re-using spelling for tokens we see repeatedly.
521const char *DestPtr;
522SourceLocation Spelling =
523ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
524return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
525}
526
527Module *Preprocessor::getCurrentModule() {
528if (!getLangOpts().isCompilingModule())
529return nullptr;
530
531return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
532}
533
534Module *Preprocessor::getCurrentModuleImplementation() {
535if (!getLangOpts().isCompilingModuleImplementation())
536return nullptr;
537
538return getHeaderSearchInfo().lookupModule(getLangOpts().ModuleName);
539}
540
541//===----------------------------------------------------------------------===//
542// Preprocessor Initialization Methods
543//===----------------------------------------------------------------------===//
544
545/// EnterMainSourceFile - Enter the specified FileID as the main source file,
546/// which implicitly adds the builtin defines etc.
547void Preprocessor::EnterMainSourceFile() {
548// We do not allow the preprocessor to reenter the main file. Doing so will
549// cause FileID's to accumulate information from both runs (e.g. #line
550// information) and predefined macros aren't guaranteed to be set properly.
551assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
552FileID MainFileID = SourceMgr.getMainFileID();
553
554// If MainFileID is loaded it means we loaded an AST file, no need to enter
555// a main file.
556if (!SourceMgr.isLoadedFileID(MainFileID)) {
557// Enter the main file source buffer.
558EnterSourceFile(MainFileID, nullptr, SourceLocation());
559
560// If we've been asked to skip bytes in the main file (e.g., as part of a
561// precompiled preamble), do so now.
562if (SkipMainFilePreamble.first > 0)
563CurLexer->SetByteOffset(SkipMainFilePreamble.first,
564SkipMainFilePreamble.second);
565
566// Tell the header info that the main file was entered. If the file is later
567// #imported, it won't be re-entered.
568if (OptionalFileEntryRef FE = SourceMgr.getFileEntryRefForID(MainFileID))
569markIncluded(*FE);
570}
571
572// Preprocess Predefines to populate the initial preprocessor state.
573std::unique_ptr<llvm::MemoryBuffer> SB =
574llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
575assert(SB && "Cannot create predefined source buffer");
576FileID FID = SourceMgr.createFileID(std::move(SB));
577assert(FID.isValid() && "Could not create FileID for predefines?");
578setPredefinesFileID(FID);
579
580// Start parsing the predefines.
581EnterSourceFile(FID, nullptr, SourceLocation());
582
583if (!PPOpts->PCHThroughHeader.empty()) {
584// Lookup and save the FileID for the through header. If it isn't found
585// in the search path, it's a fatal error.
586OptionalFileEntryRef File = LookupFile(
587SourceLocation(), PPOpts->PCHThroughHeader,
588/*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr,
589/*CurDir=*/nullptr, /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
590/*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,
591/*IsFrameworkFound=*/nullptr);
592if (!File) {
593Diag(SourceLocation(), diag::err_pp_through_header_not_found)
594<< PPOpts->PCHThroughHeader;
595return;
596}
597setPCHThroughHeaderFileID(
598SourceMgr.createFileID(*File, SourceLocation(), SrcMgr::C_User));
599}
600
601// Skip tokens from the Predefines and if needed the main file.
602if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||
603(usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))
604SkipTokensWhileUsingPCH();
605}
606
607void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
608assert(PCHThroughHeaderFileID.isInvalid() &&
609"PCHThroughHeaderFileID already set!");
610PCHThroughHeaderFileID = FID;
611}
612
613bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) {
614assert(PCHThroughHeaderFileID.isValid() &&
615"Invalid PCH through header FileID");
616return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
617}
618
619bool Preprocessor::creatingPCHWithThroughHeader() {
620return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
621PCHThroughHeaderFileID.isValid();
622}
623
624bool Preprocessor::usingPCHWithThroughHeader() {
625return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
626PCHThroughHeaderFileID.isValid();
627}
628
629bool Preprocessor::creatingPCHWithPragmaHdrStop() {
630return TUKind == TU_Prefix && PPOpts->PCHWithHdrStop;
631}
632
633bool Preprocessor::usingPCHWithPragmaHdrStop() {
634return TUKind != TU_Prefix && PPOpts->PCHWithHdrStop;
635}
636
637/// Skip tokens until after the #include of the through header or
638/// until after a #pragma hdrstop is seen. Tokens in the predefines file
639/// and the main file may be skipped. If the end of the predefines file
640/// is reached, skipping continues into the main file. If the end of the
641/// main file is reached, it's a fatal error.
642void Preprocessor::SkipTokensWhileUsingPCH() {
643bool ReachedMainFileEOF = false;
644bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
645bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
646Token Tok;
647while (true) {
648bool InPredefines =
649(CurLexer && CurLexer->getFileID() == getPredefinesFileID());
650CurLexerCallback(*this, Tok);
651if (Tok.is(tok::eof) && !InPredefines) {
652ReachedMainFileEOF = true;
653break;
654}
655if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
656break;
657if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
658break;
659}
660if (ReachedMainFileEOF) {
661if (UsingPCHThroughHeader)
662Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
663<< PPOpts->PCHThroughHeader << 1;
664else if (!PPOpts->PCHWithHdrStopCreate)
665Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);
666}
667}
668
669void Preprocessor::replayPreambleConditionalStack() {
670// Restore the conditional stack from the preamble, if there is one.
671if (PreambleConditionalStack.isReplaying()) {
672assert(CurPPLexer &&
673"CurPPLexer is null when calling replayPreambleConditionalStack.");
674CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
675PreambleConditionalStack.doneReplaying();
676if (PreambleConditionalStack.reachedEOFWhileSkipping())
677SkipExcludedConditionalBlock(
678PreambleConditionalStack.SkipInfo->HashTokenLoc,
679PreambleConditionalStack.SkipInfo->IfTokenLoc,
680PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
681PreambleConditionalStack.SkipInfo->FoundElse,
682PreambleConditionalStack.SkipInfo->ElseLoc);
683}
684}
685
686void Preprocessor::EndSourceFile() {
687// Notify the client that we reached the end of the source file.
688if (Callbacks)
689Callbacks->EndOfMainFile();
690}
691
692//===----------------------------------------------------------------------===//
693// Lexer Event Handling.
694//===----------------------------------------------------------------------===//
695
696/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
697/// identifier information for the token and install it into the token,
698/// updating the token kind accordingly.
699IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
700assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
701
702// Look up this token, see if it is a macro, or if it is a language keyword.
703IdentifierInfo *II;
704if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
705// No cleaning needed, just use the characters from the lexed buffer.
706II = getIdentifierInfo(Identifier.getRawIdentifier());
707} else {
708// Cleaning needed, alloca a buffer, clean into it, then use the buffer.
709SmallString<64> IdentifierBuffer;
710StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
711
712if (Identifier.hasUCN()) {
713SmallString<64> UCNIdentifierBuffer;
714expandUCNs(UCNIdentifierBuffer, CleanedStr);
715II = getIdentifierInfo(UCNIdentifierBuffer);
716} else {
717II = getIdentifierInfo(CleanedStr);
718}
719}
720
721// Update the token info (identifier info and appropriate token kind).
722// FIXME: the raw_identifier may contain leading whitespace which is removed
723// from the cleaned identifier token. The SourceLocation should be updated to
724// refer to the non-whitespace character. For instance, the text "\\\nB" (a
725// line continuation before 'B') is parsed as a single tok::raw_identifier and
726// is cleaned to tok::identifier "B". After cleaning the token's length is
727// still 3 and the SourceLocation refers to the location of the backslash.
728Identifier.setIdentifierInfo(II);
729Identifier.setKind(II->getTokenID());
730
731return II;
732}
733
734void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
735PoisonReasons[II] = DiagID;
736}
737
738void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
739assert(Ident__exception_code && Ident__exception_info);
740assert(Ident___exception_code && Ident___exception_info);
741Ident__exception_code->setIsPoisoned(Poison);
742Ident___exception_code->setIsPoisoned(Poison);
743Ident_GetExceptionCode->setIsPoisoned(Poison);
744Ident__exception_info->setIsPoisoned(Poison);
745Ident___exception_info->setIsPoisoned(Poison);
746Ident_GetExceptionInfo->setIsPoisoned(Poison);
747Ident__abnormal_termination->setIsPoisoned(Poison);
748Ident___abnormal_termination->setIsPoisoned(Poison);
749Ident_AbnormalTermination->setIsPoisoned(Poison);
750}
751
752void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
753assert(Identifier.getIdentifierInfo() &&
754"Can't handle identifiers without identifier info!");
755llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
756PoisonReasons.find(Identifier.getIdentifierInfo());
757if(it == PoisonReasons.end())
758Diag(Identifier, diag::err_pp_used_poisoned_id);
759else
760Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
761}
762
763void Preprocessor::updateOutOfDateIdentifier(const IdentifierInfo &II) const {
764assert(II.isOutOfDate() && "not out of date");
765getExternalSource()->updateOutOfDateIdentifier(II);
766}
767
768/// HandleIdentifier - This callback is invoked when the lexer reads an
769/// identifier. This callback looks up the identifier in the map and/or
770/// potentially macro expands it or turns it into a named token (like 'for').
771///
772/// Note that callers of this method are guarded by checking the
773/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
774/// IdentifierInfo methods that compute these properties will need to change to
775/// match.
776bool Preprocessor::HandleIdentifier(Token &Identifier) {
777assert(Identifier.getIdentifierInfo() &&
778"Can't handle identifiers without identifier info!");
779
780IdentifierInfo &II = *Identifier.getIdentifierInfo();
781
782// If the information about this identifier is out of date, update it from
783// the external source.
784// We have to treat __VA_ARGS__ in a special way, since it gets
785// serialized with isPoisoned = true, but our preprocessor may have
786// unpoisoned it if we're defining a C99 macro.
787if (II.isOutOfDate()) {
788bool CurrentIsPoisoned = false;
789const bool IsSpecialVariadicMacro =
790&II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
791if (IsSpecialVariadicMacro)
792CurrentIsPoisoned = II.isPoisoned();
793
794updateOutOfDateIdentifier(II);
795Identifier.setKind(II.getTokenID());
796
797if (IsSpecialVariadicMacro)
798II.setIsPoisoned(CurrentIsPoisoned);
799}
800
801// If this identifier was poisoned, and if it was not produced from a macro
802// expansion, emit an error.
803if (II.isPoisoned() && CurPPLexer) {
804HandlePoisonedIdentifier(Identifier);
805}
806
807// If this is a macro to be expanded, do it.
808if (const MacroDefinition MD = getMacroDefinition(&II)) {
809const auto *MI = MD.getMacroInfo();
810assert(MI && "macro definition with no macro info?");
811if (!DisableMacroExpansion) {
812if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
813// C99 6.10.3p10: If the preprocessing token immediately after the
814// macro name isn't a '(', this macro should not be expanded.
815if (!MI->isFunctionLike() || isNextPPTokenLParen())
816return HandleMacroExpandedIdentifier(Identifier, MD);
817} else {
818// C99 6.10.3.4p2 says that a disabled macro may never again be
819// expanded, even if it's in a context where it could be expanded in the
820// future.
821Identifier.setFlag(Token::DisableExpand);
822if (MI->isObjectLike() || isNextPPTokenLParen())
823Diag(Identifier, diag::pp_disabled_macro_expansion);
824}
825}
826}
827
828// If this identifier is a keyword in a newer Standard or proposed Standard,
829// produce a warning. Don't warn if we're not considering macro expansion,
830// since this identifier might be the name of a macro.
831// FIXME: This warning is disabled in cases where it shouldn't be, like
832// "#define constexpr constexpr", "int constexpr;"
833if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
834Diag(Identifier, getIdentifierTable().getFutureCompatDiagKind(II, getLangOpts()))
835<< II.getName();
836// Don't diagnose this keyword again in this translation unit.
837II.setIsFutureCompatKeyword(false);
838}
839
840// If this is an extension token, diagnose its use.
841// We avoid diagnosing tokens that originate from macro definitions.
842// FIXME: This warning is disabled in cases where it shouldn't be,
843// like "#define TY typeof", "TY(1) x".
844if (II.isExtensionToken() && !DisableMacroExpansion)
845Diag(Identifier, diag::ext_token_used);
846
847// If this is the 'import' contextual keyword following an '@', note
848// that the next token indicates a module name.
849//
850// Note that we do not treat 'import' as a contextual
851// keyword when we're in a caching lexer, because caching lexers only get
852// used in contexts where import declarations are disallowed.
853//
854// Likewise if this is the standard C++ import keyword.
855if (((LastTokenWasAt && II.isModulesImport()) ||
856Identifier.is(tok::kw_import)) &&
857!InMacroArgs && !DisableMacroExpansion &&
858(getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
859CurLexerCallback != CLK_CachingLexer) {
860ModuleImportLoc = Identifier.getLocation();
861NamedModuleImportPath.clear();
862IsAtImport = true;
863ModuleImportExpectsIdentifier = true;
864CurLexerCallback = CLK_LexAfterModuleImport;
865}
866return true;
867}
868
869void Preprocessor::Lex(Token &Result) {
870++LexLevel;
871
872// We loop here until a lex function returns a token; this avoids recursion.
873while (!CurLexerCallback(*this, Result))
874;
875
876if (Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure)
877return;
878
879if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
880// Remember the identifier before code completion token.
881setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
882setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
883// Set IdenfitierInfo to null to avoid confusing code that handles both
884// identifiers and completion tokens.
885Result.setIdentifierInfo(nullptr);
886}
887
888// Update StdCXXImportSeqState to track our position within a C++20 import-seq
889// if this token is being produced as a result of phase 4 of translation.
890// Update TrackGMFState to decide if we are currently in a Global Module
891// Fragment. GMF state updates should precede StdCXXImportSeq ones, since GMF state
892// depends on the prevailing StdCXXImportSeq state in two cases.
893if (getLangOpts().CPlusPlusModules && LexLevel == 1 &&
894!Result.getFlag(Token::IsReinjected)) {
895switch (Result.getKind()) {
896case tok::l_paren: case tok::l_square: case tok::l_brace:
897StdCXXImportSeqState.handleOpenBracket();
898break;
899case tok::r_paren: case tok::r_square:
900StdCXXImportSeqState.handleCloseBracket();
901break;
902case tok::r_brace:
903StdCXXImportSeqState.handleCloseBrace();
904break;
905// This token is injected to represent the translation of '#include "a.h"'
906// into "import a.h;". Mimic the notional ';'.
907case tok::annot_module_include:
908case tok::semi:
909TrackGMFState.handleSemi();
910StdCXXImportSeqState.handleSemi();
911ModuleDeclState.handleSemi();
912break;
913case tok::header_name:
914case tok::annot_header_unit:
915StdCXXImportSeqState.handleHeaderName();
916break;
917case tok::kw_export:
918TrackGMFState.handleExport();
919StdCXXImportSeqState.handleExport();
920ModuleDeclState.handleExport();
921break;
922case tok::colon:
923ModuleDeclState.handleColon();
924break;
925case tok::period:
926ModuleDeclState.handlePeriod();
927break;
928case tok::identifier:
929// Check "import" and "module" when there is no open bracket. The two
930// identifiers are not meaningful with open brackets.
931if (StdCXXImportSeqState.atTopLevel()) {
932if (Result.getIdentifierInfo()->isModulesImport()) {
933TrackGMFState.handleImport(StdCXXImportSeqState.afterTopLevelSeq());
934StdCXXImportSeqState.handleImport();
935if (StdCXXImportSeqState.afterImportSeq()) {
936ModuleImportLoc = Result.getLocation();
937NamedModuleImportPath.clear();
938IsAtImport = false;
939ModuleImportExpectsIdentifier = true;
940CurLexerCallback = CLK_LexAfterModuleImport;
941}
942break;
943} else if (Result.getIdentifierInfo() == getIdentifierInfo("module")) {
944TrackGMFState.handleModule(StdCXXImportSeqState.afterTopLevelSeq());
945ModuleDeclState.handleModule();
946break;
947}
948}
949ModuleDeclState.handleIdentifier(Result.getIdentifierInfo());
950if (ModuleDeclState.isModuleCandidate())
951break;
952[[fallthrough]];
953default:
954TrackGMFState.handleMisc();
955StdCXXImportSeqState.handleMisc();
956ModuleDeclState.handleMisc();
957break;
958}
959}
960
961if (CurLexer && ++CheckPointCounter == CheckPointStepSize) {
962CheckPoints[CurLexer->getFileID()].push_back(CurLexer->BufferPtr);
963CheckPointCounter = 0;
964}
965
966LastTokenWasAt = Result.is(tok::at);
967--LexLevel;
968
969if ((LexLevel == 0 || PreprocessToken) &&
970!Result.getFlag(Token::IsReinjected)) {
971if (LexLevel == 0)
972++TokenCount;
973if (OnToken)
974OnToken(Result);
975}
976}
977
978void Preprocessor::LexTokensUntilEOF(std::vector<Token> *Tokens) {
979while (1) {
980Token Tok;
981Lex(Tok);
982if (Tok.isOneOf(tok::unknown, tok::eof, tok::eod,
983tok::annot_repl_input_end))
984break;
985if (Tokens != nullptr)
986Tokens->push_back(Tok);
987}
988}
989
990/// Lex a header-name token (including one formed from header-name-tokens if
991/// \p AllowConcatenation is \c true).
992///
993/// \param FilenameTok Filled in with the next token. On success, this will
994/// be either a header_name token. On failure, it will be whatever other
995/// token was found instead.
996/// \param AllowMacroExpansion If \c true, allow the header name to be formed
997/// by macro expansion (concatenating tokens as necessary if the first
998/// token is a '<').
999/// \return \c true if we reached EOD or EOF while looking for a > token in
1000/// a concatenated header name and diagnosed it. \c false otherwise.
1001bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) {
1002// Lex using header-name tokenization rules if tokens are being lexed from
1003// a file. Just grab a token normally if we're in a macro expansion.
1004if (CurPPLexer)
1005CurPPLexer->LexIncludeFilename(FilenameTok);
1006else
1007Lex(FilenameTok);
1008
1009// This could be a <foo/bar.h> file coming from a macro expansion. In this
1010// case, glue the tokens together into an angle_string_literal token.
1011SmallString<128> FilenameBuffer;
1012if (FilenameTok.is(tok::less) && AllowMacroExpansion) {
1013bool StartOfLine = FilenameTok.isAtStartOfLine();
1014bool LeadingSpace = FilenameTok.hasLeadingSpace();
1015bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro();
1016
1017SourceLocation Start = FilenameTok.getLocation();
1018SourceLocation End;
1019FilenameBuffer.push_back('<');
1020
1021// Consume tokens until we find a '>'.
1022// FIXME: A header-name could be formed starting or ending with an
1023// alternative token. It's not clear whether that's ill-formed in all
1024// cases.
1025while (FilenameTok.isNot(tok::greater)) {
1026Lex(FilenameTok);
1027if (FilenameTok.isOneOf(tok::eod, tok::eof)) {
1028Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater;
1029Diag(Start, diag::note_matching) << tok::less;
1030return true;
1031}
1032
1033End = FilenameTok.getLocation();
1034
1035// FIXME: Provide code completion for #includes.
1036if (FilenameTok.is(tok::code_completion)) {
1037setCodeCompletionReached();
1038Lex(FilenameTok);
1039continue;
1040}
1041
1042// Append the spelling of this token to the buffer. If there was a space
1043// before it, add it now.
1044if (FilenameTok.hasLeadingSpace())
1045FilenameBuffer.push_back(' ');
1046
1047// Get the spelling of the token, directly into FilenameBuffer if
1048// possible.
1049size_t PreAppendSize = FilenameBuffer.size();
1050FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength());
1051
1052const char *BufPtr = &FilenameBuffer[PreAppendSize];
1053unsigned ActualLen = getSpelling(FilenameTok, BufPtr);
1054
1055// If the token was spelled somewhere else, copy it into FilenameBuffer.
1056if (BufPtr != &FilenameBuffer[PreAppendSize])
1057memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1058
1059// Resize FilenameBuffer to the correct size.
1060if (FilenameTok.getLength() != ActualLen)
1061FilenameBuffer.resize(PreAppendSize + ActualLen);
1062}
1063
1064FilenameTok.startToken();
1065FilenameTok.setKind(tok::header_name);
1066FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine);
1067FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace);
1068FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro);
1069CreateString(FilenameBuffer, FilenameTok, Start, End);
1070} else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) {
1071// Convert a string-literal token of the form " h-char-sequence "
1072// (produced by macro expansion) into a header-name token.
1073//
1074// The rules for header-names don't quite match the rules for
1075// string-literals, but all the places where they differ result in
1076// undefined behavior, so we can and do treat them the same.
1077//
1078// A string-literal with a prefix or suffix is not translated into a
1079// header-name. This could theoretically be observable via the C++20
1080// context-sensitive header-name formation rules.
1081StringRef Str = getSpelling(FilenameTok, FilenameBuffer);
1082if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"')
1083FilenameTok.setKind(tok::header_name);
1084}
1085
1086return false;
1087}
1088
1089/// Collect the tokens of a C++20 pp-import-suffix.
1090void Preprocessor::CollectPpImportSuffix(SmallVectorImpl<Token> &Toks) {
1091// FIXME: For error recovery, consider recognizing attribute syntax here
1092// and terminating / diagnosing a missing semicolon if we find anything
1093// else? (Can we leave that to the parser?)
1094unsigned BracketDepth = 0;
1095while (true) {
1096Toks.emplace_back();
1097Lex(Toks.back());
1098
1099switch (Toks.back().getKind()) {
1100case tok::l_paren: case tok::l_square: case tok::l_brace:
1101++BracketDepth;
1102break;
1103
1104case tok::r_paren: case tok::r_square: case tok::r_brace:
1105if (BracketDepth == 0)
1106return;
1107--BracketDepth;
1108break;
1109
1110case tok::semi:
1111if (BracketDepth == 0)
1112return;
1113break;
1114
1115case tok::eof:
1116return;
1117
1118default:
1119break;
1120}
1121}
1122}
1123
1124
1125/// Lex a token following the 'import' contextual keyword.
1126///
1127/// pp-import: [C++20]
1128/// import header-name pp-import-suffix[opt] ;
1129/// import header-name-tokens pp-import-suffix[opt] ;
1130/// [ObjC] @ import module-name ;
1131/// [Clang] import module-name ;
1132///
1133/// header-name-tokens:
1134/// string-literal
1135/// < [any sequence of preprocessing-tokens other than >] >
1136///
1137/// module-name:
1138/// module-name-qualifier[opt] identifier
1139///
1140/// module-name-qualifier
1141/// module-name-qualifier[opt] identifier .
1142///
1143/// We respond to a pp-import by importing macros from the named module.
1144bool Preprocessor::LexAfterModuleImport(Token &Result) {
1145// Figure out what kind of lexer we actually have.
1146recomputeCurLexerKind();
1147
1148// Lex the next token. The header-name lexing rules are used at the start of
1149// a pp-import.
1150//
1151// For now, we only support header-name imports in C++20 mode.
1152// FIXME: Should we allow this in all language modes that support an import
1153// declaration as an extension?
1154if (NamedModuleImportPath.empty() && getLangOpts().CPlusPlusModules) {
1155if (LexHeaderName(Result))
1156return true;
1157
1158if (Result.is(tok::colon) && ModuleDeclState.isNamedModule()) {
1159std::string Name = ModuleDeclState.getPrimaryName().str();
1160Name += ":";
1161NamedModuleImportPath.push_back(
1162{getIdentifierInfo(Name), Result.getLocation()});
1163CurLexerCallback = CLK_LexAfterModuleImport;
1164return true;
1165}
1166} else {
1167Lex(Result);
1168}
1169
1170// Allocate a holding buffer for a sequence of tokens and introduce it into
1171// the token stream.
1172auto EnterTokens = [this](ArrayRef<Token> Toks) {
1173auto ToksCopy = std::make_unique<Token[]>(Toks.size());
1174std::copy(Toks.begin(), Toks.end(), ToksCopy.get());
1175EnterTokenStream(std::move(ToksCopy), Toks.size(),
1176/*DisableMacroExpansion*/ true, /*IsReinject*/ false);
1177};
1178
1179bool ImportingHeader = Result.is(tok::header_name);
1180// Check for a header-name.
1181SmallVector<Token, 32> Suffix;
1182if (ImportingHeader) {
1183// Enter the header-name token into the token stream; a Lex action cannot
1184// both return a token and cache tokens (doing so would corrupt the token
1185// cache if the call to Lex comes from CachingLex / PeekAhead).
1186Suffix.push_back(Result);
1187
1188// Consume the pp-import-suffix and expand any macros in it now. We'll add
1189// it back into the token stream later.
1190CollectPpImportSuffix(Suffix);
1191if (Suffix.back().isNot(tok::semi)) {
1192// This is not a pp-import after all.
1193EnterTokens(Suffix);
1194return false;
1195}
1196
1197// C++2a [cpp.module]p1:
1198// The ';' preprocessing-token terminating a pp-import shall not have
1199// been produced by macro replacement.
1200SourceLocation SemiLoc = Suffix.back().getLocation();
1201if (SemiLoc.isMacroID())
1202Diag(SemiLoc, diag::err_header_import_semi_in_macro);
1203
1204// Reconstitute the import token.
1205Token ImportTok;
1206ImportTok.startToken();
1207ImportTok.setKind(tok::kw_import);
1208ImportTok.setLocation(ModuleImportLoc);
1209ImportTok.setIdentifierInfo(getIdentifierInfo("import"));
1210ImportTok.setLength(6);
1211
1212auto Action = HandleHeaderIncludeOrImport(
1213/*HashLoc*/ SourceLocation(), ImportTok, Suffix.front(), SemiLoc);
1214switch (Action.Kind) {
1215case ImportAction::None:
1216break;
1217
1218case ImportAction::ModuleBegin:
1219// Let the parser know we're textually entering the module.
1220Suffix.emplace_back();
1221Suffix.back().startToken();
1222Suffix.back().setKind(tok::annot_module_begin);
1223Suffix.back().setLocation(SemiLoc);
1224Suffix.back().setAnnotationEndLoc(SemiLoc);
1225Suffix.back().setAnnotationValue(Action.ModuleForHeader);
1226[[fallthrough]];
1227
1228case ImportAction::ModuleImport:
1229case ImportAction::HeaderUnitImport:
1230case ImportAction::SkippedModuleImport:
1231// We chose to import (or textually enter) the file. Convert the
1232// header-name token into a header unit annotation token.
1233Suffix[0].setKind(tok::annot_header_unit);
1234Suffix[0].setAnnotationEndLoc(Suffix[0].getLocation());
1235Suffix[0].setAnnotationValue(Action.ModuleForHeader);
1236// FIXME: Call the moduleImport callback?
1237break;
1238case ImportAction::Failure:
1239assert(TheModuleLoader.HadFatalFailure &&
1240"This should be an early exit only to a fatal error");
1241Result.setKind(tok::eof);
1242CurLexer->cutOffLexing();
1243EnterTokens(Suffix);
1244return true;
1245}
1246
1247EnterTokens(Suffix);
1248return false;
1249}
1250
1251// The token sequence
1252//
1253// import identifier (. identifier)*
1254//
1255// indicates a module import directive. We already saw the 'import'
1256// contextual keyword, so now we're looking for the identifiers.
1257if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
1258// We expected to see an identifier here, and we did; continue handling
1259// identifiers.
1260NamedModuleImportPath.push_back(
1261std::make_pair(Result.getIdentifierInfo(), Result.getLocation()));
1262ModuleImportExpectsIdentifier = false;
1263CurLexerCallback = CLK_LexAfterModuleImport;
1264return true;
1265}
1266
1267// If we're expecting a '.' or a ';', and we got a '.', then wait until we
1268// see the next identifier. (We can also see a '[[' that begins an
1269// attribute-specifier-seq here under the Standard C++ Modules.)
1270if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
1271ModuleImportExpectsIdentifier = true;
1272CurLexerCallback = CLK_LexAfterModuleImport;
1273return true;
1274}
1275
1276// If we didn't recognize a module name at all, this is not a (valid) import.
1277if (NamedModuleImportPath.empty() || Result.is(tok::eof))
1278return true;
1279
1280// Consume the pp-import-suffix and expand any macros in it now, if we're not
1281// at the semicolon already.
1282SourceLocation SemiLoc = Result.getLocation();
1283if (Result.isNot(tok::semi)) {
1284Suffix.push_back(Result);
1285CollectPpImportSuffix(Suffix);
1286if (Suffix.back().isNot(tok::semi)) {
1287// This is not an import after all.
1288EnterTokens(Suffix);
1289return false;
1290}
1291SemiLoc = Suffix.back().getLocation();
1292}
1293
1294// Under the standard C++ Modules, the dot is just part of the module name,
1295// and not a real hierarchy separator. Flatten such module names now.
1296//
1297// FIXME: Is this the right level to be performing this transformation?
1298std::string FlatModuleName;
1299if (getLangOpts().CPlusPlusModules) {
1300for (auto &Piece : NamedModuleImportPath) {
1301// If the FlatModuleName ends with colon, it implies it is a partition.
1302if (!FlatModuleName.empty() && FlatModuleName.back() != ':')
1303FlatModuleName += ".";
1304FlatModuleName += Piece.first->getName();
1305}
1306SourceLocation FirstPathLoc = NamedModuleImportPath[0].second;
1307NamedModuleImportPath.clear();
1308NamedModuleImportPath.push_back(
1309std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
1310}
1311
1312Module *Imported = nullptr;
1313// We don't/shouldn't load the standard c++20 modules when preprocessing.
1314if (getLangOpts().Modules && !isInImportingCXXNamedModules()) {
1315Imported = TheModuleLoader.loadModule(ModuleImportLoc,
1316NamedModuleImportPath,
1317Module::Hidden,
1318/*IsInclusionDirective=*/false);
1319if (Imported)
1320makeModuleVisible(Imported, SemiLoc);
1321}
1322
1323if (Callbacks)
1324Callbacks->moduleImport(ModuleImportLoc, NamedModuleImportPath, Imported);
1325
1326if (!Suffix.empty()) {
1327EnterTokens(Suffix);
1328return false;
1329}
1330return true;
1331}
1332
1333void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
1334CurSubmoduleState->VisibleModules.setVisible(
1335M, Loc, [](Module *) {},
1336[&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
1337// FIXME: Include the path in the diagnostic.
1338// FIXME: Include the import location for the conflicting module.
1339Diag(ModuleImportLoc, diag::warn_module_conflict)
1340<< Path[0]->getFullModuleName()
1341<< Conflict->getFullModuleName()
1342<< Message;
1343});
1344
1345// Add this module to the imports list of the currently-built submodule.
1346if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
1347BuildingSubmoduleStack.back().M->Imports.insert(M);
1348}
1349
1350bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
1351const char *DiagnosticTag,
1352bool AllowMacroExpansion) {
1353// We need at least one string literal.
1354if (Result.isNot(tok::string_literal)) {
1355Diag(Result, diag::err_expected_string_literal)
1356<< /*Source='in...'*/0 << DiagnosticTag;
1357return false;
1358}
1359
1360// Lex string literal tokens, optionally with macro expansion.
1361SmallVector<Token, 4> StrToks;
1362do {
1363StrToks.push_back(Result);
1364
1365if (Result.hasUDSuffix())
1366Diag(Result, diag::err_invalid_string_udl);
1367
1368if (AllowMacroExpansion)
1369Lex(Result);
1370else
1371LexUnexpandedToken(Result);
1372} while (Result.is(tok::string_literal));
1373
1374// Concatenate and parse the strings.
1375StringLiteralParser Literal(StrToks, *this);
1376assert(Literal.isOrdinary() && "Didn't allow wide strings in");
1377
1378if (Literal.hadError)
1379return false;
1380
1381if (Literal.Pascal) {
1382Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
1383<< /*Source='in...'*/0 << DiagnosticTag;
1384return false;
1385}
1386
1387String = std::string(Literal.GetString());
1388return true;
1389}
1390
1391bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
1392assert(Tok.is(tok::numeric_constant));
1393SmallString<8> IntegerBuffer;
1394bool NumberInvalid = false;
1395StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
1396if (NumberInvalid)
1397return false;
1398NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(),
1399getLangOpts(), getTargetInfo(),
1400getDiagnostics());
1401if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
1402return false;
1403llvm::APInt APVal(64, 0);
1404if (Literal.GetIntegerValue(APVal))
1405return false;
1406Lex(Tok);
1407Value = APVal.getLimitedValue();
1408return true;
1409}
1410
1411void Preprocessor::addCommentHandler(CommentHandler *Handler) {
1412assert(Handler && "NULL comment handler");
1413assert(!llvm::is_contained(CommentHandlers, Handler) &&
1414"Comment handler already registered");
1415CommentHandlers.push_back(Handler);
1416}
1417
1418void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
1419std::vector<CommentHandler *>::iterator Pos =
1420llvm::find(CommentHandlers, Handler);
1421assert(Pos != CommentHandlers.end() && "Comment handler not registered");
1422CommentHandlers.erase(Pos);
1423}
1424
1425bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
1426bool AnyPendingTokens = false;
1427for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
1428HEnd = CommentHandlers.end();
1429H != HEnd; ++H) {
1430if ((*H)->HandleComment(*this, Comment))
1431AnyPendingTokens = true;
1432}
1433if (!AnyPendingTokens || getCommentRetentionState())
1434return false;
1435Lex(result);
1436return true;
1437}
1438
1439void Preprocessor::emitMacroDeprecationWarning(const Token &Identifier) const {
1440const MacroAnnotations &A =
1441getMacroAnnotations(Identifier.getIdentifierInfo());
1442assert(A.DeprecationInfo &&
1443"Macro deprecation warning without recorded annotation!");
1444const MacroAnnotationInfo &Info = *A.DeprecationInfo;
1445if (Info.Message.empty())
1446Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1447<< Identifier.getIdentifierInfo() << 0;
1448else
1449Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1450<< Identifier.getIdentifierInfo() << 1 << Info.Message;
1451Diag(Info.Location, diag::note_pp_macro_annotation) << 0;
1452}
1453
1454void Preprocessor::emitRestrictExpansionWarning(const Token &Identifier) const {
1455const MacroAnnotations &A =
1456getMacroAnnotations(Identifier.getIdentifierInfo());
1457assert(A.RestrictExpansionInfo &&
1458"Macro restricted expansion warning without recorded annotation!");
1459const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo;
1460if (Info.Message.empty())
1461Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1462<< Identifier.getIdentifierInfo() << 0;
1463else
1464Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1465<< Identifier.getIdentifierInfo() << 1 << Info.Message;
1466Diag(Info.Location, diag::note_pp_macro_annotation) << 1;
1467}
1468
1469void Preprocessor::emitRestrictInfNaNWarning(const Token &Identifier,
1470unsigned DiagSelection) const {
1471Diag(Identifier, diag::warn_fp_nan_inf_when_disabled) << DiagSelection << 1;
1472}
1473
1474void Preprocessor::emitFinalMacroWarning(const Token &Identifier,
1475bool IsUndef) const {
1476const MacroAnnotations &A =
1477getMacroAnnotations(Identifier.getIdentifierInfo());
1478assert(A.FinalAnnotationLoc &&
1479"Final macro warning without recorded annotation!");
1480
1481Diag(Identifier, diag::warn_pragma_final_macro)
1482<< Identifier.getIdentifierInfo() << (IsUndef ? 0 : 1);
1483Diag(*A.FinalAnnotationLoc, diag::note_pp_macro_annotation) << 2;
1484}
1485
1486bool Preprocessor::isSafeBufferOptOut(const SourceManager &SourceMgr,
1487const SourceLocation &Loc) const {
1488// The lambda that tests if a `Loc` is in an opt-out region given one opt-out
1489// region map:
1490auto TestInMap = [&SourceMgr](const SafeBufferOptOutRegionsTy &Map,
1491const SourceLocation &Loc) -> bool {
1492// Try to find a region in `SafeBufferOptOutMap` where `Loc` is in:
1493auto FirstRegionEndingAfterLoc = llvm::partition_point(
1494Map, [&SourceMgr,
1495&Loc](const std::pair<SourceLocation, SourceLocation> &Region) {
1496return SourceMgr.isBeforeInTranslationUnit(Region.second, Loc);
1497});
1498
1499if (FirstRegionEndingAfterLoc != Map.end()) {
1500// To test if the start location of the found region precedes `Loc`:
1501return SourceMgr.isBeforeInTranslationUnit(
1502FirstRegionEndingAfterLoc->first, Loc);
1503}
1504// If we do not find a region whose end location passes `Loc`, we want to
1505// check if the current region is still open:
1506if (!Map.empty() && Map.back().first == Map.back().second)
1507return SourceMgr.isBeforeInTranslationUnit(Map.back().first, Loc);
1508return false;
1509};
1510
1511// What the following does:
1512//
1513// If `Loc` belongs to the local TU, we just look up `SafeBufferOptOutMap`.
1514// Otherwise, `Loc` is from a loaded AST. We look up the
1515// `LoadedSafeBufferOptOutMap` first to get the opt-out region map of the
1516// loaded AST where `Loc` is at. Then we find if `Loc` is in an opt-out
1517// region w.r.t. the region map. If the region map is absent, it means there
1518// is no opt-out pragma in that loaded AST.
1519//
1520// Opt-out pragmas in the local TU or a loaded AST is not visible to another
1521// one of them. That means if you put the pragmas around a `#include
1522// "module.h"`, where module.h is a module, it is not actually suppressing
1523// warnings in module.h. This is fine because warnings in module.h will be
1524// reported when module.h is compiled in isolation and nothing in module.h
1525// will be analyzed ever again. So you will not see warnings from the file
1526// that imports module.h anyway. And you can't even do the same thing for PCHs
1527// because they can only be included from the command line.
1528
1529if (SourceMgr.isLocalSourceLocation(Loc))
1530return TestInMap(SafeBufferOptOutMap, Loc);
1531
1532const SafeBufferOptOutRegionsTy *LoadedRegions =
1533LoadedSafeBufferOptOutMap.lookupLoadedOptOutMap(Loc, SourceMgr);
1534
1535if (LoadedRegions)
1536return TestInMap(*LoadedRegions, Loc);
1537return false;
1538}
1539
1540bool Preprocessor::enterOrExitSafeBufferOptOutRegion(
1541bool isEnter, const SourceLocation &Loc) {
1542if (isEnter) {
1543if (isPPInSafeBufferOptOutRegion())
1544return true; // invalid enter action
1545InSafeBufferOptOutRegion = true;
1546CurrentSafeBufferOptOutStart = Loc;
1547
1548// To set the start location of a new region:
1549
1550if (!SafeBufferOptOutMap.empty()) {
1551[[maybe_unused]] auto *PrevRegion = &SafeBufferOptOutMap.back();
1552assert(PrevRegion->first != PrevRegion->second &&
1553"Shall not begin a safe buffer opt-out region before closing the "
1554"previous one.");
1555}
1556// If the start location equals to the end location, we call the region a
1557// open region or a unclosed region (i.e., end location has not been set
1558// yet).
1559SafeBufferOptOutMap.emplace_back(Loc, Loc);
1560} else {
1561if (!isPPInSafeBufferOptOutRegion())
1562return true; // invalid enter action
1563InSafeBufferOptOutRegion = false;
1564
1565// To set the end location of the current open region:
1566
1567assert(!SafeBufferOptOutMap.empty() &&
1568"Misordered safe buffer opt-out regions");
1569auto *CurrRegion = &SafeBufferOptOutMap.back();
1570assert(CurrRegion->first == CurrRegion->second &&
1571"Set end location to a closed safe buffer opt-out region");
1572CurrRegion->second = Loc;
1573}
1574return false;
1575}
1576
1577bool Preprocessor::isPPInSafeBufferOptOutRegion() {
1578return InSafeBufferOptOutRegion;
1579}
1580bool Preprocessor::isPPInSafeBufferOptOutRegion(SourceLocation &StartLoc) {
1581StartLoc = CurrentSafeBufferOptOutStart;
1582return InSafeBufferOptOutRegion;
1583}
1584
1585SmallVector<SourceLocation, 64>
1586Preprocessor::serializeSafeBufferOptOutMap() const {
1587assert(!InSafeBufferOptOutRegion &&
1588"Attempt to serialize safe buffer opt-out regions before file being "
1589"completely preprocessed");
1590
1591SmallVector<SourceLocation, 64> SrcSeq;
1592
1593for (const auto &[begin, end] : SafeBufferOptOutMap) {
1594SrcSeq.push_back(begin);
1595SrcSeq.push_back(end);
1596}
1597// Only `SafeBufferOptOutMap` gets serialized. No need to serialize
1598// `LoadedSafeBufferOptOutMap` because if this TU loads a pch/module, every
1599// pch/module in the pch-chain/module-DAG will be loaded one by one in order.
1600// It means that for each loading pch/module m, it just needs to load m's own
1601// `SafeBufferOptOutMap`.
1602return SrcSeq;
1603}
1604
1605bool Preprocessor::setDeserializedSafeBufferOptOutMap(
1606const SmallVectorImpl<SourceLocation> &SourceLocations) {
1607if (SourceLocations.size() == 0)
1608return false;
1609
1610assert(SourceLocations.size() % 2 == 0 &&
1611"ill-formed SourceLocation sequence");
1612
1613auto It = SourceLocations.begin();
1614SafeBufferOptOutRegionsTy &Regions =
1615LoadedSafeBufferOptOutMap.findAndConsLoadedOptOutMap(*It, SourceMgr);
1616
1617do {
1618SourceLocation Begin = *It++;
1619SourceLocation End = *It++;
1620
1621Regions.emplace_back(Begin, End);
1622} while (It != SourceLocations.end());
1623return true;
1624}
1625
1626ModuleLoader::~ModuleLoader() = default;
1627
1628CommentHandler::~CommentHandler() = default;
1629
1630EmptylineHandler::~EmptylineHandler() = default;
1631
1632CodeCompletionHandler::~CodeCompletionHandler() = default;
1633
1634void Preprocessor::createPreprocessingRecord() {
1635if (Record)
1636return;
1637
1638Record = new PreprocessingRecord(getSourceManager());
1639addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
1640}
1641
1642const char *Preprocessor::getCheckPoint(FileID FID, const char *Start) const {
1643if (auto It = CheckPoints.find(FID); It != CheckPoints.end()) {
1644const SmallVector<const char *> &FileCheckPoints = It->second;
1645const char *Last = nullptr;
1646// FIXME: Do better than a linear search.
1647for (const char *P : FileCheckPoints) {
1648if (P > Start)
1649break;
1650Last = P;
1651}
1652return Last;
1653}
1654
1655return nullptr;
1656}
1657