clang API Documentation
00001 //===--- IdentifierTable.cpp - Hash table for identifier lookup -----------===// 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 IdentifierInfo, IdentifierVisitor, and 00011 // IdentifierTable interfaces. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #include "clang/Basic/IdentifierTable.h" 00016 #include "clang/Basic/LangOptions.h" 00017 #include "llvm/ADT/FoldingSet.h" 00018 #include "llvm/ADT/DenseMap.h" 00019 #include "llvm/ADT/SmallString.h" 00020 #include "llvm/ADT/StringSwitch.h" 00021 #include "llvm/Support/raw_ostream.h" 00022 #include "llvm/Support/ErrorHandling.h" 00023 #include <cstdio> 00024 00025 using namespace clang; 00026 00027 //===----------------------------------------------------------------------===// 00028 // IdentifierInfo Implementation 00029 //===----------------------------------------------------------------------===// 00030 00031 IdentifierInfo::IdentifierInfo() { 00032 TokenID = tok::identifier; 00033 ObjCOrBuiltinID = 0; 00034 HasMacro = false; 00035 IsExtension = false; 00036 IsCXX11CompatKeyword = false; 00037 IsPoisoned = false; 00038 IsCPPOperatorKeyword = false; 00039 NeedsHandleIdentifier = false; 00040 IsFromAST = false; 00041 ChangedAfterLoad = false; 00042 RevertedTokenID = false; 00043 OutOfDate = false; 00044 IsModulesImport = false; 00045 FETokenInfo = 0; 00046 Entry = 0; 00047 } 00048 00049 //===----------------------------------------------------------------------===// 00050 // IdentifierTable Implementation 00051 //===----------------------------------------------------------------------===// 00052 00053 IdentifierIterator::~IdentifierIterator() { } 00054 00055 IdentifierInfoLookup::~IdentifierInfoLookup() {} 00056 00057 namespace { 00058 /// \brief A simple identifier lookup iterator that represents an 00059 /// empty sequence of identifiers. 00060 class EmptyLookupIterator : public IdentifierIterator 00061 { 00062 public: 00063 virtual StringRef Next() { return StringRef(); } 00064 }; 00065 } 00066 00067 IdentifierIterator *IdentifierInfoLookup::getIdentifiers() const { 00068 return new EmptyLookupIterator(); 00069 } 00070 00071 ExternalIdentifierLookup::~ExternalIdentifierLookup() {} 00072 00073 IdentifierTable::IdentifierTable(const LangOptions &LangOpts, 00074 IdentifierInfoLookup* externalLookup) 00075 : HashTable(8192), // Start with space for 8K identifiers. 00076 ExternalLookup(externalLookup) { 00077 00078 // Populate the identifier table with info about keywords for the current 00079 // language. 00080 AddKeywords(LangOpts); 00081 00082 00083 // Add the '_experimental_modules_import' contextual keyword. 00084 get("__experimental_modules_import").setModulesImport(true); 00085 } 00086 00087 //===----------------------------------------------------------------------===// 00088 // Language Keyword Implementation 00089 //===----------------------------------------------------------------------===// 00090 00091 // Constants for TokenKinds.def 00092 namespace { 00093 enum { 00094 KEYC99 = 0x1, 00095 KEYCXX = 0x2, 00096 KEYCXX0X = 0x4, 00097 KEYGNU = 0x8, 00098 KEYMS = 0x10, 00099 BOOLSUPPORT = 0x20, 00100 KEYALTIVEC = 0x40, 00101 KEYNOCXX = 0x80, 00102 KEYBORLAND = 0x100, 00103 KEYOPENCL = 0x200, 00104 KEYC11 = 0x400, 00105 KEYARC = 0x800, 00106 KEYALL = 0x0fff 00107 }; 00108 } 00109 00110 /// AddKeyword - This method is used to associate a token ID with specific 00111 /// identifiers because they are language keywords. This causes the lexer to 00112 /// automatically map matching identifiers to specialized token codes. 00113 /// 00114 /// The C90/C99/CPP/CPP0x flags are set to 3 if the token is a keyword in a 00115 /// future language standard, set to 2 if the token should be enabled in the 00116 /// specified language, set to 1 if it is an extension in the specified 00117 /// language, and set to 0 if disabled in the specified language. 00118 static void AddKeyword(StringRef Keyword, 00119 tok::TokenKind TokenCode, unsigned Flags, 00120 const LangOptions &LangOpts, IdentifierTable &Table) { 00121 unsigned AddResult = 0; 00122 if (Flags == KEYALL) AddResult = 2; 00123 else if (LangOpts.CPlusPlus && (Flags & KEYCXX)) AddResult = 2; 00124 else if (LangOpts.CPlusPlus0x && (Flags & KEYCXX0X)) AddResult = 2; 00125 else if (LangOpts.C99 && (Flags & KEYC99)) AddResult = 2; 00126 else if (LangOpts.GNUKeywords && (Flags & KEYGNU)) AddResult = 1; 00127 else if (LangOpts.MicrosoftExt && (Flags & KEYMS)) AddResult = 1; 00128 else if (LangOpts.Borland && (Flags & KEYBORLAND)) AddResult = 1; 00129 else if (LangOpts.Bool && (Flags & BOOLSUPPORT)) AddResult = 2; 00130 else if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) AddResult = 2; 00131 else if (LangOpts.OpenCL && (Flags & KEYOPENCL)) AddResult = 2; 00132 else if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) AddResult = 2; 00133 else if (LangOpts.C11 && (Flags & KEYC11)) AddResult = 2; 00134 // We treat bridge casts as objective-C keywords so we can warn on them 00135 // in non-arc mode. 00136 else if (LangOpts.ObjC2 && (Flags & KEYARC)) AddResult = 2; 00137 else if (LangOpts.CPlusPlus && (Flags & KEYCXX0X)) AddResult = 3; 00138 00139 // Don't add this keyword if disabled in this language. 00140 if (AddResult == 0) return; 00141 00142 IdentifierInfo &Info = 00143 Table.get(Keyword, AddResult == 3 ? tok::identifier : TokenCode); 00144 Info.setIsExtensionToken(AddResult == 1); 00145 Info.setIsCXX11CompatKeyword(AddResult == 3); 00146 } 00147 00148 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative 00149 /// representations. 00150 static void AddCXXOperatorKeyword(StringRef Keyword, 00151 tok::TokenKind TokenCode, 00152 IdentifierTable &Table) { 00153 IdentifierInfo &Info = Table.get(Keyword, TokenCode); 00154 Info.setIsCPlusPlusOperatorKeyword(); 00155 } 00156 00157 /// AddObjCKeyword - Register an Objective-C @keyword like "class" "selector" or 00158 /// "property". 00159 static void AddObjCKeyword(StringRef Name, 00160 tok::ObjCKeywordKind ObjCID, 00161 IdentifierTable &Table) { 00162 Table.get(Name).setObjCKeywordID(ObjCID); 00163 } 00164 00165 /// AddKeywords - Add all keywords to the symbol table. 00166 /// 00167 void IdentifierTable::AddKeywords(const LangOptions &LangOpts) { 00168 // Add keywords and tokens for the current language. 00169 #define KEYWORD(NAME, FLAGS) \ 00170 AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \ 00171 FLAGS, LangOpts, *this); 00172 #define ALIAS(NAME, TOK, FLAGS) \ 00173 AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \ 00174 FLAGS, LangOpts, *this); 00175 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \ 00176 if (LangOpts.CXXOperatorNames) \ 00177 AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this); 00178 #define OBJC1_AT_KEYWORD(NAME) \ 00179 if (LangOpts.ObjC1) \ 00180 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this); 00181 #define OBJC2_AT_KEYWORD(NAME) \ 00182 if (LangOpts.ObjC2) \ 00183 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this); 00184 #define TESTING_KEYWORD(NAME, FLAGS) 00185 #include "clang/Basic/TokenKinds.def" 00186 00187 if (LangOpts.ParseUnknownAnytype) 00188 AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL, 00189 LangOpts, *this); 00190 } 00191 00192 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const { 00193 // We use a perfect hash function here involving the length of the keyword, 00194 // the first and third character. For preprocessor ID's there are no 00195 // collisions (if there were, the switch below would complain about duplicate 00196 // case values). Note that this depends on 'if' being null terminated. 00197 00198 #define HASH(LEN, FIRST, THIRD) \ 00199 (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31) 00200 #define CASE(LEN, FIRST, THIRD, NAME) \ 00201 case HASH(LEN, FIRST, THIRD): \ 00202 return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME 00203 00204 unsigned Len = getLength(); 00205 if (Len < 2) return tok::pp_not_keyword; 00206 const char *Name = getNameStart(); 00207 switch (HASH(Len, Name[0], Name[2])) { 00208 default: return tok::pp_not_keyword; 00209 CASE( 2, 'i', '\0', if); 00210 CASE( 4, 'e', 'i', elif); 00211 CASE( 4, 'e', 's', else); 00212 CASE( 4, 'l', 'n', line); 00213 CASE( 4, 's', 'c', sccs); 00214 CASE( 5, 'e', 'd', endif); 00215 CASE( 5, 'e', 'r', error); 00216 CASE( 5, 'i', 'e', ident); 00217 CASE( 5, 'i', 'd', ifdef); 00218 CASE( 5, 'u', 'd', undef); 00219 00220 CASE( 6, 'a', 's', assert); 00221 CASE( 6, 'd', 'f', define); 00222 CASE( 6, 'i', 'n', ifndef); 00223 CASE( 6, 'i', 'p', import); 00224 CASE( 6, 'p', 'a', pragma); 00225 00226 CASE( 7, 'd', 'f', defined); 00227 CASE( 7, 'i', 'c', include); 00228 CASE( 7, 'w', 'r', warning); 00229 00230 CASE( 8, 'u', 'a', unassert); 00231 CASE(12, 'i', 'c', include_next); 00232 00233 CASE(14, '_', 'p', __public_macro); 00234 00235 CASE(15, '_', 'p', __private_macro); 00236 00237 CASE(16, '_', 'i', __include_macros); 00238 #undef CASE 00239 #undef HASH 00240 } 00241 } 00242 00243 //===----------------------------------------------------------------------===// 00244 // Stats Implementation 00245 //===----------------------------------------------------------------------===// 00246 00247 /// PrintStats - Print statistics about how well the identifier table is doing 00248 /// at hashing identifiers. 00249 void IdentifierTable::PrintStats() const { 00250 unsigned NumBuckets = HashTable.getNumBuckets(); 00251 unsigned NumIdentifiers = HashTable.getNumItems(); 00252 unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers; 00253 unsigned AverageIdentifierSize = 0; 00254 unsigned MaxIdentifierLength = 0; 00255 00256 // TODO: Figure out maximum times an identifier had to probe for -stats. 00257 for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator 00258 I = HashTable.begin(), E = HashTable.end(); I != E; ++I) { 00259 unsigned IdLen = I->getKeyLength(); 00260 AverageIdentifierSize += IdLen; 00261 if (MaxIdentifierLength < IdLen) 00262 MaxIdentifierLength = IdLen; 00263 } 00264 00265 fprintf(stderr, "\n*** Identifier Table Stats:\n"); 00266 fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers); 00267 fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets); 00268 fprintf(stderr, "Hash density (#identifiers per bucket): %f\n", 00269 NumIdentifiers/(double)NumBuckets); 00270 fprintf(stderr, "Ave identifier length: %f\n", 00271 (AverageIdentifierSize/(double)NumIdentifiers)); 00272 fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength); 00273 00274 // Compute statistics about the memory allocated for identifiers. 00275 HashTable.getAllocator().PrintStats(); 00276 } 00277 00278 //===----------------------------------------------------------------------===// 00279 // SelectorTable Implementation 00280 //===----------------------------------------------------------------------===// 00281 00282 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) { 00283 return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr()); 00284 } 00285 00286 namespace clang { 00287 /// MultiKeywordSelector - One of these variable length records is kept for each 00288 /// selector containing more than one keyword. We use a folding set 00289 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to 00290 /// this class is provided strictly through Selector. 00291 class MultiKeywordSelector 00292 : public DeclarationNameExtra, public llvm::FoldingSetNode { 00293 MultiKeywordSelector(unsigned nKeys) { 00294 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys; 00295 } 00296 public: 00297 // Constructor for keyword selectors. 00298 MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) { 00299 assert((nKeys > 1) && "not a multi-keyword selector"); 00300 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys; 00301 00302 // Fill in the trailing keyword array. 00303 IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1); 00304 for (unsigned i = 0; i != nKeys; ++i) 00305 KeyInfo[i] = IIV[i]; 00306 } 00307 00308 // getName - Derive the full selector name and return it. 00309 std::string getName() const; 00310 00311 unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; } 00312 00313 typedef IdentifierInfo *const *keyword_iterator; 00314 keyword_iterator keyword_begin() const { 00315 return reinterpret_cast<keyword_iterator>(this+1); 00316 } 00317 keyword_iterator keyword_end() const { 00318 return keyword_begin()+getNumArgs(); 00319 } 00320 IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const { 00321 assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index"); 00322 return keyword_begin()[i]; 00323 } 00324 static void Profile(llvm::FoldingSetNodeID &ID, 00325 keyword_iterator ArgTys, unsigned NumArgs) { 00326 ID.AddInteger(NumArgs); 00327 for (unsigned i = 0; i != NumArgs; ++i) 00328 ID.AddPointer(ArgTys[i]); 00329 } 00330 void Profile(llvm::FoldingSetNodeID &ID) { 00331 Profile(ID, keyword_begin(), getNumArgs()); 00332 } 00333 }; 00334 } // end namespace clang. 00335 00336 unsigned Selector::getNumArgs() const { 00337 unsigned IIF = getIdentifierInfoFlag(); 00338 if (IIF <= ZeroArg) 00339 return 0; 00340 if (IIF == OneArg) 00341 return 1; 00342 // We point to a MultiKeywordSelector. 00343 MultiKeywordSelector *SI = getMultiKeywordSelector(); 00344 return SI->getNumArgs(); 00345 } 00346 00347 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const { 00348 if (getIdentifierInfoFlag() < MultiArg) { 00349 assert(argIndex == 0 && "illegal keyword index"); 00350 return getAsIdentifierInfo(); 00351 } 00352 // We point to a MultiKeywordSelector. 00353 MultiKeywordSelector *SI = getMultiKeywordSelector(); 00354 return SI->getIdentifierInfoForSlot(argIndex); 00355 } 00356 00357 StringRef Selector::getNameForSlot(unsigned int argIndex) const { 00358 IdentifierInfo *II = getIdentifierInfoForSlot(argIndex); 00359 return II? II->getName() : StringRef(); 00360 } 00361 00362 std::string MultiKeywordSelector::getName() const { 00363 SmallString<256> Str; 00364 llvm::raw_svector_ostream OS(Str); 00365 for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) { 00366 if (*I) 00367 OS << (*I)->getName(); 00368 OS << ':'; 00369 } 00370 00371 return OS.str(); 00372 } 00373 00374 std::string Selector::getAsString() const { 00375 if (InfoPtr == 0) 00376 return "<null selector>"; 00377 00378 if (getIdentifierInfoFlag() < MultiArg) { 00379 IdentifierInfo *II = getAsIdentifierInfo(); 00380 00381 // If the number of arguments is 0 then II is guaranteed to not be null. 00382 if (getNumArgs() == 0) 00383 return II->getName(); 00384 00385 if (!II) 00386 return ":"; 00387 00388 return II->getName().str() + ":"; 00389 } 00390 00391 // We have a multiple keyword selector. 00392 return getMultiKeywordSelector()->getName(); 00393 } 00394 00395 /// Interpreting the given string using the normal CamelCase 00396 /// conventions, determine whether the given string starts with the 00397 /// given "word", which is assumed to end in a lowercase letter. 00398 static bool startsWithWord(StringRef name, StringRef word) { 00399 if (name.size() < word.size()) return false; 00400 return ((name.size() == word.size() || 00401 !islower(name[word.size()])) 00402 && name.startswith(word)); 00403 } 00404 00405 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) { 00406 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); 00407 if (!first) return OMF_None; 00408 00409 StringRef name = first->getName(); 00410 if (sel.isUnarySelector()) { 00411 if (name == "autorelease") return OMF_autorelease; 00412 if (name == "dealloc") return OMF_dealloc; 00413 if (name == "finalize") return OMF_finalize; 00414 if (name == "release") return OMF_release; 00415 if (name == "retain") return OMF_retain; 00416 if (name == "retainCount") return OMF_retainCount; 00417 if (name == "self") return OMF_self; 00418 } 00419 00420 if (name == "performSelector") return OMF_performSelector; 00421 00422 // The other method families may begin with a prefix of underscores. 00423 while (!name.empty() && name.front() == '_') 00424 name = name.substr(1); 00425 00426 if (name.empty()) return OMF_None; 00427 switch (name.front()) { 00428 case 'a': 00429 if (startsWithWord(name, "alloc")) return OMF_alloc; 00430 break; 00431 case 'c': 00432 if (startsWithWord(name, "copy")) return OMF_copy; 00433 break; 00434 case 'i': 00435 if (startsWithWord(name, "init")) return OMF_init; 00436 break; 00437 case 'm': 00438 if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy; 00439 break; 00440 case 'n': 00441 if (startsWithWord(name, "new")) return OMF_new; 00442 break; 00443 default: 00444 break; 00445 } 00446 00447 return OMF_None; 00448 } 00449 00450 namespace { 00451 struct SelectorTableImpl { 00452 llvm::FoldingSet<MultiKeywordSelector> Table; 00453 llvm::BumpPtrAllocator Allocator; 00454 }; 00455 } // end anonymous namespace. 00456 00457 static SelectorTableImpl &getSelectorTableImpl(void *P) { 00458 return *static_cast<SelectorTableImpl*>(P); 00459 } 00460 00461 /*static*/ Selector 00462 SelectorTable::constructSetterName(IdentifierTable &Idents, 00463 SelectorTable &SelTable, 00464 const IdentifierInfo *Name) { 00465 SmallString<100> SelectorName; 00466 SelectorName = "set"; 00467 SelectorName += Name->getName(); 00468 SelectorName[3] = toupper(SelectorName[3]); 00469 IdentifierInfo *SetterName = &Idents.get(SelectorName); 00470 return SelTable.getUnarySelector(SetterName); 00471 } 00472 00473 size_t SelectorTable::getTotalMemory() const { 00474 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl); 00475 return SelTabImpl.Allocator.getTotalMemory(); 00476 } 00477 00478 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) { 00479 if (nKeys < 2) 00480 return Selector(IIV[0], nKeys); 00481 00482 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl); 00483 00484 // Unique selector, to guarantee there is one per name. 00485 llvm::FoldingSetNodeID ID; 00486 MultiKeywordSelector::Profile(ID, IIV, nKeys); 00487 00488 void *InsertPos = 0; 00489 if (MultiKeywordSelector *SI = 00490 SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos)) 00491 return Selector(SI); 00492 00493 // MultiKeywordSelector objects are not allocated with new because they have a 00494 // variable size array (for parameter types) at the end of them. 00495 unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *); 00496 MultiKeywordSelector *SI = 00497 (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size, 00498 llvm::alignOf<MultiKeywordSelector>()); 00499 new (SI) MultiKeywordSelector(nKeys, IIV); 00500 SelTabImpl.Table.InsertNode(SI, InsertPos); 00501 return Selector(SI); 00502 } 00503 00504 SelectorTable::SelectorTable() { 00505 Impl = new SelectorTableImpl(); 00506 } 00507 00508 SelectorTable::~SelectorTable() { 00509 delete &getSelectorTableImpl(Impl); 00510 } 00511 00512 const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) { 00513 switch (Operator) { 00514 case OO_None: 00515 case NUM_OVERLOADED_OPERATORS: 00516 return 0; 00517 00518 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 00519 case OO_##Name: return Spelling; 00520 #include "clang/Basic/OperatorKinds.def" 00521 } 00522 00523 llvm_unreachable("Invalid OverloadedOperatorKind!"); 00524 }