clang  14.0.0git
IdentifierTable.cpp
Go to the documentation of this file.
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 
15 #include "clang/Basic/CharInfo.h"
18 #include "clang/Basic/Specifiers.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/Support/Allocator.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <cassert>
30 #include <cstdio>
31 #include <cstring>
32 #include <string>
33 
34 using namespace clang;
35 
36 // A check to make sure the ObjCOrBuiltinID has sufficient room to store the
37 // largest possible target/aux-target combination. If we exceed this, we likely
38 // need to just change the ObjCOrBuiltinIDBits value in IdentifierTable.h.
39 static_assert(2 * LargestBuiltinID < (2 << (ObjCOrBuiltinIDBits - 1)),
40  "Insufficient ObjCOrBuiltinID Bits");
41 
42 //===----------------------------------------------------------------------===//
43 // IdentifierTable Implementation
44 //===----------------------------------------------------------------------===//
45 
47 
49 
50 namespace {
51 
52 /// A simple identifier lookup iterator that represents an
53 /// empty sequence of identifiers.
54 class EmptyLookupIterator : public IdentifierIterator
55 {
56 public:
57  StringRef Next() override { return StringRef(); }
58 };
59 
60 } // namespace
61 
63  return new EmptyLookupIterator();
64 }
65 
67  : HashTable(8192), // Start with space for 8K identifiers.
68  ExternalLookup(ExternalLookup) {}
69 
71  IdentifierInfoLookup *ExternalLookup)
72  : IdentifierTable(ExternalLookup) {
73  // Populate the identifier table with info about keywords for the current
74  // language.
75  AddKeywords(LangOpts);
76 }
77 
78 //===----------------------------------------------------------------------===//
79 // Language Keyword Implementation
80 //===----------------------------------------------------------------------===//
81 
82 // Constants for TokenKinds.def
83 namespace {
84 
85  enum {
86  KEYC99 = 0x1,
87  KEYCXX = 0x2,
88  KEYCXX11 = 0x4,
89  KEYGNU = 0x8,
90  KEYMS = 0x10,
91  BOOLSUPPORT = 0x20,
92  KEYALTIVEC = 0x40,
93  KEYNOCXX = 0x80,
94  KEYBORLAND = 0x100,
95  KEYOPENCLC = 0x200,
96  KEYC11 = 0x400,
97  KEYNOMS18 = 0x800,
98  KEYNOOPENCL = 0x1000,
99  WCHARSUPPORT = 0x2000,
100  HALFSUPPORT = 0x4000,
101  CHAR8SUPPORT = 0x8000,
102  KEYCONCEPTS = 0x10000,
103  KEYOBJC = 0x20000,
104  KEYZVECTOR = 0x40000,
105  KEYCOROUTINES = 0x80000,
106  KEYMODULES = 0x100000,
107  KEYCXX20 = 0x200000,
108  KEYOPENCLCXX = 0x400000,
109  KEYMSCOMPAT = 0x800000,
110  KEYSYCL = 0x1000000,
111  KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX20,
112  KEYALL = (0x1ffffff & ~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  if (LangOpts.isSYCL() && (Flags & KEYSYCL))
160  return KS_Enabled;
161  return KS_Disabled;
162 }
163 
164 /// AddKeyword - This method is used to associate a token ID with specific
165 /// identifiers because they are language keywords. This causes the lexer to
166 /// automatically map matching identifiers to specialized token codes.
167 static void AddKeyword(StringRef Keyword,
168  tok::TokenKind TokenCode, unsigned Flags,
169  const LangOptions &LangOpts, IdentifierTable &Table) {
170  KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags);
171 
172  // Don't add this keyword under MSVCCompat.
173  if (LangOpts.MSVCCompat && (Flags & KEYNOMS18) &&
175  return;
176 
177  // Don't add this keyword under OpenCL.
178  if (LangOpts.OpenCL && (Flags & KEYNOOPENCL))
179  return;
180 
181  // Don't add this keyword if disabled in this language.
182  if (AddResult == KS_Disabled) return;
183 
184  IdentifierInfo &Info =
185  Table.get(Keyword, AddResult == KS_Future ? tok::identifier : TokenCode);
186  Info.setIsExtensionToken(AddResult == KS_Extension);
187  Info.setIsFutureCompatKeyword(AddResult == KS_Future);
188 }
189 
190 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
191 /// representations.
192 static void AddCXXOperatorKeyword(StringRef Keyword,
193  tok::TokenKind TokenCode,
194  IdentifierTable &Table) {
195  IdentifierInfo &Info = Table.get(Keyword, TokenCode);
197 }
198 
199 /// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector"
200 /// or "property".
201 static void AddObjCKeyword(StringRef Name,
202  tok::ObjCKeywordKind ObjCID,
203  IdentifierTable &Table) {
204  Table.get(Name).setObjCKeywordID(ObjCID);
205 }
206 
207 /// AddKeywords - Add all keywords to the symbol table.
208 ///
210  // Add keywords and tokens for the current language.
211 #define KEYWORD(NAME, FLAGS) \
212  AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \
213  FLAGS, LangOpts, *this);
214 #define ALIAS(NAME, TOK, FLAGS) \
215  AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \
216  FLAGS, LangOpts, *this);
217 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
218  if (LangOpts.CXXOperatorNames) \
219  AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
220 #define OBJC_AT_KEYWORD(NAME) \
221  if (LangOpts.ObjC) \
222  AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
223 #define TESTING_KEYWORD(NAME, FLAGS)
224 #include "clang/Basic/TokenKinds.def"
225 
226  if (LangOpts.ParseUnknownAnytype)
227  AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
228  LangOpts, *this);
229 
230  if (LangOpts.DeclSpecKeyword)
231  AddKeyword("__declspec", tok::kw___declspec, KEYALL, LangOpts, *this);
232 
233  if (LangOpts.IEEE128)
234  AddKeyword("__ieee128", tok::kw___float128, KEYALL, LangOpts, *this);
235 
236  // Add the 'import' contextual keyword.
237  get("import").setModulesImport(true);
238 }
239 
240 /// Checks if the specified token kind represents a keyword in the
241 /// specified language.
242 /// \returns Status of the keyword in the language.
243 static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts,
244  tok::TokenKind K) {
245  switch (K) {
246 #define KEYWORD(NAME, FLAGS) \
247  case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS);
248 #include "clang/Basic/TokenKinds.def"
249  default: return KS_Disabled;
250  }
251 }
252 
253 /// Returns true if the identifier represents a keyword in the
254 /// specified language.
255 bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) const {
256  switch (getTokenKwStatus(LangOpts, getTokenID())) {
257  case KS_Enabled:
258  case KS_Extension:
259  return true;
260  default:
261  return false;
262  }
263 }
264 
265 /// Returns true if the identifier represents a C++ keyword in the
266 /// specified language.
267 bool IdentifierInfo::isCPlusPlusKeyword(const LangOptions &LangOpts) const {
268  if (!LangOpts.CPlusPlus || !isKeyword(LangOpts))
269  return false;
270  // This is a C++ keyword if this identifier is not a keyword when checked
271  // using LangOptions without C++ support.
272  LangOptions LangOptsNoCPP = LangOpts;
273  LangOptsNoCPP.CPlusPlus = false;
274  LangOptsNoCPP.CPlusPlus11 = false;
275  LangOptsNoCPP.CPlusPlus20 = false;
276  return !isKeyword(LangOptsNoCPP);
277 }
278 
280 IdentifierInfo::isReserved(const LangOptions &LangOpts) const {
281  StringRef Name = getName();
282 
283  // '_' is a reserved identifier, but its use is so common (e.g. to store
284  // ignored values) that we don't warn on it.
285  if (Name.size() <= 1)
287 
288  // [lex.name] p3
289  if (Name[0] == '_') {
290 
291  // Each name that begins with an underscore followed by an uppercase letter
292  // or another underscore is reserved.
293  if (Name[1] == '_')
295 
296  if ('A' <= Name[1] && Name[1] <= 'Z')
299 
300  // This is a bit misleading: it actually means it's only reserved if we're
301  // at global scope because it starts with an underscore.
303  }
304 
305  // Each name that contains a double underscore (__) is reserved.
306  if (LangOpts.CPlusPlus && Name.contains("__"))
308 
310 }
311 
313  // We use a perfect hash function here involving the length of the keyword,
314  // the first and third character. For preprocessor ID's there are no
315  // collisions (if there were, the switch below would complain about duplicate
316  // case values). Note that this depends on 'if' being null terminated.
317 
318 #define HASH(LEN, FIRST, THIRD) \
319  (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
320 #define CASE(LEN, FIRST, THIRD, NAME) \
321  case HASH(LEN, FIRST, THIRD): \
322  return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
323 
324  unsigned Len = getLength();
325  if (Len < 2) return tok::pp_not_keyword;
326  const char *Name = getNameStart();
327  switch (HASH(Len, Name[0], Name[2])) {
328  default: return tok::pp_not_keyword;
329  CASE( 2, 'i', '\0', if);
330  CASE( 4, 'e', 'i', elif);
331  CASE( 4, 'e', 's', else);
332  CASE( 4, 'l', 'n', line);
333  CASE( 4, 's', 'c', sccs);
334  CASE( 5, 'e', 'd', endif);
335  CASE( 5, 'e', 'r', error);
336  CASE( 5, 'i', 'e', ident);
337  CASE( 5, 'i', 'd', ifdef);
338  CASE( 5, 'u', 'd', undef);
339 
340  CASE( 6, 'a', 's', assert);
341  CASE( 6, 'd', 'f', define);
342  CASE( 6, 'i', 'n', ifndef);
343  CASE( 6, 'i', 'p', import);
344  CASE( 6, 'p', 'a', pragma);
345 
346  CASE( 7, 'd', 'f', defined);
347  CASE( 7, 'e', 'i', elifdef);
348  CASE( 7, 'i', 'c', include);
349  CASE( 7, 'w', 'r', warning);
350 
351  CASE( 8, 'e', 'i', elifndef);
352  CASE( 8, 'u', 'a', unassert);
353  CASE(12, 'i', 'c', include_next);
354 
355  CASE(14, '_', 'p', __public_macro);
356 
357  CASE(15, '_', 'p', __private_macro);
358 
359  CASE(16, '_', 'i', __include_macros);
360 #undef CASE
361 #undef HASH
362  }
363 }
364 
365 //===----------------------------------------------------------------------===//
366 // Stats Implementation
367 //===----------------------------------------------------------------------===//
368 
369 /// PrintStats - Print statistics about how well the identifier table is doing
370 /// at hashing identifiers.
372  unsigned NumBuckets = HashTable.getNumBuckets();
373  unsigned NumIdentifiers = HashTable.getNumItems();
374  unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
375  unsigned AverageIdentifierSize = 0;
376  unsigned MaxIdentifierLength = 0;
377 
378  // TODO: Figure out maximum times an identifier had to probe for -stats.
379  for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
380  I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
381  unsigned IdLen = I->getKeyLength();
382  AverageIdentifierSize += IdLen;
383  if (MaxIdentifierLength < IdLen)
384  MaxIdentifierLength = IdLen;
385  }
386 
387  fprintf(stderr, "\n*** Identifier Table Stats:\n");
388  fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
389  fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
390  fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
391  NumIdentifiers/(double)NumBuckets);
392  fprintf(stderr, "Ave identifier length: %f\n",
393  (AverageIdentifierSize/(double)NumIdentifiers));
394  fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
395 
396  // Compute statistics about the memory allocated for identifiers.
397  HashTable.getAllocator().PrintStats();
398 }
399 
400 //===----------------------------------------------------------------------===//
401 // SelectorTable Implementation
402 //===----------------------------------------------------------------------===//
403 
405  return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
406 }
407 
408 namespace clang {
409 
410 /// One of these variable length records is kept for each
411 /// selector containing more than one keyword. We use a folding set
412 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
413 /// this class is provided strictly through Selector.
414 class alignas(IdentifierInfoAlignment) MultiKeywordSelector
416  public llvm::FoldingSetNode {
417  MultiKeywordSelector(unsigned nKeys) : DeclarationNameExtra(nKeys) {}
418 
419 public:
420  // Constructor for keyword selectors.
421  MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV)
422  : DeclarationNameExtra(nKeys) {
423  assert((nKeys > 1) && "not a multi-keyword selector");
424 
425  // Fill in the trailing keyword array.
426  IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this + 1);
427  for (unsigned i = 0; i != nKeys; ++i)
428  KeyInfo[i] = IIV[i];
429  }
430 
431  // getName - Derive the full selector name and return it.
432  std::string getName() const;
433 
434  using DeclarationNameExtra::getNumArgs;
435 
437 
439  return reinterpret_cast<keyword_iterator>(this + 1);
440  }
441 
443  return keyword_begin() + getNumArgs();
444  }
445 
447  assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
448  return keyword_begin()[i];
449  }
450 
451  static void Profile(llvm::FoldingSetNodeID &ID, keyword_iterator ArgTys,
452  unsigned NumArgs) {
453  ID.AddInteger(NumArgs);
454  for (unsigned i = 0; i != NumArgs; ++i)
455  ID.AddPointer(ArgTys[i]);
456  }
457 
458  void Profile(llvm::FoldingSetNodeID &ID) {
459  Profile(ID, keyword_begin(), getNumArgs());
460  }
461 };
462 
463 } // namespace clang.
464 
465 bool Selector::isKeywordSelector(ArrayRef<StringRef> Names) const {
466  assert(!Names.empty() && "must have >= 1 selector slots");
467  if (getNumArgs() != Names.size())
468  return false;
469  for (unsigned I = 0, E = Names.size(); I != E; ++I) {
470  if (getNameForSlot(I) != Names[I])
471  return false;
472  }
473  return true;
474 }
475 
476 bool Selector::isUnarySelector(StringRef Name) const {
477  return isUnarySelector() && getNameForSlot(0) == Name;
478 }
479 
480 unsigned Selector::getNumArgs() const {
481  unsigned IIF = getIdentifierInfoFlag();
482  if (IIF <= ZeroArg)
483  return 0;
484  if (IIF == OneArg)
485  return 1;
486  // We point to a MultiKeywordSelector.
487  MultiKeywordSelector *SI = getMultiKeywordSelector();
488  return SI->getNumArgs();
489 }
490 
491 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
492  if (getIdentifierInfoFlag() < MultiArg) {
493  assert(argIndex == 0 && "illegal keyword index");
494  return getAsIdentifierInfo();
495  }
496 
497  // We point to a MultiKeywordSelector.
498  MultiKeywordSelector *SI = getMultiKeywordSelector();
499  return SI->getIdentifierInfoForSlot(argIndex);
500 }
501 
502 StringRef Selector::getNameForSlot(unsigned int argIndex) const {
503  IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
504  return II ? II->getName() : StringRef();
505 }
506 
508  SmallString<256> Str;
509  llvm::raw_svector_ostream OS(Str);
510  for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
511  if (*I)
512  OS << (*I)->getName();
513  OS << ':';
514  }
515 
516  return std::string(OS.str());
517 }
518 
520  if (InfoPtr == 0)
521  return "<null selector>";
522 
523  if (getIdentifierInfoFlag() < MultiArg) {
524  IdentifierInfo *II = getAsIdentifierInfo();
525 
526  if (getNumArgs() == 0) {
527  assert(II && "If the number of arguments is 0 then II is guaranteed to "
528  "not be null.");
529  return std::string(II->getName());
530  }
531 
532  if (!II)
533  return ":";
534 
535  return II->getName().str() + ":";
536  }
537 
538  // We have a multiple keyword selector.
539  return getMultiKeywordSelector()->getName();
540 }
541 
542 void Selector::print(llvm::raw_ostream &OS) const {
543  OS << getAsString();
544 }
545 
546 LLVM_DUMP_METHOD void Selector::dump() const { print(llvm::errs()); }
547 
548 /// Interpreting the given string using the normal CamelCase
549 /// conventions, determine whether the given string starts with the
550 /// given "word", which is assumed to end in a lowercase letter.
551 static bool startsWithWord(StringRef name, StringRef word) {
552  if (name.size() < word.size()) return false;
553  return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
554  name.startswith(word));
555 }
556 
557 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
559  if (!first) return OMF_None;
560 
561  StringRef name = first->getName();
562  if (sel.isUnarySelector()) {
563  if (name == "autorelease") return OMF_autorelease;
564  if (name == "dealloc") return OMF_dealloc;
565  if (name == "finalize") return OMF_finalize;
566  if (name == "release") return OMF_release;
567  if (name == "retain") return OMF_retain;
568  if (name == "retainCount") return OMF_retainCount;
569  if (name == "self") return OMF_self;
570  if (name == "initialize") return OMF_initialize;
571  }
572 
573  if (name == "performSelector" || name == "performSelectorInBackground" ||
574  name == "performSelectorOnMainThread")
575  return OMF_performSelector;
576 
577  // The other method families may begin with a prefix of underscores.
578  while (!name.empty() && name.front() == '_')
579  name = name.substr(1);
580 
581  if (name.empty()) return OMF_None;
582  switch (name.front()) {
583  case 'a':
584  if (startsWithWord(name, "alloc")) return OMF_alloc;
585  break;
586  case 'c':
587  if (startsWithWord(name, "copy")) return OMF_copy;
588  break;
589  case 'i':
590  if (startsWithWord(name, "init")) return OMF_init;
591  break;
592  case 'm':
593  if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
594  break;
595  case 'n':
596  if (startsWithWord(name, "new")) return OMF_new;
597  break;
598  default:
599  break;
600  }
601 
602  return OMF_None;
603 }
604 
605 ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
607  if (!first) return OIT_None;
608 
609  StringRef name = first->getName();
610 
611  if (name.empty()) return OIT_None;
612  switch (name.front()) {
613  case 'a':
614  if (startsWithWord(name, "array")) return OIT_Array;
615  break;
616  case 'd':
617  if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
618  if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
619  break;
620  case 's':
621  if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
622  if (startsWithWord(name, "standard")) return OIT_Singleton;
623  break;
624  case 'i':
625  if (startsWithWord(name, "init")) return OIT_Init;
626  break;
627  default:
628  break;
629  }
630  return OIT_None;
631 }
632 
633 ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) {
635  if (!first) return SFF_None;
636 
637  StringRef name = first->getName();
638 
639  switch (name.front()) {
640  case 'a':
641  if (name == "appendFormat") return SFF_NSString;
642  break;
643 
644  case 'i':
645  if (name == "initWithFormat") return SFF_NSString;
646  break;
647 
648  case 'l':
649  if (name == "localizedStringWithFormat") return SFF_NSString;
650  break;
651 
652  case 's':
653  if (name == "stringByAppendingFormat" ||
654  name == "stringWithFormat") return SFF_NSString;
655  break;
656  }
657  return SFF_None;
658 }
659 
660 namespace {
661 
662 struct SelectorTableImpl {
663  llvm::FoldingSet<MultiKeywordSelector> Table;
664  llvm::BumpPtrAllocator Allocator;
665 };
666 
667 } // namespace
668 
669 static SelectorTableImpl &getSelectorTableImpl(void *P) {
670  return *static_cast<SelectorTableImpl*>(P);
671 }
672 
674 SelectorTable::constructSetterName(StringRef Name) {
675  SmallString<64> SetterName("set");
676  SetterName += Name;
677  SetterName[3] = toUppercase(SetterName[3]);
678  return SetterName;
679 }
680 
681 Selector
682 SelectorTable::constructSetterSelector(IdentifierTable &Idents,
683  SelectorTable &SelTable,
684  const IdentifierInfo *Name) {
685  IdentifierInfo *SetterName =
686  &Idents.get(constructSetterName(Name->getName()));
687  return SelTable.getUnarySelector(SetterName);
688 }
689 
690 std::string SelectorTable::getPropertyNameFromSetterSelector(Selector Sel) {
691  StringRef Name = Sel.getNameForSlot(0);
692  assert(Name.startswith("set") && "invalid setter name");
693  return (Twine(toLowercase(Name[3])) + Name.drop_front(4)).str();
694 }
695 
696 size_t SelectorTable::getTotalMemory() const {
697  SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
698  return SelTabImpl.Allocator.getTotalMemory();
699 }
700 
701 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
702  if (nKeys < 2)
703  return Selector(IIV[0], nKeys);
704 
705  SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
706 
707  // Unique selector, to guarantee there is one per name.
708  llvm::FoldingSetNodeID ID;
709  MultiKeywordSelector::Profile(ID, IIV, nKeys);
710 
711  void *InsertPos = nullptr;
712  if (MultiKeywordSelector *SI =
713  SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
714  return Selector(SI);
715 
716  // MultiKeywordSelector objects are not allocated with new because they have a
717  // variable size array (for parameter types) at the end of them.
718  unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
720  (MultiKeywordSelector *)SelTabImpl.Allocator.Allocate(
721  Size, alignof(MultiKeywordSelector));
722  new (SI) MultiKeywordSelector(nKeys, IIV);
723  SelTabImpl.Table.InsertNode(SI, InsertPos);
724  return Selector(SI);
725 }
726 
727 SelectorTable::SelectorTable() {
728  Impl = new SelectorTableImpl();
729 }
730 
731 SelectorTable::~SelectorTable() {
732  delete &getSelectorTableImpl(Impl);
733 }
734 
736  switch (Operator) {
737  case OO_None:
739  return nullptr;
740 
741 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
742  case OO_##Name: return Spelling;
743 #include "clang/Basic/OperatorKinds.def"
744  }
745 
746  llvm_unreachable("Invalid OverloadedOperatorKind!");
747 }
748 
750  bool isContextSensitive) {
751  switch (kind) {
752  case NullabilityKind::NonNull:
753  return isContextSensitive ? "nonnull" : "_Nonnull";
754 
755  case NullabilityKind::Nullable:
756  return isContextSensitive ? "nullable" : "_Nullable";
757 
758  case NullabilityKind::NullableResult:
759  assert(!isContextSensitive &&
760  "_Nullable_result isn't supported as context-sensitive keyword");
761  return "_Nullable_result";
762 
763  case NullabilityKind::Unspecified:
764  return isContextSensitive ? "null_unspecified" : "_Null_unspecified";
765  }
766  llvm_unreachable("Unknown nullability kind.");
767 }
AddCXXOperatorKeyword
static void AddCXXOperatorKeyword(StringRef Keyword, tok::TokenKind TokenCode, IdentifierTable &Table)
AddCXXOperatorKeyword - Register a C++ operator keyword alternative representations.
Definition: IdentifierTable.cpp:192
clang::OMF_autorelease
@ OMF_autorelease
Definition: IdentifierTable.h:674
Specifiers.h
clang::ReservedIdentifierStatus::StartsWithUnderscoreAtGlobalScope
@ StartsWithUnderscoreAtGlobalScope
clang::IdentifierInfo::setModulesImport
void setModulesImport(bool I)
Set whether this identifier is the contextual keyword import.
Definition: IdentifierTable.h:402
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::ObjCMethodFamily
ObjCMethodFamily
A family of Objective-C methods.
Definition: IdentifierTable.h:658
clang::ReservedIdentifierStatus::NotReserved
@ NotReserved
include
include(CheckIncludeFiles) set(LLVM_LINK_COMPONENTS support) set(DIRECTORY_WATCHER_SOURCES DirectoryScanner.cpp) set(DIRECTORY_WATCHER_LINK_LIBS "") if(APPLE) check_include_files("CoreServices/CoreServices.h" HAVE_CORESERVICES) if(HAVE_CORESERVICES) list(APPEND DIRECTORY_WATCHER_SOURCES mac/DirectoryWatcher-mac.cpp) set(DIRECTORY_WATCHER_LINK_LIBS "-framework CoreServices") endif() elseif(CMAKE_SYSTEM_NAME MATCHES "Linux") check_include_files("sys/inotify.h" HAVE_INOTIFY) if(HAVE_INOTIFY) list(APPEND DIRECTORY_WATCHER_SOURCES linux/DirectoryWatcher-linux.cpp) find_package(Threads REQUIRED) endif() elseif(CMAKE_SYSTEM_NAME MATCHES "Windows") list(APPEND DIRECTORY_WATCHER_SOURCES windows/DirectoryWatcher-windows.cpp) else() list(APPEND DIRECTORY_WATCHER_SOURCES default/DirectoryWatcher-not-implemented.cpp) endif() add_clang_library(clangDirectoryWatcher $
Definition: CMakeLists.txt:1
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:564
clang::OMF_None
@ OMF_None
No particular method family.
Definition: IdentifierTable.h:660
clang::OMF_release
@ OMF_release
Definition: IdentifierTable.h:677
clang::ObjCOrBuiltinIDBits
static constexpr int ObjCOrBuiltinIDBits
Definition: IdentifierTable.h:59
clang::IdentifierInfoLookup::getIdentifiers
virtual IdentifierIterator * getIdentifiers()
Retrieve an iterator into the set of all identifiers known to this identifier lookup source.
Definition: IdentifierTable.cpp:62
clang::ObjCInstanceTypeFamily
ObjCInstanceTypeFamily
A family of Objective-C methods.
Definition: IdentifierTable.h:698
clang::Selector::isUnarySelector
bool isUnarySelector() const
Definition: IdentifierTable.h:797
clang::OMF_finalize
@ OMF_finalize
Definition: IdentifierTable.h:676
clang::OMF_init
@ OMF_init
Definition: IdentifierTable.h:668
clang::IdentifierInfo::isReserved
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine whether this is a name reserved for the implementation (C99 7.1.3, C++ [lib....
Definition: IdentifierTable.cpp:280
clang::detail::DeclarationNameExtra::getNumArgs
unsigned getNumArgs() const
Return the number of arguments in an ObjC selector.
Definition: IdentifierTable.h:963
clang::ReservedIdentifierStatus::ContainsDoubleUnderscore
@ ContainsDoubleUnderscore
AddObjCKeyword
static void AddObjCKeyword(StringRef Name, tok::ObjCKeywordKind ObjCID, IdentifierTable &Table)
AddObjCKeyword - Register an Objective-C @keyword like "class" "selector" or "property".
Definition: IdentifierTable.cpp:201
clang::isLowercase
LLVM_READONLY bool isLowercase(unsigned char c)
Return true if this character is a lowercase ASCII letter: [a-z].
Definition: CharInfo.h:104
CASE
#define CASE(LEN, FIRST, THIRD, NAME)
clang::OMF_retainCount
@ OMF_retainCount
Definition: IdentifierTable.h:679
startsWithWord
static bool startsWithWord(StringRef name, StringRef word)
Interpreting the given string using the normal CamelCase conventions, determine whether the given str...
Definition: IdentifierTable.cpp:551
clang::toLowercase
LLVM_READONLY char toLowercase(char c)
Converts the given ASCII character to its lowercase equivalent.
Definition: CharInfo.h:169
print
void print(llvm::raw_ostream &OS, const Pointer &P, ASTContext &Ctx, QualType Ty)
Definition: InterpFrame.cpp:62
clang::IdentifierInfo::getTokenID
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
Definition: IdentifierTable.h:233
clang::MultiKeywordSelector::getIdentifierInfoForSlot
IdentifierInfo * getIdentifierInfoForSlot(unsigned i) const
Definition: IdentifierTable.cpp:446
clang::IdentifierIterator::~IdentifierIterator
virtual ~IdentifierIterator()
clang::MultiKeywordSelector::Profile
void Profile(llvm::FoldingSetNodeID &ID)
Definition: IdentifierTable.cpp:458
clang::ReservedIdentifierStatus::StartsWithUnderscoreFollowedByCapitalLetter
@ StartsWithUnderscoreFollowedByCapitalLetter
llvm::DenseMapInfo
Definition: TypeOrdering.h:37
clang::OIT_ReturnsSelf
@ OIT_ReturnsSelf
Definition: IdentifierTable.h:704
TokenKinds.h
clang::OMF_copy
@ OMF_copy
Definition: IdentifierTable.h:667
clang::OIT_Dictionary
@ OIT_Dictionary
Definition: IdentifierTable.h:701
clang::MultiKeywordSelector::keyword_iterator
IdentifierInfo *const * keyword_iterator
Definition: IdentifierTable.cpp:436
clang::getAsString
llvm::StringRef getAsString(SyncScope S)
Definition: SyncScope.h:50
clang::LangOptions::isCompatibleWithMSVC
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:410
clang::OIT_Array
@ OIT_Array
Definition: IdentifierTable.h:700
clang::IdentifierInfo::isCPlusPlusKeyword
bool isCPlusPlusKeyword(const LangOptions &LangOpts) const
Return true if this token is a C++ keyword in the specified language.
Definition: IdentifierTable.cpp:267
clang::Selector::getNameForSlot
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
Definition: IdentifierTable.cpp:502
clang::OMF_retain
@ OMF_retain
Definition: IdentifierTable.h:678
OperatorKinds.h
clang::OMF_dealloc
@ OMF_dealloc
Definition: IdentifierTable.h:675
clang::OIT_Init
@ OIT_Init
Definition: IdentifierTable.h:703
getKeywordStatus
static KeywordStatus getKeywordStatus(const LangOptions &LangOpts, unsigned Flags)
Translates flags as specified in TokenKinds.def into keyword status in the given language standard.
Definition: IdentifierTable.cpp:128
clang::IdentifierInfo::setIsFutureCompatKeyword
void setIsFutureCompatKeyword(bool Val)
Definition: IdentifierTable.h:307
LangOptions.h
clang::ReservedIdentifierStatus
ReservedIdentifierStatus
Definition: IdentifierTable.h:43
clang::LargestBuiltinID
static constexpr uint64_t LargestBuiltinID
Definition: TargetBuiltins.h:323
clang::detail::DeclarationNameExtra
DeclarationNameExtra is used as a base of various uncommon special names.
Definition: IdentifierTable.h:920
clang::IdentifierInfo::getLength
unsigned getLength() const
Efficiently return the length of this identifier info.
Definition: IdentifierTable.h:172
AddKeyword
static void AddKeyword(StringRef Keyword, tok::TokenKind TokenCode, unsigned Flags, const LangOptions &LangOpts, IdentifierTable &Table)
AddKeyword - This method is used to associate a token ID with specific identifiers because they are l...
Definition: IdentifierTable.cpp:167
IdentifierTable.h
llvm::SmallString
Definition: LLVM.h:37
clang::SelectorTable
This table allows us to fully hide how we implement multi-keyword caching.
Definition: IdentifierTable.h:865
clang::IdentifierIterator
An iterator that walks over all of the known identifiers in the lookup table.
Definition: IdentifierTable.h:483
clang::IdentifierInfo::setObjCKeywordID
void setObjCKeywordID(tok::ObjCKeywordKind ID)
Definition: IdentifierTable.h:269
clang::NUM_OVERLOADED_OPERATORS
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
clang::tok::ObjCKeywordKind
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition: TokenKinds.h:41
clang::getOperatorSpelling
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
Definition: IdentifierTable.cpp:735
clang::SFF_NSString
@ SFF_NSString
Definition: IdentifierTable.h:709
clang::IdentifierInfo::setIsCPlusPlusOperatorKeyword
void setIsCPlusPlusOperatorKeyword(bool Val=true)
isCPlusPlusOperatorKeyword/setIsCPlusPlusOperatorKeyword controls whether this identifier is a C++ al...
Definition: IdentifierTable.h:330
clang::OMF_initialize
@ OMF_initialize
Definition: IdentifierTable.h:681
HASH
#define HASH(LEN, FIRST, THIRD)
getName
static std::string getName(const CallEvent &Call)
Definition: ReturnValueChecker.cpp:60
clang::OMF_self
@ OMF_self
Definition: IdentifierTable.h:680
clang::OverloadedOperatorKind
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
clang::toUppercase
LLVM_READONLY char toUppercase(char c)
Converts the given ASCII character to its uppercase equivalent.
Definition: CharInfo.h:178
clang::IdentifierInfo::isKeyword
bool isKeyword(const LangOptions &LangOpts) const
Return true if this token is a keyword in the specified language.
Definition: IdentifierTable.cpp:255
clang::OMF_performSelector
@ OMF_performSelector
Definition: IdentifierTable.h:684
clang::OO_None
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
clang::tok::TokenKind
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
clang::MultiKeywordSelector::Profile
static void Profile(llvm::FoldingSetNodeID &ID, keyword_iterator ArgTys, unsigned NumArgs)
Definition: IdentifierTable.cpp:451
P
StringRef P
Definition: ASTMatchersInternal.cpp:563
CharInfo.h
clang::getNullabilitySpelling
llvm::StringRef getNullabilitySpelling(NullabilityKind kind, bool isContextSensitive=false)
Retrieve the spelling of the given nullability kind.
Definition: IdentifierTable.cpp:749
getSelectorTableImpl
static SelectorTableImpl & getSelectorTableImpl(void *P)
Definition: IdentifierTable.cpp:669
dump
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Definition: CoverageMappingGen.cpp:1521
llvm::ArrayRef
Definition: LLVM.h:34
clang::tok::PPKeywordKind
PPKeywordKind
Provides a namespace for preprocessor keywords which start with a '#' at the beginning of the line.
Definition: TokenKinds.h:33
clang::MultiKeywordSelector::keyword_begin
keyword_iterator keyword_begin() const
Definition: IdentifierTable.cpp:438
clang::IdentifierInfo::getPPKeywordID
tok::PPKeywordKind getPPKeywordID() const
Return the preprocessor keyword ID for this identifier.
Definition: IdentifierTable.cpp:312
clang::Selector::getIdentifierInfoForSlot
IdentifierInfo * getIdentifierInfoForSlot(unsigned argIndex) const
Retrieve the identifier at a given position in the selector.
Definition: IdentifierTable.cpp:491
TargetBuiltins.h
clang::IdentifierInfoLookup::~IdentifierInfoLookup
virtual ~IdentifierInfoLookup()
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:67
clang::IdentifierTable::AddKeywords
void AddKeywords(const LangOptions &LangOpts)
Populate the identifier table with info about the language keywords for the language specified by Lan...
Definition: IdentifierTable.cpp:209
getTokenKwStatus
static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts, tok::TokenKind K)
Checks if the specified token kind represents a keyword in the specified language.
Definition: IdentifierTable.cpp:243
clang::OMF_new
@ OMF_new
Definition: IdentifierTable.h:670
clang::LangOptions::isSYCL
bool isSYCL() const
Definition: LangOptions.h:472
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:58
clang::IdentifierInfo::getNameStart
const char * getNameStart() const
Return the beginning of the actual null-terminated string for this identifier.
Definition: IdentifierTable.h:169
clang::SelectorTable::getUnarySelector
Selector getUnarySelector(IdentifierInfo *ID)
Definition: IdentifierTable.h:881
clang::NullabilityKind
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:306
clang::ObjCStringFormatFamily
ObjCStringFormatFamily
Definition: IdentifierTable.h:707
clang::MultiKeywordSelector
One of these variable length records is kept for each selector containing more than one keyword.
Definition: IdentifierTable.cpp:414
clang::IdentifierTable::IdentifierTable
IdentifierTable(IdentifierInfoLookup *ExternalLookup=nullptr)
Create the identifier table.
Definition: IdentifierTable.cpp:66
clang::IdentifierInfo::getName
StringRef getName() const
Return the actual identifier string.
Definition: IdentifierTable.h:175
clang::Builtin::ID
ID
Definition: Builtins.h:48
clang
Definition: CalledOnceCheck.h:17
clang::LangOptions::MSVC2015
@ MSVC2015
Definition: LangOptions.h:122
clang::Selector
Smart pointer class that efficiently represents Objective-C method names.
Definition: IdentifierTable.h:720
clang::IdentifierTable::PrintStats
void PrintStats() const
Print some statistics to stderr that indicate how well the hashing is doing.
Definition: IdentifierTable.cpp:371
endif
endif() if(clang_vc AND LLVM_APPEND_VC_REV) set(clang_source_dir $
Definition: CMakeLists.txt:15
clang::OMF_alloc
@ OMF_alloc
Definition: IdentifierTable.h:666
clang::OMF_mutableCopy
@ OMF_mutableCopy
Definition: IdentifierTable.h:669
clang::IdentifierTable
Implements an efficient mapping from strings to IdentifierInfo nodes.
Definition: IdentifierTable.h:531
clang::IdentifierInfoLookup
Provides lookups to, and iteration over, IdentiferInfo objects.
Definition: IdentifierTable.h:502
clang::MultiKeywordSelector::keyword_end
keyword_iterator keyword_end() const
Definition: IdentifierTable.cpp:442
clang::MultiKeywordSelector::MultiKeywordSelector
MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV)
Definition: IdentifierTable.cpp:421
clang::SFF_None
@ SFF_None
Definition: IdentifierTable.h:708
clang::transformer::name
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
Definition: RangeSelector.cpp:200
clang::OIT_Singleton
@ OIT_Singleton
Definition: IdentifierTable.h:702
clang::diag::kind
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:60
clang::OIT_None
@ OIT_None
Definition: IdentifierTable.h:699
clang::ReservedIdentifierStatus::StartsWithDoubleUnderscore
@ StartsWithDoubleUnderscore
clang::IdentifierInfo::setIsExtensionToken
void setIsExtensionToken(bool Val)
Definition: IdentifierTable.h:293