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