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