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/FoldingSet.h"
21 #include "llvm/ADT/PointerIntPair.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/Support/Allocator.h"
31 /// \brief Encapsulates the data about a macro definition (e.g. its tokens).
33 /// There's an instance of this class for every #define.
35 //===--------------------------------------------------------------------===//
36 // State set when the macro is defined.
38 /// \brief The location the macro is defined.
39 SourceLocation Location;
40 /// \brief The location of the last token in the macro.
41 SourceLocation EndLocation;
43 /// \brief The list of arguments for a function-like macro.
45 /// ParameterList points to the first of NumParameters pointers.
47 /// This can be empty, for, e.g. "#define X()". In a C99-style variadic
48 /// macro, this includes the \c __VA_ARGS__ identifier on the list.
49 IdentifierInfo **ParameterList;
51 /// \see ParameterList
52 unsigned NumParameters;
54 /// \brief This is the list of tokens that the macro is defined to.
55 SmallVector<Token, 8> ReplacementTokens;
57 /// \brief Length in characters of the macro definition.
58 mutable unsigned DefinitionLength;
59 mutable bool IsDefinitionLengthCached : 1;
61 /// \brief True if this macro is function-like, false if it is object-like.
62 bool IsFunctionLike : 1;
64 /// \brief True if this macro is of the form "#define X(...)" or
65 /// "#define X(Y,Z,...)".
67 /// The __VA_ARGS__ token should be replaced with the contents of "..." in an
69 bool IsC99Varargs : 1;
71 /// \brief True if this macro is of the form "#define X(a...)".
73 /// The "a" identifier in the replacement list will be replaced with all
74 /// arguments of the macro starting with the specified one.
75 bool IsGNUVarargs : 1;
77 /// \brief True if this macro requires processing before expansion.
79 /// This is the case for builtin macros such as __LINE__, so long as they have
80 /// not been redefined, but not for regular predefined macros from the
81 /// "<built-in>" memory buffer (see Preprocessing::getPredefinesFileID).
82 bool IsBuiltinMacro : 1;
84 /// \brief Whether this macro contains the sequence ", ## __VA_ARGS__"
85 bool HasCommaPasting : 1;
87 //===--------------------------------------------------------------------===//
88 // State that changes as the macro is used.
90 /// \brief True if we have started an expansion of this macro already.
92 /// This disables recursive expansion, which would be quite bad for things
93 /// like \#define A A.
96 /// \brief True if this macro is either defined in the main file and has
97 /// been used, or if it is not defined in the main file.
99 /// This is used to emit -Wunused-macros diagnostics.
102 /// \brief True if this macro can be redefined without emitting a warning.
103 bool IsAllowRedefinitionsWithoutWarning : 1;
105 /// \brief Must warn if the macro is unused at the end of translation unit.
106 bool IsWarnIfUnused : 1;
108 /// \brief Whether this macro was used as header guard.
109 bool UsedForHeaderGuard : 1;
111 // Only the Preprocessor gets to create and destroy these.
112 MacroInfo(SourceLocation DefLoc);
113 ~MacroInfo() = default;
116 /// \brief Return the location that the macro was defined at.
117 SourceLocation getDefinitionLoc() const { return Location; }
119 /// \brief Set the location of the last token in the macro.
120 void setDefinitionEndLoc(SourceLocation EndLoc) { EndLocation = EndLoc; }
122 /// \brief Return the location of the last token in the macro.
123 SourceLocation getDefinitionEndLoc() const { return EndLocation; }
125 /// \brief Get length in characters of the macro definition.
126 unsigned getDefinitionLength(const SourceManager &SM) const {
127 if (IsDefinitionLengthCached)
128 return DefinitionLength;
129 return getDefinitionLengthSlow(SM);
132 /// \brief Return true if the specified macro definition is equal to
133 /// this macro in spelling, arguments, and whitespace.
135 /// \param Syntactically if true, the macro definitions can be identical even
136 /// if they use different identifiers for the function macro parameters.
137 /// Otherwise the comparison is lexical and this implements the rules in
139 bool isIdenticalTo(const MacroInfo &Other, Preprocessor &PP,
140 bool Syntactically) const;
142 /// \brief Set or clear the isBuiltinMacro flag.
143 void setIsBuiltinMacro(bool Val = true) { IsBuiltinMacro = Val; }
145 /// \brief Set the value of the IsUsed flag.
146 void setIsUsed(bool Val) { IsUsed = Val; }
148 /// \brief Set the value of the IsAllowRedefinitionsWithoutWarning flag.
149 void setIsAllowRedefinitionsWithoutWarning(bool Val) {
150 IsAllowRedefinitionsWithoutWarning = Val;
153 /// \brief Set the value of the IsWarnIfUnused flag.
154 void setIsWarnIfUnused(bool val) { IsWarnIfUnused = val; }
156 /// \brief Set the specified list of identifiers as the parameter list for
158 void setParameterList(ArrayRef<IdentifierInfo *> List,
159 llvm::BumpPtrAllocator &PPAllocator) {
160 assert(ParameterList == nullptr && NumParameters == 0 &&
161 "Parameter list already set!");
165 NumParameters = List.size();
166 ParameterList = PPAllocator.Allocate<IdentifierInfo *>(List.size());
167 std::copy(List.begin(), List.end(), ParameterList);
170 /// Parameters - The list of parameters for a function-like macro. This can
171 /// be empty, for, e.g. "#define X()".
172 typedef IdentifierInfo *const *param_iterator;
173 bool param_empty() const { return NumParameters == 0; }
174 param_iterator param_begin() const { return ParameterList; }
175 param_iterator param_end() const { return ParameterList + NumParameters; }
176 unsigned getNumParams() const { return NumParameters; }
177 ArrayRef<const IdentifierInfo *> params() const {
178 return ArrayRef<const IdentifierInfo *>(ParameterList, NumParameters);
181 /// \brief Return the parameter number of the specified identifier,
182 /// or -1 if the identifier is not a formal parameter identifier.
183 int getParameterNum(const IdentifierInfo *Arg) const {
184 for (param_iterator I = param_begin(), E = param_end(); I != E; ++I)
186 return I - param_begin();
190 /// Function/Object-likeness. Keep track of whether this macro has formal
192 void setIsFunctionLike() { IsFunctionLike = true; }
193 bool isFunctionLike() const { return IsFunctionLike; }
194 bool isObjectLike() const { return !IsFunctionLike; }
196 /// Varargs querying methods. This can only be set for function-like macros.
197 void setIsC99Varargs() { IsC99Varargs = true; }
198 void setIsGNUVarargs() { IsGNUVarargs = true; }
199 bool isC99Varargs() const { return IsC99Varargs; }
200 bool isGNUVarargs() const { return IsGNUVarargs; }
201 bool isVariadic() const { return IsC99Varargs | IsGNUVarargs; }
203 /// \brief Return true if this macro requires processing before expansion.
205 /// This is true only for builtin macro, such as \__LINE__, whose values
206 /// are not given by fixed textual expansions. Regular predefined macros
207 /// from the "<built-in>" buffer are not reported as builtins by this
209 bool isBuiltinMacro() const { return IsBuiltinMacro; }
211 bool hasCommaPasting() const { return HasCommaPasting; }
212 void setHasCommaPasting() { HasCommaPasting = true; }
214 /// \brief Return false if this macro is defined in the main file and has
215 /// not yet been used.
216 bool isUsed() const { return IsUsed; }
218 /// \brief Return true if this macro can be redefined without warning.
219 bool isAllowRedefinitionsWithoutWarning() const {
220 return IsAllowRedefinitionsWithoutWarning;
223 /// \brief Return true if we should emit a warning if the macro is unused.
224 bool isWarnIfUnused() const { return IsWarnIfUnused; }
226 /// \brief Return the number of tokens that this macro expands to.
228 unsigned getNumTokens() const { return ReplacementTokens.size(); }
230 const Token &getReplacementToken(unsigned Tok) const {
231 assert(Tok < ReplacementTokens.size() && "Invalid token #");
232 return ReplacementTokens[Tok];
235 typedef SmallVectorImpl<Token>::const_iterator tokens_iterator;
236 tokens_iterator tokens_begin() const { return ReplacementTokens.begin(); }
237 tokens_iterator tokens_end() const { return ReplacementTokens.end(); }
238 bool tokens_empty() const { return ReplacementTokens.empty(); }
239 ArrayRef<Token> tokens() const { return ReplacementTokens; }
241 /// \brief Add the specified token to the replacement text for the macro.
242 void AddTokenToBody(const Token &Tok) {
244 !IsDefinitionLengthCached &&
245 "Changing replacement tokens after definition length got calculated");
246 ReplacementTokens.push_back(Tok);
249 /// \brief Return true if this macro is enabled.
251 /// In other words, that we are not currently in an expansion of this macro.
252 bool isEnabled() const { return !IsDisabled; }
255 assert(IsDisabled && "Cannot enable an already-enabled macro!");
259 void DisableMacro() {
260 assert(!IsDisabled && "Cannot disable an already-disabled macro!");
264 /// \brief Determine whether this macro was used for a header guard.
265 bool isUsedForHeaderGuard() const { return UsedForHeaderGuard; }
267 void setUsedForHeaderGuard(bool Val) { UsedForHeaderGuard = Val; }
272 unsigned getDefinitionLengthSlow(const SourceManager &SM) const;
274 friend class Preprocessor;
277 class DefMacroDirective;
279 /// \brief Encapsulates changes to the "macros namespace" (the location where
280 /// the macro name became active, the location where it was undefined, etc.).
282 /// MacroDirectives, associated with an identifier, are used to model the macro
283 /// history. Usually a macro definition (MacroInfo) is where a macro name
284 /// becomes active (MacroDirective) but #pragma push_macro / pop_macro can
285 /// create additional DefMacroDirectives for the same MacroInfo.
286 class MacroDirective {
288 enum Kind { MD_Define, MD_Undefine, MD_Visibility };
291 /// \brief Previous macro directive for the same identifier, or NULL.
292 MacroDirective *Previous;
296 /// \brief MacroDirective kind.
299 /// \brief True if the macro directive was loaded from a PCH file.
300 unsigned IsFromPCH : 1;
302 // Used by VisibilityMacroDirective ----------------------------------------//
304 /// \brief Whether the macro has public visibility (when described in a
306 unsigned IsPublic : 1;
308 MacroDirective(Kind K, SourceLocation Loc)
309 : Previous(nullptr), Loc(Loc), MDKind(K), IsFromPCH(false),
313 Kind getKind() const { return Kind(MDKind); }
315 SourceLocation getLocation() const { return Loc; }
317 /// \brief Set previous definition of the macro with the same name.
318 void setPrevious(MacroDirective *Prev) { Previous = Prev; }
320 /// \brief Get previous definition of the macro with the same name.
321 const MacroDirective *getPrevious() const { return Previous; }
323 /// \brief Get previous definition of the macro with the same name.
324 MacroDirective *getPrevious() { return Previous; }
326 /// \brief Return true if the macro directive was loaded from a PCH file.
327 bool isFromPCH() const { return IsFromPCH; }
329 void setIsFromPCH() { IsFromPCH = true; }
332 DefMacroDirective *DefDirective;
333 SourceLocation UndefLoc;
337 DefInfo() : DefDirective(nullptr), IsPublic(true) {}
339 DefInfo(DefMacroDirective *DefDirective, SourceLocation UndefLoc,
341 : DefDirective(DefDirective), UndefLoc(UndefLoc), IsPublic(isPublic) {}
343 const DefMacroDirective *getDirective() const { return DefDirective; }
344 DefMacroDirective *getDirective() { return DefDirective; }
346 inline SourceLocation getLocation() const;
347 inline MacroInfo *getMacroInfo();
348 const MacroInfo *getMacroInfo() const {
349 return const_cast<DefInfo *>(this)->getMacroInfo();
352 SourceLocation getUndefLocation() const { return UndefLoc; }
353 bool isUndefined() const { return UndefLoc.isValid(); }
355 bool isPublic() const { return IsPublic; }
357 bool isValid() const { return DefDirective != nullptr; }
358 bool isInvalid() const { return !isValid(); }
360 explicit operator bool() const { return isValid(); }
362 inline DefInfo getPreviousDefinition();
363 const DefInfo getPreviousDefinition() const {
364 return const_cast<DefInfo *>(this)->getPreviousDefinition();
368 /// \brief Traverses the macro directives history and returns the next
369 /// macro definition directive along with info about its undefined location
370 /// (if there is one) and if it is public or private.
371 DefInfo getDefinition();
372 const DefInfo getDefinition() const {
373 return const_cast<MacroDirective *>(this)->getDefinition();
376 bool isDefined() const {
377 if (const DefInfo Def = getDefinition())
378 return !Def.isUndefined();
382 const MacroInfo *getMacroInfo() const {
383 return getDefinition().getMacroInfo();
385 MacroInfo *getMacroInfo() { return getDefinition().getMacroInfo(); }
387 /// \brief Find macro definition active in the specified source location. If
388 /// this macro was not defined there, return NULL.
389 const DefInfo findDirectiveAtLoc(SourceLocation L, SourceManager &SM) const;
393 static bool classof(const MacroDirective *) { return true; }
396 /// \brief A directive for a defined macro or a macro imported from a module.
397 class DefMacroDirective : public MacroDirective {
401 DefMacroDirective(MacroInfo *MI, SourceLocation Loc)
402 : MacroDirective(MD_Define, Loc), Info(MI) {
403 assert(MI && "MacroInfo is null");
405 explicit DefMacroDirective(MacroInfo *MI)
406 : DefMacroDirective(MI, MI->getDefinitionLoc()) {}
408 /// \brief The data for the macro definition.
409 const MacroInfo *getInfo() const { return Info; }
410 MacroInfo *getInfo() { return Info; }
412 static bool classof(const MacroDirective *MD) {
413 return MD->getKind() == MD_Define;
415 static bool classof(const DefMacroDirective *) { return true; }
418 /// \brief A directive for an undefined macro.
419 class UndefMacroDirective : public MacroDirective {
421 explicit UndefMacroDirective(SourceLocation UndefLoc)
422 : MacroDirective(MD_Undefine, UndefLoc) {
423 assert(UndefLoc.isValid() && "Invalid UndefLoc!");
426 static bool classof(const MacroDirective *MD) {
427 return MD->getKind() == MD_Undefine;
429 static bool classof(const UndefMacroDirective *) { return true; }
432 /// \brief A directive for setting the module visibility of a macro.
433 class VisibilityMacroDirective : public MacroDirective {
435 explicit VisibilityMacroDirective(SourceLocation Loc, bool Public)
436 : MacroDirective(MD_Visibility, Loc) {
440 /// \brief Determine whether this macro is part of the public API of its
442 bool isPublic() const { return IsPublic; }
444 static bool classof(const MacroDirective *MD) {
445 return MD->getKind() == MD_Visibility;
447 static bool classof(const VisibilityMacroDirective *) { return true; }
450 inline SourceLocation MacroDirective::DefInfo::getLocation() const {
452 return SourceLocation();
453 return DefDirective->getLocation();
456 inline MacroInfo *MacroDirective::DefInfo::getMacroInfo() {
459 return DefDirective->getInfo();
462 inline MacroDirective::DefInfo
463 MacroDirective::DefInfo::getPreviousDefinition() {
464 if (isInvalid() || DefDirective->getPrevious() == nullptr)
466 return DefDirective->getPrevious()->getDefinition();
469 /// \brief Represents a macro directive exported by a module.
471 /// There's an instance of this class for every macro #define or #undef that is
472 /// the final directive for a macro name within a module. These entities also
473 /// represent the macro override graph.
475 /// These are stored in a FoldingSet in the preprocessor.
476 class ModuleMacro : public llvm::FoldingSetNode {
477 /// The name defined by the macro.
479 /// The body of the #define, or nullptr if this is a #undef.
481 /// The module that exports this macro.
482 Module *OwningModule;
483 /// The number of module macros that override this one.
484 unsigned NumOverriddenBy;
485 /// The number of modules whose macros are directly overridden by this one.
486 unsigned NumOverrides;
487 // ModuleMacro *OverriddenMacros[NumOverrides];
489 friend class Preprocessor;
491 ModuleMacro(Module *OwningModule, IdentifierInfo *II, MacroInfo *Macro,
492 ArrayRef<ModuleMacro *> Overrides)
493 : II(II), Macro(Macro), OwningModule(OwningModule), NumOverriddenBy(0),
494 NumOverrides(Overrides.size()) {
495 std::copy(Overrides.begin(), Overrides.end(),
496 reinterpret_cast<ModuleMacro **>(this + 1));
500 static ModuleMacro *create(Preprocessor &PP, Module *OwningModule,
501 IdentifierInfo *II, MacroInfo *Macro,
502 ArrayRef<ModuleMacro *> Overrides);
504 void Profile(llvm::FoldingSetNodeID &ID) const {
505 return Profile(ID, OwningModule, II);
507 static void Profile(llvm::FoldingSetNodeID &ID, Module *OwningModule,
508 IdentifierInfo *II) {
509 ID.AddPointer(OwningModule);
513 /// Get the ID of the module that exports this macro.
514 Module *getOwningModule() const { return OwningModule; }
516 /// Get definition for this exported #define, or nullptr if this
517 /// represents a #undef.
518 MacroInfo *getMacroInfo() const { return Macro; }
520 /// Iterators over the overridden module IDs.
522 typedef ModuleMacro *const *overrides_iterator;
523 overrides_iterator overrides_begin() const {
524 return reinterpret_cast<overrides_iterator>(this + 1);
526 overrides_iterator overrides_end() const {
527 return overrides_begin() + NumOverrides;
529 ArrayRef<ModuleMacro *> overrides() const {
530 return llvm::makeArrayRef(overrides_begin(), overrides_end());
534 /// Get the number of macros that override this one.
535 unsigned getNumOverridingMacros() const { return NumOverriddenBy; }
538 /// \brief A description of the current definition of a macro.
540 /// The definition of a macro comprises a set of (at least one) defining
541 /// entities, which are either local MacroDirectives or imported ModuleMacros.
542 class MacroDefinition {
543 llvm::PointerIntPair<DefMacroDirective *, 1, bool> LatestLocalAndAmbiguous;
544 ArrayRef<ModuleMacro *> ModuleMacros;
547 MacroDefinition() : LatestLocalAndAmbiguous(), ModuleMacros() {}
548 MacroDefinition(DefMacroDirective *MD, ArrayRef<ModuleMacro *> MMs,
550 : LatestLocalAndAmbiguous(MD, IsAmbiguous), ModuleMacros(MMs) {}
552 /// \brief Determine whether there is a definition of this macro.
553 explicit operator bool() const {
554 return getLocalDirective() || !ModuleMacros.empty();
557 /// \brief Get the MacroInfo that should be used for this definition.
558 MacroInfo *getMacroInfo() const {
559 if (!ModuleMacros.empty())
560 return ModuleMacros.back()->getMacroInfo();
561 if (auto *MD = getLocalDirective())
562 return MD->getMacroInfo();
566 /// \brief \c true if the definition is ambiguous, \c false otherwise.
567 bool isAmbiguous() const { return LatestLocalAndAmbiguous.getInt(); }
569 /// \brief Get the latest non-imported, non-\#undef'd macro definition
571 DefMacroDirective *getLocalDirective() const {
572 return LatestLocalAndAmbiguous.getPointer();
575 /// \brief Get the active module macros for this macro.
576 ArrayRef<ModuleMacro *> getModuleMacros() const { return ModuleMacros; }
578 template <typename Fn> void forAllDefinitions(Fn F) const {
579 if (auto *MD = getLocalDirective())
580 F(MD->getMacroInfo());
581 for (auto *MM : getModuleMacros())
582 F(MM->getMacroInfo());
586 } // end namespace clang