]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Lex/Preprocessor.h
Merge ^/head r285793 through r285923.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / Lex / Preprocessor.h
1 //===--- Preprocessor.h - C Language Family Preprocessor --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief Defines the clang::Preprocessor interface.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CLANG_LEX_PREPROCESSOR_H
16 #define LLVM_CLANG_LEX_PREPROCESSOR_H
17
18 #include "clang/Basic/Builtins.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Basic/IdentifierTable.h"
21 #include "clang/Basic/SourceLocation.h"
22 #include "clang/Lex/Lexer.h"
23 #include "clang/Lex/MacroInfo.h"
24 #include "clang/Lex/ModuleMap.h"
25 #include "clang/Lex/PPCallbacks.h"
26 #include "clang/Lex/PTHLexer.h"
27 #include "clang/Lex/PTHManager.h"
28 #include "clang/Lex/TokenLexer.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/IntrusiveRefCntPtr.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/TinyPtrVector.h"
35 #include "llvm/Support/Allocator.h"
36 #include <memory>
37 #include <vector>
38
39 namespace llvm {
40   template<unsigned InternalLen> class SmallString;
41 }
42
43 namespace clang {
44
45 class SourceManager;
46 class ExternalPreprocessorSource;
47 class FileManager;
48 class FileEntry;
49 class HeaderSearch;
50 class PragmaNamespace;
51 class PragmaHandler;
52 class CommentHandler;
53 class ScratchBuffer;
54 class TargetInfo;
55 class PPCallbacks;
56 class CodeCompletionHandler;
57 class DirectoryLookup;
58 class PreprocessingRecord;
59 class ModuleLoader;
60 class PreprocessorOptions;
61
62 /// \brief Stores token information for comparing actual tokens with
63 /// predefined values.  Only handles simple tokens and identifiers.
64 class TokenValue {
65   tok::TokenKind Kind;
66   IdentifierInfo *II;
67
68 public:
69   TokenValue(tok::TokenKind Kind) : Kind(Kind), II(nullptr) {
70     assert(Kind != tok::raw_identifier && "Raw identifiers are not supported.");
71     assert(Kind != tok::identifier &&
72            "Identifiers should be created by TokenValue(IdentifierInfo *)");
73     assert(!tok::isLiteral(Kind) && "Literals are not supported.");
74     assert(!tok::isAnnotation(Kind) && "Annotations are not supported.");
75   }
76   TokenValue(IdentifierInfo *II) : Kind(tok::identifier), II(II) {}
77   bool operator==(const Token &Tok) const {
78     return Tok.getKind() == Kind &&
79         (!II || II == Tok.getIdentifierInfo());
80   }
81 };
82
83 /// \brief Context in which macro name is used.
84 enum MacroUse {
85   MU_Other  = 0,  // other than #define or #undef
86   MU_Define = 1,  // macro name specified in #define
87   MU_Undef  = 2   // macro name specified in #undef
88 };
89
90 /// \brief Engages in a tight little dance with the lexer to efficiently
91 /// preprocess tokens.
92 ///
93 /// Lexers know only about tokens within a single source file, and don't
94 /// know anything about preprocessor-level issues like the \#include stack,
95 /// token expansion, etc.
96 class Preprocessor : public RefCountedBase<Preprocessor> {
97   IntrusiveRefCntPtr<PreprocessorOptions> PPOpts;
98   DiagnosticsEngine        *Diags;
99   LangOptions       &LangOpts;
100   const TargetInfo  *Target;
101   FileManager       &FileMgr;
102   SourceManager     &SourceMgr;
103   std::unique_ptr<ScratchBuffer> ScratchBuf;
104   HeaderSearch      &HeaderInfo;
105   ModuleLoader      &TheModuleLoader;
106
107   /// \brief External source of macros.
108   ExternalPreprocessorSource *ExternalSource;
109
110
111   /// An optional PTHManager object used for getting tokens from
112   /// a token cache rather than lexing the original source file.
113   std::unique_ptr<PTHManager> PTH;
114
115   /// A BumpPtrAllocator object used to quickly allocate and release
116   /// objects internal to the Preprocessor.
117   llvm::BumpPtrAllocator BP;
118
119   /// Identifiers for builtin macros and other builtins.
120   IdentifierInfo *Ident__LINE__, *Ident__FILE__;   // __LINE__, __FILE__
121   IdentifierInfo *Ident__DATE__, *Ident__TIME__;   // __DATE__, __TIME__
122   IdentifierInfo *Ident__INCLUDE_LEVEL__;          // __INCLUDE_LEVEL__
123   IdentifierInfo *Ident__BASE_FILE__;              // __BASE_FILE__
124   IdentifierInfo *Ident__TIMESTAMP__;              // __TIMESTAMP__
125   IdentifierInfo *Ident__COUNTER__;                // __COUNTER__
126   IdentifierInfo *Ident_Pragma, *Ident__pragma;    // _Pragma, __pragma
127   IdentifierInfo *Ident__identifier;               // __identifier
128   IdentifierInfo *Ident__VA_ARGS__;                // __VA_ARGS__
129   IdentifierInfo *Ident__has_feature;              // __has_feature
130   IdentifierInfo *Ident__has_extension;            // __has_extension
131   IdentifierInfo *Ident__has_builtin;              // __has_builtin
132   IdentifierInfo *Ident__has_attribute;            // __has_attribute
133   IdentifierInfo *Ident__has_include;              // __has_include
134   IdentifierInfo *Ident__has_include_next;         // __has_include_next
135   IdentifierInfo *Ident__has_warning;              // __has_warning
136   IdentifierInfo *Ident__is_identifier;            // __is_identifier
137   IdentifierInfo *Ident__building_module;          // __building_module
138   IdentifierInfo *Ident__MODULE__;                 // __MODULE__
139   IdentifierInfo *Ident__has_cpp_attribute;        // __has_cpp_attribute
140   IdentifierInfo *Ident__has_declspec;             // __has_declspec_attribute
141
142   SourceLocation DATELoc, TIMELoc;
143   unsigned CounterValue;  // Next __COUNTER__ value.
144
145   enum {
146     /// \brief Maximum depth of \#includes.
147     MaxAllowedIncludeStackDepth = 200
148   };
149
150   // State that is set before the preprocessor begins.
151   bool KeepComments : 1;
152   bool KeepMacroComments : 1;
153   bool SuppressIncludeNotFoundError : 1;
154
155   // State that changes while the preprocessor runs:
156   bool InMacroArgs : 1;            // True if parsing fn macro invocation args.
157
158   /// Whether the preprocessor owns the header search object.
159   bool OwnsHeaderSearch : 1;
160
161   /// True if macro expansion is disabled.
162   bool DisableMacroExpansion : 1;
163
164   /// Temporarily disables DisableMacroExpansion (i.e. enables expansion)
165   /// when parsing preprocessor directives.
166   bool MacroExpansionInDirectivesOverride : 1;
167
168   class ResetMacroExpansionHelper;
169
170   /// \brief Whether we have already loaded macros from the external source.
171   mutable bool ReadMacrosFromExternalSource : 1;
172
173   /// \brief True if pragmas are enabled.
174   bool PragmasEnabled : 1;
175
176   /// \brief True if the current build action is a preprocessing action.
177   bool PreprocessedOutput : 1;
178
179   /// \brief True if we are currently preprocessing a #if or #elif directive
180   bool ParsingIfOrElifDirective;
181
182   /// \brief True if we are pre-expanding macro arguments.
183   bool InMacroArgPreExpansion;
184
185   /// \brief Mapping/lookup information for all identifiers in
186   /// the program, including program keywords.
187   mutable IdentifierTable Identifiers;
188
189   /// \brief This table contains all the selectors in the program.
190   ///
191   /// Unlike IdentifierTable above, this table *isn't* populated by the
192   /// preprocessor. It is declared/expanded here because its role/lifetime is
193   /// conceptually similar to the IdentifierTable. In addition, the current
194   /// control flow (in clang::ParseAST()), make it convenient to put here.
195   ///
196   /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to
197   /// the lifetime of the preprocessor.
198   SelectorTable Selectors;
199
200   /// \brief Information about builtins.
201   Builtin::Context BuiltinInfo;
202
203   /// \brief Tracks all of the pragmas that the client registered
204   /// with this preprocessor.
205   std::unique_ptr<PragmaNamespace> PragmaHandlers;
206
207   /// \brief Pragma handlers of the original source is stored here during the
208   /// parsing of a model file.
209   std::unique_ptr<PragmaNamespace> PragmaHandlersBackup;
210
211   /// \brief Tracks all of the comment handlers that the client registered
212   /// with this preprocessor.
213   std::vector<CommentHandler *> CommentHandlers;
214
215   /// \brief True if we want to ignore EOF token and continue later on (thus 
216   /// avoid tearing the Lexer and etc. down).
217   bool IncrementalProcessing;
218
219   /// The kind of translation unit we are processing.
220   TranslationUnitKind TUKind;
221
222   /// \brief The code-completion handler.
223   CodeCompletionHandler *CodeComplete;
224
225   /// \brief The file that we're performing code-completion for, if any.
226   const FileEntry *CodeCompletionFile;
227
228   /// \brief The offset in file for the code-completion point.
229   unsigned CodeCompletionOffset;
230
231   /// \brief The location for the code-completion point. This gets instantiated
232   /// when the CodeCompletionFile gets \#include'ed for preprocessing.
233   SourceLocation CodeCompletionLoc;
234
235   /// \brief The start location for the file of the code-completion point.
236   ///
237   /// This gets instantiated when the CodeCompletionFile gets \#include'ed
238   /// for preprocessing.
239   SourceLocation CodeCompletionFileLoc;
240
241   /// \brief The source location of the \c import contextual keyword we just 
242   /// lexed, if any.
243   SourceLocation ModuleImportLoc;
244
245   /// \brief The module import path that we're currently processing.
246   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> ModuleImportPath;
247
248   /// \brief Whether the last token we lexed was an '@'.
249   bool LastTokenWasAt;
250
251   /// \brief Whether the module import expects an identifier next. Otherwise,
252   /// it expects a '.' or ';'.
253   bool ModuleImportExpectsIdentifier;
254   
255   /// \brief The source location of the currently-active
256   /// \#pragma clang arc_cf_code_audited begin.
257   SourceLocation PragmaARCCFCodeAuditedLoc;
258
259   /// \brief The source location of the currently-active
260   /// \#pragma clang assume_nonnull begin.
261   SourceLocation PragmaAssumeNonNullLoc;
262
263   /// \brief True if we hit the code-completion point.
264   bool CodeCompletionReached;
265
266   /// \brief The directory that the main file should be considered to occupy,
267   /// if it does not correspond to a real file (as happens when building a
268   /// module).
269   const DirectoryEntry *MainFileDir;
270
271   /// \brief The number of bytes that we will initially skip when entering the
272   /// main file, along with a flag that indicates whether skipping this number
273   /// of bytes will place the lexer at the start of a line.
274   ///
275   /// This is used when loading a precompiled preamble.
276   std::pair<int, bool> SkipMainFilePreamble;
277
278   /// \brief The current top of the stack that we're lexing from if
279   /// not expanding a macro and we are lexing directly from source code.
280   ///
281   /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null.
282   std::unique_ptr<Lexer> CurLexer;
283
284   /// \brief The current top of stack that we're lexing from if
285   /// not expanding from a macro and we are lexing from a PTH cache.
286   ///
287   /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null.
288   std::unique_ptr<PTHLexer> CurPTHLexer;
289
290   /// \brief The current top of the stack what we're lexing from
291   /// if not expanding a macro.
292   ///
293   /// This is an alias for either CurLexer or  CurPTHLexer.
294   PreprocessorLexer *CurPPLexer;
295
296   /// \brief Used to find the current FileEntry, if CurLexer is non-null
297   /// and if applicable.
298   ///
299   /// This allows us to implement \#include_next and find directory-specific
300   /// properties.
301   const DirectoryLookup *CurDirLookup;
302
303   /// \brief The current macro we are expanding, if we are expanding a macro.
304   ///
305   /// One of CurLexer and CurTokenLexer must be null.
306   std::unique_ptr<TokenLexer> CurTokenLexer;
307
308   /// \brief The kind of lexer we're currently working with.
309   enum CurLexerKind {
310     CLK_Lexer,
311     CLK_PTHLexer,
312     CLK_TokenLexer,
313     CLK_CachingLexer,
314     CLK_LexAfterModuleImport
315   } CurLexerKind;
316
317   /// \brief If the current lexer is for a submodule that is being built, this
318   /// is that submodule.
319   Module *CurSubmodule;
320
321   /// \brief Keeps track of the stack of files currently
322   /// \#included, and macros currently being expanded from, not counting
323   /// CurLexer/CurTokenLexer.
324   struct IncludeStackInfo {
325     enum CurLexerKind           CurLexerKind;
326     Module                     *TheSubmodule;
327     std::unique_ptr<Lexer>      TheLexer;
328     std::unique_ptr<PTHLexer>   ThePTHLexer;
329     PreprocessorLexer          *ThePPLexer;
330     std::unique_ptr<TokenLexer> TheTokenLexer;
331     const DirectoryLookup      *TheDirLookup;
332
333     // The following constructors are completely useless copies of the default
334     // versions, only needed to pacify MSVC.
335     IncludeStackInfo(enum CurLexerKind CurLexerKind, Module *TheSubmodule,
336                      std::unique_ptr<Lexer> &&TheLexer,
337                      std::unique_ptr<PTHLexer> &&ThePTHLexer,
338                      PreprocessorLexer *ThePPLexer,
339                      std::unique_ptr<TokenLexer> &&TheTokenLexer,
340                      const DirectoryLookup *TheDirLookup)
341         : CurLexerKind(std::move(CurLexerKind)),
342           TheSubmodule(std::move(TheSubmodule)), TheLexer(std::move(TheLexer)),
343           ThePTHLexer(std::move(ThePTHLexer)),
344           ThePPLexer(std::move(ThePPLexer)),
345           TheTokenLexer(std::move(TheTokenLexer)),
346           TheDirLookup(std::move(TheDirLookup)) {}
347     IncludeStackInfo(IncludeStackInfo &&RHS)
348         : CurLexerKind(std::move(RHS.CurLexerKind)),
349           TheSubmodule(std::move(RHS.TheSubmodule)),
350           TheLexer(std::move(RHS.TheLexer)),
351           ThePTHLexer(std::move(RHS.ThePTHLexer)),
352           ThePPLexer(std::move(RHS.ThePPLexer)),
353           TheTokenLexer(std::move(RHS.TheTokenLexer)),
354           TheDirLookup(std::move(RHS.TheDirLookup)) {}
355   };
356   std::vector<IncludeStackInfo> IncludeMacroStack;
357
358   /// \brief Actions invoked when some preprocessor activity is
359   /// encountered (e.g. a file is \#included, etc).
360   std::unique_ptr<PPCallbacks> Callbacks;
361
362   struct MacroExpandsInfo {
363     Token Tok;
364     MacroDefinition MD;
365     SourceRange Range;
366     MacroExpandsInfo(Token Tok, MacroDefinition MD, SourceRange Range)
367       : Tok(Tok), MD(MD), Range(Range) { }
368   };
369   SmallVector<MacroExpandsInfo, 2> DelayedMacroExpandsCallbacks;
370
371   /// Information about a name that has been used to define a module macro.
372   struct ModuleMacroInfo {
373     ModuleMacroInfo(MacroDirective *MD)
374         : MD(MD), ActiveModuleMacrosGeneration(0), IsAmbiguous(false) {}
375
376     /// The most recent macro directive for this identifier.
377     MacroDirective *MD;
378     /// The active module macros for this identifier.
379     llvm::TinyPtrVector<ModuleMacro*> ActiveModuleMacros;
380     /// The generation number at which we last updated ActiveModuleMacros.
381     /// \see Preprocessor::VisibleModules.
382     unsigned ActiveModuleMacrosGeneration;
383     /// Whether this macro name is ambiguous.
384     bool IsAmbiguous;
385     /// The module macros that are overridden by this macro.
386     llvm::TinyPtrVector<ModuleMacro*> OverriddenMacros;
387   };
388
389   /// The state of a macro for an identifier.
390   class MacroState {
391     mutable llvm::PointerUnion<MacroDirective *, ModuleMacroInfo *> State;
392
393     ModuleMacroInfo *getModuleInfo(Preprocessor &PP,
394                                    const IdentifierInfo *II) const {
395       // FIXME: Find a spare bit on IdentifierInfo and store a
396       //        HasModuleMacros flag.
397       if (!II->hasMacroDefinition() ||
398           (!PP.getLangOpts().Modules &&
399            !PP.getLangOpts().ModulesLocalVisibility) ||
400           !PP.CurSubmoduleState->VisibleModules.getGeneration())
401         return nullptr;
402
403       auto *Info = State.dyn_cast<ModuleMacroInfo*>();
404       if (!Info) {
405         Info = new (PP.getPreprocessorAllocator())
406             ModuleMacroInfo(State.get<MacroDirective *>());
407         State = Info;
408       }
409
410       if (PP.CurSubmoduleState->VisibleModules.getGeneration() !=
411           Info->ActiveModuleMacrosGeneration)
412         PP.updateModuleMacroInfo(II, *Info);
413       return Info;
414     }
415
416   public:
417     MacroState() : MacroState(nullptr) {}
418     MacroState(MacroDirective *MD) : State(MD) {}
419     MacroState(MacroState &&O) LLVM_NOEXCEPT : State(O.State) {
420       O.State = (MacroDirective *)nullptr;
421     }
422     MacroState &operator=(MacroState &&O) LLVM_NOEXCEPT {
423       auto S = O.State;
424       O.State = (MacroDirective *)nullptr;
425       State = S;
426       return *this;
427     }
428     ~MacroState() {
429       if (auto *Info = State.dyn_cast<ModuleMacroInfo*>())
430         Info->~ModuleMacroInfo();
431     }
432
433     MacroDirective *getLatest() const {
434       if (auto *Info = State.dyn_cast<ModuleMacroInfo*>())
435         return Info->MD;
436       return State.get<MacroDirective*>();
437     }
438     void setLatest(MacroDirective *MD) {
439       if (auto *Info = State.dyn_cast<ModuleMacroInfo*>())
440         Info->MD = MD;
441       else
442         State = MD;
443     }
444
445     bool isAmbiguous(Preprocessor &PP, const IdentifierInfo *II) const {
446       auto *Info = getModuleInfo(PP, II);
447       return Info ? Info->IsAmbiguous : false;
448     }
449     ArrayRef<ModuleMacro *>
450     getActiveModuleMacros(Preprocessor &PP, const IdentifierInfo *II) const {
451       if (auto *Info = getModuleInfo(PP, II))
452         return Info->ActiveModuleMacros;
453       return None;
454     }
455
456     MacroDirective::DefInfo findDirectiveAtLoc(SourceLocation Loc,
457                                                SourceManager &SourceMgr) const {
458       // FIXME: Incorporate module macros into the result of this.
459       if (auto *Latest = getLatest())
460         return Latest->findDirectiveAtLoc(Loc, SourceMgr);
461       return MacroDirective::DefInfo();
462     }
463
464     void overrideActiveModuleMacros(Preprocessor &PP, IdentifierInfo *II) {
465       if (auto *Info = getModuleInfo(PP, II)) {
466         Info->OverriddenMacros.insert(Info->OverriddenMacros.end(),
467                                       Info->ActiveModuleMacros.begin(),
468                                       Info->ActiveModuleMacros.end());
469         Info->ActiveModuleMacros.clear();
470         Info->IsAmbiguous = false;
471       }
472     }
473     ArrayRef<ModuleMacro*> getOverriddenMacros() const {
474       if (auto *Info = State.dyn_cast<ModuleMacroInfo*>())
475         return Info->OverriddenMacros;
476       return None;
477     }
478     void setOverriddenMacros(Preprocessor &PP,
479                              ArrayRef<ModuleMacro *> Overrides) {
480       auto *Info = State.dyn_cast<ModuleMacroInfo*>();
481       if (!Info) {
482         if (Overrides.empty())
483           return;
484         Info = new (PP.getPreprocessorAllocator())
485             ModuleMacroInfo(State.get<MacroDirective *>());
486         State = Info;
487       }
488       Info->OverriddenMacros.clear();
489       Info->OverriddenMacros.insert(Info->OverriddenMacros.end(),
490                                     Overrides.begin(), Overrides.end());
491       Info->ActiveModuleMacrosGeneration = 0;
492     }
493   };
494
495   /// For each IdentifierInfo that was associated with a macro, we
496   /// keep a mapping to the history of all macro definitions and #undefs in
497   /// the reverse order (the latest one is in the head of the list).
498   ///
499   /// This mapping lives within the \p CurSubmoduleState.
500   typedef llvm::DenseMap<const IdentifierInfo *, MacroState> MacroMap;
501
502   friend class ASTReader;
503
504   struct SubmoduleState;
505
506   /// \brief Information about a submodule that we're currently building.
507   struct BuildingSubmoduleInfo {
508     BuildingSubmoduleInfo(Module *M, SourceLocation ImportLoc,
509                           SubmoduleState *OuterSubmoduleState)
510         : M(M), ImportLoc(ImportLoc), OuterSubmoduleState(OuterSubmoduleState) {
511     }
512
513     /// The module that we are building.
514     Module *M;
515     /// The location at which the module was included.
516     SourceLocation ImportLoc;
517     /// The previous SubmoduleState.
518     SubmoduleState *OuterSubmoduleState;
519   };
520   SmallVector<BuildingSubmoduleInfo, 8> BuildingSubmoduleStack;
521
522   /// \brief Information about a submodule's preprocessor state.
523   struct SubmoduleState {
524     /// The macros for the submodule.
525     MacroMap Macros;
526     /// The set of modules that are visible within the submodule.
527     VisibleModuleSet VisibleModules;
528     // FIXME: CounterValue?
529     // FIXME: PragmaPushMacroInfo?
530   };
531   std::map<Module*, SubmoduleState> Submodules;
532
533   /// The preprocessor state for preprocessing outside of any submodule.
534   SubmoduleState NullSubmoduleState;
535
536   /// The current submodule state. Will be \p NullSubmoduleState if we're not
537   /// in a submodule.
538   SubmoduleState *CurSubmoduleState;
539
540   /// The set of known macros exported from modules.
541   llvm::FoldingSet<ModuleMacro> ModuleMacros;
542
543   /// The list of module macros, for each identifier, that are not overridden by
544   /// any other module macro.
545   llvm::DenseMap<const IdentifierInfo *, llvm::TinyPtrVector<ModuleMacro*>>
546       LeafModuleMacros;
547
548   /// \brief Macros that we want to warn because they are not used at the end
549   /// of the translation unit.
550   ///
551   /// We store just their SourceLocations instead of
552   /// something like MacroInfo*. The benefit of this is that when we are
553   /// deserializing from PCH, we don't need to deserialize identifier & macros
554   /// just so that we can report that they are unused, we just warn using
555   /// the SourceLocations of this set (that will be filled by the ASTReader).
556   /// We are using SmallPtrSet instead of a vector for faster removal.
557   typedef llvm::SmallPtrSet<SourceLocation, 32> WarnUnusedMacroLocsTy;
558   WarnUnusedMacroLocsTy WarnUnusedMacroLocs;
559
560   /// \brief A "freelist" of MacroArg objects that can be
561   /// reused for quick allocation.
562   MacroArgs *MacroArgCache;
563   friend class MacroArgs;
564
565   /// For each IdentifierInfo used in a \#pragma push_macro directive,
566   /// we keep a MacroInfo stack used to restore the previous macro value.
567   llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> > PragmaPushMacroInfo;
568
569   // Various statistics we track for performance analysis.
570   unsigned NumDirectives, NumDefined, NumUndefined, NumPragma;
571   unsigned NumIf, NumElse, NumEndif;
572   unsigned NumEnteredSourceFiles, MaxIncludeStackDepth;
573   unsigned NumMacroExpanded, NumFnMacroExpanded, NumBuiltinMacroExpanded;
574   unsigned NumFastMacroExpanded, NumTokenPaste, NumFastTokenPaste;
575   unsigned NumSkipped;
576
577   /// \brief The predefined macros that preprocessor should use from the
578   /// command line etc.
579   std::string Predefines;
580
581   /// \brief The file ID for the preprocessor predefines.
582   FileID PredefinesFileID;
583
584   /// \{
585   /// \brief Cache of macro expanders to reduce malloc traffic.
586   enum { TokenLexerCacheSize = 8 };
587   unsigned NumCachedTokenLexers;
588   std::unique_ptr<TokenLexer> TokenLexerCache[TokenLexerCacheSize];
589   /// \}
590
591   /// \brief Keeps macro expanded tokens for TokenLexers.
592   //
593   /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
594   /// going to lex in the cache and when it finishes the tokens are removed
595   /// from the end of the cache.
596   SmallVector<Token, 16> MacroExpandedTokens;
597   std::vector<std::pair<TokenLexer *, size_t> > MacroExpandingLexersStack;
598
599   /// \brief A record of the macro definitions and expansions that
600   /// occurred during preprocessing.
601   ///
602   /// This is an optional side structure that can be enabled with
603   /// \c createPreprocessingRecord() prior to preprocessing.
604   PreprocessingRecord *Record;
605
606   /// Cached tokens state.
607   typedef SmallVector<Token, 1> CachedTokensTy;
608
609   /// \brief Cached tokens are stored here when we do backtracking or
610   /// lookahead. They are "lexed" by the CachingLex() method.
611   CachedTokensTy CachedTokens;
612
613   /// \brief The position of the cached token that CachingLex() should
614   /// "lex" next.
615   ///
616   /// If it points beyond the CachedTokens vector, it means that a normal
617   /// Lex() should be invoked.
618   CachedTokensTy::size_type CachedLexPos;
619
620   /// \brief Stack of backtrack positions, allowing nested backtracks.
621   ///
622   /// The EnableBacktrackAtThisPos() method pushes a position to
623   /// indicate where CachedLexPos should be set when the BackTrack() method is
624   /// invoked (at which point the last position is popped).
625   std::vector<CachedTokensTy::size_type> BacktrackPositions;
626
627   struct MacroInfoChain {
628     MacroInfo MI;
629     MacroInfoChain *Next;
630   };
631
632   /// MacroInfos are managed as a chain for easy disposal.  This is the head
633   /// of that list.
634   MacroInfoChain *MIChainHead;
635
636   struct DeserializedMacroInfoChain {
637     MacroInfo MI;
638     unsigned OwningModuleID; // MUST be immediately after the MacroInfo object
639                      // so it can be accessed by MacroInfo::getOwningModuleID().
640     DeserializedMacroInfoChain *Next;
641   };
642   DeserializedMacroInfoChain *DeserialMIChainHead;
643
644 public:
645   Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
646                DiagnosticsEngine &diags, LangOptions &opts,
647                SourceManager &SM, HeaderSearch &Headers,
648                ModuleLoader &TheModuleLoader,
649                IdentifierInfoLookup *IILookup = nullptr,
650                bool OwnsHeaderSearch = false,
651                TranslationUnitKind TUKind = TU_Complete);
652
653   ~Preprocessor();
654
655   /// \brief Initialize the preprocessor using information about the target.
656   ///
657   /// \param Target is owned by the caller and must remain valid for the
658   /// lifetime of the preprocessor.
659   void Initialize(const TargetInfo &Target);
660
661   /// \brief Initialize the preprocessor to parse a model file
662   ///
663   /// To parse model files the preprocessor of the original source is reused to
664   /// preserver the identifier table. However to avoid some duplicate
665   /// information in the preprocessor some cleanup is needed before it is used
666   /// to parse model files. This method does that cleanup.
667   void InitializeForModelFile();
668
669   /// \brief Cleanup after model file parsing
670   void FinalizeForModelFile();
671
672   /// \brief Retrieve the preprocessor options used to initialize this
673   /// preprocessor.
674   PreprocessorOptions &getPreprocessorOpts() const { return *PPOpts; }
675   
676   DiagnosticsEngine &getDiagnostics() const { return *Diags; }
677   void setDiagnostics(DiagnosticsEngine &D) { Diags = &D; }
678
679   const LangOptions &getLangOpts() const { return LangOpts; }
680   const TargetInfo &getTargetInfo() const { return *Target; }
681   FileManager &getFileManager() const { return FileMgr; }
682   SourceManager &getSourceManager() const { return SourceMgr; }
683   HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; }
684
685   IdentifierTable &getIdentifierTable() { return Identifiers; }
686   const IdentifierTable &getIdentifierTable() const { return Identifiers; }
687   SelectorTable &getSelectorTable() { return Selectors; }
688   Builtin::Context &getBuiltinInfo() { return BuiltinInfo; }
689   llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; }
690
691   void setPTHManager(PTHManager* pm);
692
693   PTHManager *getPTHManager() { return PTH.get(); }
694
695   void setExternalSource(ExternalPreprocessorSource *Source) {
696     ExternalSource = Source;
697   }
698
699   ExternalPreprocessorSource *getExternalSource() const {
700     return ExternalSource;
701   }
702
703   /// \brief Retrieve the module loader associated with this preprocessor.
704   ModuleLoader &getModuleLoader() const { return TheModuleLoader; }
705
706   bool hadModuleLoaderFatalFailure() const {
707     return TheModuleLoader.HadFatalFailure;
708   }
709
710   /// \brief True if we are currently preprocessing a #if or #elif directive
711   bool isParsingIfOrElifDirective() const { 
712     return ParsingIfOrElifDirective;
713   }
714
715   /// \brief Control whether the preprocessor retains comments in output.
716   void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) {
717     this->KeepComments = KeepComments | KeepMacroComments;
718     this->KeepMacroComments = KeepMacroComments;
719   }
720
721   bool getCommentRetentionState() const { return KeepComments; }
722
723   void setPragmasEnabled(bool Enabled) { PragmasEnabled = Enabled; }
724   bool getPragmasEnabled() const { return PragmasEnabled; }
725
726   void SetSuppressIncludeNotFoundError(bool Suppress) {
727     SuppressIncludeNotFoundError = Suppress;
728   }
729
730   bool GetSuppressIncludeNotFoundError() {
731     return SuppressIncludeNotFoundError;
732   }
733
734   /// Sets whether the preprocessor is responsible for producing output or if
735   /// it is producing tokens to be consumed by Parse and Sema.
736   void setPreprocessedOutput(bool IsPreprocessedOutput) {
737     PreprocessedOutput = IsPreprocessedOutput;
738   }
739
740   /// Returns true if the preprocessor is responsible for generating output,
741   /// false if it is producing tokens to be consumed by Parse and Sema.
742   bool isPreprocessedOutput() const { return PreprocessedOutput; }
743
744   /// \brief Return true if we are lexing directly from the specified lexer.
745   bool isCurrentLexer(const PreprocessorLexer *L) const {
746     return CurPPLexer == L;
747   }
748
749   /// \brief Return the current lexer being lexed from.
750   ///
751   /// Note that this ignores any potentially active macro expansions and _Pragma
752   /// expansions going on at the time.
753   PreprocessorLexer *getCurrentLexer() const { return CurPPLexer; }
754
755   /// \brief Return the current file lexer being lexed from.
756   ///
757   /// Note that this ignores any potentially active macro expansions and _Pragma
758   /// expansions going on at the time.
759   PreprocessorLexer *getCurrentFileLexer() const;
760
761   /// \brief Return the submodule owning the file being lexed.
762   Module *getCurrentSubmodule() const { return CurSubmodule; }
763
764   /// \brief Returns the FileID for the preprocessor predefines.
765   FileID getPredefinesFileID() const { return PredefinesFileID; }
766
767   /// \{
768   /// \brief Accessors for preprocessor callbacks.
769   ///
770   /// Note that this class takes ownership of any PPCallbacks object given to
771   /// it.
772   PPCallbacks *getPPCallbacks() const { return Callbacks.get(); }
773   void addPPCallbacks(std::unique_ptr<PPCallbacks> C) {
774     if (Callbacks)
775       C = llvm::make_unique<PPChainedCallbacks>(std::move(C),
776                                                 std::move(Callbacks));
777     Callbacks = std::move(C);
778   }
779   /// \}
780
781   bool isMacroDefined(StringRef Id) {
782     return isMacroDefined(&Identifiers.get(Id));
783   }
784   bool isMacroDefined(const IdentifierInfo *II) {
785     return II->hasMacroDefinition() &&
786            (!getLangOpts().Modules || (bool)getMacroDefinition(II));
787   }
788
789   MacroDefinition getMacroDefinition(const IdentifierInfo *II) {
790     if (!II->hasMacroDefinition())
791       return MacroDefinition();
792
793     MacroState &S = CurSubmoduleState->Macros[II];
794     auto *MD = S.getLatest();
795     while (MD && isa<VisibilityMacroDirective>(MD))
796       MD = MD->getPrevious();
797     return MacroDefinition(dyn_cast_or_null<DefMacroDirective>(MD),
798                            S.getActiveModuleMacros(*this, II),
799                            S.isAmbiguous(*this, II));
800   }
801
802   MacroDefinition getMacroDefinitionAtLoc(const IdentifierInfo *II,
803                                           SourceLocation Loc) {
804     if (!II->hadMacroDefinition())
805       return MacroDefinition();
806
807     MacroState &S = CurSubmoduleState->Macros[II];
808     MacroDirective::DefInfo DI;
809     if (auto *MD = S.getLatest())
810       DI = MD->findDirectiveAtLoc(Loc, getSourceManager());
811     // FIXME: Compute the set of active module macros at the specified location.
812     return MacroDefinition(DI.getDirective(),
813                            S.getActiveModuleMacros(*this, II),
814                            S.isAmbiguous(*this, II));
815   }
816
817   /// \brief Given an identifier, return its latest non-imported MacroDirective
818   /// if it is \#define'd and not \#undef'd, or null if it isn't \#define'd.
819   MacroDirective *getLocalMacroDirective(const IdentifierInfo *II) const {
820     if (!II->hasMacroDefinition())
821       return nullptr;
822
823     auto *MD = getLocalMacroDirectiveHistory(II);
824     if (!MD || MD->getDefinition().isUndefined())
825       return nullptr;
826
827     return MD;
828   }
829
830   const MacroInfo *getMacroInfo(const IdentifierInfo *II) const {
831     return const_cast<Preprocessor*>(this)->getMacroInfo(II);
832   }
833
834   MacroInfo *getMacroInfo(const IdentifierInfo *II) {
835     if (!II->hasMacroDefinition())
836       return nullptr;
837     if (auto MD = getMacroDefinition(II))
838       return MD.getMacroInfo();
839     return nullptr;
840   }
841
842   /// \brief Given an identifier, return the latest non-imported macro
843   /// directive for that identifier.
844   ///
845   /// One can iterate over all previous macro directives from the most recent
846   /// one.
847   MacroDirective *getLocalMacroDirectiveHistory(const IdentifierInfo *II) const;
848
849   /// \brief Add a directive to the macro directive history for this identifier.
850   void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD);
851   DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI,
852                                              SourceLocation Loc) {
853     DefMacroDirective *MD = AllocateDefMacroDirective(MI, Loc);
854     appendMacroDirective(II, MD);
855     return MD;
856   }
857   DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II,
858                                              MacroInfo *MI) {
859     return appendDefMacroDirective(II, MI, MI->getDefinitionLoc());
860   }
861   /// \brief Set a MacroDirective that was loaded from a PCH file.
862   void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *MD);
863
864   /// \brief Register an exported macro for a module and identifier.
865   ModuleMacro *addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro,
866                               ArrayRef<ModuleMacro *> Overrides, bool &IsNew);
867   ModuleMacro *getModuleMacro(Module *Mod, IdentifierInfo *II);
868
869   /// \brief Get the list of leaf (non-overridden) module macros for a name.
870   ArrayRef<ModuleMacro*> getLeafModuleMacros(const IdentifierInfo *II) const {
871     auto I = LeafModuleMacros.find(II);
872     if (I != LeafModuleMacros.end())
873       return I->second;
874     return None;
875   }
876
877   /// \{
878   /// Iterators for the macro history table. Currently defined macros have
879   /// IdentifierInfo::hasMacroDefinition() set and an empty
880   /// MacroInfo::getUndefLoc() at the head of the list.
881   typedef MacroMap::const_iterator macro_iterator;
882   macro_iterator macro_begin(bool IncludeExternalMacros = true) const;
883   macro_iterator macro_end(bool IncludeExternalMacros = true) const;
884   llvm::iterator_range<macro_iterator>
885   macros(bool IncludeExternalMacros = true) const {
886     return llvm::make_range(macro_begin(IncludeExternalMacros),
887                             macro_end(IncludeExternalMacros));
888   }
889   /// \}
890
891   /// \brief Return the name of the macro defined before \p Loc that has
892   /// spelling \p Tokens.  If there are multiple macros with same spelling,
893   /// return the last one defined.
894   StringRef getLastMacroWithSpelling(SourceLocation Loc,
895                                      ArrayRef<TokenValue> Tokens) const;
896
897   const std::string &getPredefines() const { return Predefines; }
898   /// \brief Set the predefines for this Preprocessor.
899   ///
900   /// These predefines are automatically injected when parsing the main file.
901   void setPredefines(const char *P) { Predefines = P; }
902   void setPredefines(StringRef P) { Predefines = P; }
903
904   /// Return information about the specified preprocessor
905   /// identifier token.
906   IdentifierInfo *getIdentifierInfo(StringRef Name) const {
907     return &Identifiers.get(Name);
908   }
909
910   /// \brief Add the specified pragma handler to this preprocessor.
911   ///
912   /// If \p Namespace is non-null, then it is a token required to exist on the
913   /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
914   void AddPragmaHandler(StringRef Namespace, PragmaHandler *Handler);
915   void AddPragmaHandler(PragmaHandler *Handler) {
916     AddPragmaHandler(StringRef(), Handler);
917   }
918
919   /// \brief Remove the specific pragma handler from this preprocessor.
920   ///
921   /// If \p Namespace is non-null, then it should be the namespace that
922   /// \p Handler was added to. It is an error to remove a handler that
923   /// has not been registered.
924   void RemovePragmaHandler(StringRef Namespace, PragmaHandler *Handler);
925   void RemovePragmaHandler(PragmaHandler *Handler) {
926     RemovePragmaHandler(StringRef(), Handler);
927   }
928
929   /// Install empty handlers for all pragmas (making them ignored).
930   void IgnorePragmas();
931
932   /// \brief Add the specified comment handler to the preprocessor.
933   void addCommentHandler(CommentHandler *Handler);
934
935   /// \brief Remove the specified comment handler.
936   ///
937   /// It is an error to remove a handler that has not been registered.
938   void removeCommentHandler(CommentHandler *Handler);
939
940   /// \brief Set the code completion handler to the given object.
941   void setCodeCompletionHandler(CodeCompletionHandler &Handler) {
942     CodeComplete = &Handler;
943   }
944
945   /// \brief Retrieve the current code-completion handler.
946   CodeCompletionHandler *getCodeCompletionHandler() const {
947     return CodeComplete;
948   }
949
950   /// \brief Clear out the code completion handler.
951   void clearCodeCompletionHandler() {
952     CodeComplete = nullptr;
953   }
954
955   /// \brief Hook used by the lexer to invoke the "natural language" code
956   /// completion point.
957   void CodeCompleteNaturalLanguage();
958
959   /// \brief Retrieve the preprocessing record, or NULL if there is no
960   /// preprocessing record.
961   PreprocessingRecord *getPreprocessingRecord() const { return Record; }
962
963   /// \brief Create a new preprocessing record, which will keep track of
964   /// all macro expansions, macro definitions, etc.
965   void createPreprocessingRecord();
966
967   /// \brief Enter the specified FileID as the main source file,
968   /// which implicitly adds the builtin defines etc.
969   void EnterMainSourceFile();
970
971   /// \brief Inform the preprocessor callbacks that processing is complete.
972   void EndSourceFile();
973
974   /// \brief Add a source file to the top of the include stack and
975   /// start lexing tokens from it instead of the current buffer.
976   ///
977   /// Emits a diagnostic, doesn't enter the file, and returns true on error.
978   bool EnterSourceFile(FileID CurFileID, const DirectoryLookup *Dir,
979                        SourceLocation Loc);
980
981   /// \brief Add a Macro to the top of the include stack and start lexing
982   /// tokens from it instead of the current buffer.
983   ///
984   /// \param Args specifies the tokens input to a function-like macro.
985   /// \param ILEnd specifies the location of the ')' for a function-like macro
986   /// or the identifier for an object-like macro.
987   void EnterMacro(Token &Identifier, SourceLocation ILEnd, MacroInfo *Macro,
988                   MacroArgs *Args);
989
990   /// \brief Add a "macro" context to the top of the include stack,
991   /// which will cause the lexer to start returning the specified tokens.
992   ///
993   /// If \p DisableMacroExpansion is true, tokens lexed from the token stream
994   /// will not be subject to further macro expansion. Otherwise, these tokens
995   /// will be re-macro-expanded when/if expansion is enabled.
996   ///
997   /// If \p OwnsTokens is false, this method assumes that the specified stream
998   /// of tokens has a permanent owner somewhere, so they do not need to be
999   /// copied. If it is true, it assumes the array of tokens is allocated with
1000   /// \c new[] and must be freed.
1001   void EnterTokenStream(const Token *Toks, unsigned NumToks,
1002                         bool DisableMacroExpansion, bool OwnsTokens);
1003
1004   /// \brief Pop the current lexer/macro exp off the top of the lexer stack.
1005   ///
1006   /// This should only be used in situations where the current state of the
1007   /// top-of-stack lexer is known.
1008   void RemoveTopOfLexerStack();
1009
1010   /// From the point that this method is called, and until
1011   /// CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor
1012   /// keeps track of the lexed tokens so that a subsequent Backtrack() call will
1013   /// make the Preprocessor re-lex the same tokens.
1014   ///
1015   /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can
1016   /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will
1017   /// be combined with the EnableBacktrackAtThisPos calls in reverse order.
1018   ///
1019   /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack
1020   /// at some point after EnableBacktrackAtThisPos. If you don't, caching of
1021   /// tokens will continue indefinitely.
1022   ///
1023   void EnableBacktrackAtThisPos();
1024
1025   /// \brief Disable the last EnableBacktrackAtThisPos call.
1026   void CommitBacktrackedTokens();
1027
1028   /// \brief Make Preprocessor re-lex the tokens that were lexed since
1029   /// EnableBacktrackAtThisPos() was previously called.
1030   void Backtrack();
1031
1032   /// \brief True if EnableBacktrackAtThisPos() was called and
1033   /// caching of tokens is on.
1034   bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); }
1035
1036   /// \brief Lex the next token for this preprocessor.
1037   void Lex(Token &Result);
1038
1039   void LexAfterModuleImport(Token &Result);
1040
1041   void makeModuleVisible(Module *M, SourceLocation Loc);
1042
1043   SourceLocation getModuleImportLoc(Module *M) const {
1044     return CurSubmoduleState->VisibleModules.getImportLoc(M);
1045   }
1046
1047   /// \brief Lex a string literal, which may be the concatenation of multiple
1048   /// string literals and may even come from macro expansion.
1049   /// \returns true on success, false if a error diagnostic has been generated.
1050   bool LexStringLiteral(Token &Result, std::string &String,
1051                         const char *DiagnosticTag, bool AllowMacroExpansion) {
1052     if (AllowMacroExpansion)
1053       Lex(Result);
1054     else
1055       LexUnexpandedToken(Result);
1056     return FinishLexStringLiteral(Result, String, DiagnosticTag,
1057                                   AllowMacroExpansion);
1058   }
1059
1060   /// \brief Complete the lexing of a string literal where the first token has
1061   /// already been lexed (see LexStringLiteral).
1062   bool FinishLexStringLiteral(Token &Result, std::string &String,
1063                               const char *DiagnosticTag,
1064                               bool AllowMacroExpansion);
1065
1066   /// \brief Lex a token.  If it's a comment, keep lexing until we get
1067   /// something not a comment.
1068   ///
1069   /// This is useful in -E -C mode where comments would foul up preprocessor
1070   /// directive handling.
1071   void LexNonComment(Token &Result) {
1072     do
1073       Lex(Result);
1074     while (Result.getKind() == tok::comment);
1075   }
1076
1077   /// \brief Just like Lex, but disables macro expansion of identifier tokens.
1078   void LexUnexpandedToken(Token &Result) {
1079     // Disable macro expansion.
1080     bool OldVal = DisableMacroExpansion;
1081     DisableMacroExpansion = true;
1082     // Lex the token.
1083     Lex(Result);
1084
1085     // Reenable it.
1086     DisableMacroExpansion = OldVal;
1087   }
1088
1089   /// \brief Like LexNonComment, but this disables macro expansion of
1090   /// identifier tokens.
1091   void LexUnexpandedNonComment(Token &Result) {
1092     do
1093       LexUnexpandedToken(Result);
1094     while (Result.getKind() == tok::comment);
1095   }
1096
1097   /// \brief Parses a simple integer literal to get its numeric value.  Floating
1098   /// point literals and user defined literals are rejected.  Used primarily to
1099   /// handle pragmas that accept integer arguments.
1100   bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value);
1101
1102   /// Disables macro expansion everywhere except for preprocessor directives.
1103   void SetMacroExpansionOnlyInDirectives() {
1104     DisableMacroExpansion = true;
1105     MacroExpansionInDirectivesOverride = true;
1106   }
1107
1108   /// \brief Peeks ahead N tokens and returns that token without consuming any
1109   /// tokens.
1110   ///
1111   /// LookAhead(0) returns the next token that would be returned by Lex(),
1112   /// LookAhead(1) returns the token after it, etc.  This returns normal
1113   /// tokens after phase 5.  As such, it is equivalent to using
1114   /// 'Lex', not 'LexUnexpandedToken'.
1115   const Token &LookAhead(unsigned N) {
1116     if (CachedLexPos + N < CachedTokens.size())
1117       return CachedTokens[CachedLexPos+N];
1118     else
1119       return PeekAhead(N+1);
1120   }
1121
1122   /// \brief When backtracking is enabled and tokens are cached,
1123   /// this allows to revert a specific number of tokens.
1124   ///
1125   /// Note that the number of tokens being reverted should be up to the last
1126   /// backtrack position, not more.
1127   void RevertCachedTokens(unsigned N) {
1128     assert(isBacktrackEnabled() &&
1129            "Should only be called when tokens are cached for backtracking");
1130     assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back())
1131          && "Should revert tokens up to the last backtrack position, not more");
1132     assert(signed(CachedLexPos) - signed(N) >= 0 &&
1133            "Corrupted backtrack positions ?");
1134     CachedLexPos -= N;
1135   }
1136
1137   /// \brief Enters a token in the token stream to be lexed next.
1138   ///
1139   /// If BackTrack() is called afterwards, the token will remain at the
1140   /// insertion point.
1141   void EnterToken(const Token &Tok) {
1142     EnterCachingLexMode();
1143     CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok);
1144   }
1145
1146   /// We notify the Preprocessor that if it is caching tokens (because
1147   /// backtrack is enabled) it should replace the most recent cached tokens
1148   /// with the given annotation token. This function has no effect if
1149   /// backtracking is not enabled.
1150   ///
1151   /// Note that the use of this function is just for optimization, so that the
1152   /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is
1153   /// invoked.
1154   void AnnotateCachedTokens(const Token &Tok) {
1155     assert(Tok.isAnnotation() && "Expected annotation token");
1156     if (CachedLexPos != 0 && isBacktrackEnabled())
1157       AnnotatePreviousCachedTokens(Tok);
1158   }
1159
1160   /// Get the location of the last cached token, suitable for setting the end
1161   /// location of an annotation token.
1162   SourceLocation getLastCachedTokenLocation() const {
1163     assert(CachedLexPos != 0);
1164     return CachedTokens[CachedLexPos-1].getLastLoc();
1165   }
1166
1167   /// \brief Replace the last token with an annotation token.
1168   ///
1169   /// Like AnnotateCachedTokens(), this routine replaces an
1170   /// already-parsed (and resolved) token with an annotation
1171   /// token. However, this routine only replaces the last token with
1172   /// the annotation token; it does not affect any other cached
1173   /// tokens. This function has no effect if backtracking is not
1174   /// enabled.
1175   void ReplaceLastTokenWithAnnotation(const Token &Tok) {
1176     assert(Tok.isAnnotation() && "Expected annotation token");
1177     if (CachedLexPos != 0 && isBacktrackEnabled())
1178       CachedTokens[CachedLexPos-1] = Tok;
1179   }
1180
1181   /// Update the current token to represent the provided
1182   /// identifier, in order to cache an action performed by typo correction.
1183   void TypoCorrectToken(const Token &Tok) {
1184     assert(Tok.getIdentifierInfo() && "Expected identifier token");
1185     if (CachedLexPos != 0 && isBacktrackEnabled())
1186       CachedTokens[CachedLexPos-1] = Tok;
1187   }
1188
1189   /// \brief Recompute the current lexer kind based on the CurLexer/CurPTHLexer/
1190   /// CurTokenLexer pointers.
1191   void recomputeCurLexerKind();
1192
1193   /// \brief Returns true if incremental processing is enabled
1194   bool isIncrementalProcessingEnabled() const { return IncrementalProcessing; }
1195
1196   /// \brief Enables the incremental processing
1197   void enableIncrementalProcessing(bool value = true) {
1198     IncrementalProcessing = value;
1199   }
1200   
1201   /// \brief Specify the point at which code-completion will be performed.
1202   ///
1203   /// \param File the file in which code completion should occur. If
1204   /// this file is included multiple times, code-completion will
1205   /// perform completion the first time it is included. If NULL, this
1206   /// function clears out the code-completion point.
1207   ///
1208   /// \param Line the line at which code completion should occur
1209   /// (1-based).
1210   ///
1211   /// \param Column the column at which code completion should occur
1212   /// (1-based).
1213   ///
1214   /// \returns true if an error occurred, false otherwise.
1215   bool SetCodeCompletionPoint(const FileEntry *File,
1216                               unsigned Line, unsigned Column);
1217
1218   /// \brief Determine if we are performing code completion.
1219   bool isCodeCompletionEnabled() const { return CodeCompletionFile != nullptr; }
1220
1221   /// \brief Returns the location of the code-completion point.
1222   ///
1223   /// Returns an invalid location if code-completion is not enabled or the file
1224   /// containing the code-completion point has not been lexed yet.
1225   SourceLocation getCodeCompletionLoc() const { return CodeCompletionLoc; }
1226
1227   /// \brief Returns the start location of the file of code-completion point.
1228   ///
1229   /// Returns an invalid location if code-completion is not enabled or the file
1230   /// containing the code-completion point has not been lexed yet.
1231   SourceLocation getCodeCompletionFileLoc() const {
1232     return CodeCompletionFileLoc;
1233   }
1234
1235   /// \brief Returns true if code-completion is enabled and we have hit the
1236   /// code-completion point.
1237   bool isCodeCompletionReached() const { return CodeCompletionReached; }
1238
1239   /// \brief Note that we hit the code-completion point.
1240   void setCodeCompletionReached() {
1241     assert(isCodeCompletionEnabled() && "Code-completion not enabled!");
1242     CodeCompletionReached = true;
1243     // Silence any diagnostics that occur after we hit the code-completion.
1244     getDiagnostics().setSuppressAllDiagnostics(true);
1245   }
1246
1247   /// \brief The location of the currently-active \#pragma clang
1248   /// arc_cf_code_audited begin.
1249   ///
1250   /// Returns an invalid location if there is no such pragma active.
1251   SourceLocation getPragmaARCCFCodeAuditedLoc() const {
1252     return PragmaARCCFCodeAuditedLoc;
1253   }
1254
1255   /// \brief Set the location of the currently-active \#pragma clang
1256   /// arc_cf_code_audited begin.  An invalid location ends the pragma.
1257   void setPragmaARCCFCodeAuditedLoc(SourceLocation Loc) {
1258     PragmaARCCFCodeAuditedLoc = Loc;
1259   }
1260
1261   /// \brief The location of the currently-active \#pragma clang
1262   /// assume_nonnull begin.
1263   ///
1264   /// Returns an invalid location if there is no such pragma active.
1265   SourceLocation getPragmaAssumeNonNullLoc() const {
1266     return PragmaAssumeNonNullLoc;
1267   }
1268
1269   /// \brief Set the location of the currently-active \#pragma clang
1270   /// assume_nonnull begin.  An invalid location ends the pragma.
1271   void setPragmaAssumeNonNullLoc(SourceLocation Loc) {
1272     PragmaAssumeNonNullLoc = Loc;
1273   }
1274
1275   /// \brief Set the directory in which the main file should be considered
1276   /// to have been found, if it is not a real file.
1277   void setMainFileDir(const DirectoryEntry *Dir) {
1278     MainFileDir = Dir;
1279   }
1280
1281   /// \brief Instruct the preprocessor to skip part of the main source file.
1282   ///
1283   /// \param Bytes The number of bytes in the preamble to skip.
1284   ///
1285   /// \param StartOfLine Whether skipping these bytes puts the lexer at the
1286   /// start of a line.
1287   void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine) {
1288     SkipMainFilePreamble.first = Bytes;
1289     SkipMainFilePreamble.second = StartOfLine;
1290   }
1291
1292   /// Forwarding function for diagnostics.  This emits a diagnostic at
1293   /// the specified Token's location, translating the token's start
1294   /// position in the current buffer into a SourcePosition object for rendering.
1295   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const {
1296     return Diags->Report(Loc, DiagID);
1297   }
1298
1299   DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) const {
1300     return Diags->Report(Tok.getLocation(), DiagID);
1301   }
1302
1303   /// Return the 'spelling' of the token at the given
1304   /// location; does not go up to the spelling location or down to the
1305   /// expansion location.
1306   ///
1307   /// \param buffer A buffer which will be used only if the token requires
1308   ///   "cleaning", e.g. if it contains trigraphs or escaped newlines
1309   /// \param invalid If non-null, will be set \c true if an error occurs.
1310   StringRef getSpelling(SourceLocation loc,
1311                         SmallVectorImpl<char> &buffer,
1312                         bool *invalid = nullptr) const {
1313     return Lexer::getSpelling(loc, buffer, SourceMgr, LangOpts, invalid);
1314   }
1315
1316   /// \brief Return the 'spelling' of the Tok token.
1317   ///
1318   /// The spelling of a token is the characters used to represent the token in
1319   /// the source file after trigraph expansion and escaped-newline folding.  In
1320   /// particular, this wants to get the true, uncanonicalized, spelling of
1321   /// things like digraphs, UCNs, etc.
1322   ///
1323   /// \param Invalid If non-null, will be set \c true if an error occurs.
1324   std::string getSpelling(const Token &Tok, bool *Invalid = nullptr) const {
1325     return Lexer::getSpelling(Tok, SourceMgr, LangOpts, Invalid);
1326   }
1327
1328   /// \brief Get the spelling of a token into a preallocated buffer, instead
1329   /// of as an std::string.
1330   ///
1331   /// The caller is required to allocate enough space for the token, which is
1332   /// guaranteed to be at least Tok.getLength() bytes long. The length of the
1333   /// actual result is returned.
1334   ///
1335   /// Note that this method may do two possible things: it may either fill in
1336   /// the buffer specified with characters, or it may *change the input pointer*
1337   /// to point to a constant buffer with the data already in it (avoiding a
1338   /// copy).  The caller is not allowed to modify the returned buffer pointer
1339   /// if an internal buffer is returned.
1340   unsigned getSpelling(const Token &Tok, const char *&Buffer,
1341                        bool *Invalid = nullptr) const {
1342     return Lexer::getSpelling(Tok, Buffer, SourceMgr, LangOpts, Invalid);
1343   }
1344
1345   /// \brief Get the spelling of a token into a SmallVector.
1346   ///
1347   /// Note that the returned StringRef may not point to the
1348   /// supplied buffer if a copy can be avoided.
1349   StringRef getSpelling(const Token &Tok,
1350                         SmallVectorImpl<char> &Buffer,
1351                         bool *Invalid = nullptr) const;
1352
1353   /// \brief Relex the token at the specified location.
1354   /// \returns true if there was a failure, false on success.
1355   bool getRawToken(SourceLocation Loc, Token &Result,
1356                    bool IgnoreWhiteSpace = false) {
1357     return Lexer::getRawToken(Loc, Result, SourceMgr, LangOpts, IgnoreWhiteSpace);
1358   }
1359
1360   /// \brief Given a Token \p Tok that is a numeric constant with length 1,
1361   /// return the character.
1362   char
1363   getSpellingOfSingleCharacterNumericConstant(const Token &Tok,
1364                                               bool *Invalid = nullptr) const {
1365     assert(Tok.is(tok::numeric_constant) &&
1366            Tok.getLength() == 1 && "Called on unsupported token");
1367     assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1");
1368
1369     // If the token is carrying a literal data pointer, just use it.
1370     if (const char *D = Tok.getLiteralData())
1371       return *D;
1372
1373     // Otherwise, fall back on getCharacterData, which is slower, but always
1374     // works.
1375     return *SourceMgr.getCharacterData(Tok.getLocation(), Invalid);
1376   }
1377
1378   /// \brief Retrieve the name of the immediate macro expansion.
1379   ///
1380   /// This routine starts from a source location, and finds the name of the
1381   /// macro responsible for its immediate expansion. It looks through any
1382   /// intervening macro argument expansions to compute this. It returns a
1383   /// StringRef that refers to the SourceManager-owned buffer of the source
1384   /// where that macro name is spelled. Thus, the result shouldn't out-live
1385   /// the SourceManager.
1386   StringRef getImmediateMacroName(SourceLocation Loc) {
1387     return Lexer::getImmediateMacroName(Loc, SourceMgr, getLangOpts());
1388   }
1389
1390   /// \brief Plop the specified string into a scratch buffer and set the
1391   /// specified token's location and length to it. 
1392   ///
1393   /// If specified, the source location provides a location of the expansion
1394   /// point of the token.
1395   void CreateString(StringRef Str, Token &Tok,
1396                     SourceLocation ExpansionLocStart = SourceLocation(),
1397                     SourceLocation ExpansionLocEnd = SourceLocation());
1398
1399   /// \brief Computes the source location just past the end of the
1400   /// token at this source location.
1401   ///
1402   /// This routine can be used to produce a source location that
1403   /// points just past the end of the token referenced by \p Loc, and
1404   /// is generally used when a diagnostic needs to point just after a
1405   /// token where it expected something different that it received. If
1406   /// the returned source location would not be meaningful (e.g., if
1407   /// it points into a macro), this routine returns an invalid
1408   /// source location.
1409   ///
1410   /// \param Offset an offset from the end of the token, where the source
1411   /// location should refer to. The default offset (0) produces a source
1412   /// location pointing just past the end of the token; an offset of 1 produces
1413   /// a source location pointing to the last character in the token, etc.
1414   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0) {
1415     return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
1416   }
1417
1418   /// \brief Returns true if the given MacroID location points at the first
1419   /// token of the macro expansion.
1420   ///
1421   /// \param MacroBegin If non-null and function returns true, it is set to
1422   /// begin location of the macro.
1423   bool isAtStartOfMacroExpansion(SourceLocation loc,
1424                                  SourceLocation *MacroBegin = nullptr) const {
1425     return Lexer::isAtStartOfMacroExpansion(loc, SourceMgr, LangOpts,
1426                                             MacroBegin);
1427   }
1428
1429   /// \brief Returns true if the given MacroID location points at the last
1430   /// token of the macro expansion.
1431   ///
1432   /// \param MacroEnd If non-null and function returns true, it is set to
1433   /// end location of the macro.
1434   bool isAtEndOfMacroExpansion(SourceLocation loc,
1435                                SourceLocation *MacroEnd = nullptr) const {
1436     return Lexer::isAtEndOfMacroExpansion(loc, SourceMgr, LangOpts, MacroEnd);
1437   }
1438
1439   /// \brief Print the token to stderr, used for debugging.
1440   void DumpToken(const Token &Tok, bool DumpFlags = false) const;
1441   void DumpLocation(SourceLocation Loc) const;
1442   void DumpMacro(const MacroInfo &MI) const;
1443   void dumpMacroInfo(const IdentifierInfo *II);
1444
1445   /// \brief Given a location that specifies the start of a
1446   /// token, return a new location that specifies a character within the token.
1447   SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,
1448                                          unsigned Char) const {
1449     return Lexer::AdvanceToTokenCharacter(TokStart, Char, SourceMgr, LangOpts);
1450   }
1451
1452   /// \brief Increment the counters for the number of token paste operations
1453   /// performed.
1454   ///
1455   /// If fast was specified, this is a 'fast paste' case we handled.
1456   void IncrementPasteCounter(bool isFast) {
1457     if (isFast)
1458       ++NumFastTokenPaste;
1459     else
1460       ++NumTokenPaste;
1461   }
1462
1463   void PrintStats();
1464
1465   size_t getTotalMemory() const;
1466
1467   /// When the macro expander pastes together a comment (/##/) in Microsoft
1468   /// mode, this method handles updating the current state, returning the
1469   /// token on the next source line.
1470   void HandleMicrosoftCommentPaste(Token &Tok);
1471
1472   //===--------------------------------------------------------------------===//
1473   // Preprocessor callback methods.  These are invoked by a lexer as various
1474   // directives and events are found.
1475
1476   /// Given a tok::raw_identifier token, look up the
1477   /// identifier information for the token and install it into the token,
1478   /// updating the token kind accordingly.
1479   IdentifierInfo *LookUpIdentifierInfo(Token &Identifier) const;
1480
1481 private:
1482   llvm::DenseMap<IdentifierInfo*,unsigned> PoisonReasons;
1483
1484 public:
1485
1486   /// \brief Specifies the reason for poisoning an identifier.
1487   ///
1488   /// If that identifier is accessed while poisoned, then this reason will be
1489   /// used instead of the default "poisoned" diagnostic.
1490   void SetPoisonReason(IdentifierInfo *II, unsigned DiagID);
1491
1492   /// \brief Display reason for poisoned identifier.
1493   void HandlePoisonedIdentifier(Token & Tok);
1494
1495   void MaybeHandlePoisonedIdentifier(Token & Identifier) {
1496     if(IdentifierInfo * II = Identifier.getIdentifierInfo()) {
1497       if(II->isPoisoned()) {
1498         HandlePoisonedIdentifier(Identifier);
1499       }
1500     }
1501   }
1502
1503 private:
1504   /// Identifiers used for SEH handling in Borland. These are only
1505   /// allowed in particular circumstances
1506   // __except block
1507   IdentifierInfo *Ident__exception_code,
1508                  *Ident___exception_code,
1509                  *Ident_GetExceptionCode;
1510   // __except filter expression
1511   IdentifierInfo *Ident__exception_info,
1512                  *Ident___exception_info,
1513                  *Ident_GetExceptionInfo;
1514   // __finally
1515   IdentifierInfo *Ident__abnormal_termination,
1516                  *Ident___abnormal_termination,
1517                  *Ident_AbnormalTermination;
1518
1519   const char *getCurLexerEndPos();
1520
1521 public:
1522   void PoisonSEHIdentifiers(bool Poison = true); // Borland
1523
1524   /// \brief Callback invoked when the lexer reads an identifier and has
1525   /// filled in the tokens IdentifierInfo member. 
1526   ///
1527   /// This callback potentially macro expands it or turns it into a named
1528   /// token (like 'for').
1529   ///
1530   /// \returns true if we actually computed a token, false if we need to
1531   /// lex again.
1532   bool HandleIdentifier(Token &Identifier);
1533
1534
1535   /// \brief Callback invoked when the lexer hits the end of the current file.
1536   ///
1537   /// This either returns the EOF token and returns true, or
1538   /// pops a level off the include stack and returns false, at which point the
1539   /// client should call lex again.
1540   bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false);
1541
1542   /// \brief Callback invoked when the current TokenLexer hits the end of its
1543   /// token stream.
1544   bool HandleEndOfTokenLexer(Token &Result);
1545
1546   /// \brief Callback invoked when the lexer sees a # token at the start of a
1547   /// line.
1548   ///
1549   /// This consumes the directive, modifies the lexer/preprocessor state, and
1550   /// advances the lexer(s) so that the next token read is the correct one.
1551   void HandleDirective(Token &Result);
1552
1553   /// \brief Ensure that the next token is a tok::eod token.
1554   ///
1555   /// If not, emit a diagnostic and consume up until the eod.
1556   /// If \p EnableMacros is true, then we consider macros that expand to zero
1557   /// tokens as being ok.
1558   void CheckEndOfDirective(const char *Directive, bool EnableMacros = false);
1559
1560   /// \brief Read and discard all tokens remaining on the current line until
1561   /// the tok::eod token is found.
1562   void DiscardUntilEndOfDirective();
1563
1564   /// \brief Returns true if the preprocessor has seen a use of
1565   /// __DATE__ or __TIME__ in the file so far.
1566   bool SawDateOrTime() const {
1567     return DATELoc != SourceLocation() || TIMELoc != SourceLocation();
1568   }
1569   unsigned getCounterValue() const { return CounterValue; }
1570   void setCounterValue(unsigned V) { CounterValue = V; }
1571
1572   /// \brief Retrieves the module that we're currently building, if any.
1573   Module *getCurrentModule();
1574   
1575   /// \brief Allocate a new MacroInfo object with the provided SourceLocation.
1576   MacroInfo *AllocateMacroInfo(SourceLocation L);
1577
1578   /// \brief Allocate a new MacroInfo object loaded from an AST file.
1579   MacroInfo *AllocateDeserializedMacroInfo(SourceLocation L,
1580                                            unsigned SubModuleID);
1581
1582   /// \brief Turn the specified lexer token into a fully checked and spelled
1583   /// filename, e.g. as an operand of \#include. 
1584   ///
1585   /// The caller is expected to provide a buffer that is large enough to hold
1586   /// the spelling of the filename, but is also expected to handle the case
1587   /// when this method decides to use a different buffer.
1588   ///
1589   /// \returns true if the input filename was in <>'s or false if it was
1590   /// in ""'s.
1591   bool GetIncludeFilenameSpelling(SourceLocation Loc,StringRef &Filename);
1592
1593   /// \brief Given a "foo" or \<foo> reference, look up the indicated file.
1594   ///
1595   /// Returns null on failure.  \p isAngled indicates whether the file
1596   /// reference is for system \#include's or not (i.e. using <> instead of "").
1597   const FileEntry *LookupFile(SourceLocation FilenameLoc, StringRef Filename,
1598                               bool isAngled, const DirectoryLookup *FromDir,
1599                               const FileEntry *FromFile,
1600                               const DirectoryLookup *&CurDir,
1601                               SmallVectorImpl<char> *SearchPath,
1602                               SmallVectorImpl<char> *RelativePath,
1603                               ModuleMap::KnownHeader *SuggestedModule,
1604                               bool SkipCache = false);
1605
1606   /// \brief Get the DirectoryLookup structure used to find the current
1607   /// FileEntry, if CurLexer is non-null and if applicable. 
1608   ///
1609   /// This allows us to implement \#include_next and find directory-specific
1610   /// properties.
1611   const DirectoryLookup *GetCurDirLookup() { return CurDirLookup; }
1612
1613   /// \brief Return true if we're in the top-level file, not in a \#include.
1614   bool isInPrimaryFile() const;
1615
1616   /// \brief Handle cases where the \#include name is expanded
1617   /// from a macro as multiple tokens, which need to be glued together. 
1618   ///
1619   /// This occurs for code like:
1620   /// \code
1621   ///    \#define FOO <x/y.h>
1622   ///    \#include FOO
1623   /// \endcode
1624   /// because in this case, "<x/y.h>" is returned as 7 tokens, not one.
1625   ///
1626   /// This code concatenates and consumes tokens up to the '>' token.  It
1627   /// returns false if the > was found, otherwise it returns true if it finds
1628   /// and consumes the EOD marker.
1629   bool ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
1630                               SourceLocation &End);
1631
1632   /// \brief Lex an on-off-switch (C99 6.10.6p2) and verify that it is
1633   /// followed by EOD.  Return true if the token is not a valid on-off-switch.
1634   bool LexOnOffSwitch(tok::OnOffSwitch &OOS);
1635
1636   bool CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
1637                       bool *ShadowFlag = nullptr);
1638
1639 private:
1640
1641   void PushIncludeMacroStack() {
1642     assert(CurLexerKind != CLK_CachingLexer && "cannot push a caching lexer");
1643     IncludeMacroStack.emplace_back(
1644         CurLexerKind, CurSubmodule, std::move(CurLexer), std::move(CurPTHLexer),
1645         CurPPLexer, std::move(CurTokenLexer), CurDirLookup);
1646     CurPPLexer = nullptr;
1647   }
1648
1649   void PopIncludeMacroStack() {
1650     CurLexer = std::move(IncludeMacroStack.back().TheLexer);
1651     CurPTHLexer = std::move(IncludeMacroStack.back().ThePTHLexer);
1652     CurPPLexer = IncludeMacroStack.back().ThePPLexer;
1653     CurTokenLexer = std::move(IncludeMacroStack.back().TheTokenLexer);
1654     CurDirLookup  = IncludeMacroStack.back().TheDirLookup;
1655     CurSubmodule = IncludeMacroStack.back().TheSubmodule;
1656     CurLexerKind = IncludeMacroStack.back().CurLexerKind;
1657     IncludeMacroStack.pop_back();
1658   }
1659
1660   void PropagateLineStartLeadingSpaceInfo(Token &Result);
1661
1662   void EnterSubmodule(Module *M, SourceLocation ImportLoc);
1663   void LeaveSubmodule();
1664
1665   /// Update the set of active module macros and ambiguity flag for a module
1666   /// macro name.
1667   void updateModuleMacroInfo(const IdentifierInfo *II, ModuleMacroInfo &Info);
1668
1669   /// \brief Allocate a new MacroInfo object.
1670   MacroInfo *AllocateMacroInfo();
1671
1672   DefMacroDirective *AllocateDefMacroDirective(MacroInfo *MI,
1673                                                SourceLocation Loc);
1674   UndefMacroDirective *AllocateUndefMacroDirective(SourceLocation UndefLoc);
1675   VisibilityMacroDirective *AllocateVisibilityMacroDirective(SourceLocation Loc,
1676                                                              bool isPublic);
1677
1678   /// \brief Lex and validate a macro name, which occurs after a
1679   /// \#define or \#undef.
1680   ///
1681   /// \param MacroNameTok Token that represents the name defined or undefined.
1682   /// \param IsDefineUndef Kind if preprocessor directive.
1683   /// \param ShadowFlag Points to flag that is set if macro name shadows
1684   ///                   a keyword.
1685   ///
1686   /// This emits a diagnostic, sets the token kind to eod,
1687   /// and discards the rest of the macro line if the macro name is invalid.
1688   void ReadMacroName(Token &MacroNameTok, MacroUse IsDefineUndef = MU_Other,
1689                      bool *ShadowFlag = nullptr);
1690
1691   /// The ( starting an argument list of a macro definition has just been read.
1692   /// Lex the rest of the arguments and the closing ), updating \p MI with
1693   /// what we learn and saving in \p LastTok the last token read.
1694   /// Return true if an error occurs parsing the arg list.
1695   bool ReadMacroDefinitionArgList(MacroInfo *MI, Token& LastTok);
1696
1697   /// We just read a \#if or related directive and decided that the
1698   /// subsequent tokens are in the \#if'd out portion of the
1699   /// file.  Lex the rest of the file, until we see an \#endif.  If \p
1700   /// FoundNonSkipPortion is true, then we have already emitted code for part of
1701   /// this \#if directive, so \#else/\#elif blocks should never be entered. If
1702   /// \p FoundElse is false, then \#else directives are ok, if not, then we have
1703   /// already seen one so a \#else directive is a duplicate.  When this returns,
1704   /// the caller can lex the first valid token.
1705   void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
1706                                     bool FoundNonSkipPortion, bool FoundElse,
1707                                     SourceLocation ElseLoc = SourceLocation());
1708
1709   /// \brief A fast PTH version of SkipExcludedConditionalBlock.
1710   void PTHSkipExcludedConditionalBlock();
1711
1712   /// \brief Evaluate an integer constant expression that may occur after a
1713   /// \#if or \#elif directive and return it as a bool.
1714   ///
1715   /// If the expression is equivalent to "!defined(X)" return X in IfNDefMacro.
1716   bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro);
1717
1718   /// \brief Install the standard preprocessor pragmas:
1719   /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1720   void RegisterBuiltinPragmas();
1721
1722   /// \brief Register builtin macros such as __LINE__ with the identifier table.
1723   void RegisterBuiltinMacros();
1724
1725   /// If an identifier token is read that is to be expanded as a macro, handle
1726   /// it and return the next token as 'Tok'.  If we lexed a token, return true;
1727   /// otherwise the caller should lex again.
1728   bool HandleMacroExpandedIdentifier(Token &Tok, const MacroDefinition &MD);
1729
1730   /// \brief Cache macro expanded tokens for TokenLexers.
1731   //
1732   /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
1733   /// going to lex in the cache and when it finishes the tokens are removed
1734   /// from the end of the cache.
1735   Token *cacheMacroExpandedTokens(TokenLexer *tokLexer,
1736                                   ArrayRef<Token> tokens);
1737   void removeCachedMacroExpandedTokensOfLastLexer();
1738   friend void TokenLexer::ExpandFunctionArguments();
1739
1740   /// Determine whether the next preprocessor token to be
1741   /// lexed is a '('.  If so, consume the token and return true, if not, this
1742   /// method should have no observable side-effect on the lexed tokens.
1743   bool isNextPPTokenLParen();
1744
1745   /// After reading "MACRO(", this method is invoked to read all of the formal
1746   /// arguments specified for the macro invocation.  Returns null on error.
1747   MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI,
1748                                        SourceLocation &ExpansionEnd);
1749
1750   /// \brief If an identifier token is read that is to be expanded
1751   /// as a builtin macro, handle it and return the next token as 'Tok'.
1752   void ExpandBuiltinMacro(Token &Tok);
1753
1754   /// \brief Read a \c _Pragma directive, slice it up, process it, then
1755   /// return the first token after the directive.
1756   /// This assumes that the \c _Pragma token has just been read into \p Tok.
1757   void Handle_Pragma(Token &Tok);
1758
1759   /// \brief Like Handle_Pragma except the pragma text is not enclosed within
1760   /// a string literal.
1761   void HandleMicrosoft__pragma(Token &Tok);
1762
1763   /// \brief Add a lexer to the top of the include stack and
1764   /// start lexing tokens from it instead of the current buffer.
1765   void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir);
1766
1767   /// \brief Add a lexer to the top of the include stack and
1768   /// start getting tokens from it using the PTH cache.
1769   void EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *Dir);
1770
1771   /// \brief Set the FileID for the preprocessor predefines.
1772   void setPredefinesFileID(FileID FID) {
1773     assert(PredefinesFileID.isInvalid() && "PredefinesFileID already set!");
1774     PredefinesFileID = FID;
1775   }
1776
1777   /// \brief Returns true if we are lexing from a file and not a
1778   /// pragma or a macro.
1779   static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) {
1780     return L ? !L->isPragmaLexer() : P != nullptr;
1781   }
1782
1783   static bool IsFileLexer(const IncludeStackInfo& I) {
1784     return IsFileLexer(I.TheLexer.get(), I.ThePPLexer);
1785   }
1786
1787   bool IsFileLexer() const {
1788     return IsFileLexer(CurLexer.get(), CurPPLexer);
1789   }
1790
1791   //===--------------------------------------------------------------------===//
1792   // Caching stuff.
1793   void CachingLex(Token &Result);
1794   bool InCachingLexMode() const {
1795     // If the Lexer pointers are 0 and IncludeMacroStack is empty, it means
1796     // that we are past EOF, not that we are in CachingLex mode.
1797     return !CurPPLexer && !CurTokenLexer && !CurPTHLexer &&
1798            !IncludeMacroStack.empty();
1799   }
1800   void EnterCachingLexMode();
1801   void ExitCachingLexMode() {
1802     if (InCachingLexMode())
1803       RemoveTopOfLexerStack();
1804   }
1805   const Token &PeekAhead(unsigned N);
1806   void AnnotatePreviousCachedTokens(const Token &Tok);
1807
1808   //===--------------------------------------------------------------------===//
1809   /// Handle*Directive - implement the various preprocessor directives.  These
1810   /// should side-effect the current preprocessor object so that the next call
1811   /// to Lex() will return the appropriate token next.
1812   void HandleLineDirective(Token &Tok);
1813   void HandleDigitDirective(Token &Tok);
1814   void HandleUserDiagnosticDirective(Token &Tok, bool isWarning);
1815   void HandleIdentSCCSDirective(Token &Tok);
1816   void HandleMacroPublicDirective(Token &Tok);
1817   void HandleMacroPrivateDirective(Token &Tok);
1818
1819   // File inclusion.
1820   void HandleIncludeDirective(SourceLocation HashLoc,
1821                               Token &Tok,
1822                               const DirectoryLookup *LookupFrom = nullptr,
1823                               const FileEntry *LookupFromFile = nullptr,
1824                               bool isImport = false);
1825   void HandleIncludeNextDirective(SourceLocation HashLoc, Token &Tok);
1826   void HandleIncludeMacrosDirective(SourceLocation HashLoc, Token &Tok);
1827   void HandleImportDirective(SourceLocation HashLoc, Token &Tok);
1828   void HandleMicrosoftImportDirective(Token &Tok);
1829
1830 public:
1831   // Module inclusion testing.
1832   /// \brief Find the module that owns the source or header file that
1833   /// \p Loc points to. If the location is in a file that was included
1834   /// into a module, or is outside any module, returns nullptr.
1835   Module *getModuleForLocation(SourceLocation Loc);
1836
1837   /// \brief Find the module that contains the specified location, either
1838   /// directly or indirectly.
1839   Module *getModuleContainingLocation(SourceLocation Loc);
1840
1841 private:
1842   // Macro handling.
1843   void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterTopLevelIfndef);
1844   void HandleUndefDirective(Token &Tok);
1845
1846   // Conditional Inclusion.
1847   void HandleIfdefDirective(Token &Tok, bool isIfndef,
1848                             bool ReadAnyTokensBeforeDirective);
1849   void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective);
1850   void HandleEndifDirective(Token &Tok);
1851   void HandleElseDirective(Token &Tok);
1852   void HandleElifDirective(Token &Tok);
1853
1854   // Pragmas.
1855   void HandlePragmaDirective(SourceLocation IntroducerLoc,
1856                              PragmaIntroducerKind Introducer);
1857 public:
1858   void HandlePragmaOnce(Token &OnceTok);
1859   void HandlePragmaMark();
1860   void HandlePragmaPoison(Token &PoisonTok);
1861   void HandlePragmaSystemHeader(Token &SysHeaderTok);
1862   void HandlePragmaDependency(Token &DependencyTok);
1863   void HandlePragmaPushMacro(Token &Tok);
1864   void HandlePragmaPopMacro(Token &Tok);
1865   void HandlePragmaIncludeAlias(Token &Tok);
1866   IdentifierInfo *ParsePragmaPushOrPopMacro(Token &Tok);
1867
1868   // Return true and store the first token only if any CommentHandler
1869   // has inserted some tokens and getCommentRetentionState() is false.
1870   bool HandleComment(Token &Token, SourceRange Comment);
1871
1872   /// \brief A macro is used, update information about macros that need unused
1873   /// warnings.
1874   void markMacroAsUsed(MacroInfo *MI);
1875 };
1876
1877 /// \brief Abstract base class that describes a handler that will receive
1878 /// source ranges for each of the comments encountered in the source file.
1879 class CommentHandler {
1880 public:
1881   virtual ~CommentHandler();
1882
1883   // The handler shall return true if it has pushed any tokens
1884   // to be read using e.g. EnterToken or EnterTokenStream.
1885   virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) = 0;
1886 };
1887
1888 }  // end namespace clang
1889
1890 #endif