clang API Documentation

MacroInfo.cpp
Go to the documentation of this file.
00001 //===--- MacroInfo.cpp - Information about #defined identifiers -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the MacroInfo interface.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Lex/MacroInfo.h"
00015 #include "clang/Lex/Preprocessor.h"
00016 using namespace clang;
00017 
00018 MacroInfo::MacroInfo(SourceLocation DefLoc)
00019   : Location(DefLoc),
00020     ArgumentList(nullptr),
00021     NumArguments(0),
00022     IsDefinitionLengthCached(false),
00023     IsFunctionLike(false),
00024     IsC99Varargs(false),
00025     IsGNUVarargs(false),
00026     IsBuiltinMacro(false),
00027     HasCommaPasting(false),
00028     IsDisabled(false),
00029     IsUsed(false),
00030     IsAllowRedefinitionsWithoutWarning(false),
00031     IsWarnIfUnused(false),
00032     FromASTFile(false),
00033     UsedForHeaderGuard(false) {
00034 }
00035 
00036 unsigned MacroInfo::getDefinitionLengthSlow(SourceManager &SM) const {
00037   assert(!IsDefinitionLengthCached);
00038   IsDefinitionLengthCached = true;
00039 
00040   if (ReplacementTokens.empty())
00041     return (DefinitionLength = 0);
00042 
00043   const Token &firstToken = ReplacementTokens.front();
00044   const Token &lastToken = ReplacementTokens.back();
00045   SourceLocation macroStart = firstToken.getLocation();
00046   SourceLocation macroEnd = lastToken.getLocation();
00047   assert(macroStart.isValid() && macroEnd.isValid());
00048   assert((macroStart.isFileID() || firstToken.is(tok::comment)) &&
00049          "Macro defined in macro?");
00050   assert((macroEnd.isFileID() || lastToken.is(tok::comment)) &&
00051          "Macro defined in macro?");
00052   std::pair<FileID, unsigned>
00053       startInfo = SM.getDecomposedExpansionLoc(macroStart);
00054   std::pair<FileID, unsigned>
00055       endInfo = SM.getDecomposedExpansionLoc(macroEnd);
00056   assert(startInfo.first == endInfo.first &&
00057          "Macro definition spanning multiple FileIDs ?");
00058   assert(startInfo.second <= endInfo.second);
00059   DefinitionLength = endInfo.second - startInfo.second;
00060   DefinitionLength += lastToken.getLength();
00061 
00062   return DefinitionLength;
00063 }
00064 
00065 /// \brief Return true if the specified macro definition is equal to
00066 /// this macro in spelling, arguments, and whitespace.
00067 ///
00068 /// \param Syntactically if true, the macro definitions can be identical even
00069 /// if they use different identifiers for the function macro parameters.
00070 /// Otherwise the comparison is lexical and this implements the rules in
00071 /// C99 6.10.3.
00072 bool MacroInfo::isIdenticalTo(const MacroInfo &Other, Preprocessor &PP,
00073                               bool Syntactically) const {
00074   bool Lexically = !Syntactically;
00075 
00076   // Check # tokens in replacement, number of args, and various flags all match.
00077   if (ReplacementTokens.size() != Other.ReplacementTokens.size() ||
00078       getNumArgs() != Other.getNumArgs() ||
00079       isFunctionLike() != Other.isFunctionLike() ||
00080       isC99Varargs() != Other.isC99Varargs() ||
00081       isGNUVarargs() != Other.isGNUVarargs())
00082     return false;
00083 
00084   if (Lexically) {
00085     // Check arguments.
00086     for (arg_iterator I = arg_begin(), OI = Other.arg_begin(), E = arg_end();
00087          I != E; ++I, ++OI)
00088       if (*I != *OI) return false;
00089   }
00090 
00091   // Check all the tokens.
00092   for (unsigned i = 0, e = ReplacementTokens.size(); i != e; ++i) {
00093     const Token &A = ReplacementTokens[i];
00094     const Token &B = Other.ReplacementTokens[i];
00095     if (A.getKind() != B.getKind())
00096       return false;
00097 
00098     // If this isn't the first first token, check that the whitespace and
00099     // start-of-line characteristics match.
00100     if (i != 0 &&
00101         (A.isAtStartOfLine() != B.isAtStartOfLine() ||
00102          A.hasLeadingSpace() != B.hasLeadingSpace()))
00103       return false;
00104 
00105     // If this is an identifier, it is easy.
00106     if (A.getIdentifierInfo() || B.getIdentifierInfo()) {
00107       if (A.getIdentifierInfo() == B.getIdentifierInfo())
00108         continue;
00109       if (Lexically)
00110         return false;
00111       // With syntactic equivalence the parameter names can be different as long
00112       // as they are used in the same place.
00113       int AArgNum = getArgumentNum(A.getIdentifierInfo());
00114       if (AArgNum == -1)
00115         return false;
00116       if (AArgNum != Other.getArgumentNum(B.getIdentifierInfo()))
00117         return false;
00118       continue;
00119     }
00120 
00121     // Otherwise, check the spelling.
00122     if (PP.getSpelling(A) != PP.getSpelling(B))
00123       return false;
00124   }
00125 
00126   return true;
00127 }
00128 
00129 void MacroInfo::dump() const {
00130   llvm::raw_ostream &Out = llvm::errs();
00131 
00132   // FIXME: Dump locations.
00133   Out << "MacroInfo " << this;
00134   if (IsBuiltinMacro) Out << " builtin";
00135   if (IsDisabled) Out << " disabled";
00136   if (IsUsed) Out << " used";
00137   if (IsAllowRedefinitionsWithoutWarning)
00138     Out << " allow_redefinitions_without_warning";
00139   if (IsWarnIfUnused) Out << " warn_if_unused";
00140   if (FromASTFile) Out << " imported";
00141   if (UsedForHeaderGuard) Out << " header_guard";
00142 
00143   Out << "\n    #define <macro>";
00144   if (IsFunctionLike) {
00145     Out << "(";
00146     for (unsigned I = 0; I != NumArguments; ++I) {
00147       if (I) Out << ", ";
00148       Out << ArgumentList[I]->getName();
00149     }
00150     if (IsC99Varargs || IsGNUVarargs) {
00151       if (NumArguments && IsC99Varargs) Out << ", ";
00152       Out << "...";
00153     }
00154     Out << ")";
00155   }
00156 
00157   for (const Token &Tok : ReplacementTokens) {
00158     Out << " ";
00159     if (const char *Punc = tok::getPunctuatorSpelling(Tok.getKind()))
00160       Out << Punc;
00161     else if (const char *Kwd = tok::getKeywordSpelling(Tok.getKind()))
00162       Out << Kwd;
00163     else if (Tok.is(tok::identifier))
00164       Out << Tok.getIdentifierInfo()->getName();
00165     else if (Tok.isLiteral() && Tok.getLiteralData())
00166       Out << StringRef(Tok.getLiteralData(), Tok.getLength());
00167     else
00168       Out << Tok.getName();
00169   }
00170 }
00171 
00172 MacroDirective::DefInfo MacroDirective::getDefinition() {
00173   MacroDirective *MD = this;
00174   SourceLocation UndefLoc;
00175   Optional<bool> isPublic;
00176   for (; MD; MD = MD->getPrevious()) {
00177     if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
00178       return DefInfo(DefMD, UndefLoc,
00179                      !isPublic.hasValue() || isPublic.getValue());
00180 
00181     if (UndefMacroDirective *UndefMD = dyn_cast<UndefMacroDirective>(MD)) {
00182       UndefLoc = UndefMD->getLocation();
00183       continue;
00184     }
00185 
00186     VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD);
00187     if (!isPublic.hasValue())
00188       isPublic = VisMD->isPublic();
00189   }
00190 
00191   return DefInfo(nullptr, UndefLoc,
00192                  !isPublic.hasValue() || isPublic.getValue());
00193 }
00194 
00195 const MacroDirective::DefInfo
00196 MacroDirective::findDirectiveAtLoc(SourceLocation L, SourceManager &SM) const {
00197   assert(L.isValid() && "SourceLocation is invalid.");
00198   for (DefInfo Def = getDefinition(); Def; Def = Def.getPreviousDefinition()) {
00199     if (Def.getLocation().isInvalid() ||  // For macros defined on the command line.
00200         SM.isBeforeInTranslationUnit(Def.getLocation(), L))
00201       return (!Def.isUndefined() ||
00202               SM.isBeforeInTranslationUnit(L, Def.getUndefLocation()))
00203                   ? Def : DefInfo();
00204   }
00205   return DefInfo();
00206 }
00207 
00208 void MacroDirective::dump() const {
00209   llvm::raw_ostream &Out = llvm::errs();
00210 
00211   switch (getKind()) {
00212   case MD_Define: Out << "DefMacroDirective"; break;
00213   case MD_Undefine: Out << "UndefMacroDirective"; break;
00214   case MD_Visibility: Out << "VisibilityMacroDirective"; break;
00215   }
00216   Out << " " << this;
00217   // FIXME: Dump SourceLocation.
00218   if (auto *Prev = getPrevious())
00219     Out << " prev " << Prev;
00220   if (IsFromPCH) Out << " from_pch";
00221   if (IsImported) Out << " imported";
00222   if (IsAmbiguous) Out << " ambiguous";
00223 
00224   if (IsPublic)
00225     Out << " public";
00226   else if (isa<VisibilityMacroDirective>(this))
00227     Out << " private";
00228 
00229   if (auto *DMD = dyn_cast<DefMacroDirective>(this)) {
00230     if (auto *Info = DMD->getInfo()) {
00231       Out << "\n  ";
00232       Info->dump();
00233     }
00234   }
00235   Out << "\n";
00236 }