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