xref: /minix3/external/bsd/llvm/dist/clang/lib/Lex/Preprocessor.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1f4a2713aSLionel Sambuc //===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc //  This file implements the Preprocessor interface.
11f4a2713aSLionel Sambuc //
12f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
13f4a2713aSLionel Sambuc //
14f4a2713aSLionel Sambuc // Options to support:
15f4a2713aSLionel Sambuc //   -H       - Print the name of each header file used.
16f4a2713aSLionel Sambuc //   -d[DNI] - Dump various things.
17f4a2713aSLionel Sambuc //   -fworking-directory - #line's with preprocessor's working dir.
18f4a2713aSLionel Sambuc //   -fpreprocessed
19f4a2713aSLionel Sambuc //   -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20f4a2713aSLionel Sambuc //   -W*
21f4a2713aSLionel Sambuc //   -w
22f4a2713aSLionel Sambuc //
23f4a2713aSLionel Sambuc // Messages to emit:
24f4a2713aSLionel Sambuc //   "Multiple include guards may be useful for:\n"
25f4a2713aSLionel Sambuc //
26f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
27f4a2713aSLionel Sambuc 
28f4a2713aSLionel Sambuc #include "clang/Lex/Preprocessor.h"
29f4a2713aSLionel Sambuc #include "clang/Basic/FileManager.h"
30*0a6a1f1dSLionel Sambuc #include "clang/Basic/FileSystemStatCache.h"
31f4a2713aSLionel Sambuc #include "clang/Basic/SourceManager.h"
32f4a2713aSLionel Sambuc #include "clang/Basic/TargetInfo.h"
33f4a2713aSLionel Sambuc #include "clang/Lex/CodeCompletionHandler.h"
34f4a2713aSLionel Sambuc #include "clang/Lex/ExternalPreprocessorSource.h"
35f4a2713aSLionel Sambuc #include "clang/Lex/HeaderSearch.h"
36f4a2713aSLionel Sambuc #include "clang/Lex/LexDiagnostic.h"
37f4a2713aSLionel Sambuc #include "clang/Lex/LiteralSupport.h"
38*0a6a1f1dSLionel Sambuc #include "clang/Lex/MacroArgs.h"
39f4a2713aSLionel Sambuc #include "clang/Lex/MacroInfo.h"
40f4a2713aSLionel Sambuc #include "clang/Lex/ModuleLoader.h"
41f4a2713aSLionel Sambuc #include "clang/Lex/Pragma.h"
42f4a2713aSLionel Sambuc #include "clang/Lex/PreprocessingRecord.h"
43f4a2713aSLionel Sambuc #include "clang/Lex/PreprocessorOptions.h"
44f4a2713aSLionel Sambuc #include "clang/Lex/ScratchBuffer.h"
45f4a2713aSLionel Sambuc #include "llvm/ADT/APFloat.h"
46f4a2713aSLionel Sambuc #include "llvm/ADT/STLExtras.h"
47*0a6a1f1dSLionel Sambuc #include "llvm/ADT/SmallString.h"
48f4a2713aSLionel Sambuc #include "llvm/ADT/StringExtras.h"
49f4a2713aSLionel Sambuc #include "llvm/Support/Capacity.h"
50f4a2713aSLionel Sambuc #include "llvm/Support/ConvertUTF.h"
51f4a2713aSLionel Sambuc #include "llvm/Support/MemoryBuffer.h"
52f4a2713aSLionel Sambuc #include "llvm/Support/raw_ostream.h"
53f4a2713aSLionel Sambuc using namespace clang;
54f4a2713aSLionel Sambuc 
55f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
~ExternalPreprocessorSource()56f4a2713aSLionel Sambuc ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
57f4a2713aSLionel Sambuc 
Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,DiagnosticsEngine & diags,LangOptions & opts,SourceManager & SM,HeaderSearch & Headers,ModuleLoader & TheModuleLoader,IdentifierInfoLookup * IILookup,bool OwnsHeaders,TranslationUnitKind TUKind)58f4a2713aSLionel Sambuc Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
59f4a2713aSLionel Sambuc                            DiagnosticsEngine &diags, LangOptions &opts,
60*0a6a1f1dSLionel Sambuc                            SourceManager &SM, HeaderSearch &Headers,
61*0a6a1f1dSLionel Sambuc                            ModuleLoader &TheModuleLoader,
62f4a2713aSLionel Sambuc                            IdentifierInfoLookup *IILookup, bool OwnsHeaders,
63*0a6a1f1dSLionel Sambuc                            TranslationUnitKind TUKind)
64*0a6a1f1dSLionel Sambuc     : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(nullptr),
65*0a6a1f1dSLionel Sambuc       FileMgr(Headers.getFileMgr()), SourceMgr(SM),
66*0a6a1f1dSLionel Sambuc       ScratchBuf(new ScratchBuffer(SourceMgr)),HeaderInfo(Headers),
67*0a6a1f1dSLionel Sambuc       TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
68*0a6a1f1dSLionel Sambuc       Identifiers(opts, IILookup),
69*0a6a1f1dSLionel Sambuc       PragmaHandlers(new PragmaNamespace(StringRef())),
70*0a6a1f1dSLionel Sambuc       IncrementalProcessing(false), TUKind(TUKind),
71*0a6a1f1dSLionel Sambuc       CodeComplete(nullptr), CodeCompletionFile(nullptr),
72*0a6a1f1dSLionel Sambuc       CodeCompletionOffset(0), LastTokenWasAt(false),
73*0a6a1f1dSLionel Sambuc       ModuleImportExpectsIdentifier(false), CodeCompletionReached(0),
74*0a6a1f1dSLionel Sambuc       MainFileDir(nullptr), SkipMainFilePreamble(0, true), CurPPLexer(nullptr),
75*0a6a1f1dSLionel Sambuc       CurDirLookup(nullptr), CurLexerKind(CLK_Lexer), CurSubmodule(nullptr),
76*0a6a1f1dSLionel Sambuc       Callbacks(nullptr), MacroArgCache(nullptr), Record(nullptr),
77*0a6a1f1dSLionel Sambuc       MIChainHead(nullptr), DeserialMIChainHead(nullptr) {
78f4a2713aSLionel Sambuc   OwnsHeaderSearch = OwnsHeaders;
79f4a2713aSLionel Sambuc 
80f4a2713aSLionel Sambuc   CounterValue = 0; // __COUNTER__ starts at 0.
81f4a2713aSLionel Sambuc 
82f4a2713aSLionel Sambuc   // Clear stats.
83f4a2713aSLionel Sambuc   NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
84f4a2713aSLionel Sambuc   NumIf = NumElse = NumEndif = 0;
85f4a2713aSLionel Sambuc   NumEnteredSourceFiles = 0;
86f4a2713aSLionel Sambuc   NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
87f4a2713aSLionel Sambuc   NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
88f4a2713aSLionel Sambuc   MaxIncludeStackDepth = 0;
89f4a2713aSLionel Sambuc   NumSkipped = 0;
90f4a2713aSLionel Sambuc 
91f4a2713aSLionel Sambuc   // Default to discarding comments.
92f4a2713aSLionel Sambuc   KeepComments = false;
93f4a2713aSLionel Sambuc   KeepMacroComments = false;
94f4a2713aSLionel Sambuc   SuppressIncludeNotFoundError = false;
95f4a2713aSLionel Sambuc 
96f4a2713aSLionel Sambuc   // Macro expansion is enabled.
97f4a2713aSLionel Sambuc   DisableMacroExpansion = false;
98f4a2713aSLionel Sambuc   MacroExpansionInDirectivesOverride = false;
99f4a2713aSLionel Sambuc   InMacroArgs = false;
100f4a2713aSLionel Sambuc   InMacroArgPreExpansion = false;
101f4a2713aSLionel Sambuc   NumCachedTokenLexers = 0;
102f4a2713aSLionel Sambuc   PragmasEnabled = true;
103f4a2713aSLionel Sambuc   ParsingIfOrElifDirective = false;
104f4a2713aSLionel Sambuc   PreprocessedOutput = false;
105f4a2713aSLionel Sambuc 
106f4a2713aSLionel Sambuc   CachedLexPos = 0;
107f4a2713aSLionel Sambuc 
108f4a2713aSLionel Sambuc   // We haven't read anything from the external source.
109f4a2713aSLionel Sambuc   ReadMacrosFromExternalSource = false;
110f4a2713aSLionel Sambuc 
111f4a2713aSLionel Sambuc   // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
112f4a2713aSLionel Sambuc   // This gets unpoisoned where it is allowed.
113f4a2713aSLionel Sambuc   (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
114f4a2713aSLionel Sambuc   SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
115f4a2713aSLionel Sambuc 
116f4a2713aSLionel Sambuc   // Initialize the pragma handlers.
117f4a2713aSLionel Sambuc   RegisterBuiltinPragmas();
118f4a2713aSLionel Sambuc 
119f4a2713aSLionel Sambuc   // Initialize builtin macros like __LINE__ and friends.
120f4a2713aSLionel Sambuc   RegisterBuiltinMacros();
121f4a2713aSLionel Sambuc 
122f4a2713aSLionel Sambuc   if(LangOpts.Borland) {
123f4a2713aSLionel Sambuc     Ident__exception_info        = getIdentifierInfo("_exception_info");
124f4a2713aSLionel Sambuc     Ident___exception_info       = getIdentifierInfo("__exception_info");
125f4a2713aSLionel Sambuc     Ident_GetExceptionInfo       = getIdentifierInfo("GetExceptionInformation");
126f4a2713aSLionel Sambuc     Ident__exception_code        = getIdentifierInfo("_exception_code");
127f4a2713aSLionel Sambuc     Ident___exception_code       = getIdentifierInfo("__exception_code");
128f4a2713aSLionel Sambuc     Ident_GetExceptionCode       = getIdentifierInfo("GetExceptionCode");
129f4a2713aSLionel Sambuc     Ident__abnormal_termination  = getIdentifierInfo("_abnormal_termination");
130f4a2713aSLionel Sambuc     Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
131f4a2713aSLionel Sambuc     Ident_AbnormalTermination    = getIdentifierInfo("AbnormalTermination");
132f4a2713aSLionel Sambuc   } else {
133*0a6a1f1dSLionel Sambuc     Ident__exception_info = Ident__exception_code = nullptr;
134*0a6a1f1dSLionel Sambuc     Ident__abnormal_termination = Ident___exception_info = nullptr;
135*0a6a1f1dSLionel Sambuc     Ident___exception_code = Ident___abnormal_termination = nullptr;
136*0a6a1f1dSLionel Sambuc     Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
137*0a6a1f1dSLionel Sambuc     Ident_AbnormalTermination = nullptr;
138f4a2713aSLionel Sambuc   }
139f4a2713aSLionel Sambuc }
140f4a2713aSLionel Sambuc 
~Preprocessor()141f4a2713aSLionel Sambuc Preprocessor::~Preprocessor() {
142f4a2713aSLionel Sambuc   assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
143f4a2713aSLionel Sambuc 
144*0a6a1f1dSLionel Sambuc   IncludeMacroStack.clear();
145*0a6a1f1dSLionel Sambuc 
146*0a6a1f1dSLionel Sambuc   // Destroy any macro definitions.
147*0a6a1f1dSLionel Sambuc   while (MacroInfoChain *I = MIChainHead) {
148*0a6a1f1dSLionel Sambuc     MIChainHead = I->Next;
149*0a6a1f1dSLionel Sambuc     I->~MacroInfoChain();
150f4a2713aSLionel Sambuc   }
151f4a2713aSLionel Sambuc 
152f4a2713aSLionel Sambuc   // Free any cached macro expanders.
153*0a6a1f1dSLionel Sambuc   // This populates MacroArgCache, so all TokenLexers need to be destroyed
154*0a6a1f1dSLionel Sambuc   // before the code below that frees up the MacroArgCache list.
155*0a6a1f1dSLionel Sambuc   std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
156*0a6a1f1dSLionel Sambuc   CurTokenLexer.reset();
157f4a2713aSLionel Sambuc 
158*0a6a1f1dSLionel Sambuc   while (DeserializedMacroInfoChain *I = DeserialMIChainHead) {
159*0a6a1f1dSLionel Sambuc     DeserialMIChainHead = I->Next;
160*0a6a1f1dSLionel Sambuc     I->~DeserializedMacroInfoChain();
161*0a6a1f1dSLionel Sambuc   }
162f4a2713aSLionel Sambuc 
163f4a2713aSLionel Sambuc   // Free any cached MacroArgs.
164f4a2713aSLionel Sambuc   for (MacroArgs *ArgList = MacroArgCache; ArgList;)
165f4a2713aSLionel Sambuc     ArgList = ArgList->deallocate();
166f4a2713aSLionel Sambuc 
167f4a2713aSLionel Sambuc   // Delete the header search info, if we own it.
168f4a2713aSLionel Sambuc   if (OwnsHeaderSearch)
169f4a2713aSLionel Sambuc     delete &HeaderInfo;
170f4a2713aSLionel Sambuc }
171f4a2713aSLionel Sambuc 
Initialize(const TargetInfo & Target)172f4a2713aSLionel Sambuc void Preprocessor::Initialize(const TargetInfo &Target) {
173f4a2713aSLionel Sambuc   assert((!this->Target || this->Target == &Target) &&
174f4a2713aSLionel Sambuc          "Invalid override of target information");
175f4a2713aSLionel Sambuc   this->Target = &Target;
176f4a2713aSLionel Sambuc 
177f4a2713aSLionel Sambuc   // Initialize information about built-ins.
178f4a2713aSLionel Sambuc   BuiltinInfo.InitializeTarget(Target);
179f4a2713aSLionel Sambuc   HeaderInfo.setTarget(Target);
180f4a2713aSLionel Sambuc }
181f4a2713aSLionel Sambuc 
InitializeForModelFile()182*0a6a1f1dSLionel Sambuc void Preprocessor::InitializeForModelFile() {
183*0a6a1f1dSLionel Sambuc   NumEnteredSourceFiles = 0;
184*0a6a1f1dSLionel Sambuc 
185*0a6a1f1dSLionel Sambuc   // Reset pragmas
186*0a6a1f1dSLionel Sambuc   PragmaHandlersBackup = std::move(PragmaHandlers);
187*0a6a1f1dSLionel Sambuc   PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
188*0a6a1f1dSLionel Sambuc   RegisterBuiltinPragmas();
189*0a6a1f1dSLionel Sambuc 
190*0a6a1f1dSLionel Sambuc   // Reset PredefinesFileID
191*0a6a1f1dSLionel Sambuc   PredefinesFileID = FileID();
192*0a6a1f1dSLionel Sambuc }
193*0a6a1f1dSLionel Sambuc 
FinalizeForModelFile()194*0a6a1f1dSLionel Sambuc void Preprocessor::FinalizeForModelFile() {
195*0a6a1f1dSLionel Sambuc   NumEnteredSourceFiles = 1;
196*0a6a1f1dSLionel Sambuc 
197*0a6a1f1dSLionel Sambuc   PragmaHandlers = std::move(PragmaHandlersBackup);
198*0a6a1f1dSLionel Sambuc }
199*0a6a1f1dSLionel Sambuc 
setPTHManager(PTHManager * pm)200f4a2713aSLionel Sambuc void Preprocessor::setPTHManager(PTHManager* pm) {
201f4a2713aSLionel Sambuc   PTH.reset(pm);
202f4a2713aSLionel Sambuc   FileMgr.addStatCache(PTH->createStatCache());
203f4a2713aSLionel Sambuc }
204f4a2713aSLionel Sambuc 
DumpToken(const Token & Tok,bool DumpFlags) const205f4a2713aSLionel Sambuc void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
206f4a2713aSLionel Sambuc   llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
207f4a2713aSLionel Sambuc                << getSpelling(Tok) << "'";
208f4a2713aSLionel Sambuc 
209f4a2713aSLionel Sambuc   if (!DumpFlags) return;
210f4a2713aSLionel Sambuc 
211f4a2713aSLionel Sambuc   llvm::errs() << "\t";
212f4a2713aSLionel Sambuc   if (Tok.isAtStartOfLine())
213f4a2713aSLionel Sambuc     llvm::errs() << " [StartOfLine]";
214f4a2713aSLionel Sambuc   if (Tok.hasLeadingSpace())
215f4a2713aSLionel Sambuc     llvm::errs() << " [LeadingSpace]";
216f4a2713aSLionel Sambuc   if (Tok.isExpandDisabled())
217f4a2713aSLionel Sambuc     llvm::errs() << " [ExpandDisabled]";
218f4a2713aSLionel Sambuc   if (Tok.needsCleaning()) {
219f4a2713aSLionel Sambuc     const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
220f4a2713aSLionel Sambuc     llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
221f4a2713aSLionel Sambuc                  << "']";
222f4a2713aSLionel Sambuc   }
223f4a2713aSLionel Sambuc 
224f4a2713aSLionel Sambuc   llvm::errs() << "\tLoc=<";
225f4a2713aSLionel Sambuc   DumpLocation(Tok.getLocation());
226f4a2713aSLionel Sambuc   llvm::errs() << ">";
227f4a2713aSLionel Sambuc }
228f4a2713aSLionel Sambuc 
DumpLocation(SourceLocation Loc) const229f4a2713aSLionel Sambuc void Preprocessor::DumpLocation(SourceLocation Loc) const {
230f4a2713aSLionel Sambuc   Loc.dump(SourceMgr);
231f4a2713aSLionel Sambuc }
232f4a2713aSLionel Sambuc 
DumpMacro(const MacroInfo & MI) const233f4a2713aSLionel Sambuc void Preprocessor::DumpMacro(const MacroInfo &MI) const {
234f4a2713aSLionel Sambuc   llvm::errs() << "MACRO: ";
235f4a2713aSLionel Sambuc   for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
236f4a2713aSLionel Sambuc     DumpToken(MI.getReplacementToken(i));
237f4a2713aSLionel Sambuc     llvm::errs() << "  ";
238f4a2713aSLionel Sambuc   }
239f4a2713aSLionel Sambuc   llvm::errs() << "\n";
240f4a2713aSLionel Sambuc }
241f4a2713aSLionel Sambuc 
PrintStats()242f4a2713aSLionel Sambuc void Preprocessor::PrintStats() {
243f4a2713aSLionel Sambuc   llvm::errs() << "\n*** Preprocessor Stats:\n";
244f4a2713aSLionel Sambuc   llvm::errs() << NumDirectives << " directives found:\n";
245f4a2713aSLionel Sambuc   llvm::errs() << "  " << NumDefined << " #define.\n";
246f4a2713aSLionel Sambuc   llvm::errs() << "  " << NumUndefined << " #undef.\n";
247f4a2713aSLionel Sambuc   llvm::errs() << "  #include/#include_next/#import:\n";
248f4a2713aSLionel Sambuc   llvm::errs() << "    " << NumEnteredSourceFiles << " source files entered.\n";
249f4a2713aSLionel Sambuc   llvm::errs() << "    " << MaxIncludeStackDepth << " max include stack depth\n";
250f4a2713aSLionel Sambuc   llvm::errs() << "  " << NumIf << " #if/#ifndef/#ifdef.\n";
251f4a2713aSLionel Sambuc   llvm::errs() << "  " << NumElse << " #else/#elif.\n";
252f4a2713aSLionel Sambuc   llvm::errs() << "  " << NumEndif << " #endif.\n";
253f4a2713aSLionel Sambuc   llvm::errs() << "  " << NumPragma << " #pragma.\n";
254f4a2713aSLionel Sambuc   llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
255f4a2713aSLionel Sambuc 
256f4a2713aSLionel Sambuc   llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
257f4a2713aSLionel Sambuc              << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
258f4a2713aSLionel Sambuc              << NumFastMacroExpanded << " on the fast path.\n";
259f4a2713aSLionel Sambuc   llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
260f4a2713aSLionel Sambuc              << " token paste (##) operations performed, "
261f4a2713aSLionel Sambuc              << NumFastTokenPaste << " on the fast path.\n";
262f4a2713aSLionel Sambuc 
263f4a2713aSLionel Sambuc   llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
264f4a2713aSLionel Sambuc 
265f4a2713aSLionel Sambuc   llvm::errs() << "\n  BumpPtr: " << BP.getTotalMemory();
266f4a2713aSLionel Sambuc   llvm::errs() << "\n  Macro Expanded Tokens: "
267f4a2713aSLionel Sambuc                << llvm::capacity_in_bytes(MacroExpandedTokens);
268f4a2713aSLionel Sambuc   llvm::errs() << "\n  Predefines Buffer: " << Predefines.capacity();
269f4a2713aSLionel Sambuc   llvm::errs() << "\n  Macros: " << llvm::capacity_in_bytes(Macros);
270f4a2713aSLionel Sambuc   llvm::errs() << "\n  #pragma push_macro Info: "
271f4a2713aSLionel Sambuc                << llvm::capacity_in_bytes(PragmaPushMacroInfo);
272f4a2713aSLionel Sambuc   llvm::errs() << "\n  Poison Reasons: "
273f4a2713aSLionel Sambuc                << llvm::capacity_in_bytes(PoisonReasons);
274f4a2713aSLionel Sambuc   llvm::errs() << "\n  Comment Handlers: "
275f4a2713aSLionel Sambuc                << llvm::capacity_in_bytes(CommentHandlers) << "\n";
276f4a2713aSLionel Sambuc }
277f4a2713aSLionel Sambuc 
278f4a2713aSLionel Sambuc Preprocessor::macro_iterator
macro_begin(bool IncludeExternalMacros) const279f4a2713aSLionel Sambuc Preprocessor::macro_begin(bool IncludeExternalMacros) const {
280f4a2713aSLionel Sambuc   if (IncludeExternalMacros && ExternalSource &&
281f4a2713aSLionel Sambuc       !ReadMacrosFromExternalSource) {
282f4a2713aSLionel Sambuc     ReadMacrosFromExternalSource = true;
283f4a2713aSLionel Sambuc     ExternalSource->ReadDefinedMacros();
284f4a2713aSLionel Sambuc   }
285f4a2713aSLionel Sambuc 
286f4a2713aSLionel Sambuc   return Macros.begin();
287f4a2713aSLionel Sambuc }
288f4a2713aSLionel Sambuc 
getTotalMemory() const289f4a2713aSLionel Sambuc size_t Preprocessor::getTotalMemory() const {
290f4a2713aSLionel Sambuc   return BP.getTotalMemory()
291f4a2713aSLionel Sambuc     + llvm::capacity_in_bytes(MacroExpandedTokens)
292f4a2713aSLionel Sambuc     + Predefines.capacity() /* Predefines buffer. */
293f4a2713aSLionel Sambuc     + llvm::capacity_in_bytes(Macros)
294f4a2713aSLionel Sambuc     + llvm::capacity_in_bytes(PragmaPushMacroInfo)
295f4a2713aSLionel Sambuc     + llvm::capacity_in_bytes(PoisonReasons)
296f4a2713aSLionel Sambuc     + llvm::capacity_in_bytes(CommentHandlers);
297f4a2713aSLionel Sambuc }
298f4a2713aSLionel Sambuc 
299f4a2713aSLionel Sambuc Preprocessor::macro_iterator
macro_end(bool IncludeExternalMacros) const300f4a2713aSLionel Sambuc Preprocessor::macro_end(bool IncludeExternalMacros) const {
301f4a2713aSLionel Sambuc   if (IncludeExternalMacros && ExternalSource &&
302f4a2713aSLionel Sambuc       !ReadMacrosFromExternalSource) {
303f4a2713aSLionel Sambuc     ReadMacrosFromExternalSource = true;
304f4a2713aSLionel Sambuc     ExternalSource->ReadDefinedMacros();
305f4a2713aSLionel Sambuc   }
306f4a2713aSLionel Sambuc 
307f4a2713aSLionel Sambuc   return Macros.end();
308f4a2713aSLionel Sambuc }
309f4a2713aSLionel Sambuc 
310f4a2713aSLionel Sambuc /// \brief Compares macro tokens with a specified token value sequence.
MacroDefinitionEquals(const MacroInfo * MI,ArrayRef<TokenValue> Tokens)311f4a2713aSLionel Sambuc static bool MacroDefinitionEquals(const MacroInfo *MI,
312f4a2713aSLionel Sambuc                                   ArrayRef<TokenValue> Tokens) {
313f4a2713aSLionel Sambuc   return Tokens.size() == MI->getNumTokens() &&
314f4a2713aSLionel Sambuc       std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
315f4a2713aSLionel Sambuc }
316f4a2713aSLionel Sambuc 
getLastMacroWithSpelling(SourceLocation Loc,ArrayRef<TokenValue> Tokens) const317f4a2713aSLionel Sambuc StringRef Preprocessor::getLastMacroWithSpelling(
318f4a2713aSLionel Sambuc                                     SourceLocation Loc,
319f4a2713aSLionel Sambuc                                     ArrayRef<TokenValue> Tokens) const {
320f4a2713aSLionel Sambuc   SourceLocation BestLocation;
321f4a2713aSLionel Sambuc   StringRef BestSpelling;
322f4a2713aSLionel Sambuc   for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
323f4a2713aSLionel Sambuc        I != E; ++I) {
324f4a2713aSLionel Sambuc     if (!I->second->getMacroInfo()->isObjectLike())
325f4a2713aSLionel Sambuc       continue;
326f4a2713aSLionel Sambuc     const MacroDirective::DefInfo
327f4a2713aSLionel Sambuc       Def = I->second->findDirectiveAtLoc(Loc, SourceMgr);
328f4a2713aSLionel Sambuc     if (!Def)
329f4a2713aSLionel Sambuc       continue;
330f4a2713aSLionel Sambuc     if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
331f4a2713aSLionel Sambuc       continue;
332f4a2713aSLionel Sambuc     SourceLocation Location = Def.getLocation();
333f4a2713aSLionel Sambuc     // Choose the macro defined latest.
334f4a2713aSLionel Sambuc     if (BestLocation.isInvalid() ||
335f4a2713aSLionel Sambuc         (Location.isValid() &&
336f4a2713aSLionel Sambuc          SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
337f4a2713aSLionel Sambuc       BestLocation = Location;
338f4a2713aSLionel Sambuc       BestSpelling = I->first->getName();
339f4a2713aSLionel Sambuc     }
340f4a2713aSLionel Sambuc   }
341f4a2713aSLionel Sambuc   return BestSpelling;
342f4a2713aSLionel Sambuc }
343f4a2713aSLionel Sambuc 
recomputeCurLexerKind()344f4a2713aSLionel Sambuc void Preprocessor::recomputeCurLexerKind() {
345f4a2713aSLionel Sambuc   if (CurLexer)
346f4a2713aSLionel Sambuc     CurLexerKind = CLK_Lexer;
347f4a2713aSLionel Sambuc   else if (CurPTHLexer)
348f4a2713aSLionel Sambuc     CurLexerKind = CLK_PTHLexer;
349f4a2713aSLionel Sambuc   else if (CurTokenLexer)
350f4a2713aSLionel Sambuc     CurLexerKind = CLK_TokenLexer;
351f4a2713aSLionel Sambuc   else
352f4a2713aSLionel Sambuc     CurLexerKind = CLK_CachingLexer;
353f4a2713aSLionel Sambuc }
354f4a2713aSLionel Sambuc 
SetCodeCompletionPoint(const FileEntry * File,unsigned CompleteLine,unsigned CompleteColumn)355f4a2713aSLionel Sambuc bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
356f4a2713aSLionel Sambuc                                           unsigned CompleteLine,
357f4a2713aSLionel Sambuc                                           unsigned CompleteColumn) {
358f4a2713aSLionel Sambuc   assert(File);
359f4a2713aSLionel Sambuc   assert(CompleteLine && CompleteColumn && "Starts from 1:1");
360f4a2713aSLionel Sambuc   assert(!CodeCompletionFile && "Already set");
361f4a2713aSLionel Sambuc 
362f4a2713aSLionel Sambuc   using llvm::MemoryBuffer;
363f4a2713aSLionel Sambuc 
364f4a2713aSLionel Sambuc   // Load the actual file's contents.
365f4a2713aSLionel Sambuc   bool Invalid = false;
366f4a2713aSLionel Sambuc   const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
367f4a2713aSLionel Sambuc   if (Invalid)
368f4a2713aSLionel Sambuc     return true;
369f4a2713aSLionel Sambuc 
370f4a2713aSLionel Sambuc   // Find the byte position of the truncation point.
371f4a2713aSLionel Sambuc   const char *Position = Buffer->getBufferStart();
372f4a2713aSLionel Sambuc   for (unsigned Line = 1; Line < CompleteLine; ++Line) {
373f4a2713aSLionel Sambuc     for (; *Position; ++Position) {
374f4a2713aSLionel Sambuc       if (*Position != '\r' && *Position != '\n')
375f4a2713aSLionel Sambuc         continue;
376f4a2713aSLionel Sambuc 
377f4a2713aSLionel Sambuc       // Eat \r\n or \n\r as a single line.
378f4a2713aSLionel Sambuc       if ((Position[1] == '\r' || Position[1] == '\n') &&
379f4a2713aSLionel Sambuc           Position[0] != Position[1])
380f4a2713aSLionel Sambuc         ++Position;
381f4a2713aSLionel Sambuc       ++Position;
382f4a2713aSLionel Sambuc       break;
383f4a2713aSLionel Sambuc     }
384f4a2713aSLionel Sambuc   }
385f4a2713aSLionel Sambuc 
386f4a2713aSLionel Sambuc   Position += CompleteColumn - 1;
387f4a2713aSLionel Sambuc 
388*0a6a1f1dSLionel Sambuc   // If pointing inside the preamble, adjust the position at the beginning of
389*0a6a1f1dSLionel Sambuc   // the file after the preamble.
390*0a6a1f1dSLionel Sambuc   if (SkipMainFilePreamble.first &&
391*0a6a1f1dSLionel Sambuc       SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
392*0a6a1f1dSLionel Sambuc     if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
393*0a6a1f1dSLionel Sambuc       Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
394*0a6a1f1dSLionel Sambuc   }
395*0a6a1f1dSLionel Sambuc 
396*0a6a1f1dSLionel Sambuc   if (Position > Buffer->getBufferEnd())
397*0a6a1f1dSLionel Sambuc     Position = Buffer->getBufferEnd();
398*0a6a1f1dSLionel Sambuc 
399f4a2713aSLionel Sambuc   CodeCompletionFile = File;
400f4a2713aSLionel Sambuc   CodeCompletionOffset = Position - Buffer->getBufferStart();
401f4a2713aSLionel Sambuc 
402*0a6a1f1dSLionel Sambuc   std::unique_ptr<MemoryBuffer> NewBuffer =
403f4a2713aSLionel Sambuc       MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
404f4a2713aSLionel Sambuc                                           Buffer->getBufferIdentifier());
405f4a2713aSLionel Sambuc   char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
406f4a2713aSLionel Sambuc   char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
407f4a2713aSLionel Sambuc   *NewPos = '\0';
408f4a2713aSLionel Sambuc   std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
409*0a6a1f1dSLionel Sambuc   SourceMgr.overrideFileContents(File, std::move(NewBuffer));
410f4a2713aSLionel Sambuc 
411f4a2713aSLionel Sambuc   return false;
412f4a2713aSLionel Sambuc }
413f4a2713aSLionel Sambuc 
CodeCompleteNaturalLanguage()414f4a2713aSLionel Sambuc void Preprocessor::CodeCompleteNaturalLanguage() {
415f4a2713aSLionel Sambuc   if (CodeComplete)
416f4a2713aSLionel Sambuc     CodeComplete->CodeCompleteNaturalLanguage();
417f4a2713aSLionel Sambuc   setCodeCompletionReached();
418f4a2713aSLionel Sambuc }
419f4a2713aSLionel Sambuc 
420f4a2713aSLionel Sambuc /// getSpelling - This method is used to get the spelling of a token into a
421f4a2713aSLionel Sambuc /// SmallVector. Note that the returned StringRef may not point to the
422f4a2713aSLionel Sambuc /// supplied buffer if a copy can be avoided.
getSpelling(const Token & Tok,SmallVectorImpl<char> & Buffer,bool * Invalid) const423f4a2713aSLionel Sambuc StringRef Preprocessor::getSpelling(const Token &Tok,
424f4a2713aSLionel Sambuc                                           SmallVectorImpl<char> &Buffer,
425f4a2713aSLionel Sambuc                                           bool *Invalid) const {
426f4a2713aSLionel Sambuc   // NOTE: this has to be checked *before* testing for an IdentifierInfo.
427f4a2713aSLionel Sambuc   if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
428f4a2713aSLionel Sambuc     // Try the fast path.
429f4a2713aSLionel Sambuc     if (const IdentifierInfo *II = Tok.getIdentifierInfo())
430f4a2713aSLionel Sambuc       return II->getName();
431f4a2713aSLionel Sambuc   }
432f4a2713aSLionel Sambuc 
433f4a2713aSLionel Sambuc   // Resize the buffer if we need to copy into it.
434f4a2713aSLionel Sambuc   if (Tok.needsCleaning())
435f4a2713aSLionel Sambuc     Buffer.resize(Tok.getLength());
436f4a2713aSLionel Sambuc 
437f4a2713aSLionel Sambuc   const char *Ptr = Buffer.data();
438f4a2713aSLionel Sambuc   unsigned Len = getSpelling(Tok, Ptr, Invalid);
439f4a2713aSLionel Sambuc   return StringRef(Ptr, Len);
440f4a2713aSLionel Sambuc }
441f4a2713aSLionel Sambuc 
442f4a2713aSLionel Sambuc /// CreateString - Plop the specified string into a scratch buffer and return a
443f4a2713aSLionel Sambuc /// location for it.  If specified, the source location provides a source
444f4a2713aSLionel Sambuc /// location for the token.
CreateString(StringRef Str,Token & Tok,SourceLocation ExpansionLocStart,SourceLocation ExpansionLocEnd)445f4a2713aSLionel Sambuc void Preprocessor::CreateString(StringRef Str, Token &Tok,
446f4a2713aSLionel Sambuc                                 SourceLocation ExpansionLocStart,
447f4a2713aSLionel Sambuc                                 SourceLocation ExpansionLocEnd) {
448f4a2713aSLionel Sambuc   Tok.setLength(Str.size());
449f4a2713aSLionel Sambuc 
450f4a2713aSLionel Sambuc   const char *DestPtr;
451f4a2713aSLionel Sambuc   SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
452f4a2713aSLionel Sambuc 
453f4a2713aSLionel Sambuc   if (ExpansionLocStart.isValid())
454f4a2713aSLionel Sambuc     Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
455f4a2713aSLionel Sambuc                                        ExpansionLocEnd, Str.size());
456f4a2713aSLionel Sambuc   Tok.setLocation(Loc);
457f4a2713aSLionel Sambuc 
458f4a2713aSLionel Sambuc   // If this is a raw identifier or a literal token, set the pointer data.
459f4a2713aSLionel Sambuc   if (Tok.is(tok::raw_identifier))
460f4a2713aSLionel Sambuc     Tok.setRawIdentifierData(DestPtr);
461f4a2713aSLionel Sambuc   else if (Tok.isLiteral())
462f4a2713aSLionel Sambuc     Tok.setLiteralData(DestPtr);
463f4a2713aSLionel Sambuc }
464f4a2713aSLionel Sambuc 
getCurrentModule()465f4a2713aSLionel Sambuc Module *Preprocessor::getCurrentModule() {
466f4a2713aSLionel Sambuc   if (getLangOpts().CurrentModule.empty())
467*0a6a1f1dSLionel Sambuc     return nullptr;
468f4a2713aSLionel Sambuc 
469f4a2713aSLionel Sambuc   return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
470f4a2713aSLionel Sambuc }
471f4a2713aSLionel Sambuc 
472f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
473f4a2713aSLionel Sambuc // Preprocessor Initialization Methods
474f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
475f4a2713aSLionel Sambuc 
476f4a2713aSLionel Sambuc 
477f4a2713aSLionel Sambuc /// EnterMainSourceFile - Enter the specified FileID as the main source file,
478f4a2713aSLionel Sambuc /// which implicitly adds the builtin defines etc.
EnterMainSourceFile()479f4a2713aSLionel Sambuc void Preprocessor::EnterMainSourceFile() {
480f4a2713aSLionel Sambuc   // We do not allow the preprocessor to reenter the main file.  Doing so will
481f4a2713aSLionel Sambuc   // cause FileID's to accumulate information from both runs (e.g. #line
482f4a2713aSLionel Sambuc   // information) and predefined macros aren't guaranteed to be set properly.
483f4a2713aSLionel Sambuc   assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
484f4a2713aSLionel Sambuc   FileID MainFileID = SourceMgr.getMainFileID();
485f4a2713aSLionel Sambuc 
486f4a2713aSLionel Sambuc   // If MainFileID is loaded it means we loaded an AST file, no need to enter
487f4a2713aSLionel Sambuc   // a main file.
488f4a2713aSLionel Sambuc   if (!SourceMgr.isLoadedFileID(MainFileID)) {
489f4a2713aSLionel Sambuc     // Enter the main file source buffer.
490*0a6a1f1dSLionel Sambuc     EnterSourceFile(MainFileID, nullptr, SourceLocation());
491f4a2713aSLionel Sambuc 
492f4a2713aSLionel Sambuc     // If we've been asked to skip bytes in the main file (e.g., as part of a
493f4a2713aSLionel Sambuc     // precompiled preamble), do so now.
494f4a2713aSLionel Sambuc     if (SkipMainFilePreamble.first > 0)
495f4a2713aSLionel Sambuc       CurLexer->SkipBytes(SkipMainFilePreamble.first,
496f4a2713aSLionel Sambuc                           SkipMainFilePreamble.second);
497f4a2713aSLionel Sambuc 
498f4a2713aSLionel Sambuc     // Tell the header info that the main file was entered.  If the file is later
499f4a2713aSLionel Sambuc     // #imported, it won't be re-entered.
500f4a2713aSLionel Sambuc     if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
501f4a2713aSLionel Sambuc       HeaderInfo.IncrementIncludeCount(FE);
502f4a2713aSLionel Sambuc   }
503f4a2713aSLionel Sambuc 
504f4a2713aSLionel Sambuc   // Preprocess Predefines to populate the initial preprocessor state.
505*0a6a1f1dSLionel Sambuc   std::unique_ptr<llvm::MemoryBuffer> SB =
506f4a2713aSLionel Sambuc     llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
507f4a2713aSLionel Sambuc   assert(SB && "Cannot create predefined source buffer");
508*0a6a1f1dSLionel Sambuc   FileID FID = SourceMgr.createFileID(std::move(SB));
509f4a2713aSLionel Sambuc   assert(!FID.isInvalid() && "Could not create FileID for predefines?");
510f4a2713aSLionel Sambuc   setPredefinesFileID(FID);
511f4a2713aSLionel Sambuc 
512f4a2713aSLionel Sambuc   // Start parsing the predefines.
513*0a6a1f1dSLionel Sambuc   EnterSourceFile(FID, nullptr, SourceLocation());
514f4a2713aSLionel Sambuc }
515f4a2713aSLionel Sambuc 
EndSourceFile()516f4a2713aSLionel Sambuc void Preprocessor::EndSourceFile() {
517f4a2713aSLionel Sambuc   // Notify the client that we reached the end of the source file.
518f4a2713aSLionel Sambuc   if (Callbacks)
519f4a2713aSLionel Sambuc     Callbacks->EndOfMainFile();
520f4a2713aSLionel Sambuc }
521f4a2713aSLionel Sambuc 
522f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
523f4a2713aSLionel Sambuc // Lexer Event Handling.
524f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
525f4a2713aSLionel Sambuc 
526f4a2713aSLionel Sambuc /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
527f4a2713aSLionel Sambuc /// identifier information for the token and install it into the token,
528f4a2713aSLionel Sambuc /// updating the token kind accordingly.
LookUpIdentifierInfo(Token & Identifier) const529f4a2713aSLionel Sambuc IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
530*0a6a1f1dSLionel Sambuc   assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
531f4a2713aSLionel Sambuc 
532f4a2713aSLionel Sambuc   // Look up this token, see if it is a macro, or if it is a language keyword.
533f4a2713aSLionel Sambuc   IdentifierInfo *II;
534f4a2713aSLionel Sambuc   if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
535f4a2713aSLionel Sambuc     // No cleaning needed, just use the characters from the lexed buffer.
536*0a6a1f1dSLionel Sambuc     II = getIdentifierInfo(Identifier.getRawIdentifier());
537f4a2713aSLionel Sambuc   } else {
538f4a2713aSLionel Sambuc     // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
539f4a2713aSLionel Sambuc     SmallString<64> IdentifierBuffer;
540f4a2713aSLionel Sambuc     StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
541f4a2713aSLionel Sambuc 
542f4a2713aSLionel Sambuc     if (Identifier.hasUCN()) {
543f4a2713aSLionel Sambuc       SmallString<64> UCNIdentifierBuffer;
544f4a2713aSLionel Sambuc       expandUCNs(UCNIdentifierBuffer, CleanedStr);
545f4a2713aSLionel Sambuc       II = getIdentifierInfo(UCNIdentifierBuffer);
546f4a2713aSLionel Sambuc     } else {
547f4a2713aSLionel Sambuc       II = getIdentifierInfo(CleanedStr);
548f4a2713aSLionel Sambuc     }
549f4a2713aSLionel Sambuc   }
550f4a2713aSLionel Sambuc 
551f4a2713aSLionel Sambuc   // Update the token info (identifier info and appropriate token kind).
552f4a2713aSLionel Sambuc   Identifier.setIdentifierInfo(II);
553f4a2713aSLionel Sambuc   Identifier.setKind(II->getTokenID());
554f4a2713aSLionel Sambuc 
555f4a2713aSLionel Sambuc   return II;
556f4a2713aSLionel Sambuc }
557f4a2713aSLionel Sambuc 
SetPoisonReason(IdentifierInfo * II,unsigned DiagID)558f4a2713aSLionel Sambuc void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
559f4a2713aSLionel Sambuc   PoisonReasons[II] = DiagID;
560f4a2713aSLionel Sambuc }
561f4a2713aSLionel Sambuc 
PoisonSEHIdentifiers(bool Poison)562f4a2713aSLionel Sambuc void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
563f4a2713aSLionel Sambuc   assert(Ident__exception_code && Ident__exception_info);
564f4a2713aSLionel Sambuc   assert(Ident___exception_code && Ident___exception_info);
565f4a2713aSLionel Sambuc   Ident__exception_code->setIsPoisoned(Poison);
566f4a2713aSLionel Sambuc   Ident___exception_code->setIsPoisoned(Poison);
567f4a2713aSLionel Sambuc   Ident_GetExceptionCode->setIsPoisoned(Poison);
568f4a2713aSLionel Sambuc   Ident__exception_info->setIsPoisoned(Poison);
569f4a2713aSLionel Sambuc   Ident___exception_info->setIsPoisoned(Poison);
570f4a2713aSLionel Sambuc   Ident_GetExceptionInfo->setIsPoisoned(Poison);
571f4a2713aSLionel Sambuc   Ident__abnormal_termination->setIsPoisoned(Poison);
572f4a2713aSLionel Sambuc   Ident___abnormal_termination->setIsPoisoned(Poison);
573f4a2713aSLionel Sambuc   Ident_AbnormalTermination->setIsPoisoned(Poison);
574f4a2713aSLionel Sambuc }
575f4a2713aSLionel Sambuc 
HandlePoisonedIdentifier(Token & Identifier)576f4a2713aSLionel Sambuc void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
577f4a2713aSLionel Sambuc   assert(Identifier.getIdentifierInfo() &&
578f4a2713aSLionel Sambuc          "Can't handle identifiers without identifier info!");
579f4a2713aSLionel Sambuc   llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
580f4a2713aSLionel Sambuc     PoisonReasons.find(Identifier.getIdentifierInfo());
581f4a2713aSLionel Sambuc   if(it == PoisonReasons.end())
582f4a2713aSLionel Sambuc     Diag(Identifier, diag::err_pp_used_poisoned_id);
583f4a2713aSLionel Sambuc   else
584f4a2713aSLionel Sambuc     Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
585f4a2713aSLionel Sambuc }
586f4a2713aSLionel Sambuc 
587f4a2713aSLionel Sambuc /// HandleIdentifier - This callback is invoked when the lexer reads an
588f4a2713aSLionel Sambuc /// identifier.  This callback looks up the identifier in the map and/or
589f4a2713aSLionel Sambuc /// potentially macro expands it or turns it into a named token (like 'for').
590f4a2713aSLionel Sambuc ///
591f4a2713aSLionel Sambuc /// Note that callers of this method are guarded by checking the
592f4a2713aSLionel Sambuc /// IdentifierInfo's 'isHandleIdentifierCase' bit.  If this method changes, the
593f4a2713aSLionel Sambuc /// IdentifierInfo methods that compute these properties will need to change to
594f4a2713aSLionel Sambuc /// match.
HandleIdentifier(Token & Identifier)595f4a2713aSLionel Sambuc bool Preprocessor::HandleIdentifier(Token &Identifier) {
596f4a2713aSLionel Sambuc   assert(Identifier.getIdentifierInfo() &&
597f4a2713aSLionel Sambuc          "Can't handle identifiers without identifier info!");
598f4a2713aSLionel Sambuc 
599f4a2713aSLionel Sambuc   IdentifierInfo &II = *Identifier.getIdentifierInfo();
600f4a2713aSLionel Sambuc 
601f4a2713aSLionel Sambuc   // If the information about this identifier is out of date, update it from
602f4a2713aSLionel Sambuc   // the external source.
603f4a2713aSLionel Sambuc   // We have to treat __VA_ARGS__ in a special way, since it gets
604f4a2713aSLionel Sambuc   // serialized with isPoisoned = true, but our preprocessor may have
605f4a2713aSLionel Sambuc   // unpoisoned it if we're defining a C99 macro.
606f4a2713aSLionel Sambuc   if (II.isOutOfDate()) {
607f4a2713aSLionel Sambuc     bool CurrentIsPoisoned = false;
608f4a2713aSLionel Sambuc     if (&II == Ident__VA_ARGS__)
609f4a2713aSLionel Sambuc       CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
610f4a2713aSLionel Sambuc 
611f4a2713aSLionel Sambuc     ExternalSource->updateOutOfDateIdentifier(II);
612f4a2713aSLionel Sambuc     Identifier.setKind(II.getTokenID());
613f4a2713aSLionel Sambuc 
614f4a2713aSLionel Sambuc     if (&II == Ident__VA_ARGS__)
615f4a2713aSLionel Sambuc       II.setIsPoisoned(CurrentIsPoisoned);
616f4a2713aSLionel Sambuc   }
617f4a2713aSLionel Sambuc 
618f4a2713aSLionel Sambuc   // If this identifier was poisoned, and if it was not produced from a macro
619f4a2713aSLionel Sambuc   // expansion, emit an error.
620f4a2713aSLionel Sambuc   if (II.isPoisoned() && CurPPLexer) {
621f4a2713aSLionel Sambuc     HandlePoisonedIdentifier(Identifier);
622f4a2713aSLionel Sambuc   }
623f4a2713aSLionel Sambuc 
624f4a2713aSLionel Sambuc   // If this is a macro to be expanded, do it.
625f4a2713aSLionel Sambuc   if (MacroDirective *MD = getMacroDirective(&II)) {
626f4a2713aSLionel Sambuc     MacroInfo *MI = MD->getMacroInfo();
627f4a2713aSLionel Sambuc     if (!DisableMacroExpansion) {
628f4a2713aSLionel Sambuc       if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
629f4a2713aSLionel Sambuc         // C99 6.10.3p10: If the preprocessing token immediately after the
630f4a2713aSLionel Sambuc         // macro name isn't a '(', this macro should not be expanded.
631f4a2713aSLionel Sambuc         if (!MI->isFunctionLike() || isNextPPTokenLParen())
632f4a2713aSLionel Sambuc           return HandleMacroExpandedIdentifier(Identifier, MD);
633f4a2713aSLionel Sambuc       } else {
634f4a2713aSLionel Sambuc         // C99 6.10.3.4p2 says that a disabled macro may never again be
635f4a2713aSLionel Sambuc         // expanded, even if it's in a context where it could be expanded in the
636f4a2713aSLionel Sambuc         // future.
637f4a2713aSLionel Sambuc         Identifier.setFlag(Token::DisableExpand);
638f4a2713aSLionel Sambuc         if (MI->isObjectLike() || isNextPPTokenLParen())
639f4a2713aSLionel Sambuc           Diag(Identifier, diag::pp_disabled_macro_expansion);
640f4a2713aSLionel Sambuc       }
641f4a2713aSLionel Sambuc     }
642f4a2713aSLionel Sambuc   }
643f4a2713aSLionel Sambuc 
644f4a2713aSLionel Sambuc   // If this identifier is a keyword in C++11, produce a warning. Don't warn if
645f4a2713aSLionel Sambuc   // we're not considering macro expansion, since this identifier might be the
646f4a2713aSLionel Sambuc   // name of a macro.
647f4a2713aSLionel Sambuc   // FIXME: This warning is disabled in cases where it shouldn't be, like
648f4a2713aSLionel Sambuc   //   "#define constexpr constexpr", "int constexpr;"
649*0a6a1f1dSLionel Sambuc   if (II.isCXX11CompatKeyword() && !DisableMacroExpansion) {
650f4a2713aSLionel Sambuc     Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
651f4a2713aSLionel Sambuc     // Don't diagnose this keyword again in this translation unit.
652f4a2713aSLionel Sambuc     II.setIsCXX11CompatKeyword(false);
653f4a2713aSLionel Sambuc   }
654f4a2713aSLionel Sambuc 
655f4a2713aSLionel Sambuc   // C++ 2.11p2: If this is an alternative representation of a C++ operator,
656f4a2713aSLionel Sambuc   // then we act as if it is the actual operator and not the textual
657f4a2713aSLionel Sambuc   // representation of it.
658f4a2713aSLionel Sambuc   if (II.isCPlusPlusOperatorKeyword())
659*0a6a1f1dSLionel Sambuc     Identifier.setIdentifierInfo(nullptr);
660f4a2713aSLionel Sambuc 
661f4a2713aSLionel Sambuc   // If this is an extension token, diagnose its use.
662f4a2713aSLionel Sambuc   // We avoid diagnosing tokens that originate from macro definitions.
663f4a2713aSLionel Sambuc   // FIXME: This warning is disabled in cases where it shouldn't be,
664f4a2713aSLionel Sambuc   // like "#define TY typeof", "TY(1) x".
665f4a2713aSLionel Sambuc   if (II.isExtensionToken() && !DisableMacroExpansion)
666f4a2713aSLionel Sambuc     Diag(Identifier, diag::ext_token_used);
667f4a2713aSLionel Sambuc 
668f4a2713aSLionel Sambuc   // If this is the 'import' contextual keyword following an '@', note
669f4a2713aSLionel Sambuc   // that the next token indicates a module name.
670f4a2713aSLionel Sambuc   //
671f4a2713aSLionel Sambuc   // Note that we do not treat 'import' as a contextual
672f4a2713aSLionel Sambuc   // keyword when we're in a caching lexer, because caching lexers only get
673f4a2713aSLionel Sambuc   // used in contexts where import declarations are disallowed.
674f4a2713aSLionel Sambuc   if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs &&
675*0a6a1f1dSLionel Sambuc       !DisableMacroExpansion &&
676*0a6a1f1dSLionel Sambuc       (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
677f4a2713aSLionel Sambuc       CurLexerKind != CLK_CachingLexer) {
678f4a2713aSLionel Sambuc     ModuleImportLoc = Identifier.getLocation();
679f4a2713aSLionel Sambuc     ModuleImportPath.clear();
680f4a2713aSLionel Sambuc     ModuleImportExpectsIdentifier = true;
681f4a2713aSLionel Sambuc     CurLexerKind = CLK_LexAfterModuleImport;
682f4a2713aSLionel Sambuc   }
683f4a2713aSLionel Sambuc   return true;
684f4a2713aSLionel Sambuc }
685f4a2713aSLionel Sambuc 
Lex(Token & Result)686f4a2713aSLionel Sambuc void Preprocessor::Lex(Token &Result) {
687f4a2713aSLionel Sambuc   // We loop here until a lex function retuns a token; this avoids recursion.
688f4a2713aSLionel Sambuc   bool ReturnedToken;
689f4a2713aSLionel Sambuc   do {
690f4a2713aSLionel Sambuc     switch (CurLexerKind) {
691f4a2713aSLionel Sambuc     case CLK_Lexer:
692f4a2713aSLionel Sambuc       ReturnedToken = CurLexer->Lex(Result);
693f4a2713aSLionel Sambuc       break;
694f4a2713aSLionel Sambuc     case CLK_PTHLexer:
695f4a2713aSLionel Sambuc       ReturnedToken = CurPTHLexer->Lex(Result);
696f4a2713aSLionel Sambuc       break;
697f4a2713aSLionel Sambuc     case CLK_TokenLexer:
698f4a2713aSLionel Sambuc       ReturnedToken = CurTokenLexer->Lex(Result);
699f4a2713aSLionel Sambuc       break;
700f4a2713aSLionel Sambuc     case CLK_CachingLexer:
701f4a2713aSLionel Sambuc       CachingLex(Result);
702f4a2713aSLionel Sambuc       ReturnedToken = true;
703f4a2713aSLionel Sambuc       break;
704f4a2713aSLionel Sambuc     case CLK_LexAfterModuleImport:
705f4a2713aSLionel Sambuc       LexAfterModuleImport(Result);
706f4a2713aSLionel Sambuc       ReturnedToken = true;
707f4a2713aSLionel Sambuc       break;
708f4a2713aSLionel Sambuc     }
709f4a2713aSLionel Sambuc   } while (!ReturnedToken);
710f4a2713aSLionel Sambuc 
711f4a2713aSLionel Sambuc   LastTokenWasAt = Result.is(tok::at);
712f4a2713aSLionel Sambuc }
713f4a2713aSLionel Sambuc 
714f4a2713aSLionel Sambuc 
715f4a2713aSLionel Sambuc /// \brief Lex a token following the 'import' contextual keyword.
716f4a2713aSLionel Sambuc ///
LexAfterModuleImport(Token & Result)717f4a2713aSLionel Sambuc void Preprocessor::LexAfterModuleImport(Token &Result) {
718f4a2713aSLionel Sambuc   // Figure out what kind of lexer we actually have.
719f4a2713aSLionel Sambuc   recomputeCurLexerKind();
720f4a2713aSLionel Sambuc 
721f4a2713aSLionel Sambuc   // Lex the next token.
722f4a2713aSLionel Sambuc   Lex(Result);
723f4a2713aSLionel Sambuc 
724f4a2713aSLionel Sambuc   // The token sequence
725f4a2713aSLionel Sambuc   //
726f4a2713aSLionel Sambuc   //   import identifier (. identifier)*
727f4a2713aSLionel Sambuc   //
728f4a2713aSLionel Sambuc   // indicates a module import directive. We already saw the 'import'
729f4a2713aSLionel Sambuc   // contextual keyword, so now we're looking for the identifiers.
730f4a2713aSLionel Sambuc   if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
731f4a2713aSLionel Sambuc     // We expected to see an identifier here, and we did; continue handling
732f4a2713aSLionel Sambuc     // identifiers.
733f4a2713aSLionel Sambuc     ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
734f4a2713aSLionel Sambuc                                               Result.getLocation()));
735f4a2713aSLionel Sambuc     ModuleImportExpectsIdentifier = false;
736f4a2713aSLionel Sambuc     CurLexerKind = CLK_LexAfterModuleImport;
737f4a2713aSLionel Sambuc     return;
738f4a2713aSLionel Sambuc   }
739f4a2713aSLionel Sambuc 
740f4a2713aSLionel Sambuc   // If we're expecting a '.' or a ';', and we got a '.', then wait until we
741f4a2713aSLionel Sambuc   // see the next identifier.
742f4a2713aSLionel Sambuc   if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
743f4a2713aSLionel Sambuc     ModuleImportExpectsIdentifier = true;
744f4a2713aSLionel Sambuc     CurLexerKind = CLK_LexAfterModuleImport;
745f4a2713aSLionel Sambuc     return;
746f4a2713aSLionel Sambuc   }
747f4a2713aSLionel Sambuc 
748f4a2713aSLionel Sambuc   // If we have a non-empty module path, load the named module.
749*0a6a1f1dSLionel Sambuc   if (!ModuleImportPath.empty()) {
750*0a6a1f1dSLionel Sambuc     Module *Imported = nullptr;
751*0a6a1f1dSLionel Sambuc     if (getLangOpts().Modules)
752*0a6a1f1dSLionel Sambuc       Imported = TheModuleLoader.loadModule(ModuleImportLoc,
753f4a2713aSLionel Sambuc                                             ModuleImportPath,
754f4a2713aSLionel Sambuc                                             Module::MacrosVisible,
755f4a2713aSLionel Sambuc                                             /*IsIncludeDirective=*/false);
756*0a6a1f1dSLionel Sambuc     if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
757f4a2713aSLionel Sambuc       Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
758f4a2713aSLionel Sambuc   }
759f4a2713aSLionel Sambuc }
760f4a2713aSLionel Sambuc 
FinishLexStringLiteral(Token & Result,std::string & String,const char * DiagnosticTag,bool AllowMacroExpansion)761f4a2713aSLionel Sambuc bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
762f4a2713aSLionel Sambuc                                           const char *DiagnosticTag,
763f4a2713aSLionel Sambuc                                           bool AllowMacroExpansion) {
764f4a2713aSLionel Sambuc   // We need at least one string literal.
765f4a2713aSLionel Sambuc   if (Result.isNot(tok::string_literal)) {
766f4a2713aSLionel Sambuc     Diag(Result, diag::err_expected_string_literal)
767f4a2713aSLionel Sambuc       << /*Source='in...'*/0 << DiagnosticTag;
768f4a2713aSLionel Sambuc     return false;
769f4a2713aSLionel Sambuc   }
770f4a2713aSLionel Sambuc 
771f4a2713aSLionel Sambuc   // Lex string literal tokens, optionally with macro expansion.
772f4a2713aSLionel Sambuc   SmallVector<Token, 4> StrToks;
773f4a2713aSLionel Sambuc   do {
774f4a2713aSLionel Sambuc     StrToks.push_back(Result);
775f4a2713aSLionel Sambuc 
776f4a2713aSLionel Sambuc     if (Result.hasUDSuffix())
777f4a2713aSLionel Sambuc       Diag(Result, diag::err_invalid_string_udl);
778f4a2713aSLionel Sambuc 
779f4a2713aSLionel Sambuc     if (AllowMacroExpansion)
780f4a2713aSLionel Sambuc       Lex(Result);
781f4a2713aSLionel Sambuc     else
782f4a2713aSLionel Sambuc       LexUnexpandedToken(Result);
783f4a2713aSLionel Sambuc   } while (Result.is(tok::string_literal));
784f4a2713aSLionel Sambuc 
785f4a2713aSLionel Sambuc   // Concatenate and parse the strings.
786*0a6a1f1dSLionel Sambuc   StringLiteralParser Literal(StrToks, *this);
787f4a2713aSLionel Sambuc   assert(Literal.isAscii() && "Didn't allow wide strings in");
788f4a2713aSLionel Sambuc 
789f4a2713aSLionel Sambuc   if (Literal.hadError)
790f4a2713aSLionel Sambuc     return false;
791f4a2713aSLionel Sambuc 
792f4a2713aSLionel Sambuc   if (Literal.Pascal) {
793f4a2713aSLionel Sambuc     Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
794f4a2713aSLionel Sambuc       << /*Source='in...'*/0 << DiagnosticTag;
795f4a2713aSLionel Sambuc     return false;
796f4a2713aSLionel Sambuc   }
797f4a2713aSLionel Sambuc 
798f4a2713aSLionel Sambuc   String = Literal.GetString();
799f4a2713aSLionel Sambuc   return true;
800f4a2713aSLionel Sambuc }
801f4a2713aSLionel Sambuc 
parseSimpleIntegerLiteral(Token & Tok,uint64_t & Value)802*0a6a1f1dSLionel Sambuc bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
803*0a6a1f1dSLionel Sambuc   assert(Tok.is(tok::numeric_constant));
804*0a6a1f1dSLionel Sambuc   SmallString<8> IntegerBuffer;
805*0a6a1f1dSLionel Sambuc   bool NumberInvalid = false;
806*0a6a1f1dSLionel Sambuc   StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
807*0a6a1f1dSLionel Sambuc   if (NumberInvalid)
808*0a6a1f1dSLionel Sambuc     return false;
809*0a6a1f1dSLionel Sambuc   NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
810*0a6a1f1dSLionel Sambuc   if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
811*0a6a1f1dSLionel Sambuc     return false;
812*0a6a1f1dSLionel Sambuc   llvm::APInt APVal(64, 0);
813*0a6a1f1dSLionel Sambuc   if (Literal.GetIntegerValue(APVal))
814*0a6a1f1dSLionel Sambuc     return false;
815*0a6a1f1dSLionel Sambuc   Lex(Tok);
816*0a6a1f1dSLionel Sambuc   Value = APVal.getLimitedValue();
817*0a6a1f1dSLionel Sambuc   return true;
818*0a6a1f1dSLionel Sambuc }
819*0a6a1f1dSLionel Sambuc 
addCommentHandler(CommentHandler * Handler)820f4a2713aSLionel Sambuc void Preprocessor::addCommentHandler(CommentHandler *Handler) {
821f4a2713aSLionel Sambuc   assert(Handler && "NULL comment handler");
822f4a2713aSLionel Sambuc   assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
823f4a2713aSLionel Sambuc          CommentHandlers.end() && "Comment handler already registered");
824f4a2713aSLionel Sambuc   CommentHandlers.push_back(Handler);
825f4a2713aSLionel Sambuc }
826f4a2713aSLionel Sambuc 
removeCommentHandler(CommentHandler * Handler)827f4a2713aSLionel Sambuc void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
828f4a2713aSLionel Sambuc   std::vector<CommentHandler *>::iterator Pos
829f4a2713aSLionel Sambuc   = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
830f4a2713aSLionel Sambuc   assert(Pos != CommentHandlers.end() && "Comment handler not registered");
831f4a2713aSLionel Sambuc   CommentHandlers.erase(Pos);
832f4a2713aSLionel Sambuc }
833f4a2713aSLionel Sambuc 
HandleComment(Token & result,SourceRange Comment)834f4a2713aSLionel Sambuc bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
835f4a2713aSLionel Sambuc   bool AnyPendingTokens = false;
836f4a2713aSLionel Sambuc   for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
837f4a2713aSLionel Sambuc        HEnd = CommentHandlers.end();
838f4a2713aSLionel Sambuc        H != HEnd; ++H) {
839f4a2713aSLionel Sambuc     if ((*H)->HandleComment(*this, Comment))
840f4a2713aSLionel Sambuc       AnyPendingTokens = true;
841f4a2713aSLionel Sambuc   }
842f4a2713aSLionel Sambuc   if (!AnyPendingTokens || getCommentRetentionState())
843f4a2713aSLionel Sambuc     return false;
844f4a2713aSLionel Sambuc   Lex(result);
845f4a2713aSLionel Sambuc   return true;
846f4a2713aSLionel Sambuc }
847f4a2713aSLionel Sambuc 
~ModuleLoader()848f4a2713aSLionel Sambuc ModuleLoader::~ModuleLoader() { }
849f4a2713aSLionel Sambuc 
~CommentHandler()850f4a2713aSLionel Sambuc CommentHandler::~CommentHandler() { }
851f4a2713aSLionel Sambuc 
~CodeCompletionHandler()852f4a2713aSLionel Sambuc CodeCompletionHandler::~CodeCompletionHandler() { }
853f4a2713aSLionel Sambuc 
createPreprocessingRecord()854f4a2713aSLionel Sambuc void Preprocessor::createPreprocessingRecord() {
855f4a2713aSLionel Sambuc   if (Record)
856f4a2713aSLionel Sambuc     return;
857f4a2713aSLionel Sambuc 
858f4a2713aSLionel Sambuc   Record = new PreprocessingRecord(getSourceManager());
859*0a6a1f1dSLionel Sambuc   addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
860f4a2713aSLionel Sambuc }
861