Home | History | Annotate | Download | only in Lex
      1 //===--- PPCallbacks.h - Callbacks for Preprocessor actions -----*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 ///
     10 /// \file
     11 /// \brief Defines the PPCallbacks interface.
     12 ///
     13 //===----------------------------------------------------------------------===//
     14 
     15 #ifndef LLVM_CLANG_LEX_PPCALLBACKS_H
     16 #define LLVM_CLANG_LEX_PPCALLBACKS_H
     17 
     18 #include "clang/Basic/DiagnosticIDs.h"
     19 #include "clang/Basic/SourceLocation.h"
     20 #include "clang/Basic/SourceManager.h"
     21 #include "clang/Lex/ModuleLoader.h"
     22 #include "clang/Lex/Pragma.h"
     23 #include "llvm/ADT/StringRef.h"
     24 
     25 namespace clang {
     26   class Token;
     27   class IdentifierInfo;
     28   class MacroDefinition;
     29   class MacroDirective;
     30   class MacroArgs;
     31 
     32 /// \brief This interface provides a way to observe the actions of the
     33 /// preprocessor as it does its thing.
     34 ///
     35 /// Clients can define their hooks here to implement preprocessor level tools.
     36 class PPCallbacks {
     37 public:
     38   virtual ~PPCallbacks();
     39 
     40   enum FileChangeReason {
     41     EnterFile, ExitFile, SystemHeaderPragma, RenameFile
     42   };
     43 
     44   /// \brief Callback invoked whenever a source file is entered or exited.
     45   ///
     46   /// \param Loc Indicates the new location.
     47   /// \param PrevFID the file that was exited if \p Reason is ExitFile.
     48   virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
     49                            SrcMgr::CharacteristicKind FileType,
     50                            FileID PrevFID = FileID()) {
     51   }
     52 
     53   /// \brief Callback invoked whenever a source file is skipped as the result
     54   /// of header guard optimization.
     55   ///
     56   /// \param SkippedFile The file that is skipped instead of entering \#include
     57   ///
     58   /// \param FilenameTok The file name token in \#include "FileName" directive
     59   /// or macro expanded file name token from \#include MACRO(PARAMS) directive.
     60   /// Note that FilenameTok contains corresponding quotes/angles symbols.
     61   virtual void FileSkipped(const FileEntry &SkippedFile,
     62                            const Token &FilenameTok,
     63                            SrcMgr::CharacteristicKind FileType) {
     64   }
     65 
     66   /// \brief Callback invoked whenever an inclusion directive results in a
     67   /// file-not-found error.
     68   ///
     69   /// \param FileName The name of the file being included, as written in the
     70   /// source code.
     71   ///
     72   /// \param RecoveryPath If this client indicates that it can recover from
     73   /// this missing file, the client should set this as an additional header
     74   /// search patch.
     75   ///
     76   /// \returns true to indicate that the preprocessor should attempt to recover
     77   /// by adding \p RecoveryPath as a header search path.
     78   virtual bool FileNotFound(StringRef FileName,
     79                             SmallVectorImpl<char> &RecoveryPath) {
     80     return false;
     81   }
     82 
     83   /// \brief Callback invoked whenever an inclusion directive of
     84   /// any kind (\c \#include, \c \#import, etc.) has been processed, regardless
     85   /// of whether the inclusion will actually result in an inclusion.
     86   ///
     87   /// \param HashLoc The location of the '#' that starts the inclusion
     88   /// directive.
     89   ///
     90   /// \param IncludeTok The token that indicates the kind of inclusion
     91   /// directive, e.g., 'include' or 'import'.
     92   ///
     93   /// \param FileName The name of the file being included, as written in the
     94   /// source code.
     95   ///
     96   /// \param IsAngled Whether the file name was enclosed in angle brackets;
     97   /// otherwise, it was enclosed in quotes.
     98   ///
     99   /// \param FilenameRange The character range of the quotes or angle brackets
    100   /// for the written file name.
    101   ///
    102   /// \param File The actual file that may be included by this inclusion
    103   /// directive.
    104   ///
    105   /// \param SearchPath Contains the search path which was used to find the file
    106   /// in the file system. If the file was found via an absolute include path,
    107   /// SearchPath will be empty. For framework includes, the SearchPath and
    108   /// RelativePath will be split up. For example, if an include of "Some/Some.h"
    109   /// is found via the framework path
    110   /// "path/to/Frameworks/Some.framework/Headers/Some.h", SearchPath will be
    111   /// "path/to/Frameworks/Some.framework/Headers" and RelativePath will be
    112   /// "Some.h".
    113   ///
    114   /// \param RelativePath The path relative to SearchPath, at which the include
    115   /// file was found. This is equal to FileName except for framework includes.
    116   ///
    117   /// \param Imported The module, whenever an inclusion directive was
    118   /// automatically turned into a module import or null otherwise.
    119   ///
    120   virtual void InclusionDirective(SourceLocation HashLoc,
    121                                   const Token &IncludeTok,
    122                                   StringRef FileName,
    123                                   bool IsAngled,
    124                                   CharSourceRange FilenameRange,
    125                                   const FileEntry *File,
    126                                   StringRef SearchPath,
    127                                   StringRef RelativePath,
    128                                   const Module *Imported) {
    129   }
    130 
    131   /// \brief Callback invoked whenever there was an explicit module-import
    132   /// syntax.
    133   ///
    134   /// \param ImportLoc The location of import directive token.
    135   ///
    136   /// \param Path The identifiers (and their locations) of the module
    137   /// "path", e.g., "std.vector" would be split into "std" and "vector".
    138   ///
    139   /// \param Imported The imported module; can be null if importing failed.
    140   ///
    141   virtual void moduleImport(SourceLocation ImportLoc,
    142                             ModuleIdPath Path,
    143                             const Module *Imported) {
    144   }
    145 
    146   /// \brief Callback invoked when the end of the main file is reached.
    147   ///
    148   /// No subsequent callbacks will be made.
    149   virtual void EndOfMainFile() {
    150   }
    151 
    152   /// \brief Callback invoked when a \#ident or \#sccs directive is read.
    153   /// \param Loc The location of the directive.
    154   /// \param str The text of the directive.
    155   ///
    156   virtual void Ident(SourceLocation Loc, StringRef str) {
    157   }
    158 
    159   /// \brief Callback invoked when start reading any pragma directive.
    160   virtual void PragmaDirective(SourceLocation Loc,
    161                                PragmaIntroducerKind Introducer) {
    162   }
    163 
    164   /// \brief Callback invoked when a \#pragma comment directive is read.
    165   virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
    166                              StringRef Str) {
    167   }
    168 
    169   /// \brief Callback invoked when a \#pragma detect_mismatch directive is
    170   /// read.
    171   virtual void PragmaDetectMismatch(SourceLocation Loc, StringRef Name,
    172                                     StringRef Value) {
    173   }
    174 
    175   /// \brief Callback invoked when a \#pragma clang __debug directive is read.
    176   /// \param Loc The location of the debug directive.
    177   /// \param DebugType The identifier following __debug.
    178   virtual void PragmaDebug(SourceLocation Loc, StringRef DebugType) {
    179   }
    180 
    181   /// \brief Determines the kind of \#pragma invoking a call to PragmaMessage.
    182   enum PragmaMessageKind {
    183     /// \brief \#pragma message has been invoked.
    184     PMK_Message,
    185 
    186     /// \brief \#pragma GCC warning has been invoked.
    187     PMK_Warning,
    188 
    189     /// \brief \#pragma GCC error has been invoked.
    190     PMK_Error
    191   };
    192 
    193   /// \brief Callback invoked when a \#pragma message directive is read.
    194   /// \param Loc The location of the message directive.
    195   /// \param Namespace The namespace of the message directive.
    196   /// \param Kind The type of the message directive.
    197   /// \param Str The text of the message directive.
    198   virtual void PragmaMessage(SourceLocation Loc, StringRef Namespace,
    199                              PragmaMessageKind Kind, StringRef Str) {
    200   }
    201 
    202   /// \brief Callback invoked when a \#pragma gcc diagnostic push directive
    203   /// is read.
    204   virtual void PragmaDiagnosticPush(SourceLocation Loc,
    205                                     StringRef Namespace) {
    206   }
    207 
    208   /// \brief Callback invoked when a \#pragma gcc diagnostic pop directive
    209   /// is read.
    210   virtual void PragmaDiagnosticPop(SourceLocation Loc,
    211                                    StringRef Namespace) {
    212   }
    213 
    214   /// \brief Callback invoked when a \#pragma gcc diagnostic directive is read.
    215   virtual void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
    216                                 diag::Severity mapping, StringRef Str) {}
    217 
    218   /// \brief Called when an OpenCL extension is either disabled or
    219   /// enabled with a pragma.
    220   virtual void PragmaOpenCLExtension(SourceLocation NameLoc,
    221                                      const IdentifierInfo *Name,
    222                                      SourceLocation StateLoc, unsigned State) {
    223   }
    224 
    225   /// \brief Callback invoked when a \#pragma warning directive is read.
    226   virtual void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
    227                              ArrayRef<int> Ids) {
    228   }
    229 
    230   /// \brief Callback invoked when a \#pragma warning(push) directive is read.
    231   virtual void PragmaWarningPush(SourceLocation Loc, int Level) {
    232   }
    233 
    234   /// \brief Callback invoked when a \#pragma warning(pop) directive is read.
    235   virtual void PragmaWarningPop(SourceLocation Loc) {
    236   }
    237 
    238   /// \brief Callback invoked when a \#pragma clang assume_nonnull begin directive
    239   /// is read.
    240   virtual void PragmaAssumeNonNullBegin(SourceLocation Loc) {}
    241 
    242   /// \brief Callback invoked when a \#pragma clang assume_nonnull end directive
    243   /// is read.
    244   virtual void PragmaAssumeNonNullEnd(SourceLocation Loc) {}
    245 
    246   /// \brief Called by Preprocessor::HandleMacroExpandedIdentifier when a
    247   /// macro invocation is found.
    248   virtual void MacroExpands(const Token &MacroNameTok,
    249                             const MacroDefinition &MD, SourceRange Range,
    250                             const MacroArgs *Args) {}
    251 
    252   /// \brief Hook called whenever a macro definition is seen.
    253   virtual void MacroDefined(const Token &MacroNameTok,
    254                             const MacroDirective *MD) {
    255   }
    256 
    257   /// \brief Hook called whenever a macro \#undef is seen.
    258   /// \param MacroNameTok The active Token
    259   /// \param MD A MacroDefinition for the named macro.
    260   /// \param Undef New MacroDirective if the macro was defined, null otherwise.
    261   ///
    262   /// MD is released immediately following this callback.
    263   virtual void MacroUndefined(const Token &MacroNameTok,
    264                               const MacroDefinition &MD,
    265                               const MacroDirective *Undef) {
    266   }
    267 
    268   /// \brief Hook called whenever the 'defined' operator is seen.
    269   /// \param MD The MacroDirective if the name was a macro, null otherwise.
    270   virtual void Defined(const Token &MacroNameTok, const MacroDefinition &MD,
    271                        SourceRange Range) {
    272   }
    273 
    274   /// \brief Hook called when a source range is skipped.
    275   /// \param Range The SourceRange that was skipped. The range begins at the
    276   /// \#if/\#else directive and ends after the \#endif/\#else directive.
    277   /// \param EndifLoc The end location of the 'endif' token, which may precede
    278   /// the range skipped by the directive (e.g excluding comments after an
    279   /// 'endif').
    280   virtual void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) {
    281   }
    282 
    283   enum ConditionValueKind {
    284     CVK_NotEvaluated, CVK_False, CVK_True
    285   };
    286 
    287   /// \brief Hook called whenever an \#if is seen.
    288   /// \param Loc the source location of the directive.
    289   /// \param ConditionRange The SourceRange of the expression being tested.
    290   /// \param ConditionValue The evaluated value of the condition.
    291   ///
    292   // FIXME: better to pass in a list (or tree!) of Tokens.
    293   virtual void If(SourceLocation Loc, SourceRange ConditionRange,
    294                   ConditionValueKind ConditionValue) {
    295   }
    296 
    297   /// \brief Hook called whenever an \#elif is seen.
    298   /// \param Loc the source location of the directive.
    299   /// \param ConditionRange The SourceRange of the expression being tested.
    300   /// \param ConditionValue The evaluated value of the condition.
    301   /// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive.
    302   // FIXME: better to pass in a list (or tree!) of Tokens.
    303   virtual void Elif(SourceLocation Loc, SourceRange ConditionRange,
    304                     ConditionValueKind ConditionValue, SourceLocation IfLoc) {
    305   }
    306 
    307   /// \brief Hook called whenever an \#ifdef is seen.
    308   /// \param Loc the source location of the directive.
    309   /// \param MacroNameTok Information on the token being tested.
    310   /// \param MD The MacroDefinition if the name was a macro, null otherwise.
    311   virtual void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
    312                      const MacroDefinition &MD) {
    313   }
    314 
    315   /// \brief Hook called whenever an \#ifndef is seen.
    316   /// \param Loc the source location of the directive.
    317   /// \param MacroNameTok Information on the token being tested.
    318   /// \param MD The MacroDefiniton if the name was a macro, null otherwise.
    319   virtual void Ifndef(SourceLocation Loc, const Token &MacroNameTok,
    320                       const MacroDefinition &MD) {
    321   }
    322 
    323   /// \brief Hook called whenever an \#else is seen.
    324   /// \param Loc the source location of the directive.
    325   /// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive.
    326   virtual void Else(SourceLocation Loc, SourceLocation IfLoc) {
    327   }
    328 
    329   /// \brief Hook called whenever an \#endif is seen.
    330   /// \param Loc the source location of the directive.
    331   /// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive.
    332   virtual void Endif(SourceLocation Loc, SourceLocation IfLoc) {
    333   }
    334 };
    335 
    336 /// \brief Simple wrapper class for chaining callbacks.
    337 class PPChainedCallbacks : public PPCallbacks {
    338   virtual void anchor();
    339   std::unique_ptr<PPCallbacks> First, Second;
    340 
    341 public:
    342   PPChainedCallbacks(std::unique_ptr<PPCallbacks> _First,
    343                      std::unique_ptr<PPCallbacks> _Second)
    344     : First(std::move(_First)), Second(std::move(_Second)) {}
    345 
    346   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
    347                    SrcMgr::CharacteristicKind FileType,
    348                    FileID PrevFID) override {
    349     First->FileChanged(Loc, Reason, FileType, PrevFID);
    350     Second->FileChanged(Loc, Reason, FileType, PrevFID);
    351   }
    352 
    353   void FileSkipped(const FileEntry &SkippedFile,
    354                    const Token &FilenameTok,
    355                    SrcMgr::CharacteristicKind FileType) override {
    356     First->FileSkipped(SkippedFile, FilenameTok, FileType);
    357     Second->FileSkipped(SkippedFile, FilenameTok, FileType);
    358   }
    359 
    360   bool FileNotFound(StringRef FileName,
    361                     SmallVectorImpl<char> &RecoveryPath) override {
    362     return First->FileNotFound(FileName, RecoveryPath) ||
    363            Second->FileNotFound(FileName, RecoveryPath);
    364   }
    365 
    366   void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
    367                           StringRef FileName, bool IsAngled,
    368                           CharSourceRange FilenameRange, const FileEntry *File,
    369                           StringRef SearchPath, StringRef RelativePath,
    370                           const Module *Imported) override {
    371     First->InclusionDirective(HashLoc, IncludeTok, FileName, IsAngled,
    372                               FilenameRange, File, SearchPath, RelativePath,
    373                               Imported);
    374     Second->InclusionDirective(HashLoc, IncludeTok, FileName, IsAngled,
    375                                FilenameRange, File, SearchPath, RelativePath,
    376                                Imported);
    377   }
    378 
    379   void moduleImport(SourceLocation ImportLoc, ModuleIdPath Path,
    380                     const Module *Imported) override {
    381     First->moduleImport(ImportLoc, Path, Imported);
    382     Second->moduleImport(ImportLoc, Path, Imported);
    383   }
    384 
    385   void EndOfMainFile() override {
    386     First->EndOfMainFile();
    387     Second->EndOfMainFile();
    388   }
    389 
    390   void Ident(SourceLocation Loc, StringRef str) override {
    391     First->Ident(Loc, str);
    392     Second->Ident(Loc, str);
    393   }
    394 
    395   void PragmaDirective(SourceLocation Loc,
    396                        PragmaIntroducerKind Introducer) override {
    397     First->PragmaDirective(Loc, Introducer);
    398     Second->PragmaDirective(Loc, Introducer);
    399   }
    400 
    401   void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
    402                      StringRef Str) override {
    403     First->PragmaComment(Loc, Kind, Str);
    404     Second->PragmaComment(Loc, Kind, Str);
    405   }
    406 
    407   void PragmaDetectMismatch(SourceLocation Loc, StringRef Name,
    408                             StringRef Value) override {
    409     First->PragmaDetectMismatch(Loc, Name, Value);
    410     Second->PragmaDetectMismatch(Loc, Name, Value);
    411   }
    412 
    413   void PragmaMessage(SourceLocation Loc, StringRef Namespace,
    414                      PragmaMessageKind Kind, StringRef Str) override {
    415     First->PragmaMessage(Loc, Namespace, Kind, Str);
    416     Second->PragmaMessage(Loc, Namespace, Kind, Str);
    417   }
    418 
    419   void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override {
    420     First->PragmaDiagnosticPush(Loc, Namespace);
    421     Second->PragmaDiagnosticPush(Loc, Namespace);
    422   }
    423 
    424   void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override {
    425     First->PragmaDiagnosticPop(Loc, Namespace);
    426     Second->PragmaDiagnosticPop(Loc, Namespace);
    427   }
    428 
    429   void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
    430                         diag::Severity mapping, StringRef Str) override {
    431     First->PragmaDiagnostic(Loc, Namespace, mapping, Str);
    432     Second->PragmaDiagnostic(Loc, Namespace, mapping, Str);
    433   }
    434 
    435   void PragmaOpenCLExtension(SourceLocation NameLoc, const IdentifierInfo *Name,
    436                              SourceLocation StateLoc, unsigned State) override {
    437     First->PragmaOpenCLExtension(NameLoc, Name, StateLoc, State);
    438     Second->PragmaOpenCLExtension(NameLoc, Name, StateLoc, State);
    439   }
    440 
    441   void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
    442                      ArrayRef<int> Ids) override {
    443     First->PragmaWarning(Loc, WarningSpec, Ids);
    444     Second->PragmaWarning(Loc, WarningSpec, Ids);
    445   }
    446 
    447   void PragmaWarningPush(SourceLocation Loc, int Level) override {
    448     First->PragmaWarningPush(Loc, Level);
    449     Second->PragmaWarningPush(Loc, Level);
    450   }
    451 
    452   void PragmaWarningPop(SourceLocation Loc) override {
    453     First->PragmaWarningPop(Loc);
    454     Second->PragmaWarningPop(Loc);
    455   }
    456 
    457   void PragmaAssumeNonNullBegin(SourceLocation Loc) override {
    458     First->PragmaAssumeNonNullBegin(Loc);
    459     Second->PragmaAssumeNonNullBegin(Loc);
    460   }
    461 
    462   void PragmaAssumeNonNullEnd(SourceLocation Loc) override {
    463     First->PragmaAssumeNonNullEnd(Loc);
    464     Second->PragmaAssumeNonNullEnd(Loc);
    465   }
    466 
    467   void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
    468                     SourceRange Range, const MacroArgs *Args) override {
    469     First->MacroExpands(MacroNameTok, MD, Range, Args);
    470     Second->MacroExpands(MacroNameTok, MD, Range, Args);
    471   }
    472 
    473   void MacroDefined(const Token &MacroNameTok,
    474                     const MacroDirective *MD) override {
    475     First->MacroDefined(MacroNameTok, MD);
    476     Second->MacroDefined(MacroNameTok, MD);
    477   }
    478 
    479   void MacroUndefined(const Token &MacroNameTok,
    480                       const MacroDefinition &MD,
    481                       const MacroDirective *Undef) override {
    482     First->MacroUndefined(MacroNameTok, MD, Undef);
    483     Second->MacroUndefined(MacroNameTok, MD, Undef);
    484   }
    485 
    486   void Defined(const Token &MacroNameTok, const MacroDefinition &MD,
    487                SourceRange Range) override {
    488     First->Defined(MacroNameTok, MD, Range);
    489     Second->Defined(MacroNameTok, MD, Range);
    490   }
    491 
    492   void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override {
    493     First->SourceRangeSkipped(Range, EndifLoc);
    494     Second->SourceRangeSkipped(Range, EndifLoc);
    495   }
    496 
    497   /// \brief Hook called whenever an \#if is seen.
    498   void If(SourceLocation Loc, SourceRange ConditionRange,
    499           ConditionValueKind ConditionValue) override {
    500     First->If(Loc, ConditionRange, ConditionValue);
    501     Second->If(Loc, ConditionRange, ConditionValue);
    502   }
    503 
    504   /// \brief Hook called whenever an \#elif is seen.
    505   void Elif(SourceLocation Loc, SourceRange ConditionRange,
    506             ConditionValueKind ConditionValue, SourceLocation IfLoc) override {
    507     First->Elif(Loc, ConditionRange, ConditionValue, IfLoc);
    508     Second->Elif(Loc, ConditionRange, ConditionValue, IfLoc);
    509   }
    510 
    511   /// \brief Hook called whenever an \#ifdef is seen.
    512   void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
    513              const MacroDefinition &MD) override {
    514     First->Ifdef(Loc, MacroNameTok, MD);
    515     Second->Ifdef(Loc, MacroNameTok, MD);
    516   }
    517 
    518   /// \brief Hook called whenever an \#ifndef is seen.
    519   void Ifndef(SourceLocation Loc, const Token &MacroNameTok,
    520               const MacroDefinition &MD) override {
    521     First->Ifndef(Loc, MacroNameTok, MD);
    522     Second->Ifndef(Loc, MacroNameTok, MD);
    523   }
    524 
    525   /// \brief Hook called whenever an \#else is seen.
    526   void Else(SourceLocation Loc, SourceLocation IfLoc) override {
    527     First->Else(Loc, IfLoc);
    528     Second->Else(Loc, IfLoc);
    529   }
    530 
    531   /// \brief Hook called whenever an \#endif is seen.
    532   void Endif(SourceLocation Loc, SourceLocation IfLoc) override {
    533     First->Endif(Loc, IfLoc);
    534     Second->Endif(Loc, IfLoc);
    535   }
    536 };
    537 
    538 }  // end namespace clang
    539 
    540 #endif
    541