1 //===- IdentifierTable.cpp - Hash table for identifier lookup -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the IdentifierInfo, IdentifierVisitor, and 10 // IdentifierTable interfaces. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Basic/IdentifierTable.h" 15 #include "clang/Basic/CharInfo.h" 16 #include "clang/Basic/LangOptions.h" 17 #include "clang/Basic/OperatorKinds.h" 18 #include "clang/Basic/Specifiers.h" 19 #include "clang/Basic/TokenKinds.h" 20 #include "llvm/ADT/DenseMapInfo.h" 21 #include "llvm/ADT/FoldingSet.h" 22 #include "llvm/ADT/SmallString.h" 23 #include "llvm/ADT/StringMap.h" 24 #include "llvm/ADT/StringRef.h" 25 #include "llvm/Support/Allocator.h" 26 #include "llvm/Support/ErrorHandling.h" 27 #include "llvm/Support/raw_ostream.h" 28 #include <cassert> 29 #include <cstdio> 30 #include <cstring> 31 #include <string> 32 33 using namespace clang; 34 35 //===----------------------------------------------------------------------===// 36 // IdentifierTable Implementation 37 //===----------------------------------------------------------------------===// 38 39 IdentifierIterator::~IdentifierIterator() = default; 40 41 IdentifierInfoLookup::~IdentifierInfoLookup() = default; 42 43 namespace { 44 45 /// A simple identifier lookup iterator that represents an 46 /// empty sequence of identifiers. 47 class EmptyLookupIterator : public IdentifierIterator 48 { 49 public: 50 StringRef Next() override { return StringRef(); } 51 }; 52 53 } // namespace 54 55 IdentifierIterator *IdentifierInfoLookup::getIdentifiers() { 56 return new EmptyLookupIterator(); 57 } 58 59 IdentifierTable::IdentifierTable(IdentifierInfoLookup *ExternalLookup) 60 : HashTable(8192), // Start with space for 8K identifiers. 61 ExternalLookup(ExternalLookup) {} 62 63 IdentifierTable::IdentifierTable(const LangOptions &LangOpts, 64 IdentifierInfoLookup *ExternalLookup) 65 : IdentifierTable(ExternalLookup) { 66 // Populate the identifier table with info about keywords for the current 67 // language. 68 AddKeywords(LangOpts); 69 } 70 71 //===----------------------------------------------------------------------===// 72 // Language Keyword Implementation 73 //===----------------------------------------------------------------------===// 74 75 // Constants for TokenKinds.def 76 namespace { 77 78 enum { 79 KEYC99 = 0x1, 80 KEYCXX = 0x2, 81 KEYCXX11 = 0x4, 82 KEYGNU = 0x8, 83 KEYMS = 0x10, 84 BOOLSUPPORT = 0x20, 85 KEYALTIVEC = 0x40, 86 KEYNOCXX = 0x80, 87 KEYBORLAND = 0x100, 88 KEYOPENCLC = 0x200, 89 KEYC11 = 0x400, 90 KEYNOMS18 = 0x800, 91 KEYNOOPENCL = 0x1000, 92 WCHARSUPPORT = 0x2000, 93 HALFSUPPORT = 0x4000, 94 CHAR8SUPPORT = 0x8000, 95 KEYCONCEPTS = 0x10000, 96 KEYOBJC = 0x20000, 97 KEYZVECTOR = 0x40000, 98 KEYCOROUTINES = 0x80000, 99 KEYMODULES = 0x100000, 100 KEYCXX20 = 0x200000, 101 KEYOPENCLCXX = 0x400000, 102 KEYMSCOMPAT = 0x800000, 103 KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX20, 104 KEYALL = (0xffffff & ~KEYNOMS18 & 105 ~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude. 106 }; 107 108 /// How a keyword is treated in the selected standard. 109 enum KeywordStatus { 110 KS_Disabled, // Disabled 111 KS_Extension, // Is an extension 112 KS_Enabled, // Enabled 113 KS_Future // Is a keyword in future standard 114 }; 115 116 } // namespace 117 118 /// Translates flags as specified in TokenKinds.def into keyword status 119 /// in the given language standard. 120 static KeywordStatus getKeywordStatus(const LangOptions &LangOpts, 121 unsigned Flags) { 122 if (Flags == KEYALL) return KS_Enabled; 123 if (LangOpts.CPlusPlus && (Flags & KEYCXX)) return KS_Enabled; 124 if (LangOpts.CPlusPlus11 && (Flags & KEYCXX11)) return KS_Enabled; 125 if (LangOpts.CPlusPlus20 && (Flags & KEYCXX20)) return KS_Enabled; 126 if (LangOpts.C99 && (Flags & KEYC99)) return KS_Enabled; 127 if (LangOpts.GNUKeywords && (Flags & KEYGNU)) return KS_Extension; 128 if (LangOpts.MicrosoftExt && (Flags & KEYMS)) return KS_Extension; 129 if (LangOpts.MSVCCompat && (Flags & KEYMSCOMPAT)) return KS_Enabled; 130 if (LangOpts.Borland && (Flags & KEYBORLAND)) return KS_Extension; 131 if (LangOpts.Bool && (Flags & BOOLSUPPORT)) return KS_Enabled; 132 if (LangOpts.Half && (Flags & HALFSUPPORT)) return KS_Enabled; 133 if (LangOpts.WChar && (Flags & WCHARSUPPORT)) return KS_Enabled; 134 if (LangOpts.Char8 && (Flags & CHAR8SUPPORT)) return KS_Enabled; 135 if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) return KS_Enabled; 136 if (LangOpts.ZVector && (Flags & KEYZVECTOR)) return KS_Enabled; 137 if (LangOpts.OpenCL && !LangOpts.OpenCLCPlusPlus && (Flags & KEYOPENCLC)) 138 return KS_Enabled; 139 if (LangOpts.OpenCLCPlusPlus && (Flags & KEYOPENCLCXX)) return KS_Enabled; 140 if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) return KS_Enabled; 141 if (LangOpts.C11 && (Flags & KEYC11)) return KS_Enabled; 142 // We treat bridge casts as objective-C keywords so we can warn on them 143 // in non-arc mode. 144 if (LangOpts.ObjC && (Flags & KEYOBJC)) return KS_Enabled; 145 if (LangOpts.CPlusPlus20 && (Flags & KEYCONCEPTS)) return KS_Enabled; 146 if (LangOpts.Coroutines && (Flags & KEYCOROUTINES)) return KS_Enabled; 147 if (LangOpts.ModulesTS && (Flags & KEYMODULES)) return KS_Enabled; 148 if (LangOpts.CPlusPlus && (Flags & KEYALLCXX)) return KS_Future; 149 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus20 && (Flags & CHAR8SUPPORT)) 150 return KS_Future; 151 return KS_Disabled; 152 } 153 154 /// AddKeyword - This method is used to associate a token ID with specific 155 /// identifiers because they are language keywords. This causes the lexer to 156 /// automatically map matching identifiers to specialized token codes. 157 static void AddKeyword(StringRef Keyword, 158 tok::TokenKind TokenCode, unsigned Flags, 159 const LangOptions &LangOpts, IdentifierTable &Table) { 160 KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags); 161 162 // Don't add this keyword under MSVCCompat. 163 if (LangOpts.MSVCCompat && (Flags & KEYNOMS18) && 164 !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015)) 165 return; 166 167 // Don't add this keyword under OpenCL. 168 if (LangOpts.OpenCL && (Flags & KEYNOOPENCL)) 169 return; 170 171 // Don't add this keyword if disabled in this language. 172 if (AddResult == KS_Disabled) return; 173 174 IdentifierInfo &Info = 175 Table.get(Keyword, AddResult == KS_Future ? tok::identifier : TokenCode); 176 Info.setIsExtensionToken(AddResult == KS_Extension); 177 Info.setIsFutureCompatKeyword(AddResult == KS_Future); 178 } 179 180 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative 181 /// representations. 182 static void AddCXXOperatorKeyword(StringRef Keyword, 183 tok::TokenKind TokenCode, 184 IdentifierTable &Table) { 185 IdentifierInfo &Info = Table.get(Keyword, TokenCode); 186 Info.setIsCPlusPlusOperatorKeyword(); 187 } 188 189 /// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector" 190 /// or "property". 191 static void AddObjCKeyword(StringRef Name, 192 tok::ObjCKeywordKind ObjCID, 193 IdentifierTable &Table) { 194 Table.get(Name).setObjCKeywordID(ObjCID); 195 } 196 197 /// AddKeywords - Add all keywords to the symbol table. 198 /// 199 void IdentifierTable::AddKeywords(const LangOptions &LangOpts) { 200 // Add keywords and tokens for the current language. 201 #define KEYWORD(NAME, FLAGS) \ 202 AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \ 203 FLAGS, LangOpts, *this); 204 #define ALIAS(NAME, TOK, FLAGS) \ 205 AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \ 206 FLAGS, LangOpts, *this); 207 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \ 208 if (LangOpts.CXXOperatorNames) \ 209 AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this); 210 #define OBJC_AT_KEYWORD(NAME) \ 211 if (LangOpts.ObjC) \ 212 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this); 213 #define TESTING_KEYWORD(NAME, FLAGS) 214 #include "clang/Basic/TokenKinds.def" 215 216 if (LangOpts.ParseUnknownAnytype) 217 AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL, 218 LangOpts, *this); 219 220 if (LangOpts.DeclSpecKeyword) 221 AddKeyword("__declspec", tok::kw___declspec, KEYALL, LangOpts, *this); 222 223 // Add the 'import' contextual keyword. 224 get("import").setModulesImport(true); 225 } 226 227 /// Checks if the specified token kind represents a keyword in the 228 /// specified language. 229 /// \returns Status of the keyword in the language. 230 static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts, 231 tok::TokenKind K) { 232 switch (K) { 233 #define KEYWORD(NAME, FLAGS) \ 234 case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS); 235 #include "clang/Basic/TokenKinds.def" 236 default: return KS_Disabled; 237 } 238 } 239 240 /// Returns true if the identifier represents a keyword in the 241 /// specified language. 242 bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) const { 243 switch (getTokenKwStatus(LangOpts, getTokenID())) { 244 case KS_Enabled: 245 case KS_Extension: 246 return true; 247 default: 248 return false; 249 } 250 } 251 252 /// Returns true if the identifier represents a C++ keyword in the 253 /// specified language. 254 bool IdentifierInfo::isCPlusPlusKeyword(const LangOptions &LangOpts) const { 255 if (!LangOpts.CPlusPlus || !isKeyword(LangOpts)) 256 return false; 257 // This is a C++ keyword if this identifier is not a keyword when checked 258 // using LangOptions without C++ support. 259 LangOptions LangOptsNoCPP = LangOpts; 260 LangOptsNoCPP.CPlusPlus = false; 261 LangOptsNoCPP.CPlusPlus11 = false; 262 LangOptsNoCPP.CPlusPlus20 = false; 263 return !isKeyword(LangOptsNoCPP); 264 } 265 266 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const { 267 // We use a perfect hash function here involving the length of the keyword, 268 // the first and third character. For preprocessor ID's there are no 269 // collisions (if there were, the switch below would complain about duplicate 270 // case values). Note that this depends on 'if' being null terminated. 271 272 #define HASH(LEN, FIRST, THIRD) \ 273 (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31) 274 #define CASE(LEN, FIRST, THIRD, NAME) \ 275 case HASH(LEN, FIRST, THIRD): \ 276 return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME 277 278 unsigned Len = getLength(); 279 if (Len < 2) return tok::pp_not_keyword; 280 const char *Name = getNameStart(); 281 switch (HASH(Len, Name[0], Name[2])) { 282 default: return tok::pp_not_keyword; 283 CASE( 2, 'i', '\0', if); 284 CASE( 4, 'e', 'i', elif); 285 CASE( 4, 'e', 's', else); 286 CASE( 4, 'l', 'n', line); 287 CASE( 4, 's', 'c', sccs); 288 CASE( 5, 'e', 'd', endif); 289 CASE( 5, 'e', 'r', error); 290 CASE( 5, 'i', 'e', ident); 291 CASE( 5, 'i', 'd', ifdef); 292 CASE( 5, 'u', 'd', undef); 293 294 CASE( 6, 'a', 's', assert); 295 CASE( 6, 'd', 'f', define); 296 CASE( 6, 'i', 'n', ifndef); 297 CASE( 6, 'i', 'p', import); 298 CASE( 6, 'p', 'a', pragma); 299 300 CASE( 7, 'd', 'f', defined); 301 CASE( 7, 'i', 'c', include); 302 CASE( 7, 'w', 'r', warning); 303 304 CASE( 8, 'u', 'a', unassert); 305 CASE(12, 'i', 'c', include_next); 306 307 CASE(14, '_', 'p', __public_macro); 308 309 CASE(15, '_', 'p', __private_macro); 310 311 CASE(16, '_', 'i', __include_macros); 312 #undef CASE 313 #undef HASH 314 } 315 } 316 317 //===----------------------------------------------------------------------===// 318 // Stats Implementation 319 //===----------------------------------------------------------------------===// 320 321 /// PrintStats - Print statistics about how well the identifier table is doing 322 /// at hashing identifiers. 323 void IdentifierTable::PrintStats() const { 324 unsigned NumBuckets = HashTable.getNumBuckets(); 325 unsigned NumIdentifiers = HashTable.getNumItems(); 326 unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers; 327 unsigned AverageIdentifierSize = 0; 328 unsigned MaxIdentifierLength = 0; 329 330 // TODO: Figure out maximum times an identifier had to probe for -stats. 331 for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator 332 I = HashTable.begin(), E = HashTable.end(); I != E; ++I) { 333 unsigned IdLen = I->getKeyLength(); 334 AverageIdentifierSize += IdLen; 335 if (MaxIdentifierLength < IdLen) 336 MaxIdentifierLength = IdLen; 337 } 338 339 fprintf(stderr, "\n*** Identifier Table Stats:\n"); 340 fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers); 341 fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets); 342 fprintf(stderr, "Hash density (#identifiers per bucket): %f\n", 343 NumIdentifiers/(double)NumBuckets); 344 fprintf(stderr, "Ave identifier length: %f\n", 345 (AverageIdentifierSize/(double)NumIdentifiers)); 346 fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength); 347 348 // Compute statistics about the memory allocated for identifiers. 349 HashTable.getAllocator().PrintStats(); 350 } 351 352 //===----------------------------------------------------------------------===// 353 // SelectorTable Implementation 354 //===----------------------------------------------------------------------===// 355 356 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) { 357 return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr()); 358 } 359 360 namespace clang { 361 362 /// One of these variable length records is kept for each 363 /// selector containing more than one keyword. We use a folding set 364 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to 365 /// this class is provided strictly through Selector. 366 class alignas(IdentifierInfoAlignment) MultiKeywordSelector 367 : public detail::DeclarationNameExtra, 368 public llvm::FoldingSetNode { 369 MultiKeywordSelector(unsigned nKeys) : DeclarationNameExtra(nKeys) {} 370 371 public: 372 // Constructor for keyword selectors. 373 MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) 374 : DeclarationNameExtra(nKeys) { 375 assert((nKeys > 1) && "not a multi-keyword selector"); 376 377 // Fill in the trailing keyword array. 378 IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this + 1); 379 for (unsigned i = 0; i != nKeys; ++i) 380 KeyInfo[i] = IIV[i]; 381 } 382 383 // getName - Derive the full selector name and return it. 384 std::string getName() const; 385 386 using DeclarationNameExtra::getNumArgs; 387 388 using keyword_iterator = IdentifierInfo *const *; 389 390 keyword_iterator keyword_begin() const { 391 return reinterpret_cast<keyword_iterator>(this + 1); 392 } 393 394 keyword_iterator keyword_end() const { 395 return keyword_begin() + getNumArgs(); 396 } 397 398 IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const { 399 assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index"); 400 return keyword_begin()[i]; 401 } 402 403 static void Profile(llvm::FoldingSetNodeID &ID, keyword_iterator ArgTys, 404 unsigned NumArgs) { 405 ID.AddInteger(NumArgs); 406 for (unsigned i = 0; i != NumArgs; ++i) 407 ID.AddPointer(ArgTys[i]); 408 } 409 410 void Profile(llvm::FoldingSetNodeID &ID) { 411 Profile(ID, keyword_begin(), getNumArgs()); 412 } 413 }; 414 415 } // namespace clang. 416 417 bool Selector::isKeywordSelector(ArrayRef<StringRef> Names) const { 418 assert(!Names.empty() && "must have >= 1 selector slots"); 419 if (getNumArgs() != Names.size()) 420 return false; 421 for (unsigned I = 0, E = Names.size(); I != E; ++I) { 422 if (getNameForSlot(I) != Names[I]) 423 return false; 424 } 425 return true; 426 } 427 428 bool Selector::isUnarySelector(StringRef Name) const { 429 return isUnarySelector() && getNameForSlot(0) == Name; 430 } 431 432 unsigned Selector::getNumArgs() const { 433 unsigned IIF = getIdentifierInfoFlag(); 434 if (IIF <= ZeroArg) 435 return 0; 436 if (IIF == OneArg) 437 return 1; 438 // We point to a MultiKeywordSelector. 439 MultiKeywordSelector *SI = getMultiKeywordSelector(); 440 return SI->getNumArgs(); 441 } 442 443 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const { 444 if (getIdentifierInfoFlag() < MultiArg) { 445 assert(argIndex == 0 && "illegal keyword index"); 446 return getAsIdentifierInfo(); 447 } 448 449 // We point to a MultiKeywordSelector. 450 MultiKeywordSelector *SI = getMultiKeywordSelector(); 451 return SI->getIdentifierInfoForSlot(argIndex); 452 } 453 454 StringRef Selector::getNameForSlot(unsigned int argIndex) const { 455 IdentifierInfo *II = getIdentifierInfoForSlot(argIndex); 456 return II ? II->getName() : StringRef(); 457 } 458 459 std::string MultiKeywordSelector::getName() const { 460 SmallString<256> Str; 461 llvm::raw_svector_ostream OS(Str); 462 for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) { 463 if (*I) 464 OS << (*I)->getName(); 465 OS << ':'; 466 } 467 468 return std::string(OS.str()); 469 } 470 471 std::string Selector::getAsString() const { 472 if (InfoPtr == 0) 473 return "<null selector>"; 474 475 if (getIdentifierInfoFlag() < MultiArg) { 476 IdentifierInfo *II = getAsIdentifierInfo(); 477 478 if (getNumArgs() == 0) { 479 assert(II && "If the number of arguments is 0 then II is guaranteed to " 480 "not be null."); 481 return std::string(II->getName()); 482 } 483 484 if (!II) 485 return ":"; 486 487 return II->getName().str() + ":"; 488 } 489 490 // We have a multiple keyword selector. 491 return getMultiKeywordSelector()->getName(); 492 } 493 494 void Selector::print(llvm::raw_ostream &OS) const { 495 OS << getAsString(); 496 } 497 498 LLVM_DUMP_METHOD void Selector::dump() const { print(llvm::errs()); } 499 500 /// Interpreting the given string using the normal CamelCase 501 /// conventions, determine whether the given string starts with the 502 /// given "word", which is assumed to end in a lowercase letter. 503 static bool startsWithWord(StringRef name, StringRef word) { 504 if (name.size() < word.size()) return false; 505 return ((name.size() == word.size() || !isLowercase(name[word.size()])) && 506 name.startswith(word)); 507 } 508 509 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) { 510 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); 511 if (!first) return OMF_None; 512 513 StringRef name = first->getName(); 514 if (sel.isUnarySelector()) { 515 if (name == "autorelease") return OMF_autorelease; 516 if (name == "dealloc") return OMF_dealloc; 517 if (name == "finalize") return OMF_finalize; 518 if (name == "release") return OMF_release; 519 if (name == "retain") return OMF_retain; 520 if (name == "retainCount") return OMF_retainCount; 521 if (name == "self") return OMF_self; 522 if (name == "initialize") return OMF_initialize; 523 } 524 525 if (name == "performSelector" || name == "performSelectorInBackground" || 526 name == "performSelectorOnMainThread") 527 return OMF_performSelector; 528 529 // The other method families may begin with a prefix of underscores. 530 while (!name.empty() && name.front() == '_') 531 name = name.substr(1); 532 533 if (name.empty()) return OMF_None; 534 switch (name.front()) { 535 case 'a': 536 if (startsWithWord(name, "alloc")) return OMF_alloc; 537 break; 538 case 'c': 539 if (startsWithWord(name, "copy")) return OMF_copy; 540 break; 541 case 'i': 542 if (startsWithWord(name, "init")) return OMF_init; 543 break; 544 case 'm': 545 if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy; 546 break; 547 case 'n': 548 if (startsWithWord(name, "new")) return OMF_new; 549 break; 550 default: 551 break; 552 } 553 554 return OMF_None; 555 } 556 557 ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) { 558 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); 559 if (!first) return OIT_None; 560 561 StringRef name = first->getName(); 562 563 if (name.empty()) return OIT_None; 564 switch (name.front()) { 565 case 'a': 566 if (startsWithWord(name, "array")) return OIT_Array; 567 break; 568 case 'd': 569 if (startsWithWord(name, "default")) return OIT_ReturnsSelf; 570 if (startsWithWord(name, "dictionary")) return OIT_Dictionary; 571 break; 572 case 's': 573 if (startsWithWord(name, "shared")) return OIT_ReturnsSelf; 574 if (startsWithWord(name, "standard")) return OIT_Singleton; 575 break; 576 case 'i': 577 if (startsWithWord(name, "init")) return OIT_Init; 578 break; 579 default: 580 break; 581 } 582 return OIT_None; 583 } 584 585 ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) { 586 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); 587 if (!first) return SFF_None; 588 589 StringRef name = first->getName(); 590 591 switch (name.front()) { 592 case 'a': 593 if (name == "appendFormat") return SFF_NSString; 594 break; 595 596 case 'i': 597 if (name == "initWithFormat") return SFF_NSString; 598 break; 599 600 case 'l': 601 if (name == "localizedStringWithFormat") return SFF_NSString; 602 break; 603 604 case 's': 605 if (name == "stringByAppendingFormat" || 606 name == "stringWithFormat") return SFF_NSString; 607 break; 608 } 609 return SFF_None; 610 } 611 612 namespace { 613 614 struct SelectorTableImpl { 615 llvm::FoldingSet<MultiKeywordSelector> Table; 616 llvm::BumpPtrAllocator Allocator; 617 }; 618 619 } // namespace 620 621 static SelectorTableImpl &getSelectorTableImpl(void *P) { 622 return *static_cast<SelectorTableImpl*>(P); 623 } 624 625 SmallString<64> 626 SelectorTable::constructSetterName(StringRef Name) { 627 SmallString<64> SetterName("set"); 628 SetterName += Name; 629 SetterName[3] = toUppercase(SetterName[3]); 630 return SetterName; 631 } 632 633 Selector 634 SelectorTable::constructSetterSelector(IdentifierTable &Idents, 635 SelectorTable &SelTable, 636 const IdentifierInfo *Name) { 637 IdentifierInfo *SetterName = 638 &Idents.get(constructSetterName(Name->getName())); 639 return SelTable.getUnarySelector(SetterName); 640 } 641 642 std::string SelectorTable::getPropertyNameFromSetterSelector(Selector Sel) { 643 StringRef Name = Sel.getNameForSlot(0); 644 assert(Name.startswith("set") && "invalid setter name"); 645 return (Twine(toLowercase(Name[3])) + Name.drop_front(4)).str(); 646 } 647 648 size_t SelectorTable::getTotalMemory() const { 649 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl); 650 return SelTabImpl.Allocator.getTotalMemory(); 651 } 652 653 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) { 654 if (nKeys < 2) 655 return Selector(IIV[0], nKeys); 656 657 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl); 658 659 // Unique selector, to guarantee there is one per name. 660 llvm::FoldingSetNodeID ID; 661 MultiKeywordSelector::Profile(ID, IIV, nKeys); 662 663 void *InsertPos = nullptr; 664 if (MultiKeywordSelector *SI = 665 SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos)) 666 return Selector(SI); 667 668 // MultiKeywordSelector objects are not allocated with new because they have a 669 // variable size array (for parameter types) at the end of them. 670 unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *); 671 MultiKeywordSelector *SI = 672 (MultiKeywordSelector *)SelTabImpl.Allocator.Allocate( 673 Size, alignof(MultiKeywordSelector)); 674 new (SI) MultiKeywordSelector(nKeys, IIV); 675 SelTabImpl.Table.InsertNode(SI, InsertPos); 676 return Selector(SI); 677 } 678 679 SelectorTable::SelectorTable() { 680 Impl = new SelectorTableImpl(); 681 } 682 683 SelectorTable::~SelectorTable() { 684 delete &getSelectorTableImpl(Impl); 685 } 686 687 const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) { 688 switch (Operator) { 689 case OO_None: 690 case NUM_OVERLOADED_OPERATORS: 691 return nullptr; 692 693 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 694 case OO_##Name: return Spelling; 695 #include "clang/Basic/OperatorKinds.def" 696 } 697 698 llvm_unreachable("Invalid OverloadedOperatorKind!"); 699 } 700 701 StringRef clang::getNullabilitySpelling(NullabilityKind kind, 702 bool isContextSensitive) { 703 switch (kind) { 704 case NullabilityKind::NonNull: 705 return isContextSensitive ? "nonnull" : "_Nonnull"; 706 707 case NullabilityKind::Nullable: 708 return isContextSensitive ? "nullable" : "_Nullable"; 709 710 case NullabilityKind::Unspecified: 711 return isContextSensitive ? "null_unspecified" : "_Null_unspecified"; 712 } 713 llvm_unreachable("Unknown nullability kind."); 714 } 715