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