clang API Documentation

IdentifierResolver.cpp
Go to the documentation of this file.
00001 //===- IdentifierResolver.cpp - Lexical Scope Name lookup -------*- C++ -*-===//
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 IdentifierResolver class, which is used for lexical
00011 // scoped lookup, based on declaration names.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Sema/IdentifierResolver.h"
00016 #include "clang/AST/Decl.h"
00017 #include "clang/Basic/LangOptions.h"
00018 #include "clang/Lex/ExternalPreprocessorSource.h"
00019 #include "clang/Lex/Preprocessor.h"
00020 #include "clang/Sema/Scope.h"
00021 
00022 using namespace clang;
00023 
00024 //===----------------------------------------------------------------------===//
00025 // IdDeclInfoMap class
00026 //===----------------------------------------------------------------------===//
00027 
00028 /// IdDeclInfoMap - Associates IdDeclInfos with declaration names.
00029 /// Allocates 'pools' (vectors of IdDeclInfos) to avoid allocating each
00030 /// individual IdDeclInfo to heap.
00031 class IdentifierResolver::IdDeclInfoMap {
00032   static const unsigned int POOL_SIZE = 512;
00033 
00034   /// We use our own linked-list implementation because it is sadly
00035   /// impossible to add something to a pre-C++0x STL container without
00036   /// a completely unnecessary copy.
00037   struct IdDeclInfoPool {
00038     IdDeclInfoPool(IdDeclInfoPool *Next) : Next(Next) {}
00039     
00040     IdDeclInfoPool *Next;
00041     IdDeclInfo Pool[POOL_SIZE];
00042   };
00043   
00044   IdDeclInfoPool *CurPool;
00045   unsigned int CurIndex;
00046 
00047 public:
00048   IdDeclInfoMap() : CurPool(nullptr), CurIndex(POOL_SIZE) {}
00049 
00050   ~IdDeclInfoMap() {
00051     IdDeclInfoPool *Cur = CurPool;
00052     while (IdDeclInfoPool *P = Cur) {
00053       Cur = Cur->Next;
00054       delete P;
00055     }
00056   }
00057 
00058   /// Returns the IdDeclInfo associated to the DeclarationName.
00059   /// It creates a new IdDeclInfo if one was not created before for this id.
00060   IdDeclInfo &operator[](DeclarationName Name);
00061 };
00062 
00063 
00064 //===----------------------------------------------------------------------===//
00065 // IdDeclInfo Implementation
00066 //===----------------------------------------------------------------------===//
00067 
00068 /// RemoveDecl - Remove the decl from the scope chain.
00069 /// The decl must already be part of the decl chain.
00070 void IdentifierResolver::IdDeclInfo::RemoveDecl(NamedDecl *D) {
00071   for (DeclsTy::iterator I = Decls.end(); I != Decls.begin(); --I) {
00072     if (D == *(I-1)) {
00073       Decls.erase(I-1);
00074       return;
00075     }
00076   }
00077 
00078   llvm_unreachable("Didn't find this decl on its identifier's chain!");
00079 }
00080 
00081 //===----------------------------------------------------------------------===//
00082 // IdentifierResolver Implementation
00083 //===----------------------------------------------------------------------===//
00084 
00085 IdentifierResolver::IdentifierResolver(Preprocessor &PP)
00086   : LangOpt(PP.getLangOpts()), PP(PP),
00087     IdDeclInfos(new IdDeclInfoMap) {
00088 }
00089 
00090 IdentifierResolver::~IdentifierResolver() {
00091   delete IdDeclInfos;
00092 }
00093 
00094 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
00095 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
00096 /// true if 'D' belongs to the given declaration context.
00097 bool IdentifierResolver::isDeclInScope(Decl *D, DeclContext *Ctx, Scope *S,
00098                                        bool AllowInlineNamespace) const {
00099   Ctx = Ctx->getRedeclContext();
00100 
00101   if (Ctx->isFunctionOrMethod() || S->isFunctionPrototypeScope()) {
00102     // Ignore the scopes associated within transparent declaration contexts.
00103     while (S->getEntity() && S->getEntity()->isTransparentContext())
00104       S = S->getParent();
00105 
00106     if (S->isDeclScope(D))
00107       return true;
00108     if (LangOpt.CPlusPlus) {
00109       // C++ 3.3.2p3:
00110       // The name declared in a catch exception-declaration is local to the
00111       // handler and shall not be redeclared in the outermost block of the
00112       // handler.
00113       // C++ 3.3.2p4:
00114       // Names declared in the for-init-statement, and in the condition of if,
00115       // while, for, and switch statements are local to the if, while, for, or
00116       // switch statement (including the controlled statement), and shall not be
00117       // redeclared in a subsequent condition of that statement nor in the
00118       // outermost block (or, for the if statement, any of the outermost blocks)
00119       // of the controlled statement.
00120       //
00121       assert(S->getParent() && "No TUScope?");
00122       if (S->getParent()->getFlags() & Scope::ControlScope) {
00123         S = S->getParent();
00124         if (S->isDeclScope(D))
00125           return true;
00126       }
00127       if (S->getFlags() & Scope::FnTryCatchScope)
00128         return S->getParent()->isDeclScope(D);
00129     }
00130     return false;
00131   }
00132 
00133   // FIXME: If D is a local extern declaration, this check doesn't make sense;
00134   // we should be checking its lexical context instead in that case, because
00135   // that is its scope.
00136   DeclContext *DCtx = D->getDeclContext()->getRedeclContext();
00137   return AllowInlineNamespace ? Ctx->InEnclosingNamespaceSetOf(DCtx)
00138                               : Ctx->Equals(DCtx);
00139 }
00140 
00141 /// AddDecl - Link the decl to its shadowed decl chain.
00142 void IdentifierResolver::AddDecl(NamedDecl *D) {
00143   DeclarationName Name = D->getDeclName();
00144   if (IdentifierInfo *II = Name.getAsIdentifierInfo())
00145     updatingIdentifier(*II);
00146 
00147   void *Ptr = Name.getFETokenInfo<void>();
00148 
00149   if (!Ptr) {
00150     Name.setFETokenInfo(D);
00151     return;
00152   }
00153 
00154   IdDeclInfo *IDI;
00155 
00156   if (isDeclPtr(Ptr)) {
00157     Name.setFETokenInfo(nullptr);
00158     IDI = &(*IdDeclInfos)[Name];
00159     NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr);
00160     IDI->AddDecl(PrevD);
00161   } else
00162     IDI = toIdDeclInfo(Ptr);
00163 
00164   IDI->AddDecl(D);
00165 }
00166 
00167 void IdentifierResolver::InsertDeclAfter(iterator Pos, NamedDecl *D) {
00168   DeclarationName Name = D->getDeclName();
00169   if (IdentifierInfo *II = Name.getAsIdentifierInfo())
00170     updatingIdentifier(*II);
00171   
00172   void *Ptr = Name.getFETokenInfo<void>();
00173   
00174   if (!Ptr) {
00175     AddDecl(D);
00176     return;
00177   }
00178 
00179   if (isDeclPtr(Ptr)) {
00180     // We only have a single declaration: insert before or after it,
00181     // as appropriate.
00182     if (Pos == iterator()) {
00183       // Add the new declaration before the existing declaration.
00184       NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr);
00185       RemoveDecl(PrevD);
00186       AddDecl(D);
00187       AddDecl(PrevD);
00188     } else {
00189       // Add new declaration after the existing declaration.
00190       AddDecl(D);
00191     }
00192 
00193     return;
00194   }
00195 
00196   // General case: insert the declaration at the appropriate point in the 
00197   // list, which already has at least two elements.
00198   IdDeclInfo *IDI = toIdDeclInfo(Ptr);
00199   if (Pos.isIterator()) {
00200     IDI->InsertDecl(Pos.getIterator() + 1, D);
00201   } else
00202     IDI->InsertDecl(IDI->decls_begin(), D);
00203 }
00204 
00205 /// RemoveDecl - Unlink the decl from its shadowed decl chain.
00206 /// The decl must already be part of the decl chain.
00207 void IdentifierResolver::RemoveDecl(NamedDecl *D) {
00208   assert(D && "null param passed");
00209   DeclarationName Name = D->getDeclName();
00210   if (IdentifierInfo *II = Name.getAsIdentifierInfo())
00211     updatingIdentifier(*II);
00212 
00213   void *Ptr = Name.getFETokenInfo<void>();
00214 
00215   assert(Ptr && "Didn't find this decl on its identifier's chain!");
00216 
00217   if (isDeclPtr(Ptr)) {
00218     assert(D == Ptr && "Didn't find this decl on its identifier's chain!");
00219     Name.setFETokenInfo(nullptr);
00220     return;
00221   }
00222 
00223   return toIdDeclInfo(Ptr)->RemoveDecl(D);
00224 }
00225 
00226 /// begin - Returns an iterator for decls with name 'Name'.
00227 IdentifierResolver::iterator
00228 IdentifierResolver::begin(DeclarationName Name) {
00229   if (IdentifierInfo *II = Name.getAsIdentifierInfo())
00230     readingIdentifier(*II);
00231     
00232   void *Ptr = Name.getFETokenInfo<void>();
00233   if (!Ptr) return end();
00234 
00235   if (isDeclPtr(Ptr))
00236     return iterator(static_cast<NamedDecl*>(Ptr));
00237 
00238   IdDeclInfo *IDI = toIdDeclInfo(Ptr);
00239 
00240   IdDeclInfo::DeclsTy::iterator I = IDI->decls_end();
00241   if (I != IDI->decls_begin())
00242     return iterator(I-1);
00243   // No decls found.
00244   return end();
00245 }
00246 
00247 namespace {
00248   enum DeclMatchKind {
00249     DMK_Different,
00250     DMK_Replace,
00251     DMK_Ignore
00252   };
00253 }
00254 
00255 /// \brief Compare two declarations to see whether they are different or,
00256 /// if they are the same, whether the new declaration should replace the 
00257 /// existing declaration.
00258 static DeclMatchKind compareDeclarations(NamedDecl *Existing, NamedDecl *New) {
00259   // If the declarations are identical, ignore the new one.
00260   if (Existing == New)
00261     return DMK_Ignore;
00262 
00263   // If the declarations have different kinds, they're obviously different.
00264   if (Existing->getKind() != New->getKind())
00265     return DMK_Different;
00266 
00267   // If the declarations are redeclarations of each other, keep the newest one.
00268   if (Existing->getCanonicalDecl() == New->getCanonicalDecl()) {
00269     // If either of these is the most recent declaration, use it.
00270     Decl *MostRecent = Existing->getMostRecentDecl();
00271     if (Existing == MostRecent)
00272       return DMK_Ignore;
00273 
00274     if (New == MostRecent)
00275       return DMK_Replace;
00276 
00277     // If the existing declaration is somewhere in the previous declaration
00278     // chain of the new declaration, then prefer the new declaration.
00279     for (auto RD : New->redecls()) {
00280       if (RD == Existing)
00281         return DMK_Replace;
00282         
00283       if (RD->isCanonicalDecl())
00284         break;
00285     }
00286     
00287     return DMK_Ignore;
00288   }
00289   
00290   return DMK_Different;
00291 }
00292 
00293 bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name){
00294   if (IdentifierInfo *II = Name.getAsIdentifierInfo())
00295     readingIdentifier(*II);
00296   
00297   void *Ptr = Name.getFETokenInfo<void>();
00298     
00299   if (!Ptr) {
00300     Name.setFETokenInfo(D);
00301     return true;
00302   }
00303   
00304   IdDeclInfo *IDI;
00305   
00306   if (isDeclPtr(Ptr)) {
00307     NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr);
00308     
00309     switch (compareDeclarations(PrevD, D)) {
00310     case DMK_Different:
00311       break;
00312       
00313     case DMK_Ignore:
00314       return false;
00315       
00316     case DMK_Replace:
00317       Name.setFETokenInfo(D);
00318       return true;
00319     }
00320 
00321     Name.setFETokenInfo(nullptr);
00322     IDI = &(*IdDeclInfos)[Name];
00323     
00324     // If the existing declaration is not visible in translation unit scope,
00325     // then add the new top-level declaration first.
00326     if (!PrevD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
00327       IDI->AddDecl(D);
00328       IDI->AddDecl(PrevD);
00329     } else {
00330       IDI->AddDecl(PrevD);
00331       IDI->AddDecl(D);
00332     }
00333     return true;
00334   } 
00335   
00336   IDI = toIdDeclInfo(Ptr);
00337 
00338   // See whether this declaration is identical to any existing declarations.
00339   // If not, find the right place to insert it.
00340   for (IdDeclInfo::DeclsTy::iterator I = IDI->decls_begin(), 
00341                                   IEnd = IDI->decls_end();
00342        I != IEnd; ++I) {
00343     
00344     switch (compareDeclarations(*I, D)) {
00345     case DMK_Different:
00346       break;
00347       
00348     case DMK_Ignore:
00349       return false;
00350       
00351     case DMK_Replace:
00352       *I = D;
00353       return true;
00354     }
00355     
00356     if (!(*I)->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
00357       // We've found a declaration that is not visible from the translation
00358       // unit (it's in an inner scope). Insert our declaration here.
00359       IDI->InsertDecl(I, D);
00360       return true;
00361     }
00362   }
00363   
00364   // Add the declaration to the end.
00365   IDI->AddDecl(D);
00366   return true;
00367 }
00368 
00369 void IdentifierResolver::readingIdentifier(IdentifierInfo &II) {
00370   if (II.isOutOfDate())
00371     PP.getExternalSource()->updateOutOfDateIdentifier(II);  
00372 }
00373 
00374 void IdentifierResolver::updatingIdentifier(IdentifierInfo &II) {
00375   if (II.isOutOfDate())
00376     PP.getExternalSource()->updateOutOfDateIdentifier(II);
00377   
00378   if (II.isFromAST())
00379     II.setChangedSinceDeserialization();
00380 }
00381 
00382 //===----------------------------------------------------------------------===//
00383 // IdDeclInfoMap Implementation
00384 //===----------------------------------------------------------------------===//
00385 
00386 /// Returns the IdDeclInfo associated to the DeclarationName.
00387 /// It creates a new IdDeclInfo if one was not created before for this id.
00388 IdentifierResolver::IdDeclInfo &
00389 IdentifierResolver::IdDeclInfoMap::operator[](DeclarationName Name) {
00390   void *Ptr = Name.getFETokenInfo<void>();
00391 
00392   if (Ptr) return *toIdDeclInfo(Ptr);
00393 
00394   if (CurIndex == POOL_SIZE) {
00395     CurPool = new IdDeclInfoPool(CurPool);
00396     CurIndex = 0;
00397   }
00398   IdDeclInfo *IDI = &CurPool->Pool[CurIndex];
00399   Name.setFETokenInfo(reinterpret_cast<void*>(
00400                               reinterpret_cast<uintptr_t>(IDI) | 0x1)
00401                                                                      );
00402   ++CurIndex;
00403   return *IDI;
00404 }
00405 
00406 void IdentifierResolver::iterator::incrementSlowCase() {
00407   NamedDecl *D = **this;
00408   void *InfoPtr = D->getDeclName().getFETokenInfo<void>();
00409   assert(!isDeclPtr(InfoPtr) && "Decl with wrong id ?");
00410   IdDeclInfo *Info = toIdDeclInfo(InfoPtr);
00411 
00412   BaseIter I = getIterator();
00413   if (I != Info->decls_begin())
00414     *this = iterator(I-1);
00415   else // No more decls.
00416     *this = iterator();
00417 }