IdentifierTable.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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) const {
  219. switch (getTokenKwStatus(LangOpts, getTokenID())) {
  220. case KS_Enabled:
  221. case KS_Extension:
  222. return true;
  223. default:
  224. return false;
  225. }
  226. }
  227. /// \brief Returns true if the identifier represents a C++ keyword in the
  228. /// specified language.
  229. bool IdentifierInfo::isCPlusPlusKeyword(const LangOptions &LangOpts) const {
  230. if (!LangOpts.CPlusPlus || !isKeyword(LangOpts))
  231. return false;
  232. // This is a C++ keyword if this identifier is not a keyword when checked
  233. // using LangOptions without C++ support.
  234. LangOptions LangOptsNoCPP = LangOpts;
  235. LangOptsNoCPP.CPlusPlus = false;
  236. LangOptsNoCPP.CPlusPlus11 = false;
  237. return !isKeyword(LangOptsNoCPP);
  238. }
  239. tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
  240. // We use a perfect hash function here involving the length of the keyword,
  241. // the first and third character. For preprocessor ID's there are no
  242. // collisions (if there were, the switch below would complain about duplicate
  243. // case values). Note that this depends on 'if' being null terminated.
  244. #define HASH(LEN, FIRST, THIRD) \
  245. (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
  246. #define CASE(LEN, FIRST, THIRD, NAME) \
  247. case HASH(LEN, FIRST, THIRD): \
  248. return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
  249. unsigned Len = getLength();
  250. if (Len < 2) return tok::pp_not_keyword;
  251. const char *Name = getNameStart();
  252. switch (HASH(Len, Name[0], Name[2])) {
  253. default: return tok::pp_not_keyword;
  254. CASE( 2, 'i', '\0', if);
  255. CASE( 4, 'e', 'i', elif);
  256. CASE( 4, 'e', 's', else);
  257. CASE( 4, 'l', 'n', line);
  258. CASE( 4, 's', 'c', sccs);
  259. CASE( 5, 'e', 'd', endif);
  260. CASE( 5, 'e', 'r', error);
  261. CASE( 5, 'i', 'e', ident);
  262. CASE( 5, 'i', 'd', ifdef);
  263. CASE( 5, 'u', 'd', undef);
  264. CASE( 6, 'a', 's', assert);
  265. CASE( 6, 'd', 'f', define);
  266. CASE( 6, 'i', 'n', ifndef);
  267. CASE( 6, 'i', 'p', import);
  268. CASE( 6, 'p', 'a', pragma);
  269. CASE( 7, 'd', 'f', defined);
  270. CASE( 7, 'i', 'c', include);
  271. CASE( 7, 'w', 'r', warning);
  272. CASE( 8, 'u', 'a', unassert);
  273. CASE(12, 'i', 'c', include_next);
  274. CASE(14, '_', 'p', __public_macro);
  275. CASE(15, '_', 'p', __private_macro);
  276. CASE(16, '_', 'i', __include_macros);
  277. #undef CASE
  278. #undef HASH
  279. }
  280. }
  281. //===----------------------------------------------------------------------===//
  282. // Stats Implementation
  283. //===----------------------------------------------------------------------===//
  284. /// PrintStats - Print statistics about how well the identifier table is doing
  285. /// at hashing identifiers.
  286. void IdentifierTable::PrintStats() const {
  287. unsigned NumBuckets = HashTable.getNumBuckets();
  288. unsigned NumIdentifiers = HashTable.getNumItems();
  289. unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
  290. unsigned AverageIdentifierSize = 0;
  291. unsigned MaxIdentifierLength = 0;
  292. // TODO: Figure out maximum times an identifier had to probe for -stats.
  293. for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
  294. I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
  295. unsigned IdLen = I->getKeyLength();
  296. AverageIdentifierSize += IdLen;
  297. if (MaxIdentifierLength < IdLen)
  298. MaxIdentifierLength = IdLen;
  299. }
  300. fprintf(stderr, "\n*** Identifier Table Stats:\n");
  301. fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
  302. fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
  303. fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
  304. NumIdentifiers/(double)NumBuckets);
  305. fprintf(stderr, "Ave identifier length: %f\n",
  306. (AverageIdentifierSize/(double)NumIdentifiers));
  307. fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
  308. // Compute statistics about the memory allocated for identifiers.
  309. HashTable.getAllocator().PrintStats();
  310. }
  311. //===----------------------------------------------------------------------===//
  312. // SelectorTable Implementation
  313. //===----------------------------------------------------------------------===//
  314. unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
  315. return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
  316. }
  317. namespace clang {
  318. /// MultiKeywordSelector - One of these variable length records is kept for each
  319. /// selector containing more than one keyword. We use a folding set
  320. /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
  321. /// this class is provided strictly through Selector.
  322. class MultiKeywordSelector
  323. : public DeclarationNameExtra, public llvm::FoldingSetNode {
  324. MultiKeywordSelector(unsigned nKeys) {
  325. ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
  326. }
  327. public:
  328. // Constructor for keyword selectors.
  329. MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) {
  330. assert((nKeys > 1) && "not a multi-keyword selector");
  331. ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
  332. // Fill in the trailing keyword array.
  333. IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
  334. for (unsigned i = 0; i != nKeys; ++i)
  335. KeyInfo[i] = IIV[i];
  336. }
  337. // getName - Derive the full selector name and return it.
  338. std::string getName() const;
  339. unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
  340. typedef IdentifierInfo *const *keyword_iterator;
  341. keyword_iterator keyword_begin() const {
  342. return reinterpret_cast<keyword_iterator>(this+1);
  343. }
  344. keyword_iterator keyword_end() const {
  345. return keyword_begin()+getNumArgs();
  346. }
  347. IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
  348. assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
  349. return keyword_begin()[i];
  350. }
  351. static void Profile(llvm::FoldingSetNodeID &ID,
  352. keyword_iterator ArgTys, unsigned NumArgs) {
  353. ID.AddInteger(NumArgs);
  354. for (unsigned i = 0; i != NumArgs; ++i)
  355. ID.AddPointer(ArgTys[i]);
  356. }
  357. void Profile(llvm::FoldingSetNodeID &ID) {
  358. Profile(ID, keyword_begin(), getNumArgs());
  359. }
  360. };
  361. } // end namespace clang.
  362. unsigned Selector::getNumArgs() const {
  363. unsigned IIF = getIdentifierInfoFlag();
  364. if (IIF <= ZeroArg)
  365. return 0;
  366. if (IIF == OneArg)
  367. return 1;
  368. // We point to a MultiKeywordSelector.
  369. MultiKeywordSelector *SI = getMultiKeywordSelector();
  370. return SI->getNumArgs();
  371. }
  372. IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
  373. if (getIdentifierInfoFlag() < MultiArg) {
  374. assert(argIndex == 0 && "illegal keyword index");
  375. return getAsIdentifierInfo();
  376. }
  377. // We point to a MultiKeywordSelector.
  378. MultiKeywordSelector *SI = getMultiKeywordSelector();
  379. return SI->getIdentifierInfoForSlot(argIndex);
  380. }
  381. StringRef Selector::getNameForSlot(unsigned int argIndex) const {
  382. IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
  383. return II? II->getName() : StringRef();
  384. }
  385. std::string MultiKeywordSelector::getName() const {
  386. SmallString<256> Str;
  387. llvm::raw_svector_ostream OS(Str);
  388. for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
  389. if (*I)
  390. OS << (*I)->getName();
  391. OS << ':';
  392. }
  393. return OS.str();
  394. }
  395. std::string Selector::getAsString() const {
  396. if (InfoPtr == 0)
  397. return "<null selector>";
  398. if (getIdentifierInfoFlag() < MultiArg) {
  399. IdentifierInfo *II = getAsIdentifierInfo();
  400. if (getNumArgs() == 0) {
  401. assert(II && "If the number of arguments is 0 then II is guaranteed to "
  402. "not be null.");
  403. return II->getName();
  404. }
  405. if (!II)
  406. return ":";
  407. return II->getName().str() + ":";
  408. }
  409. // We have a multiple keyword selector.
  410. return getMultiKeywordSelector()->getName();
  411. }
  412. void Selector::print(llvm::raw_ostream &OS) const {
  413. OS << getAsString();
  414. }
  415. /// Interpreting the given string using the normal CamelCase
  416. /// conventions, determine whether the given string starts with the
  417. /// given "word", which is assumed to end in a lowercase letter.
  418. static bool startsWithWord(StringRef name, StringRef word) {
  419. if (name.size() < word.size()) return false;
  420. return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
  421. name.startswith(word));
  422. }
  423. ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
  424. IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
  425. if (!first) return OMF_None;
  426. StringRef name = first->getName();
  427. if (sel.isUnarySelector()) {
  428. if (name == "autorelease") return OMF_autorelease;
  429. if (name == "dealloc") return OMF_dealloc;
  430. if (name == "finalize") return OMF_finalize;
  431. if (name == "release") return OMF_release;
  432. if (name == "retain") return OMF_retain;
  433. if (name == "retainCount") return OMF_retainCount;
  434. if (name == "self") return OMF_self;
  435. if (name == "initialize") return OMF_initialize;
  436. }
  437. if (name == "performSelector" || name == "performSelectorInBackground" ||
  438. name == "performSelectorOnMainThread")
  439. return OMF_performSelector;
  440. // The other method families may begin with a prefix of underscores.
  441. while (!name.empty() && name.front() == '_')
  442. name = name.substr(1);
  443. if (name.empty()) return OMF_None;
  444. switch (name.front()) {
  445. case 'a':
  446. if (startsWithWord(name, "alloc")) return OMF_alloc;
  447. break;
  448. case 'c':
  449. if (startsWithWord(name, "copy")) return OMF_copy;
  450. break;
  451. case 'i':
  452. if (startsWithWord(name, "init")) return OMF_init;
  453. break;
  454. case 'm':
  455. if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
  456. break;
  457. case 'n':
  458. if (startsWithWord(name, "new")) return OMF_new;
  459. break;
  460. default:
  461. break;
  462. }
  463. return OMF_None;
  464. }
  465. ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
  466. IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
  467. if (!first) return OIT_None;
  468. StringRef name = first->getName();
  469. if (name.empty()) return OIT_None;
  470. switch (name.front()) {
  471. case 'a':
  472. if (startsWithWord(name, "array")) return OIT_Array;
  473. break;
  474. case 'd':
  475. if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
  476. if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
  477. break;
  478. case 's':
  479. if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
  480. if (startsWithWord(name, "standard")) return OIT_Singleton;
  481. break;
  482. case 'i':
  483. if (startsWithWord(name, "init")) return OIT_Init;
  484. default:
  485. break;
  486. }
  487. return OIT_None;
  488. }
  489. ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) {
  490. IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
  491. if (!first) return SFF_None;
  492. StringRef name = first->getName();
  493. switch (name.front()) {
  494. case 'a':
  495. if (name == "appendFormat") return SFF_NSString;
  496. break;
  497. case 'i':
  498. if (name == "initWithFormat") return SFF_NSString;
  499. break;
  500. case 'l':
  501. if (name == "localizedStringWithFormat") return SFF_NSString;
  502. break;
  503. case 's':
  504. if (name == "stringByAppendingFormat" ||
  505. name == "stringWithFormat") return SFF_NSString;
  506. break;
  507. }
  508. return SFF_None;
  509. }
  510. namespace {
  511. struct SelectorTableImpl {
  512. llvm::FoldingSet<MultiKeywordSelector> Table;
  513. llvm::BumpPtrAllocator Allocator;
  514. };
  515. } // end anonymous namespace.
  516. static SelectorTableImpl &getSelectorTableImpl(void *P) {
  517. return *static_cast<SelectorTableImpl*>(P);
  518. }
  519. SmallString<64>
  520. SelectorTable::constructSetterName(StringRef Name) {
  521. SmallString<64> SetterName("set");
  522. SetterName += Name;
  523. SetterName[3] = toUppercase(SetterName[3]);
  524. return SetterName;
  525. }
  526. Selector
  527. SelectorTable::constructSetterSelector(IdentifierTable &Idents,
  528. SelectorTable &SelTable,
  529. const IdentifierInfo *Name) {
  530. IdentifierInfo *SetterName =
  531. &Idents.get(constructSetterName(Name->getName()));
  532. return SelTable.getUnarySelector(SetterName);
  533. }
  534. size_t SelectorTable::getTotalMemory() const {
  535. SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
  536. return SelTabImpl.Allocator.getTotalMemory();
  537. }
  538. Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
  539. if (nKeys < 2)
  540. return Selector(IIV[0], nKeys);
  541. SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
  542. // Unique selector, to guarantee there is one per name.
  543. llvm::FoldingSetNodeID ID;
  544. MultiKeywordSelector::Profile(ID, IIV, nKeys);
  545. void *InsertPos = nullptr;
  546. if (MultiKeywordSelector *SI =
  547. SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
  548. return Selector(SI);
  549. // MultiKeywordSelector objects are not allocated with new because they have a
  550. // variable size array (for parameter types) at the end of them.
  551. unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
  552. MultiKeywordSelector *SI =
  553. (MultiKeywordSelector *)SelTabImpl.Allocator.Allocate(
  554. Size, alignof(MultiKeywordSelector));
  555. new (SI) MultiKeywordSelector(nKeys, IIV);
  556. SelTabImpl.Table.InsertNode(SI, InsertPos);
  557. return Selector(SI);
  558. }
  559. SelectorTable::SelectorTable() {
  560. Impl = new SelectorTableImpl();
  561. }
  562. SelectorTable::~SelectorTable() {
  563. delete &getSelectorTableImpl(Impl);
  564. }
  565. const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
  566. switch (Operator) {
  567. case OO_None:
  568. case NUM_OVERLOADED_OPERATORS:
  569. return nullptr;
  570. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  571. case OO_##Name: return Spelling;
  572. #include "clang/Basic/OperatorKinds.def"
  573. }
  574. llvm_unreachable("Invalid OverloadedOperatorKind!");
  575. }
  576. StringRef clang::getNullabilitySpelling(NullabilityKind kind,
  577. bool isContextSensitive) {
  578. switch (kind) {
  579. case NullabilityKind::NonNull:
  580. return isContextSensitive ? "nonnull" : "_Nonnull";
  581. case NullabilityKind::Nullable:
  582. return isContextSensitive ? "nullable" : "_Nullable";
  583. case NullabilityKind::Unspecified:
  584. return isContextSensitive ? "null_unspecified" : "_Null_unspecified";
  585. }
  586. llvm_unreachable("Unknown nullability kind.");
  587. }