MacroInfo.h revision 9317ab94bb68122ba6fc728eb73c1308fb913cd1
1//===--- MacroInfo.h - Information about #defined identifiers ---*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief Defines the clang::MacroInfo and clang::MacroDirective classes.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_MACROINFO_H
16#define LLVM_CLANG_MACROINFO_H
17
18#include "clang/Lex/Token.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/Support/Allocator.h"
21#include <cassert>
22
23namespace clang {
24  class Preprocessor;
25
26/// \brief Encapsulates the data about a macro definition (e.g. its tokens).
27///
28/// There's an instance of this class for every #define.
29class MacroInfo {
30  //===--------------------------------------------------------------------===//
31  // State set when the macro is defined.
32
33  /// \brief The location the macro is defined.
34  SourceLocation Location;
35  /// \brief The location of the last token in the macro.
36  SourceLocation EndLocation;
37
38  /// \brief The list of arguments for a function-like macro.
39  ///
40  /// ArgumentList points to the first of NumArguments pointers.
41  ///
42  /// This can be empty, for, e.g. "#define X()".  In a C99-style variadic macro, this
43  /// includes the \c __VA_ARGS__ identifier on the list.
44  IdentifierInfo **ArgumentList;
45
46  /// \see ArgumentList
47  unsigned NumArguments;
48
49  /// \brief This is the list of tokens that the macro is defined to.
50  SmallVector<Token, 8> ReplacementTokens;
51
52  /// \brief Length in characters of the macro definition.
53  mutable unsigned DefinitionLength;
54  mutable bool IsDefinitionLengthCached : 1;
55
56  /// \brief True if this macro is function-like, false if it is object-like.
57  bool IsFunctionLike : 1;
58
59  /// \brief True if this macro is of the form "#define X(...)" or
60  /// "#define X(Y,Z,...)".
61  ///
62  /// The __VA_ARGS__ token should be replaced with the contents of "..." in an
63  /// invocation.
64  bool IsC99Varargs : 1;
65
66  /// \brief True if this macro is of the form "#define X(a...)".
67  ///
68  /// The "a" identifier in the replacement list will be replaced with all arguments
69  /// of the macro starting with the specified one.
70  bool IsGNUVarargs : 1;
71
72  /// \brief True if this macro requires processing before expansion.
73  ///
74  /// This is the case for builtin macros such as __LINE__, so long as they have
75  /// not been redefined, but not for regular predefined macros from the "<built-in>"
76  /// memory buffer (see Preprocessing::getPredefinesFileID).
77  bool IsBuiltinMacro : 1;
78
79  /// \brief Whether this macro contains the sequence ", ## __VA_ARGS__"
80  bool HasCommaPasting : 1;
81
82private:
83  //===--------------------------------------------------------------------===//
84  // State that changes as the macro is used.
85
86  /// \brief True if we have started an expansion of this macro already.
87  ///
88  /// This disables recursive expansion, which would be quite bad for things
89  /// like \#define A A.
90  bool IsDisabled : 1;
91
92  /// \brief True if this macro is either defined in the main file and has
93  /// been used, or if it is not defined in the main file.
94  ///
95  /// This is used to emit -Wunused-macros diagnostics.
96  bool IsUsed : 1;
97
98  /// \brief True if this macro can be redefined without emitting a warning.
99  bool IsAllowRedefinitionsWithoutWarning : 1;
100
101  /// \brief Must warn if the macro is unused at the end of translation unit.
102  bool IsWarnIfUnused : 1;
103
104  /// \brief Whether this macro info was loaded from an AST file.
105  unsigned FromASTFile : 1;
106
107  ~MacroInfo() {
108    assert(ArgumentList == 0 && "Didn't call destroy before dtor!");
109  }
110
111public:
112  MacroInfo(SourceLocation DefLoc);
113
114  /// \brief Free the argument list of the macro.
115  ///
116  /// This restores this MacroInfo to a state where it can be reused for other
117  /// devious purposes.
118  void FreeArgumentList() {
119    ArgumentList = 0;
120    NumArguments = 0;
121  }
122
123  /// \brief Destroy this MacroInfo object.
124  void Destroy() {
125    FreeArgumentList();
126    this->~MacroInfo();
127  }
128
129  /// \brief Return the location that the macro was defined at.
130  SourceLocation getDefinitionLoc() const { return Location; }
131
132  /// \brief Set the location of the last token in the macro.
133  void setDefinitionEndLoc(SourceLocation EndLoc) { EndLocation = EndLoc; }
134
135  /// \brief Return the location of the last token in the macro.
136  SourceLocation getDefinitionEndLoc() const { return EndLocation; }
137
138  /// \brief Get length in characters of the macro definition.
139  unsigned getDefinitionLength(SourceManager &SM) const {
140    if (IsDefinitionLengthCached)
141      return DefinitionLength;
142    return getDefinitionLengthSlow(SM);
143  }
144
145  /// \brief Return true if the specified macro definition is equal to
146  /// this macro in spelling, arguments, and whitespace.
147  ///
148  /// This is used to emit duplicate definition warnings.  This implements the rules
149  /// in C99 6.10.3.
150  bool isIdenticalTo(const MacroInfo &Other, Preprocessor &PP) const;
151
152  /// \brief Set or clear the isBuiltinMacro flag.
153  void setIsBuiltinMacro(bool Val = true) {
154    IsBuiltinMacro = Val;
155  }
156
157  /// \brief Set the value of the IsUsed flag.
158  void setIsUsed(bool Val) {
159    IsUsed = Val;
160  }
161
162  /// \brief Set the value of the IsAllowRedefinitionsWithoutWarning flag.
163  void setIsAllowRedefinitionsWithoutWarning(bool Val) {
164    IsAllowRedefinitionsWithoutWarning = Val;
165  }
166
167  /// \brief Set the value of the IsWarnIfUnused flag.
168  void setIsWarnIfUnused(bool val) {
169    IsWarnIfUnused = val;
170  }
171
172  /// \brief Set the specified list of identifiers as the argument list for
173  /// this macro.
174  void setArgumentList(IdentifierInfo* const *List, unsigned NumArgs,
175                       llvm::BumpPtrAllocator &PPAllocator) {
176    assert(ArgumentList == 0 && NumArguments == 0 &&
177           "Argument list already set!");
178    if (NumArgs == 0) return;
179
180    NumArguments = NumArgs;
181    ArgumentList = PPAllocator.Allocate<IdentifierInfo*>(NumArgs);
182    for (unsigned i = 0; i != NumArgs; ++i)
183      ArgumentList[i] = List[i];
184  }
185
186  /// Arguments - The list of arguments for a function-like macro.  This can be
187  /// empty, for, e.g. "#define X()".
188  typedef IdentifierInfo* const *arg_iterator;
189  bool arg_empty() const { return NumArguments == 0; }
190  arg_iterator arg_begin() const { return ArgumentList; }
191  arg_iterator arg_end() const { return ArgumentList+NumArguments; }
192  unsigned getNumArgs() const { return NumArguments; }
193
194  /// \brief Return the argument number of the specified identifier,
195  /// or -1 if the identifier is not a formal argument identifier.
196  int getArgumentNum(IdentifierInfo *Arg) const {
197    for (arg_iterator I = arg_begin(), E = arg_end(); I != E; ++I)
198      if (*I == Arg) return I-arg_begin();
199    return -1;
200  }
201
202  /// Function/Object-likeness.  Keep track of whether this macro has formal
203  /// parameters.
204  void setIsFunctionLike() { IsFunctionLike = true; }
205  bool isFunctionLike() const { return IsFunctionLike; }
206  bool isObjectLike() const { return !IsFunctionLike; }
207
208  /// Varargs querying methods.  This can only be set for function-like macros.
209  void setIsC99Varargs() { IsC99Varargs = true; }
210  void setIsGNUVarargs() { IsGNUVarargs = true; }
211  bool isC99Varargs() const { return IsC99Varargs; }
212  bool isGNUVarargs() const { return IsGNUVarargs; }
213  bool isVariadic() const { return IsC99Varargs | IsGNUVarargs; }
214
215  /// \brief Return true if this macro requires processing before expansion.
216  ///
217  /// This is true only for builtin macro, such as \__LINE__, whose values
218  /// are not given by fixed textual expansions.  Regular predefined macros
219  /// from the "<built-in>" buffer are not reported as builtins by this
220  /// function.
221  bool isBuiltinMacro() const { return IsBuiltinMacro; }
222
223  bool hasCommaPasting() const { return HasCommaPasting; }
224  void setHasCommaPasting() { HasCommaPasting = true; }
225
226  /// \brief Return false if this macro is defined in the main file and has
227  /// not yet been used.
228  bool isUsed() const { return IsUsed; }
229
230  /// \brief Return true if this macro can be redefined without warning.
231  bool isAllowRedefinitionsWithoutWarning() const {
232    return IsAllowRedefinitionsWithoutWarning;
233  }
234
235  /// \brief Return true if we should emit a warning if the macro is unused.
236  bool isWarnIfUnused() const {
237    return IsWarnIfUnused;
238  }
239
240  /// \brief Return the number of tokens that this macro expands to.
241  ///
242  unsigned getNumTokens() const {
243    return ReplacementTokens.size();
244  }
245
246  const Token &getReplacementToken(unsigned Tok) const {
247    assert(Tok < ReplacementTokens.size() && "Invalid token #");
248    return ReplacementTokens[Tok];
249  }
250
251  typedef SmallVector<Token, 8>::const_iterator tokens_iterator;
252  tokens_iterator tokens_begin() const { return ReplacementTokens.begin(); }
253  tokens_iterator tokens_end() const { return ReplacementTokens.end(); }
254  bool tokens_empty() const { return ReplacementTokens.empty(); }
255
256  /// \brief Add the specified token to the replacement text for the macro.
257  void AddTokenToBody(const Token &Tok) {
258    assert(!IsDefinitionLengthCached &&
259          "Changing replacement tokens after definition length got calculated");
260    ReplacementTokens.push_back(Tok);
261  }
262
263  /// \brief Return true if this macro is enabled.
264  ///
265  /// In other words, that we are not currently in an expansion of this macro.
266  bool isEnabled() const { return !IsDisabled; }
267
268  void EnableMacro() {
269    assert(IsDisabled && "Cannot enable an already-enabled macro!");
270    IsDisabled = false;
271  }
272
273  void DisableMacro() {
274    assert(!IsDisabled && "Cannot disable an already-disabled macro!");
275    IsDisabled = true;
276  }
277
278  /// \brief Determine whether this macro info came from an AST file (such as
279  /// a precompiled header or module) rather than having been parsed.
280  bool isFromASTFile() const { return FromASTFile; }
281
282  /// \brief Retrieve the global ID of the module that owns this particular
283  /// macro info.
284  unsigned getOwningModuleID() const {
285    if (isFromASTFile())
286      return *(const unsigned*)(this+1);
287
288    return 0;
289  }
290
291private:
292  unsigned getDefinitionLengthSlow(SourceManager &SM) const;
293
294  void setOwningModuleID(unsigned ID) {
295    assert(isFromASTFile());
296    *(unsigned*)(this+1) = ID;
297  }
298
299  friend class Preprocessor;
300};
301
302/// \brief Encapsulates changes to the "macros namespace" (the location where
303/// the macro name became active, the location where it was undefined, etc.).
304///
305/// MacroDirectives, associated with an identifier, are used to model the macro
306/// history. Usually a macro definition (MacroInfo) is where a macro name
307/// becomes active (MacroDirective) but modules can have their own macro
308/// history, separate from the local (current translation unit) macro history.
309///
310/// For example, if "@import A;" imports macro FOO, there will be a new local
311/// MacroDirective created to indicate that "FOO" became active at the import
312/// location. Module "A" itself will contain another MacroDirective in its macro
313/// history (at the point of the definition of FOO) and both MacroDirectives
314/// will point to the same MacroInfo object.
315///
316class MacroDirective {
317  MacroInfo *Info;
318
319  /// \brief Previous definition, the identifier of this macro was defined to,
320  /// or NULL.
321  MacroDirective *Previous;
322
323  SourceLocation Loc;
324
325  /// \brief The location where the macro was #undef'd, or an invalid location
326  /// for macros that haven't been undefined.
327  SourceLocation UndefLocation;
328
329  /// \brief The location at which this macro was either explicitly exported
330  /// from its module or marked as private.
331  ///
332  /// If invalid, this macro has not been explicitly given any visibility.
333  SourceLocation VisibilityLocation;
334
335  /// \brief True if the macro directive was loaded from a PCH file.
336  bool IsFromPCH : 1;
337
338  /// \brief True if this macro was imported from a module.
339  bool IsImported : 1;
340
341  /// \brief Whether the macro has public (when described in a module).
342  bool IsPublic : 1;
343
344  /// \brief Whether the macro definition is currently "hidden".
345  ///
346  /// Note that this is transient state that is never serialized to the AST
347  /// file.
348  bool IsHidden : 1;
349
350  /// \brief Whether the definition of this macro is ambiguous, due to
351  /// multiple definitions coming in from multiple modules.
352  bool IsAmbiguous : 1;
353
354  /// \brief Whether this macro changed after it was loaded from an AST file.
355  bool ChangedAfterLoad : 1;
356
357public:
358  explicit MacroDirective(MacroInfo *MI)
359    : Info(MI), Previous(0), Loc(MI->getDefinitionLoc()),
360      IsFromPCH(false), IsImported(false), IsPublic(true), IsHidden(false),
361      IsAmbiguous(false), ChangedAfterLoad(false) {
362    assert(MI && "MacroInfo is null");
363  }
364
365  MacroDirective(MacroInfo *MI, SourceLocation Loc, bool isImported)
366    : Info(MI), Previous(0), Loc(Loc),
367      IsFromPCH(false), IsImported(isImported), IsPublic(true), IsHidden(false),
368      IsAmbiguous(false), ChangedAfterLoad(false) {
369    assert(MI && "MacroInfo is null");
370  }
371
372  SourceLocation getLocation() const { return Loc; }
373
374  /// \brief Set the location where macro was undefined. Can only be set once.
375  void setUndefLoc(SourceLocation UndefLoc) {
376    assert(UndefLocation.isInvalid() && "UndefLocation is already set!");
377    assert(UndefLoc.isValid() && "Invalid UndefLoc!");
378    UndefLocation = UndefLoc;
379  }
380
381  /// \brief The data for the macro definition.
382  const MacroInfo *getInfo() const { return Info; }
383  MacroInfo *getInfo() { return Info; }
384
385  /// \brief Get the location where macro was undefined.
386  SourceLocation getUndefLoc() const { return UndefLocation; }
387
388  /// \brief Set previous definition of the macro with the same name.
389  void setPrevious(MacroDirective *Prev) {
390    Previous = Prev;
391  }
392
393  /// \brief Get previous definition of the macro with the same name.
394  const MacroDirective *getPrevious() const { return Previous; }
395
396  /// \brief Get previous definition of the macro with the same name.
397  MacroDirective *getPrevious() { return Previous; }
398
399  /// \brief Find macro definition active in the specified source location. If
400  /// this macro was not defined there, return NULL.
401  const MacroDirective *findDirectiveAtLoc(SourceLocation L,
402                                           SourceManager &SM) const;
403
404  /// \brief Set the export location for this macro.
405  void setVisibility(bool Public, SourceLocation Loc) {
406    VisibilityLocation = Loc;
407    IsPublic = Public;
408  }
409
410  /// \brief Determine whether this macro is part of the public API of its
411  /// module.
412  bool isPublic() const { return IsPublic; }
413
414  /// \brief Determine the location where this macro was explicitly made
415  /// public or private within its module.
416  SourceLocation getVisibilityLocation() const { return VisibilityLocation; }
417
418  /// \brief Return true if the macro directive was loaded from a PCH file.
419  bool isFromPCH() const { return IsFromPCH; }
420
421  void setIsFromPCH() { IsFromPCH = true; }
422
423  /// \brief True if this macro was imported from a module.
424  bool isImported() const { return IsImported; }
425
426  /// \brief Determine whether this macro is currently defined (and has not
427  /// been #undef'd) or has been hidden.
428  bool isDefined() const { return UndefLocation.isInvalid() && !IsHidden; }
429
430  /// \brief Determine whether this macro definition is hidden.
431  bool isHidden() const { return IsHidden; }
432
433  /// \brief Set whether this macro definition is hidden.
434  void setHidden(bool Val) { IsHidden = Val; }
435
436  /// \brief Determine whether this macro definition is ambiguous with
437  /// other macro definitions.
438  bool isAmbiguous() const { return IsAmbiguous; }
439
440  /// \brief Set whether this macro definition is ambiguous.
441  void setAmbiguous(bool Val) { IsAmbiguous = Val; }
442
443  /// \brief Determine whether this macro has changed since it was loaded from
444  /// an AST file.
445  bool hasChangedAfterLoad() const { return ChangedAfterLoad; }
446
447  /// \brief Note whether this macro has changed after it was loaded from an
448  /// AST file.
449  void setChangedAfterLoad(bool CAL = true) { ChangedAfterLoad = CAL; }
450};
451
452}  // end namespace clang
453
454#endif
455