1 //===--- MacroInfo.h - Information about #defined identifiers ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Defines the clang::MacroInfo and clang::MacroDirective classes.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_MACROINFO_H
16 #define LLVM_CLANG_MACROINFO_H
18 #include "clang/Lex/Token.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Support/Allocator.h"
26 /// \brief Encapsulates the data about a macro definition (e.g. its tokens).
28 /// There's an instance of this class for every #define.
30 //===--------------------------------------------------------------------===//
31 // State set when the macro is defined.
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;
38 /// \brief The list of arguments for a function-like macro.
40 /// ArgumentList points to the first of NumArguments pointers.
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;
47 unsigned NumArguments;
49 /// \brief This is the list of tokens that the macro is defined to.
50 SmallVector<Token, 8> ReplacementTokens;
52 /// \brief Length in characters of the macro definition.
53 mutable unsigned DefinitionLength;
54 mutable bool IsDefinitionLengthCached : 1;
56 /// \brief True if this macro is function-like, false if it is object-like.
57 bool IsFunctionLike : 1;
59 /// \brief True if this macro is of the form "#define X(...)" or
60 /// "#define X(Y,Z,...)".
62 /// The __VA_ARGS__ token should be replaced with the contents of "..." in an
64 bool IsC99Varargs : 1;
66 /// \brief True if this macro is of the form "#define X(a...)".
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;
72 /// \brief True if this macro requires processing before expansion.
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;
79 /// \brief Whether this macro contains the sequence ", ## __VA_ARGS__"
80 bool HasCommaPasting : 1;
83 //===--------------------------------------------------------------------===//
84 // State that changes as the macro is used.
86 /// \brief True if we have started an expansion of this macro already.
88 /// This disables recursive expansion, which would be quite bad for things
89 /// like \#define A A.
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.
95 /// This is used to emit -Wunused-macros diagnostics.
98 /// \brief True if this macro can be redefined without emitting a warning.
99 bool IsAllowRedefinitionsWithoutWarning : 1;
101 /// \brief Must warn if the macro is unused at the end of translation unit.
102 bool IsWarnIfUnused : 1;
104 /// \brief Whether this macro info was loaded from an AST file.
105 unsigned FromASTFile : 1;
108 assert(ArgumentList == 0 && "Didn't call destroy before dtor!");
112 MacroInfo(SourceLocation DefLoc);
114 /// \brief Free the argument list of the macro.
116 /// This restores this MacroInfo to a state where it can be reused for other
117 /// devious purposes.
118 void FreeArgumentList() {
123 /// \brief Destroy this MacroInfo object.
129 /// \brief Return the location that the macro was defined at.
130 SourceLocation getDefinitionLoc() const { return Location; }
132 /// \brief Set the location of the last token in the macro.
133 void setDefinitionEndLoc(SourceLocation EndLoc) { EndLocation = EndLoc; }
135 /// \brief Return the location of the last token in the macro.
136 SourceLocation getDefinitionEndLoc() const { return EndLocation; }
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);
145 /// \brief Return true if the specified macro definition is equal to
146 /// this macro in spelling, arguments, and whitespace.
148 /// \param Syntactically if true, the macro definitions can be identical even
149 /// if they use different identifiers for the function macro parameters.
150 /// Otherwise the comparison is lexical and this implements the rules in
152 bool isIdenticalTo(const MacroInfo &Other, Preprocessor &PP,
153 bool Syntactically) const;
155 /// \brief Set or clear the isBuiltinMacro flag.
156 void setIsBuiltinMacro(bool Val = true) {
157 IsBuiltinMacro = Val;
160 /// \brief Set the value of the IsUsed flag.
161 void setIsUsed(bool Val) {
165 /// \brief Set the value of the IsAllowRedefinitionsWithoutWarning flag.
166 void setIsAllowRedefinitionsWithoutWarning(bool Val) {
167 IsAllowRedefinitionsWithoutWarning = Val;
170 /// \brief Set the value of the IsWarnIfUnused flag.
171 void setIsWarnIfUnused(bool val) {
172 IsWarnIfUnused = val;
175 /// \brief Set the specified list of identifiers as the argument list for
177 void setArgumentList(IdentifierInfo* const *List, unsigned NumArgs,
178 llvm::BumpPtrAllocator &PPAllocator) {
179 assert(ArgumentList == 0 && NumArguments == 0 &&
180 "Argument list already set!");
181 if (NumArgs == 0) return;
183 NumArguments = NumArgs;
184 ArgumentList = PPAllocator.Allocate<IdentifierInfo*>(NumArgs);
185 for (unsigned i = 0; i != NumArgs; ++i)
186 ArgumentList[i] = List[i];
189 /// Arguments - The list of arguments for a function-like macro. This can be
190 /// empty, for, e.g. "#define X()".
191 typedef IdentifierInfo* const *arg_iterator;
192 bool arg_empty() const { return NumArguments == 0; }
193 arg_iterator arg_begin() const { return ArgumentList; }
194 arg_iterator arg_end() const { return ArgumentList+NumArguments; }
195 unsigned getNumArgs() const { return NumArguments; }
197 /// \brief Return the argument number of the specified identifier,
198 /// or -1 if the identifier is not a formal argument identifier.
199 int getArgumentNum(IdentifierInfo *Arg) const {
200 for (arg_iterator I = arg_begin(), E = arg_end(); I != E; ++I)
201 if (*I == Arg) return I-arg_begin();
205 /// Function/Object-likeness. Keep track of whether this macro has formal
207 void setIsFunctionLike() { IsFunctionLike = true; }
208 bool isFunctionLike() const { return IsFunctionLike; }
209 bool isObjectLike() const { return !IsFunctionLike; }
211 /// Varargs querying methods. This can only be set for function-like macros.
212 void setIsC99Varargs() { IsC99Varargs = true; }
213 void setIsGNUVarargs() { IsGNUVarargs = true; }
214 bool isC99Varargs() const { return IsC99Varargs; }
215 bool isGNUVarargs() const { return IsGNUVarargs; }
216 bool isVariadic() const { return IsC99Varargs | IsGNUVarargs; }
218 /// \brief Return true if this macro requires processing before expansion.
220 /// This is true only for builtin macro, such as \__LINE__, whose values
221 /// are not given by fixed textual expansions. Regular predefined macros
222 /// from the "<built-in>" buffer are not reported as builtins by this
224 bool isBuiltinMacro() const { return IsBuiltinMacro; }
226 bool hasCommaPasting() const { return HasCommaPasting; }
227 void setHasCommaPasting() { HasCommaPasting = true; }
229 /// \brief Return false if this macro is defined in the main file and has
230 /// not yet been used.
231 bool isUsed() const { return IsUsed; }
233 /// \brief Return true if this macro can be redefined without warning.
234 bool isAllowRedefinitionsWithoutWarning() const {
235 return IsAllowRedefinitionsWithoutWarning;
238 /// \brief Return true if we should emit a warning if the macro is unused.
239 bool isWarnIfUnused() const {
240 return IsWarnIfUnused;
243 /// \brief Return the number of tokens that this macro expands to.
245 unsigned getNumTokens() const {
246 return ReplacementTokens.size();
249 const Token &getReplacementToken(unsigned Tok) const {
250 assert(Tok < ReplacementTokens.size() && "Invalid token #");
251 return ReplacementTokens[Tok];
254 typedef SmallVector<Token, 8>::const_iterator tokens_iterator;
255 tokens_iterator tokens_begin() const { return ReplacementTokens.begin(); }
256 tokens_iterator tokens_end() const { return ReplacementTokens.end(); }
257 bool tokens_empty() const { return ReplacementTokens.empty(); }
259 /// \brief Add the specified token to the replacement text for the macro.
260 void AddTokenToBody(const Token &Tok) {
261 assert(!IsDefinitionLengthCached &&
262 "Changing replacement tokens after definition length got calculated");
263 ReplacementTokens.push_back(Tok);
266 /// \brief Return true if this macro is enabled.
268 /// In other words, that we are not currently in an expansion of this macro.
269 bool isEnabled() const { return !IsDisabled; }
272 assert(IsDisabled && "Cannot enable an already-enabled macro!");
276 void DisableMacro() {
277 assert(!IsDisabled && "Cannot disable an already-disabled macro!");
281 /// \brief Determine whether this macro info came from an AST file (such as
282 /// a precompiled header or module) rather than having been parsed.
283 bool isFromASTFile() const { return FromASTFile; }
285 /// \brief Retrieve the global ID of the module that owns this particular
287 unsigned getOwningModuleID() const {
289 return *(const unsigned*)(this+1);
295 unsigned getDefinitionLengthSlow(SourceManager &SM) const;
297 void setOwningModuleID(unsigned ID) {
298 assert(isFromASTFile());
299 *(unsigned*)(this+1) = ID;
302 friend class Preprocessor;
305 class DefMacroDirective;
307 /// \brief Encapsulates changes to the "macros namespace" (the location where
308 /// the macro name became active, the location where it was undefined, etc.).
310 /// MacroDirectives, associated with an identifier, are used to model the macro
311 /// history. Usually a macro definition (MacroInfo) is where a macro name
312 /// becomes active (MacroDirective) but modules can have their own macro
313 /// history, separate from the local (current translation unit) macro history.
315 /// For example, if "@import A;" imports macro FOO, there will be a new local
316 /// MacroDirective created to indicate that "FOO" became active at the import
317 /// location. Module "A" itself will contain another MacroDirective in its macro
318 /// history (at the point of the definition of FOO) and both MacroDirectives
319 /// will point to the same MacroInfo object.
321 class MacroDirective {
330 /// \brief Previous macro directive for the same identifier, or NULL.
331 MacroDirective *Previous;
335 /// \brief MacroDirective kind.
338 /// \brief True if the macro directive was loaded from a PCH file.
341 /// \brief Whether the macro directive is currently "hidden".
343 /// Note that this is transient state that is never serialized to the AST
347 // Used by DefMacroDirective -----------------------------------------------//
349 /// \brief True if this macro was imported from a module.
352 /// \brief Whether the definition of this macro is ambiguous, due to
353 /// multiple definitions coming in from multiple modules.
354 bool IsAmbiguous : 1;
356 // Used by VisibilityMacroDirective ----------------------------------------//
358 /// \brief Whether the macro has public visibility (when described in a
362 MacroDirective(Kind K, SourceLocation Loc)
363 : Previous(0), Loc(Loc), MDKind(K), IsFromPCH(false), IsHidden(false),
364 IsImported(false), IsAmbiguous(false),
369 Kind getKind() const { return Kind(MDKind); }
371 SourceLocation getLocation() const { return Loc; }
373 /// \brief Set previous definition of the macro with the same name.
374 void setPrevious(MacroDirective *Prev) {
378 /// \brief Get previous definition of the macro with the same name.
379 const MacroDirective *getPrevious() const { return Previous; }
381 /// \brief Get previous definition of the macro with the same name.
382 MacroDirective *getPrevious() { return Previous; }
384 /// \brief Return true if the macro directive was loaded from a PCH file.
385 bool isFromPCH() const { return IsFromPCH; }
387 void setIsFromPCH() { IsFromPCH = true; }
389 /// \brief Determine whether this macro directive is hidden.
390 bool isHidden() const { return IsHidden; }
392 /// \brief Set whether this macro directive is hidden.
393 void setHidden(bool Val) { IsHidden = Val; }
396 DefMacroDirective *DefDirective;
397 SourceLocation UndefLoc;
401 DefInfo() : DefDirective(0) { }
403 DefInfo(DefMacroDirective *DefDirective, SourceLocation UndefLoc,
405 : DefDirective(DefDirective), UndefLoc(UndefLoc), IsPublic(isPublic) { }
407 const DefMacroDirective *getDirective() const { return DefDirective; }
408 DefMacroDirective *getDirective() { return DefDirective; }
410 inline SourceLocation getLocation() const;
411 inline MacroInfo *getMacroInfo();
412 const MacroInfo *getMacroInfo() const {
413 return const_cast<DefInfo*>(this)->getMacroInfo();
416 SourceLocation getUndefLocation() const { return UndefLoc; }
417 bool isUndefined() const { return UndefLoc.isValid(); }
419 bool isPublic() const { return IsPublic; }
421 bool isValid() const { return DefDirective != 0; }
422 bool isInvalid() const { return !isValid(); }
424 operator bool() const { return isValid(); }
426 inline DefInfo getPreviousDefinition(bool AllowHidden = false);
427 const DefInfo getPreviousDefinition(bool AllowHidden = false) const {
428 return const_cast<DefInfo*>(this)->getPreviousDefinition(AllowHidden);
432 /// \brief Traverses the macro directives history and returns the next
433 /// macro definition directive along with info about its undefined location
434 /// (if there is one) and if it is public or private.
435 DefInfo getDefinition(bool AllowHidden = false);
436 const DefInfo getDefinition(bool AllowHidden = false) const {
437 return const_cast<MacroDirective*>(this)->getDefinition(AllowHidden);
440 bool isDefined(bool AllowHidden = false) const {
441 if (const DefInfo Def = getDefinition(AllowHidden))
442 return !Def.isUndefined();
446 const MacroInfo *getMacroInfo(bool AllowHidden = false) const {
447 return getDefinition(AllowHidden).getMacroInfo();
449 MacroInfo *getMacroInfo(bool AllowHidden = false) {
450 return getDefinition(AllowHidden).getMacroInfo();
453 /// \brief Find macro definition active in the specified source location. If
454 /// this macro was not defined there, return NULL.
455 const DefInfo findDirectiveAtLoc(SourceLocation L, SourceManager &SM) const;
457 static bool classof(const MacroDirective *) { return true; }
460 /// \brief A directive for a defined macro or a macro imported from a module.
461 class DefMacroDirective : public MacroDirective {
465 explicit DefMacroDirective(MacroInfo *MI)
466 : MacroDirective(MD_Define, MI->getDefinitionLoc()), Info(MI) {
467 assert(MI && "MacroInfo is null");
470 DefMacroDirective(MacroInfo *MI, SourceLocation Loc, bool isImported)
471 : MacroDirective(MD_Define, Loc), Info(MI) {
472 assert(MI && "MacroInfo is null");
473 IsImported = isImported;
476 /// \brief The data for the macro definition.
477 const MacroInfo *getInfo() const { return Info; }
478 MacroInfo *getInfo() { return Info; }
480 /// \brief True if this macro was imported from a module.
481 bool isImported() const { return IsImported; }
483 /// \brief Determine whether this macro definition is ambiguous with
484 /// other macro definitions.
485 bool isAmbiguous() const { return IsAmbiguous; }
487 /// \brief Set whether this macro definition is ambiguous.
488 void setAmbiguous(bool Val) { IsAmbiguous = Val; }
490 static bool classof(const MacroDirective *MD) {
491 return MD->getKind() == MD_Define;
493 static bool classof(const DefMacroDirective *) { return true; }
496 /// \brief A directive for an undefined macro.
497 class UndefMacroDirective : public MacroDirective {
499 explicit UndefMacroDirective(SourceLocation UndefLoc)
500 : MacroDirective(MD_Undefine, UndefLoc) {
501 assert(UndefLoc.isValid() && "Invalid UndefLoc!");
504 static bool classof(const MacroDirective *MD) {
505 return MD->getKind() == MD_Undefine;
507 static bool classof(const UndefMacroDirective *) { return true; }
510 /// \brief A directive for setting the module visibility of a macro.
511 class VisibilityMacroDirective : public MacroDirective {
513 explicit VisibilityMacroDirective(SourceLocation Loc, bool Public)
514 : MacroDirective(MD_Visibility, Loc) {
518 /// \brief Determine whether this macro is part of the public API of its
520 bool isPublic() const { return IsPublic; }
522 static bool classof(const MacroDirective *MD) {
523 return MD->getKind() == MD_Visibility;
525 static bool classof(const VisibilityMacroDirective *) { return true; }
528 inline SourceLocation MacroDirective::DefInfo::getLocation() const {
530 return SourceLocation();
531 return DefDirective->getLocation();
534 inline MacroInfo *MacroDirective::DefInfo::getMacroInfo() {
537 return DefDirective->getInfo();
540 inline MacroDirective::DefInfo
541 MacroDirective::DefInfo::getPreviousDefinition(bool AllowHidden) {
542 if (isInvalid() || DefDirective->getPrevious() == 0)
544 return DefDirective->getPrevious()->getDefinition(AllowHidden);
547 } // end namespace clang