IdentifierTable.cpp 22 KB

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