IdentifierTable.cpp 23 KB

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