clang  3.7.0
MacroInfo.cpp
Go to the documentation of this file.
1 //===--- MacroInfo.cpp - Information about #defined identifiers -----------===//
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 // This file implements the MacroInfo interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Lex/MacroInfo.h"
15 #include "clang/Lex/Preprocessor.h"
16 using namespace clang;
17 
18 MacroInfo::MacroInfo(SourceLocation DefLoc)
19  : Location(DefLoc),
20  ArgumentList(nullptr),
21  NumArguments(0),
22  IsDefinitionLengthCached(false),
23  IsFunctionLike(false),
24  IsC99Varargs(false),
25  IsGNUVarargs(false),
26  IsBuiltinMacro(false),
27  HasCommaPasting(false),
28  IsDisabled(false),
29  IsUsed(false),
30  IsAllowRedefinitionsWithoutWarning(false),
31  IsWarnIfUnused(false),
32  FromASTFile(false),
33  UsedForHeaderGuard(false) {
34 }
35 
36 unsigned MacroInfo::getDefinitionLengthSlow(SourceManager &SM) const {
37  assert(!IsDefinitionLengthCached);
38  IsDefinitionLengthCached = true;
39 
40  if (ReplacementTokens.empty())
41  return (DefinitionLength = 0);
42 
43  const Token &firstToken = ReplacementTokens.front();
44  const Token &lastToken = ReplacementTokens.back();
45  SourceLocation macroStart = firstToken.getLocation();
46  SourceLocation macroEnd = lastToken.getLocation();
47  assert(macroStart.isValid() && macroEnd.isValid());
48  assert((macroStart.isFileID() || firstToken.is(tok::comment)) &&
49  "Macro defined in macro?");
50  assert((macroEnd.isFileID() || lastToken.is(tok::comment)) &&
51  "Macro defined in macro?");
52  std::pair<FileID, unsigned>
53  startInfo = SM.getDecomposedExpansionLoc(macroStart);
54  std::pair<FileID, unsigned>
55  endInfo = SM.getDecomposedExpansionLoc(macroEnd);
56  assert(startInfo.first == endInfo.first &&
57  "Macro definition spanning multiple FileIDs ?");
58  assert(startInfo.second <= endInfo.second);
59  DefinitionLength = endInfo.second - startInfo.second;
60  DefinitionLength += lastToken.getLength();
61 
62  return DefinitionLength;
63 }
64 
65 /// \brief Return true if the specified macro definition is equal to
66 /// this macro in spelling, arguments, and whitespace.
67 ///
68 /// \param Syntactically if true, the macro definitions can be identical even
69 /// if they use different identifiers for the function macro parameters.
70 /// Otherwise the comparison is lexical and this implements the rules in
71 /// C99 6.10.3.
73  bool Syntactically) const {
74  bool Lexically = !Syntactically;
75 
76  // Check # tokens in replacement, number of args, and various flags all match.
77  if (ReplacementTokens.size() != Other.ReplacementTokens.size() ||
78  getNumArgs() != Other.getNumArgs() ||
79  isFunctionLike() != Other.isFunctionLike() ||
80  isC99Varargs() != Other.isC99Varargs() ||
81  isGNUVarargs() != Other.isGNUVarargs())
82  return false;
83 
84  if (Lexically) {
85  // Check arguments.
86  for (arg_iterator I = arg_begin(), OI = Other.arg_begin(), E = arg_end();
87  I != E; ++I, ++OI)
88  if (*I != *OI) return false;
89  }
90 
91  // Check all the tokens.
92  for (unsigned i = 0, e = ReplacementTokens.size(); i != e; ++i) {
93  const Token &A = ReplacementTokens[i];
94  const Token &B = Other.ReplacementTokens[i];
95  if (A.getKind() != B.getKind())
96  return false;
97 
98  // If this isn't the first first token, check that the whitespace and
99  // start-of-line characteristics match.
100  if (i != 0 &&
101  (A.isAtStartOfLine() != B.isAtStartOfLine() ||
102  A.hasLeadingSpace() != B.hasLeadingSpace()))
103  return false;
104 
105  // If this is an identifier, it is easy.
106  if (A.getIdentifierInfo() || B.getIdentifierInfo()) {
107  if (A.getIdentifierInfo() == B.getIdentifierInfo())
108  continue;
109  if (Lexically)
110  return false;
111  // With syntactic equivalence the parameter names can be different as long
112  // as they are used in the same place.
113  int AArgNum = getArgumentNum(A.getIdentifierInfo());
114  if (AArgNum == -1)
115  return false;
116  if (AArgNum != Other.getArgumentNum(B.getIdentifierInfo()))
117  return false;
118  continue;
119  }
120 
121  // Otherwise, check the spelling.
122  if (PP.getSpelling(A) != PP.getSpelling(B))
123  return false;
124  }
125 
126  return true;
127 }
128 
129 void MacroInfo::dump() const {
130  llvm::raw_ostream &Out = llvm::errs();
131 
132  // FIXME: Dump locations.
133  Out << "MacroInfo " << this;
134  if (IsBuiltinMacro) Out << " builtin";
135  if (IsDisabled) Out << " disabled";
136  if (IsUsed) Out << " used";
137  if (IsAllowRedefinitionsWithoutWarning)
138  Out << " allow_redefinitions_without_warning";
139  if (IsWarnIfUnused) Out << " warn_if_unused";
140  if (FromASTFile) Out << " imported";
141  if (UsedForHeaderGuard) Out << " header_guard";
142 
143  Out << "\n #define <macro>";
144  if (IsFunctionLike) {
145  Out << "(";
146  for (unsigned I = 0; I != NumArguments; ++I) {
147  if (I) Out << ", ";
148  Out << ArgumentList[I]->getName();
149  }
150  if (IsC99Varargs || IsGNUVarargs) {
151  if (NumArguments && IsC99Varargs) Out << ", ";
152  Out << "...";
153  }
154  Out << ")";
155  }
156 
157  for (const Token &Tok : ReplacementTokens) {
158  Out << " ";
159  if (const char *Punc = tok::getPunctuatorSpelling(Tok.getKind()))
160  Out << Punc;
161  else if (const char *Kwd = tok::getKeywordSpelling(Tok.getKind()))
162  Out << Kwd;
163  else if (Tok.is(tok::identifier))
164  Out << Tok.getIdentifierInfo()->getName();
165  else if (Tok.isLiteral() && Tok.getLiteralData())
166  Out << StringRef(Tok.getLiteralData(), Tok.getLength());
167  else
168  Out << Tok.getName();
169  }
170 }
171 
173  MacroDirective *MD = this;
174  SourceLocation UndefLoc;
175  Optional<bool> isPublic;
176  for (; MD; MD = MD->getPrevious()) {
177  if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
178  return DefInfo(DefMD, UndefLoc,
179  !isPublic.hasValue() || isPublic.getValue());
180 
181  if (UndefMacroDirective *UndefMD = dyn_cast<UndefMacroDirective>(MD)) {
182  UndefLoc = UndefMD->getLocation();
183  continue;
184  }
185 
186  VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD);
187  if (!isPublic.hasValue())
188  isPublic = VisMD->isPublic();
189  }
190 
191  return DefInfo(nullptr, UndefLoc,
192  !isPublic.hasValue() || isPublic.getValue());
193 }
194 
197  assert(L.isValid() && "SourceLocation is invalid.");
198  for (DefInfo Def = getDefinition(); Def; Def = Def.getPreviousDefinition()) {
199  if (Def.getLocation().isInvalid() || // For macros defined on the command line.
200  SM.isBeforeInTranslationUnit(Def.getLocation(), L))
201  return (!Def.isUndefined() ||
202  SM.isBeforeInTranslationUnit(L, Def.getUndefLocation()))
203  ? Def : DefInfo();
204  }
205  return DefInfo();
206 }
207 
208 void MacroDirective::dump() const {
209  llvm::raw_ostream &Out = llvm::errs();
210 
211  switch (getKind()) {
212  case MD_Define: Out << "DefMacroDirective"; break;
213  case MD_Undefine: Out << "UndefMacroDirective"; break;
214  case MD_Visibility: Out << "VisibilityMacroDirective"; break;
215  }
216  Out << " " << this;
217  // FIXME: Dump SourceLocation.
218  if (auto *Prev = getPrevious())
219  Out << " prev " << Prev;
220  if (IsFromPCH) Out << " from_pch";
221 
222  if (isa<VisibilityMacroDirective>(this))
223  Out << (IsPublic ? " public" : " private");
224 
225  if (auto *DMD = dyn_cast<DefMacroDirective>(this)) {
226  if (auto *Info = DMD->getInfo()) {
227  Out << "\n ";
228  Info->dump();
229  }
230  }
231  Out << "\n";
232 }
233 
235  IdentifierInfo *II, MacroInfo *Macro,
236  ArrayRef<ModuleMacro *> Overrides) {
237  void *Mem = PP.getPreprocessorAllocator().Allocate(
238  sizeof(ModuleMacro) + sizeof(ModuleMacro *) * Overrides.size(),
239  llvm::alignOf<ModuleMacro>());
240  return new (Mem) ModuleMacro(OwningModule, II, Macro, Overrides);
241 }
bool isAtStartOfLine() const
Definition: Token.h:261
bool IsFromPCH
True if the macro directive was loaded from a PCH file.
Definition: MacroInfo.h:322
llvm::BumpPtrAllocator & getPreprocessorAllocator()
Definition: Preprocessor.h:689
std::pair< FileID, unsigned > getDecomposedExpansionLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
const DefInfo findDirectiveAtLoc(SourceLocation L, SourceManager &SM) const
Find macro definition active in the specified source location. If this macro was not defined there...
Definition: MacroInfo.cpp:196
Kind getKind() const
Definition: MacroInfo.h:335
Defines the clang::MacroInfo and clang::MacroDirective classes.
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
Definition: Token.h:265
A directive for an undefined macro.
Definition: MacroInfo.h:441
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Represents a macro directive exported by a module.
Definition: MacroInfo.h:498
A directive for a defined macro or a macro imported from a module.
Definition: MacroInfo.h:419
bool isFileID() const
Describes a module or submodule.
Definition: Basic/Module.h:49
A directive for setting the module visibility of a macro.
Definition: MacroInfo.h:455
const char * getKeywordSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple keyword and contextual keyword tokens like 'int' and 'dynamic_cast'...
Definition: TokenKinds.cpp:41
static ModuleMacro * create(Preprocessor &PP, Module *OwningModule, IdentifierInfo *II, MacroInfo *Macro, ArrayRef< ModuleMacro * > Overrides)
Definition: MacroInfo.cpp:234
tok::TokenKind getKind() const
Definition: Token.h:90
SourceManager & SM
IdentifierInfo *const * arg_iterator
Definition: MacroInfo.h:176
StringRef getName() const
Return the actual identifier string.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
unsigned getNumArgs() const
Definition: MacroInfo.h:180
Defines the clang::Preprocessor interface.
int getArgumentNum(const IdentifierInfo *Arg) const
Return the argument number of the specified identifier, or -1 if the identifier is not a formal argum...
Definition: MacroInfo.h:187
DefInfo getDefinition()
Traverses the macro directives history and returns the next macro definition directive along with inf...
Definition: MacroInfo.cpp:172
const char * getPunctuatorSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple punctuation tokens like '!' or '', and returns NULL for literal and...
Definition: TokenKinds.cpp:32
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:124
arg_iterator arg_end() const
Definition: MacroInfo.h:179
bool IsPublic
Whether the macro has public visibility (when described in a module).
Definition: MacroInfo.h:328
bool isPublic() const
Determine whether this macro is part of the public API of its module.
Definition: MacroInfo.h:464
bool isC99Varargs() const
Definition: MacroInfo.h:203
void dump() const
Definition: MacroInfo.cpp:129
Encapsulates changes to the "macros namespace" (the location where the macro name became active...
Definition: MacroInfo.h:308
#define false
Definition: stdbool.h:33
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
bool isValid() const
Return true if this is a valid SourceLocation object.
bool is(tok::TokenKind K) const
Definition: Token.h:95
bool isGNUVarargs() const
Definition: MacroInfo.h:204
bool isFunctionLike() const
Definition: MacroInfo.h:197
Encapsulates the data about a macro definition (e.g. its tokens).
Definition: MacroInfo.h:34
bool isIdenticalTo(const MacroInfo &Other, Preprocessor &PP, bool Syntactically) const
Return true if the specified macro definition is equal to this macro in spelling, arguments...
Definition: MacroInfo.cpp:72
void dump() const
Definition: MacroInfo.cpp:208
unsigned getLength() const
Definition: Token.h:127
arg_iterator arg_begin() const
Definition: MacroInfo.h:178
This class handles loading and caching of source files into memory.
const MacroDirective * getPrevious() const
Get previous definition of the macro with the same name.
Definition: MacroInfo.h:343
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:96
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:177