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