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_LEX_MACROINFO_H
16 #define LLVM_CLANG_LEX_MACROINFO_H
18 #include "clang/Lex/Token.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Support/Allocator.h"
27 /// \brief Encapsulates the data about a macro definition (e.g. its tokens).
29 /// There's an instance of this class for every #define.
31 //===--------------------------------------------------------------------===//
32 // State set when the macro is defined.
34 /// \brief The location the macro is defined.
35 SourceLocation Location;
36 /// \brief The location of the last token in the macro.
37 SourceLocation EndLocation;
39 /// \brief The list of arguments for a function-like macro.
41 /// ArgumentList points to the first of NumArguments pointers.
43 /// This can be empty, for, e.g. "#define X()". In a C99-style variadic macro, this
44 /// includes the \c __VA_ARGS__ identifier on the list.
45 IdentifierInfo **ArgumentList;
48 unsigned NumArguments;
50 /// \brief This is the list of tokens that the macro is defined to.
51 SmallVector<Token, 8> ReplacementTokens;
53 /// \brief Length in characters of the macro definition.
54 mutable unsigned DefinitionLength;
55 mutable bool IsDefinitionLengthCached : 1;
57 /// \brief True if this macro is function-like, false if it is object-like.
58 bool IsFunctionLike : 1;
60 /// \brief True if this macro is of the form "#define X(...)" or
61 /// "#define X(Y,Z,...)".
63 /// The __VA_ARGS__ token should be replaced with the contents of "..." in an
65 bool IsC99Varargs : 1;
67 /// \brief True if this macro is of the form "#define X(a...)".
69 /// The "a" identifier in the replacement list will be replaced with all arguments
70 /// of the macro starting with the specified one.
71 bool IsGNUVarargs : 1;
73 /// \brief True if this macro requires processing before expansion.
75 /// This is the case for builtin macros such as __LINE__, so long as they have
76 /// not been redefined, but not for regular predefined macros from the "<built-in>"
77 /// memory buffer (see Preprocessing::getPredefinesFileID).
78 bool IsBuiltinMacro : 1;
80 /// \brief Whether this macro contains the sequence ", ## __VA_ARGS__"
81 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;
107 /// \brief Whether this macro was used as header guard.
108 bool UsedForHeaderGuard : 1;
110 // Only the Preprocessor gets to create and destroy these.
111 MacroInfo(SourceLocation DefLoc);
115 /// \brief Return the location that the macro was defined at.
116 SourceLocation getDefinitionLoc() const { return Location; }
118 /// \brief Set the location of the last token in the macro.
119 void setDefinitionEndLoc(SourceLocation EndLoc) { EndLocation = EndLoc; }
121 /// \brief Return the location of the last token in the macro.
122 SourceLocation getDefinitionEndLoc() const { return EndLocation; }
124 /// \brief Get length in characters of the macro definition.
125 unsigned getDefinitionLength(SourceManager &SM) const {
126 if (IsDefinitionLengthCached)
127 return DefinitionLength;
128 return getDefinitionLengthSlow(SM);
131 /// \brief Return true if the specified macro definition is equal to
132 /// this macro in spelling, arguments, and whitespace.
134 /// \param Syntactically if true, the macro definitions can be identical even
135 /// if they use different identifiers for the function macro parameters.
136 /// Otherwise the comparison is lexical and this implements the rules in
138 bool isIdenticalTo(const MacroInfo &Other, Preprocessor &PP,
139 bool Syntactically) const;
141 /// \brief Set or clear the isBuiltinMacro flag.
142 void setIsBuiltinMacro(bool Val = true) {
143 IsBuiltinMacro = Val;
146 /// \brief Set the value of the IsUsed flag.
147 void setIsUsed(bool Val) {
151 /// \brief Set the value of the IsAllowRedefinitionsWithoutWarning flag.
152 void setIsAllowRedefinitionsWithoutWarning(bool Val) {
153 IsAllowRedefinitionsWithoutWarning = Val;
156 /// \brief Set the value of the IsWarnIfUnused flag.
157 void setIsWarnIfUnused(bool val) {
158 IsWarnIfUnused = val;
161 /// \brief Set the specified list of identifiers as the argument list for
163 void setArgumentList(IdentifierInfo* const *List, unsigned NumArgs,
164 llvm::BumpPtrAllocator &PPAllocator) {
165 assert(ArgumentList == nullptr && NumArguments == 0 &&
166 "Argument list already set!");
167 if (NumArgs == 0) return;
169 NumArguments = NumArgs;
170 ArgumentList = PPAllocator.Allocate<IdentifierInfo*>(NumArgs);
171 for (unsigned i = 0; i != NumArgs; ++i)
172 ArgumentList[i] = List[i];
175 /// Arguments - The list of arguments for a function-like macro. This can be
176 /// empty, for, e.g. "#define X()".
177 typedef IdentifierInfo* const *arg_iterator;
178 bool arg_empty() const { return NumArguments == 0; }
179 arg_iterator arg_begin() const { return ArgumentList; }
180 arg_iterator arg_end() const { return ArgumentList+NumArguments; }
181 unsigned getNumArgs() const { return NumArguments; }
183 /// \brief Return the argument number of the specified identifier,
184 /// or -1 if the identifier is not a formal argument identifier.
185 int getArgumentNum(IdentifierInfo *Arg) const {
186 for (arg_iterator I = arg_begin(), E = arg_end(); I != E; ++I)
187 if (*I == Arg) return I-arg_begin();
191 /// Function/Object-likeness. Keep track of whether this macro has formal
193 void setIsFunctionLike() { IsFunctionLike = true; }
194 bool isFunctionLike() const { return IsFunctionLike; }
195 bool isObjectLike() const { return !IsFunctionLike; }
197 /// Varargs querying methods. This can only be set for function-like macros.
198 void setIsC99Varargs() { IsC99Varargs = true; }
199 void setIsGNUVarargs() { IsGNUVarargs = true; }
200 bool isC99Varargs() const { return IsC99Varargs; }
201 bool isGNUVarargs() const { return IsGNUVarargs; }
202 bool isVariadic() const { return IsC99Varargs | IsGNUVarargs; }
204 /// \brief Return true if this macro requires processing before expansion.
206 /// This is true only for builtin macro, such as \__LINE__, whose values
207 /// are not given by fixed textual expansions. Regular predefined macros
208 /// from the "<built-in>" buffer are not reported as builtins by this
210 bool isBuiltinMacro() const { return IsBuiltinMacro; }
212 bool hasCommaPasting() const { return HasCommaPasting; }
213 void setHasCommaPasting() { HasCommaPasting = true; }
215 /// \brief Return false if this macro is defined in the main file and has
216 /// not yet been used.
217 bool isUsed() const { return IsUsed; }
219 /// \brief Return true if this macro can be redefined without warning.
220 bool isAllowRedefinitionsWithoutWarning() const {
221 return IsAllowRedefinitionsWithoutWarning;
224 /// \brief Return true if we should emit a warning if the macro is unused.
225 bool isWarnIfUnused() const {
226 return IsWarnIfUnused;
229 /// \brief Return the number of tokens that this macro expands to.
231 unsigned getNumTokens() const {
232 return ReplacementTokens.size();
235 const Token &getReplacementToken(unsigned Tok) const {
236 assert(Tok < ReplacementTokens.size() && "Invalid token #");
237 return ReplacementTokens[Tok];
240 typedef SmallVectorImpl<Token>::const_iterator tokens_iterator;
241 tokens_iterator tokens_begin() const { return ReplacementTokens.begin(); }
242 tokens_iterator tokens_end() const { return ReplacementTokens.end(); }
243 bool tokens_empty() const { return ReplacementTokens.empty(); }
245 /// \brief Add the specified token to the replacement text for the macro.
246 void AddTokenToBody(const Token &Tok) {
247 assert(!IsDefinitionLengthCached &&
248 "Changing replacement tokens after definition length got calculated");
249 ReplacementTokens.push_back(Tok);
252 /// \brief Return true if this macro is enabled.
254 /// In other words, that we are not currently in an expansion of this macro.
255 bool isEnabled() const { return !IsDisabled; }
258 assert(IsDisabled && "Cannot enable an already-enabled macro!");
262 void DisableMacro() {
263 assert(!IsDisabled && "Cannot disable an already-disabled macro!");
267 /// \brief Determine whether this macro info came from an AST file (such as
268 /// a precompiled header or module) rather than having been parsed.
269 bool isFromASTFile() const { return FromASTFile; }
271 /// \brief Determine whether this macro was used for a header guard.
272 bool isUsedForHeaderGuard() const { return UsedForHeaderGuard; }
274 void setUsedForHeaderGuard(bool Val) { UsedForHeaderGuard = Val; }
276 /// \brief Retrieve the global ID of the module that owns this particular
278 unsigned getOwningModuleID() const {
280 return *(const unsigned*)(this+1);
288 unsigned getDefinitionLengthSlow(SourceManager &SM) const;
290 void setOwningModuleID(unsigned ID) {
291 assert(isFromASTFile());
292 *(unsigned*)(this+1) = ID;
295 friend class Preprocessor;
298 class DefMacroDirective;
300 /// \brief Encapsulates changes to the "macros namespace" (the location where
301 /// the macro name became active, the location where it was undefined, etc.).
303 /// MacroDirectives, associated with an identifier, are used to model the macro
304 /// history. Usually a macro definition (MacroInfo) is where a macro name
305 /// becomes active (MacroDirective) but modules can have their own macro
306 /// history, separate from the local (current translation unit) macro history.
308 /// For example, if "@import A;" imports macro FOO, there will be a new local
309 /// MacroDirective created to indicate that "FOO" became active at the import
310 /// location. Module "A" itself will contain another MacroDirective in its macro
311 /// history (at the point of the definition of FOO) and both MacroDirectives
312 /// will point to the same MacroInfo object.
314 class MacroDirective {
323 /// \brief Previous macro directive for the same identifier, or NULL.
324 MacroDirective *Previous;
328 /// \brief MacroDirective kind.
331 /// \brief True if the macro directive was loaded from a PCH file.
334 // Used by DefMacroDirective -----------------------------------------------//
336 /// \brief Whether the definition of this macro is ambiguous, due to
337 /// multiple definitions coming in from multiple modules.
338 bool IsAmbiguous : 1;
340 // Used by VisibilityMacroDirective ----------------------------------------//
342 /// \brief Whether the macro has public visibility (when described in a
346 // Used by DefMacroDirective and UndefMacroDirective -----------------------//
348 /// \brief True if this macro was imported from a module.
351 /// \brief For an imported directive, the number of modules whose macros are
352 /// overridden by this directive. Only used if IsImported.
353 unsigned NumOverrides : 26;
355 unsigned *getModuleDataStart();
356 const unsigned *getModuleDataStart() const {
357 return const_cast<MacroDirective*>(this)->getModuleDataStart();
360 MacroDirective(Kind K, SourceLocation Loc,
361 unsigned ImportedFromModuleID = 0,
362 ArrayRef<unsigned> Overrides = None)
363 : Previous(nullptr), Loc(Loc), MDKind(K), IsFromPCH(false),
364 IsAmbiguous(false), IsPublic(true), IsImported(ImportedFromModuleID),
365 NumOverrides(Overrides.size()) {
366 assert(NumOverrides == Overrides.size() && "too many overrides");
367 assert((IsImported || !NumOverrides) && "overrides for non-module macro");
370 unsigned *Extra = getModuleDataStart();
371 *Extra++ = ImportedFromModuleID;
372 std::copy(Overrides.begin(), Overrides.end(), Extra);
377 Kind getKind() const { return Kind(MDKind); }
379 SourceLocation getLocation() const { return Loc; }
381 /// \brief Set previous definition of the macro with the same name.
382 void setPrevious(MacroDirective *Prev) {
386 /// \brief Get previous definition of the macro with the same name.
387 const MacroDirective *getPrevious() const { return Previous; }
389 /// \brief Get previous definition of the macro with the same name.
390 MacroDirective *getPrevious() { return Previous; }
392 /// \brief Return true if the macro directive was loaded from a PCH file.
393 bool isFromPCH() const { return IsFromPCH; }
395 void setIsFromPCH() { IsFromPCH = true; }
397 /// \brief True if this macro was imported from a module.
398 /// Note that this is never the case for a VisibilityMacroDirective.
399 bool isImported() const { return IsImported; }
401 /// \brief If this directive was imported from a module, get the submodule
402 /// whose directive this is. Note that this may be different from the module
403 /// that owns the MacroInfo for a DefMacroDirective due to #pragma pop_macro
404 /// and similar effects.
405 unsigned getOwningModuleID() const {
407 return *getModuleDataStart();
411 /// \brief Get the module IDs of modules whose macros are overridden by this
412 /// directive. Only valid if this is an imported directive.
413 ArrayRef<unsigned> getOverriddenModules() const {
414 assert(IsImported && "can only get overridden modules for imported macro");
415 return llvm::makeArrayRef(getModuleDataStart() + 1, NumOverrides);
419 DefMacroDirective *DefDirective;
420 SourceLocation UndefLoc;
424 DefInfo() : DefDirective(nullptr) { }
426 DefInfo(DefMacroDirective *DefDirective, SourceLocation UndefLoc,
428 : DefDirective(DefDirective), UndefLoc(UndefLoc), IsPublic(isPublic) { }
430 const DefMacroDirective *getDirective() const { return DefDirective; }
431 DefMacroDirective *getDirective() { return DefDirective; }
433 inline SourceLocation getLocation() const;
434 inline MacroInfo *getMacroInfo();
435 const MacroInfo *getMacroInfo() const {
436 return const_cast<DefInfo*>(this)->getMacroInfo();
439 SourceLocation getUndefLocation() const { return UndefLoc; }
440 bool isUndefined() const { return UndefLoc.isValid(); }
442 bool isPublic() const { return IsPublic; }
444 bool isValid() const { return DefDirective != nullptr; }
445 bool isInvalid() const { return !isValid(); }
447 LLVM_EXPLICIT operator bool() const { return isValid(); }
449 inline DefInfo getPreviousDefinition();
450 const DefInfo getPreviousDefinition() const {
451 return const_cast<DefInfo*>(this)->getPreviousDefinition();
455 /// \brief Traverses the macro directives history and returns the next
456 /// macro definition directive along with info about its undefined location
457 /// (if there is one) and if it is public or private.
458 DefInfo getDefinition();
459 const DefInfo getDefinition() const {
460 return const_cast<MacroDirective*>(this)->getDefinition();
463 bool isDefined() const {
464 if (const DefInfo Def = getDefinition())
465 return !Def.isUndefined();
469 const MacroInfo *getMacroInfo() const {
470 return getDefinition().getMacroInfo();
472 MacroInfo *getMacroInfo() {
473 return getDefinition().getMacroInfo();
476 /// \brief Find macro definition active in the specified source location. If
477 /// this macro was not defined there, return NULL.
478 const DefInfo findDirectiveAtLoc(SourceLocation L, SourceManager &SM) const;
482 static bool classof(const MacroDirective *) { return true; }
485 /// \brief A directive for a defined macro or a macro imported from a module.
486 class DefMacroDirective : public MacroDirective {
490 explicit DefMacroDirective(MacroInfo *MI)
491 : MacroDirective(MD_Define, MI->getDefinitionLoc()), Info(MI) {
492 assert(MI && "MacroInfo is null");
495 DefMacroDirective(MacroInfo *MI, SourceLocation Loc,
496 unsigned ImportedFromModuleID = 0,
497 ArrayRef<unsigned> Overrides = None)
498 : MacroDirective(MD_Define, Loc, ImportedFromModuleID, Overrides),
500 assert(MI && "MacroInfo is null");
503 /// \brief The data for the macro definition.
504 const MacroInfo *getInfo() const { return Info; }
505 MacroInfo *getInfo() { return Info; }
507 /// \brief Determine whether this macro definition is ambiguous with
508 /// other macro definitions.
509 bool isAmbiguous() const { return IsAmbiguous; }
511 /// \brief Set whether this macro definition is ambiguous.
512 void setAmbiguous(bool Val) { IsAmbiguous = Val; }
514 static bool classof(const MacroDirective *MD) {
515 return MD->getKind() == MD_Define;
517 static bool classof(const DefMacroDirective *) { return true; }
520 /// \brief A directive for an undefined macro.
521 class UndefMacroDirective : public MacroDirective {
523 explicit UndefMacroDirective(SourceLocation UndefLoc,
524 unsigned ImportedFromModuleID = 0,
525 ArrayRef<unsigned> Overrides = None)
526 : MacroDirective(MD_Undefine, UndefLoc, ImportedFromModuleID, Overrides) {
527 assert((UndefLoc.isValid() || ImportedFromModuleID) && "Invalid UndefLoc!");
530 static bool classof(const MacroDirective *MD) {
531 return MD->getKind() == MD_Undefine;
533 static bool classof(const UndefMacroDirective *) { return true; }
536 /// \brief A directive for setting the module visibility of a macro.
537 class VisibilityMacroDirective : public MacroDirective {
539 explicit VisibilityMacroDirective(SourceLocation Loc, bool Public)
540 : MacroDirective(MD_Visibility, Loc) {
544 /// \brief Determine whether this macro is part of the public API of its
546 bool isPublic() const { return IsPublic; }
548 static bool classof(const MacroDirective *MD) {
549 return MD->getKind() == MD_Visibility;
551 static bool classof(const VisibilityMacroDirective *) { return true; }
554 inline unsigned *MacroDirective::getModuleDataStart() {
555 if (auto *Def = dyn_cast<DefMacroDirective>(this))
556 return reinterpret_cast<unsigned*>(Def + 1);
558 return reinterpret_cast<unsigned*>(cast<UndefMacroDirective>(this) + 1);
561 inline SourceLocation MacroDirective::DefInfo::getLocation() const {
563 return SourceLocation();
564 return DefDirective->getLocation();
567 inline MacroInfo *MacroDirective::DefInfo::getMacroInfo() {
570 return DefDirective->getInfo();
573 inline MacroDirective::DefInfo
574 MacroDirective::DefInfo::getPreviousDefinition() {
575 if (isInvalid() || DefDirective->getPrevious() == nullptr)
577 return DefDirective->getPrevious()->getDefinition();
580 } // end namespace clang