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