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