1 //===--- MacroInfo.cpp - Information about #defined identifiers -----------===//
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 //===----------------------------------------------------------------------===//
10 // This file implements the MacroInfo interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Lex/MacroInfo.h"
15 #include "clang/Lex/Preprocessor.h"
16 using namespace clang;
18 MacroInfo::MacroInfo(SourceLocation DefLoc)
20 ArgumentList(nullptr),
22 IsDefinitionLengthCached(false),
23 IsFunctionLike(false),
26 IsBuiltinMacro(false),
27 HasCommaPasting(false),
30 IsAllowRedefinitionsWithoutWarning(false),
31 IsWarnIfUnused(false),
33 UsedForHeaderGuard(false) {
36 unsigned MacroInfo::getDefinitionLengthSlow(SourceManager &SM) const {
37 assert(!IsDefinitionLengthCached);
38 IsDefinitionLengthCached = true;
40 if (ReplacementTokens.empty())
41 return (DefinitionLength = 0);
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();
62 return DefinitionLength;
65 /// \brief Return true if the specified macro definition is equal to
66 /// this macro in spelling, arguments, and whitespace.
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
72 bool MacroInfo::isIdenticalTo(const MacroInfo &Other, Preprocessor &PP,
73 bool Syntactically) const {
74 bool Lexically = !Syntactically;
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())
86 for (arg_iterator I = arg_begin(), OI = Other.arg_begin(), E = arg_end();
88 if (*I != *OI) return false;
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())
98 // If this isn't the first first token, check that the whitespace and
99 // start-of-line characteristics match.
101 (A.isAtStartOfLine() != B.isAtStartOfLine() ||
102 A.hasLeadingSpace() != B.hasLeadingSpace()))
105 // If this is an identifier, it is easy.
106 if (A.getIdentifierInfo() || B.getIdentifierInfo()) {
107 if (A.getIdentifierInfo() == B.getIdentifierInfo())
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());
116 if (AArgNum != Other.getArgumentNum(B.getIdentifierInfo()))
121 // Otherwise, check the spelling.
122 if (PP.getSpelling(A) != PP.getSpelling(B))
129 LLVM_DUMP_METHOD void MacroInfo::dump() const {
130 llvm::raw_ostream &Out = llvm::errs();
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";
143 Out << "\n #define <macro>";
144 if (IsFunctionLike) {
146 for (unsigned I = 0; I != NumArguments; ++I) {
148 Out << ArgumentList[I]->getName();
150 if (IsC99Varargs || IsGNUVarargs) {
151 if (NumArguments && IsC99Varargs) Out << ", ";
158 for (const Token &Tok : ReplacementTokens) {
159 // Leading space is semantically meaningful in a macro definition,
160 // so preserve it in the dump output.
161 if (First || Tok.hasLeadingSpace())
165 if (const char *Punc = tok::getPunctuatorSpelling(Tok.getKind()))
167 else if (Tok.isLiteral() && Tok.getLiteralData())
168 Out << StringRef(Tok.getLiteralData(), Tok.getLength());
169 else if (auto *II = Tok.getIdentifierInfo())
170 Out << II->getName();
172 Out << Tok.getName();
176 MacroDirective::DefInfo MacroDirective::getDefinition() {
177 MacroDirective *MD = this;
178 SourceLocation UndefLoc;
179 Optional<bool> isPublic;
180 for (; MD; MD = MD->getPrevious()) {
181 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
182 return DefInfo(DefMD, UndefLoc,
183 !isPublic.hasValue() || isPublic.getValue());
185 if (UndefMacroDirective *UndefMD = dyn_cast<UndefMacroDirective>(MD)) {
186 UndefLoc = UndefMD->getLocation();
190 VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD);
191 if (!isPublic.hasValue())
192 isPublic = VisMD->isPublic();
195 return DefInfo(nullptr, UndefLoc,
196 !isPublic.hasValue() || isPublic.getValue());
199 const MacroDirective::DefInfo
200 MacroDirective::findDirectiveAtLoc(SourceLocation L, SourceManager &SM) const {
201 assert(L.isValid() && "SourceLocation is invalid.");
202 for (DefInfo Def = getDefinition(); Def; Def = Def.getPreviousDefinition()) {
203 if (Def.getLocation().isInvalid() || // For macros defined on the command line.
204 SM.isBeforeInTranslationUnit(Def.getLocation(), L))
205 return (!Def.isUndefined() ||
206 SM.isBeforeInTranslationUnit(L, Def.getUndefLocation()))
212 LLVM_DUMP_METHOD void MacroDirective::dump() const {
213 llvm::raw_ostream &Out = llvm::errs();
216 case MD_Define: Out << "DefMacroDirective"; break;
217 case MD_Undefine: Out << "UndefMacroDirective"; break;
218 case MD_Visibility: Out << "VisibilityMacroDirective"; break;
221 // FIXME: Dump SourceLocation.
222 if (auto *Prev = getPrevious())
223 Out << " prev " << Prev;
224 if (IsFromPCH) Out << " from_pch";
226 if (isa<VisibilityMacroDirective>(this))
227 Out << (IsPublic ? " public" : " private");
229 if (auto *DMD = dyn_cast<DefMacroDirective>(this)) {
230 if (auto *Info = DMD->getInfo()) {
238 ModuleMacro *ModuleMacro::create(Preprocessor &PP, Module *OwningModule,
239 IdentifierInfo *II, MacroInfo *Macro,
240 ArrayRef<ModuleMacro *> Overrides) {
241 void *Mem = PP.getPreprocessorAllocator().Allocate(
242 sizeof(ModuleMacro) + sizeof(ModuleMacro *) * Overrides.size(),
243 alignof(ModuleMacro));
244 return new (Mem) ModuleMacro(OwningModule, II, Macro, Overrides);