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
23 namespace 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.
29 class 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
82 private:
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
~MacroInfo()107 ~MacroInfo() {
108 assert(ArgumentList == 0 && "Didn't call destroy before dtor!");
109 }
110
111 public:
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.
FreeArgumentList()118 void FreeArgumentList() {
119 ArgumentList = 0;
120 NumArguments = 0;
121 }
122
123 /// \brief Destroy this MacroInfo object.
Destroy()124 void Destroy() {
125 FreeArgumentList();
126 this->~MacroInfo();
127 }
128
129 /// \brief Return the location that the macro was defined at.
getDefinitionLoc()130 SourceLocation getDefinitionLoc() const { return Location; }
131
132 /// \brief Set the location of the last token in the macro.
setDefinitionEndLoc(SourceLocation EndLoc)133 void setDefinitionEndLoc(SourceLocation EndLoc) { EndLocation = EndLoc; }
134
135 /// \brief Return the location of the last token in the macro.
getDefinitionEndLoc()136 SourceLocation getDefinitionEndLoc() const { return EndLocation; }
137
138 /// \brief Get length in characters of the macro definition.
getDefinitionLength(SourceManager & SM)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 /// \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
151 /// C99 6.10.3.
152 bool isIdenticalTo(const MacroInfo &Other, Preprocessor &PP,
153 bool Syntactically) const;
154
155 /// \brief Set or clear the isBuiltinMacro flag.
156 void setIsBuiltinMacro(bool Val = true) {
157 IsBuiltinMacro = Val;
158 }
159
160 /// \brief Set the value of the IsUsed flag.
setIsUsed(bool Val)161 void setIsUsed(bool Val) {
162 IsUsed = Val;
163 }
164
165 /// \brief Set the value of the IsAllowRedefinitionsWithoutWarning flag.
setIsAllowRedefinitionsWithoutWarning(bool Val)166 void setIsAllowRedefinitionsWithoutWarning(bool Val) {
167 IsAllowRedefinitionsWithoutWarning = Val;
168 }
169
170 /// \brief Set the value of the IsWarnIfUnused flag.
setIsWarnIfUnused(bool val)171 void setIsWarnIfUnused(bool val) {
172 IsWarnIfUnused = val;
173 }
174
175 /// \brief Set the specified list of identifiers as the argument list for
176 /// this macro.
setArgumentList(IdentifierInfo * const * List,unsigned NumArgs,llvm::BumpPtrAllocator & PPAllocator)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;
182
183 NumArguments = NumArgs;
184 ArgumentList = PPAllocator.Allocate<IdentifierInfo*>(NumArgs);
185 for (unsigned i = 0; i != NumArgs; ++i)
186 ArgumentList[i] = List[i];
187 }
188
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;
arg_empty()192 bool arg_empty() const { return NumArguments == 0; }
arg_begin()193 arg_iterator arg_begin() const { return ArgumentList; }
arg_end()194 arg_iterator arg_end() const { return ArgumentList+NumArguments; }
getNumArgs()195 unsigned getNumArgs() const { return NumArguments; }
196
197 /// \brief Return the argument number of the specified identifier,
198 /// or -1 if the identifier is not a formal argument identifier.
getArgumentNum(IdentifierInfo * Arg)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();
202 return -1;
203 }
204
205 /// Function/Object-likeness. Keep track of whether this macro has formal
206 /// parameters.
setIsFunctionLike()207 void setIsFunctionLike() { IsFunctionLike = true; }
isFunctionLike()208 bool isFunctionLike() const { return IsFunctionLike; }
isObjectLike()209 bool isObjectLike() const { return !IsFunctionLike; }
210
211 /// Varargs querying methods. This can only be set for function-like macros.
setIsC99Varargs()212 void setIsC99Varargs() { IsC99Varargs = true; }
setIsGNUVarargs()213 void setIsGNUVarargs() { IsGNUVarargs = true; }
isC99Varargs()214 bool isC99Varargs() const { return IsC99Varargs; }
isGNUVarargs()215 bool isGNUVarargs() const { return IsGNUVarargs; }
isVariadic()216 bool isVariadic() const { return IsC99Varargs | IsGNUVarargs; }
217
218 /// \brief Return true if this macro requires processing before expansion.
219 ///
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
223 /// function.
isBuiltinMacro()224 bool isBuiltinMacro() const { return IsBuiltinMacro; }
225
hasCommaPasting()226 bool hasCommaPasting() const { return HasCommaPasting; }
setHasCommaPasting()227 void setHasCommaPasting() { HasCommaPasting = true; }
228
229 /// \brief Return false if this macro is defined in the main file and has
230 /// not yet been used.
isUsed()231 bool isUsed() const { return IsUsed; }
232
233 /// \brief Return true if this macro can be redefined without warning.
isAllowRedefinitionsWithoutWarning()234 bool isAllowRedefinitionsWithoutWarning() const {
235 return IsAllowRedefinitionsWithoutWarning;
236 }
237
238 /// \brief Return true if we should emit a warning if the macro is unused.
isWarnIfUnused()239 bool isWarnIfUnused() const {
240 return IsWarnIfUnused;
241 }
242
243 /// \brief Return the number of tokens that this macro expands to.
244 ///
getNumTokens()245 unsigned getNumTokens() const {
246 return ReplacementTokens.size();
247 }
248
getReplacementToken(unsigned Tok)249 const Token &getReplacementToken(unsigned Tok) const {
250 assert(Tok < ReplacementTokens.size() && "Invalid token #");
251 return ReplacementTokens[Tok];
252 }
253
254 typedef SmallVectorImpl<Token>::const_iterator tokens_iterator;
tokens_begin()255 tokens_iterator tokens_begin() const { return ReplacementTokens.begin(); }
tokens_end()256 tokens_iterator tokens_end() const { return ReplacementTokens.end(); }
tokens_empty()257 bool tokens_empty() const { return ReplacementTokens.empty(); }
258
259 /// \brief Add the specified token to the replacement text for the macro.
AddTokenToBody(const Token & Tok)260 void AddTokenToBody(const Token &Tok) {
261 assert(!IsDefinitionLengthCached &&
262 "Changing replacement tokens after definition length got calculated");
263 ReplacementTokens.push_back(Tok);
264 }
265
266 /// \brief Return true if this macro is enabled.
267 ///
268 /// In other words, that we are not currently in an expansion of this macro.
isEnabled()269 bool isEnabled() const { return !IsDisabled; }
270
EnableMacro()271 void EnableMacro() {
272 assert(IsDisabled && "Cannot enable an already-enabled macro!");
273 IsDisabled = false;
274 }
275
DisableMacro()276 void DisableMacro() {
277 assert(!IsDisabled && "Cannot disable an already-disabled macro!");
278 IsDisabled = true;
279 }
280
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.
isFromASTFile()283 bool isFromASTFile() const { return FromASTFile; }
284
285 /// \brief Retrieve the global ID of the module that owns this particular
286 /// macro info.
getOwningModuleID()287 unsigned getOwningModuleID() const {
288 if (isFromASTFile())
289 return *(const unsigned*)(this+1);
290
291 return 0;
292 }
293
294 private:
295 unsigned getDefinitionLengthSlow(SourceManager &SM) const;
296
setOwningModuleID(unsigned ID)297 void setOwningModuleID(unsigned ID) {
298 assert(isFromASTFile());
299 *(unsigned*)(this+1) = ID;
300 }
301
302 friend class Preprocessor;
303 };
304
305 class DefMacroDirective;
306
307 /// \brief Encapsulates changes to the "macros namespace" (the location where
308 /// the macro name became active, the location where it was undefined, etc.).
309 ///
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.
314 ///
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.
320 ///
321 class MacroDirective {
322 public:
323 enum Kind {
324 MD_Define,
325 MD_Undefine,
326 MD_Visibility
327 };
328
329 protected:
330 /// \brief Previous macro directive for the same identifier, or NULL.
331 MacroDirective *Previous;
332
333 SourceLocation Loc;
334
335 /// \brief MacroDirective kind.
336 unsigned MDKind : 2;
337
338 /// \brief True if the macro directive was loaded from a PCH file.
339 bool IsFromPCH : 1;
340
341 /// \brief Whether the macro directive is currently "hidden".
342 ///
343 /// Note that this is transient state that is never serialized to the AST
344 /// file.
345 bool IsHidden : 1;
346
347 // Used by DefMacroDirective -----------------------------------------------//
348
349 /// \brief True if this macro was imported from a module.
350 bool IsImported : 1;
351
352 /// \brief Whether the definition of this macro is ambiguous, due to
353 /// multiple definitions coming in from multiple modules.
354 bool IsAmbiguous : 1;
355
356 // Used by VisibilityMacroDirective ----------------------------------------//
357
358 /// \brief Whether the macro has public visibility (when described in a
359 /// module).
360 bool IsPublic : 1;
361
MacroDirective(Kind K,SourceLocation Loc)362 MacroDirective(Kind K, SourceLocation Loc)
363 : Previous(0), Loc(Loc), MDKind(K), IsFromPCH(false), IsHidden(false),
364 IsImported(false), IsAmbiguous(false),
365 IsPublic(true) {
366 }
367
368 public:
getKind()369 Kind getKind() const { return Kind(MDKind); }
370
getLocation()371 SourceLocation getLocation() const { return Loc; }
372
373 /// \brief Set previous definition of the macro with the same name.
setPrevious(MacroDirective * Prev)374 void setPrevious(MacroDirective *Prev) {
375 Previous = Prev;
376 }
377
378 /// \brief Get previous definition of the macro with the same name.
getPrevious()379 const MacroDirective *getPrevious() const { return Previous; }
380
381 /// \brief Get previous definition of the macro with the same name.
getPrevious()382 MacroDirective *getPrevious() { return Previous; }
383
384 /// \brief Return true if the macro directive was loaded from a PCH file.
isFromPCH()385 bool isFromPCH() const { return IsFromPCH; }
386
setIsFromPCH()387 void setIsFromPCH() { IsFromPCH = true; }
388
389 /// \brief Determine whether this macro directive is hidden.
isHidden()390 bool isHidden() const { return IsHidden; }
391
392 /// \brief Set whether this macro directive is hidden.
setHidden(bool Val)393 void setHidden(bool Val) { IsHidden = Val; }
394
395 class DefInfo {
396 DefMacroDirective *DefDirective;
397 SourceLocation UndefLoc;
398 bool IsPublic;
399
400 public:
DefInfo()401 DefInfo() : DefDirective(0) { }
402
DefInfo(DefMacroDirective * DefDirective,SourceLocation UndefLoc,bool isPublic)403 DefInfo(DefMacroDirective *DefDirective, SourceLocation UndefLoc,
404 bool isPublic)
405 : DefDirective(DefDirective), UndefLoc(UndefLoc), IsPublic(isPublic) { }
406
getDirective()407 const DefMacroDirective *getDirective() const { return DefDirective; }
getDirective()408 DefMacroDirective *getDirective() { return DefDirective; }
409
410 inline SourceLocation getLocation() const;
411 inline MacroInfo *getMacroInfo();
getMacroInfo()412 const MacroInfo *getMacroInfo() const {
413 return const_cast<DefInfo*>(this)->getMacroInfo();
414 }
415
getUndefLocation()416 SourceLocation getUndefLocation() const { return UndefLoc; }
isUndefined()417 bool isUndefined() const { return UndefLoc.isValid(); }
418
isPublic()419 bool isPublic() const { return IsPublic; }
420
isValid()421 bool isValid() const { return DefDirective != 0; }
isInvalid()422 bool isInvalid() const { return !isValid(); }
423
424 LLVM_EXPLICIT operator bool() const { return isValid(); }
425
426 inline DefInfo getPreviousDefinition(bool AllowHidden = false);
427 const DefInfo getPreviousDefinition(bool AllowHidden = false) const {
428 return const_cast<DefInfo*>(this)->getPreviousDefinition(AllowHidden);
429 }
430 };
431
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);
438 }
439
440 bool isDefined(bool AllowHidden = false) const {
441 if (const DefInfo Def = getDefinition(AllowHidden))
442 return !Def.isUndefined();
443 return false;
444 }
445
446 const MacroInfo *getMacroInfo(bool AllowHidden = false) const {
447 return getDefinition(AllowHidden).getMacroInfo();
448 }
449 MacroInfo *getMacroInfo(bool AllowHidden = false) {
450 return getDefinition(AllowHidden).getMacroInfo();
451 }
452
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;
456
classof(const MacroDirective *)457 static bool classof(const MacroDirective *) { return true; }
458 };
459
460 /// \brief A directive for a defined macro or a macro imported from a module.
461 class DefMacroDirective : public MacroDirective {
462 MacroInfo *Info;
463
464 public:
DefMacroDirective(MacroInfo * MI)465 explicit DefMacroDirective(MacroInfo *MI)
466 : MacroDirective(MD_Define, MI->getDefinitionLoc()), Info(MI) {
467 assert(MI && "MacroInfo is null");
468 }
469
DefMacroDirective(MacroInfo * MI,SourceLocation Loc,bool isImported)470 DefMacroDirective(MacroInfo *MI, SourceLocation Loc, bool isImported)
471 : MacroDirective(MD_Define, Loc), Info(MI) {
472 assert(MI && "MacroInfo is null");
473 IsImported = isImported;
474 }
475
476 /// \brief The data for the macro definition.
getInfo()477 const MacroInfo *getInfo() const { return Info; }
getInfo()478 MacroInfo *getInfo() { return Info; }
479
480 /// \brief True if this macro was imported from a module.
isImported()481 bool isImported() const { return IsImported; }
482
483 /// \brief Determine whether this macro definition is ambiguous with
484 /// other macro definitions.
isAmbiguous()485 bool isAmbiguous() const { return IsAmbiguous; }
486
487 /// \brief Set whether this macro definition is ambiguous.
setAmbiguous(bool Val)488 void setAmbiguous(bool Val) { IsAmbiguous = Val; }
489
classof(const MacroDirective * MD)490 static bool classof(const MacroDirective *MD) {
491 return MD->getKind() == MD_Define;
492 }
classof(const DefMacroDirective *)493 static bool classof(const DefMacroDirective *) { return true; }
494 };
495
496 /// \brief A directive for an undefined macro.
497 class UndefMacroDirective : public MacroDirective {
498 public:
UndefMacroDirective(SourceLocation UndefLoc)499 explicit UndefMacroDirective(SourceLocation UndefLoc)
500 : MacroDirective(MD_Undefine, UndefLoc) {
501 assert(UndefLoc.isValid() && "Invalid UndefLoc!");
502 }
503
classof(const MacroDirective * MD)504 static bool classof(const MacroDirective *MD) {
505 return MD->getKind() == MD_Undefine;
506 }
classof(const UndefMacroDirective *)507 static bool classof(const UndefMacroDirective *) { return true; }
508 };
509
510 /// \brief A directive for setting the module visibility of a macro.
511 class VisibilityMacroDirective : public MacroDirective {
512 public:
VisibilityMacroDirective(SourceLocation Loc,bool Public)513 explicit VisibilityMacroDirective(SourceLocation Loc, bool Public)
514 : MacroDirective(MD_Visibility, Loc) {
515 IsPublic = Public;
516 }
517
518 /// \brief Determine whether this macro is part of the public API of its
519 /// module.
isPublic()520 bool isPublic() const { return IsPublic; }
521
classof(const MacroDirective * MD)522 static bool classof(const MacroDirective *MD) {
523 return MD->getKind() == MD_Visibility;
524 }
classof(const VisibilityMacroDirective *)525 static bool classof(const VisibilityMacroDirective *) { return true; }
526 };
527
getLocation()528 inline SourceLocation MacroDirective::DefInfo::getLocation() const {
529 if (isInvalid())
530 return SourceLocation();
531 return DefDirective->getLocation();
532 }
533
getMacroInfo()534 inline MacroInfo *MacroDirective::DefInfo::getMacroInfo() {
535 if (isInvalid())
536 return 0;
537 return DefDirective->getInfo();
538 }
539
540 inline MacroDirective::DefInfo
getPreviousDefinition(bool AllowHidden)541 MacroDirective::DefInfo::getPreviousDefinition(bool AllowHidden) {
542 if (isInvalid() || DefDirective->getPrevious() == 0)
543 return DefInfo();
544 return DefDirective->getPrevious()->getDefinition(AllowHidden);
545 }
546
547 } // end namespace clang
548
549 #endif
550