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